target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testGetPathEntityS3AV2Path() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE, AWS_S3_ATLAS_MODEL_VERSION_V2); Path path = new Path(S3A_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_V2_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3V2PseudoDir(S3A_SCHEME, S3A_PATH, entity); verifyS3V2KnownEntities(S3A_SCHEME, S3A_PATH, extractorContext.getKnownEntities()); } | public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); static final char QNAME_SEP_METADATA_NAMESPACE; static final char QNAME_SEP_ENTITY_NAME; static final String SCHEME_SEPARATOR; static final String ATTRIBUTE_QUALIFIED_NAME; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_BUCKET; static final String HDFS_TYPE_PATH; static final String ATTRIBUTE_PATH; static final String ATTRIBUTE_CLUSTER_NAME; static final String ATTRIBUTE_NAMESERVICE_ID; static final String AWS_S3_ATLAS_MODEL_VERSION_V2; static final String AWS_S3_BUCKET; static final String AWS_S3_PSEUDO_DIR; static final String AWS_S3_V2_BUCKET; static final String AWS_S3_V2_PSEUDO_DIR; static final String S3_SCHEME; static final String S3A_SCHEME; static final String ATTRIBUTE_CONTAINER; static final String ATTRIBUTE_OBJECT_PREFIX; static final String RELATIONSHIP_AWS_S3_BUCKET_S3_PSEUDO_DIRS; static final String RELATIONSHIP_AWS_S3_V2_CONTAINER_CONTAINED; static final String ADLS_GEN2_ACCOUNT; static final String ADLS_GEN2_CONTAINER; static final String ADLS_GEN2_DIRECTORY; static final String ADLS_GEN2_ACCOUNT_HOST_SUFFIX; static final String ABFS_SCHEME; static final String ABFSS_SCHEME; static final String ATTRIBUTE_ACCOUNT; static final String ATTRIBUTE_PARENT; static final String RELATIONSHIP_ADLS_GEN2_ACCOUNT_CONTAINERS; static final String RELATIONSHIP_ADLS_GEN2_PARENT_CHILDREN; static final String OZONE_VOLUME; static final String OZONE_BUCKET; static final String OZONE_KEY; static final String OZONE_SCHEME; static final String OZONE_3_SCHEME; static final String ATTRIBUTE_VOLUME; static final String RELATIONSHIP_OZONE_VOLUME_BUCKET; static final String RELATIONSHIP_OZONE_PARENT_CHILDREN; } |
@Test public void testGetPathEntityS3Path() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(S3_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3PseudoDir(S3_PATH, entity); verifyS3KnownEntities(S3_SCHEME, S3_PATH, extractorContext.getKnownEntities()); } | public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); static final char QNAME_SEP_METADATA_NAMESPACE; static final char QNAME_SEP_ENTITY_NAME; static final String SCHEME_SEPARATOR; static final String ATTRIBUTE_QUALIFIED_NAME; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_BUCKET; static final String HDFS_TYPE_PATH; static final String ATTRIBUTE_PATH; static final String ATTRIBUTE_CLUSTER_NAME; static final String ATTRIBUTE_NAMESERVICE_ID; static final String AWS_S3_ATLAS_MODEL_VERSION_V2; static final String AWS_S3_BUCKET; static final String AWS_S3_PSEUDO_DIR; static final String AWS_S3_V2_BUCKET; static final String AWS_S3_V2_PSEUDO_DIR; static final String S3_SCHEME; static final String S3A_SCHEME; static final String ATTRIBUTE_CONTAINER; static final String ATTRIBUTE_OBJECT_PREFIX; static final String RELATIONSHIP_AWS_S3_BUCKET_S3_PSEUDO_DIRS; static final String RELATIONSHIP_AWS_S3_V2_CONTAINER_CONTAINED; static final String ADLS_GEN2_ACCOUNT; static final String ADLS_GEN2_CONTAINER; static final String ADLS_GEN2_DIRECTORY; static final String ADLS_GEN2_ACCOUNT_HOST_SUFFIX; static final String ABFS_SCHEME; static final String ABFSS_SCHEME; static final String ATTRIBUTE_ACCOUNT; static final String ATTRIBUTE_PARENT; static final String RELATIONSHIP_ADLS_GEN2_ACCOUNT_CONTAINERS; static final String RELATIONSHIP_ADLS_GEN2_PARENT_CHILDREN; static final String OZONE_VOLUME; static final String OZONE_BUCKET; static final String OZONE_KEY; static final String OZONE_SCHEME; static final String OZONE_3_SCHEME; static final String ATTRIBUTE_VOLUME; static final String RELATIONSHIP_OZONE_VOLUME_BUCKET; static final String RELATIONSHIP_OZONE_PARENT_CHILDREN; } |
@Test public void testStructTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(structType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(structType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } } | @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } | AtlasStructType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } } | AtlasStructType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); } | AtlasStructType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); } | AtlasStructType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); static final String UNIQUE_ATTRIBUTE_SHADE_PROPERTY_PREFIX; } |
@Test public void testGetPathEntityS3APath() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(S3A_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3PseudoDir(S3A_PATH, entity); verifyS3KnownEntities(S3A_SCHEME, S3A_PATH, extractorContext.getKnownEntities()); } | public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); } | AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); static final char QNAME_SEP_METADATA_NAMESPACE; static final char QNAME_SEP_ENTITY_NAME; static final String SCHEME_SEPARATOR; static final String ATTRIBUTE_QUALIFIED_NAME; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_BUCKET; static final String HDFS_TYPE_PATH; static final String ATTRIBUTE_PATH; static final String ATTRIBUTE_CLUSTER_NAME; static final String ATTRIBUTE_NAMESERVICE_ID; static final String AWS_S3_ATLAS_MODEL_VERSION_V2; static final String AWS_S3_BUCKET; static final String AWS_S3_PSEUDO_DIR; static final String AWS_S3_V2_BUCKET; static final String AWS_S3_V2_PSEUDO_DIR; static final String S3_SCHEME; static final String S3A_SCHEME; static final String ATTRIBUTE_CONTAINER; static final String ATTRIBUTE_OBJECT_PREFIX; static final String RELATIONSHIP_AWS_S3_BUCKET_S3_PSEUDO_DIRS; static final String RELATIONSHIP_AWS_S3_V2_CONTAINER_CONTAINED; static final String ADLS_GEN2_ACCOUNT; static final String ADLS_GEN2_CONTAINER; static final String ADLS_GEN2_DIRECTORY; static final String ADLS_GEN2_ACCOUNT_HOST_SUFFIX; static final String ABFS_SCHEME; static final String ABFSS_SCHEME; static final String ATTRIBUTE_ACCOUNT; static final String ATTRIBUTE_PARENT; static final String RELATIONSHIP_ADLS_GEN2_ACCOUNT_CONTAINERS; static final String RELATIONSHIP_ADLS_GEN2_PARENT_CHILDREN; static final String OZONE_VOLUME; static final String OZONE_BUCKET; static final String OZONE_KEY; static final String OZONE_SCHEME; static final String OZONE_3_SCHEME; static final String ATTRIBUTE_VOLUME; static final String RELATIONSHIP_OZONE_VOLUME_BUCKET; static final String RELATIONSHIP_OZONE_PARENT_CHILDREN; } |
@Test public void updateClassificationsShouldNotThrowExceptionIfResponseIs204() { AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration); AtlasClassification atlasClassification = new AtlasClassification("Testdb"); atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a"); WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.NO_CONTENT.getStatusCode()); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); try { atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification)); } catch (AtlasServiceException e) { Assert.fail("Failed with Exception"); } } | public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); AtlasTypesDef getAllTypeDefs(SearchFilter searchFilter); List<AtlasTypeDefHeader> getAllTypeDefHeaders(SearchFilter searchFilter); boolean typeWithGuidExists(String guid); boolean typeWithNameExists(String name); AtlasEnumDef getEnumDefByName(String name); AtlasEnumDef getEnumDefByGuid(String guid); AtlasStructDef getStructDefByName(String name); AtlasStructDef getStructDefByGuid(String guid); AtlasClassificationDef getClassificationDefByName(String name); AtlasClassificationDef getClassificationDefByGuid(String guid); AtlasEntityDef getEntityDefByName(String name); AtlasEntityDef getEntityDefByGuid(String guid); AtlasRelationshipDef getRelationshipDefByName(String name); AtlasRelationshipDef getRelationshipDefByGuid(String guid); AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); AtlasBusinessMetadataDef getBusinessMetadataDefGuid(String guid); @Deprecated AtlasEnumDef createEnumDef(AtlasEnumDef enumDef); @Deprecated AtlasStructDef createStructDef(AtlasStructDef structDef); @Deprecated AtlasEntityDef createEntityDef(AtlasEntityDef entityDef); @Deprecated AtlasClassificationDef createClassificationDef(AtlasClassificationDef classificationDef); AtlasTypesDef createAtlasTypeDefs(AtlasTypesDef typesDef); AtlasTypesDef updateAtlasTypeDefs(AtlasTypesDef typesDef); void deleteAtlasTypeDefs(AtlasTypesDef typesDef); void deleteTypeByName(String typeName); AtlasEntityWithExtInfo getEntityByGuid(String guid); AtlasEntityWithExtInfo getEntityByGuid(String guid, boolean minExtInfo, boolean ignoreRelationships); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes, boolean minExtInfo, boolean ignoreRelationship); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids, boolean minExtInfo, boolean ignoreRelationships); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String,String>> uniqAttributesList); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String, String>> uniqAttributesList, boolean minExtInfo, boolean ignoreRelationship); AtlasEntityHeader getEntityHeaderByGuid(String entityGuid); AtlasEntityHeader getEntityHeaderByAttribute(String typeName, Map<String, String> uniqAttributes); List<EntityAuditEventV2> getAuditEvents(String guid, String startKey, EntityAuditEventV2.EntityAuditActionV2 auditAction, short count); EntityMutationResponse createEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse createEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse updateEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntityByAttribute(String typeName, Map<String, String> uniqAttributes, AtlasEntityWithExtInfo entityInfo); EntityMutationResponse partialUpdateEntityByGuid(String entityGuid, Object attrValue, String attrName); EntityMutationResponse deleteEntityByGuid(String guid); EntityMutationResponse deleteEntityByAttribute(String typeName, Map<String, String> uniqAttributes); EntityMutationResponse deleteEntitiesByGuids(List<String> guids); EntityMutationResponse purgeEntitiesByGuids(Set<String> guids); AtlasClassifications getClassifications(String guid); AtlasClassifications getEntityClassifications(String entityGuid, String classificationName); void addClassification(ClassificationAssociateRequest request); void addClassifications(String guid, List<AtlasClassification> classifications); void addClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); void updateClassifications(String guid, List<AtlasClassification> classifications); void updateClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); String setClassifications(AtlasEntityHeaders entityHeaders); void deleteClassification(String guid, String classificationName); void deleteClassifications(String guid, List<AtlasClassification> classifications); void removeClassification(String entityGuid, String classificationName, String associatedEntityGuid); void removeClassification(String typeName, Map<String, String> uniqAttributes, String classificationName); AtlasEntityHeaders getEntityHeaders(long tagUpdateStartTime); void addOrUpdateBusinessAttributes(String entityGuid, boolean isOverwrite, Map<String, Map<String, Object>> businessAttributes); void addOrUpdateBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); String getTemplateForBulkUpdateBusinessAttributes(); BulkImportResponse bulkUpdateBusinessAttributes(String fileName); void addLabels(String entityGuid, Set<String> labels); void addLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void removeLabels(String entityGuid, Set<String> labels); void removeLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void setLabels(String entityGuid, Set<String> labels); void setLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth); AtlasLineageInfo getLineageInfo(String typeName, Map<String, String> attributes, LineageDirection direction, int depth); AtlasSearchResult dslSearch(String query); AtlasSearchResult dslSearchWithParams(String query, int limit, int offset); AtlasSearchResult fullTextSearch(String query); AtlasSearchResult fullTextSearchWithParams(String query, int limit, int offset); AtlasSearchResult basicSearch(String typeName, String classification, String query, boolean excludeDeletedEntities, int limit, int offset); AtlasSearchResult facetedSearch(SearchParameters searchParameters); AtlasSearchResult attributeSearch(String typeName, String attrName, String attrValuePrefix, int limit, int offset); AtlasSearchResult relationshipSearch(String guid, String relation, String sortByAttribute, SortOrder sortOrder, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(String query, String typeName, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(QuickSearchParameters quickSearchParameters); AtlasSuggestionsResult getSuggestions(String prefixString, String fieldName); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); void deleteSavedSearch(String guid); AtlasSearchResult executeSavedSearch(String userName, String searchName); AtlasSearchResult executeSavedSearch(String searchGuid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid, boolean extendedInfo); AtlasRelationship createRelationship(AtlasRelationship relationship); AtlasRelationship updateRelationship(AtlasRelationship relationship); void deleteRelationshipByGuid(String guid); List<AtlasAuditEntry> getAtlasAuditByOperation(AuditSearchParameters auditSearchParameters); List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset); AtlasGlossary getGlossaryByGuid(String glossaryGuid); AtlasGlossary.AtlasGlossaryExtInfo getGlossaryExtInfo(String glossaryGuid); AtlasGlossaryTerm getGlossaryTerm(String termGuid); List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getGlossaryTermHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); AtlasGlossaryCategory getGlossaryCategory(String categoryGuid); List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedCategoryHeader> getGlossaryCategoryHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, String sortByAttribute, int limit, int offset); Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, String sortByAttribute, int limit, int offset); Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, String sortByAttribute, int limit, int offset); AtlasGlossary createGlossary(AtlasGlossary glossary); AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm); List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms); AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory); List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategories); AtlasGlossary updateGlossaryByGuid(String glossaryGuid, AtlasGlossary updatedGlossary); AtlasGlossary partialUpdateGlossaryByGuid(String glossaryGuid, Map<String, String> attributes); AtlasGlossaryTerm updateGlossaryTermByGuid(String termGuid, AtlasGlossaryTerm glossaryTerm); AtlasGlossaryTerm partialUpdateTermByGuid(String termGuid, Map<String, String> attributes); AtlasGlossaryCategory updateGlossaryCategoryByGuid(String categoryGuid, AtlasGlossaryCategory glossaryCategory); AtlasGlossaryCategory partialUpdateCategoryByGuid(String categoryGuid, Map<String, String> attributes); void deleteGlossaryByGuid(String glossaryGuid); void deleteGlossaryTermByGuid(String termGuid); void deleteGlossaryCategoryByGuid(String categoryGuid); List<AtlasRelatedObjectId> getEntitiesAssignedWithTerm(String termGuid, String sortByAttribute, int limit, int offset); void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); void disassociateTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); String getGlossaryImportTemplate(); List<AtlasGlossaryTerm> importGlossary(String fileName); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); AtlasTypesDef getAllTypeDefs(SearchFilter searchFilter); List<AtlasTypeDefHeader> getAllTypeDefHeaders(SearchFilter searchFilter); boolean typeWithGuidExists(String guid); boolean typeWithNameExists(String name); AtlasEnumDef getEnumDefByName(String name); AtlasEnumDef getEnumDefByGuid(String guid); AtlasStructDef getStructDefByName(String name); AtlasStructDef getStructDefByGuid(String guid); AtlasClassificationDef getClassificationDefByName(String name); AtlasClassificationDef getClassificationDefByGuid(String guid); AtlasEntityDef getEntityDefByName(String name); AtlasEntityDef getEntityDefByGuid(String guid); AtlasRelationshipDef getRelationshipDefByName(String name); AtlasRelationshipDef getRelationshipDefByGuid(String guid); AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); AtlasBusinessMetadataDef getBusinessMetadataDefGuid(String guid); @Deprecated AtlasEnumDef createEnumDef(AtlasEnumDef enumDef); @Deprecated AtlasStructDef createStructDef(AtlasStructDef structDef); @Deprecated AtlasEntityDef createEntityDef(AtlasEntityDef entityDef); @Deprecated AtlasClassificationDef createClassificationDef(AtlasClassificationDef classificationDef); AtlasTypesDef createAtlasTypeDefs(AtlasTypesDef typesDef); AtlasTypesDef updateAtlasTypeDefs(AtlasTypesDef typesDef); void deleteAtlasTypeDefs(AtlasTypesDef typesDef); void deleteTypeByName(String typeName); AtlasEntityWithExtInfo getEntityByGuid(String guid); AtlasEntityWithExtInfo getEntityByGuid(String guid, boolean minExtInfo, boolean ignoreRelationships); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes, boolean minExtInfo, boolean ignoreRelationship); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids, boolean minExtInfo, boolean ignoreRelationships); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String,String>> uniqAttributesList); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String, String>> uniqAttributesList, boolean minExtInfo, boolean ignoreRelationship); AtlasEntityHeader getEntityHeaderByGuid(String entityGuid); AtlasEntityHeader getEntityHeaderByAttribute(String typeName, Map<String, String> uniqAttributes); List<EntityAuditEventV2> getAuditEvents(String guid, String startKey, EntityAuditEventV2.EntityAuditActionV2 auditAction, short count); EntityMutationResponse createEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse createEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse updateEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntityByAttribute(String typeName, Map<String, String> uniqAttributes, AtlasEntityWithExtInfo entityInfo); EntityMutationResponse partialUpdateEntityByGuid(String entityGuid, Object attrValue, String attrName); EntityMutationResponse deleteEntityByGuid(String guid); EntityMutationResponse deleteEntityByAttribute(String typeName, Map<String, String> uniqAttributes); EntityMutationResponse deleteEntitiesByGuids(List<String> guids); EntityMutationResponse purgeEntitiesByGuids(Set<String> guids); AtlasClassifications getClassifications(String guid); AtlasClassifications getEntityClassifications(String entityGuid, String classificationName); void addClassification(ClassificationAssociateRequest request); void addClassifications(String guid, List<AtlasClassification> classifications); void addClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); void updateClassifications(String guid, List<AtlasClassification> classifications); void updateClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); String setClassifications(AtlasEntityHeaders entityHeaders); void deleteClassification(String guid, String classificationName); void deleteClassifications(String guid, List<AtlasClassification> classifications); void removeClassification(String entityGuid, String classificationName, String associatedEntityGuid); void removeClassification(String typeName, Map<String, String> uniqAttributes, String classificationName); AtlasEntityHeaders getEntityHeaders(long tagUpdateStartTime); void addOrUpdateBusinessAttributes(String entityGuid, boolean isOverwrite, Map<String, Map<String, Object>> businessAttributes); void addOrUpdateBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); String getTemplateForBulkUpdateBusinessAttributes(); BulkImportResponse bulkUpdateBusinessAttributes(String fileName); void addLabels(String entityGuid, Set<String> labels); void addLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void removeLabels(String entityGuid, Set<String> labels); void removeLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void setLabels(String entityGuid, Set<String> labels); void setLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth); AtlasLineageInfo getLineageInfo(String typeName, Map<String, String> attributes, LineageDirection direction, int depth); AtlasSearchResult dslSearch(String query); AtlasSearchResult dslSearchWithParams(String query, int limit, int offset); AtlasSearchResult fullTextSearch(String query); AtlasSearchResult fullTextSearchWithParams(String query, int limit, int offset); AtlasSearchResult basicSearch(String typeName, String classification, String query, boolean excludeDeletedEntities, int limit, int offset); AtlasSearchResult facetedSearch(SearchParameters searchParameters); AtlasSearchResult attributeSearch(String typeName, String attrName, String attrValuePrefix, int limit, int offset); AtlasSearchResult relationshipSearch(String guid, String relation, String sortByAttribute, SortOrder sortOrder, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(String query, String typeName, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(QuickSearchParameters quickSearchParameters); AtlasSuggestionsResult getSuggestions(String prefixString, String fieldName); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); void deleteSavedSearch(String guid); AtlasSearchResult executeSavedSearch(String userName, String searchName); AtlasSearchResult executeSavedSearch(String searchGuid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid, boolean extendedInfo); AtlasRelationship createRelationship(AtlasRelationship relationship); AtlasRelationship updateRelationship(AtlasRelationship relationship); void deleteRelationshipByGuid(String guid); List<AtlasAuditEntry> getAtlasAuditByOperation(AuditSearchParameters auditSearchParameters); List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset); AtlasGlossary getGlossaryByGuid(String glossaryGuid); AtlasGlossary.AtlasGlossaryExtInfo getGlossaryExtInfo(String glossaryGuid); AtlasGlossaryTerm getGlossaryTerm(String termGuid); List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getGlossaryTermHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); AtlasGlossaryCategory getGlossaryCategory(String categoryGuid); List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedCategoryHeader> getGlossaryCategoryHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, String sortByAttribute, int limit, int offset); Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, String sortByAttribute, int limit, int offset); Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, String sortByAttribute, int limit, int offset); AtlasGlossary createGlossary(AtlasGlossary glossary); AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm); List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms); AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory); List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategories); AtlasGlossary updateGlossaryByGuid(String glossaryGuid, AtlasGlossary updatedGlossary); AtlasGlossary partialUpdateGlossaryByGuid(String glossaryGuid, Map<String, String> attributes); AtlasGlossaryTerm updateGlossaryTermByGuid(String termGuid, AtlasGlossaryTerm glossaryTerm); AtlasGlossaryTerm partialUpdateTermByGuid(String termGuid, Map<String, String> attributes); AtlasGlossaryCategory updateGlossaryCategoryByGuid(String categoryGuid, AtlasGlossaryCategory glossaryCategory); AtlasGlossaryCategory partialUpdateCategoryByGuid(String categoryGuid, Map<String, String> attributes); void deleteGlossaryByGuid(String glossaryGuid); void deleteGlossaryTermByGuid(String termGuid); void deleteGlossaryCategoryByGuid(String categoryGuid); List<AtlasRelatedObjectId> getEntitiesAssignedWithTerm(String termGuid, String sortByAttribute, int limit, int offset); void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); void disassociateTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); String getGlossaryImportTemplate(); List<AtlasGlossaryTerm> importGlossary(String fileName); static final String TYPES_API; static final String ENTITY_API; } |
@Test public void updateClassificationsShouldThrowExceptionIfResponseIsNot204() { AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration); AtlasClassification atlasClassification = new AtlasClassification("Testdb"); atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a"); WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); try { atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification)); Assert.fail("Failed with Exception"); } catch (AtlasServiceException e) { Assert.assertTrue(e.getMessage().contains(" failed with status 200 ")); } } | public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); AtlasTypesDef getAllTypeDefs(SearchFilter searchFilter); List<AtlasTypeDefHeader> getAllTypeDefHeaders(SearchFilter searchFilter); boolean typeWithGuidExists(String guid); boolean typeWithNameExists(String name); AtlasEnumDef getEnumDefByName(String name); AtlasEnumDef getEnumDefByGuid(String guid); AtlasStructDef getStructDefByName(String name); AtlasStructDef getStructDefByGuid(String guid); AtlasClassificationDef getClassificationDefByName(String name); AtlasClassificationDef getClassificationDefByGuid(String guid); AtlasEntityDef getEntityDefByName(String name); AtlasEntityDef getEntityDefByGuid(String guid); AtlasRelationshipDef getRelationshipDefByName(String name); AtlasRelationshipDef getRelationshipDefByGuid(String guid); AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); AtlasBusinessMetadataDef getBusinessMetadataDefGuid(String guid); @Deprecated AtlasEnumDef createEnumDef(AtlasEnumDef enumDef); @Deprecated AtlasStructDef createStructDef(AtlasStructDef structDef); @Deprecated AtlasEntityDef createEntityDef(AtlasEntityDef entityDef); @Deprecated AtlasClassificationDef createClassificationDef(AtlasClassificationDef classificationDef); AtlasTypesDef createAtlasTypeDefs(AtlasTypesDef typesDef); AtlasTypesDef updateAtlasTypeDefs(AtlasTypesDef typesDef); void deleteAtlasTypeDefs(AtlasTypesDef typesDef); void deleteTypeByName(String typeName); AtlasEntityWithExtInfo getEntityByGuid(String guid); AtlasEntityWithExtInfo getEntityByGuid(String guid, boolean minExtInfo, boolean ignoreRelationships); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes, boolean minExtInfo, boolean ignoreRelationship); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids, boolean minExtInfo, boolean ignoreRelationships); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String,String>> uniqAttributesList); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String, String>> uniqAttributesList, boolean minExtInfo, boolean ignoreRelationship); AtlasEntityHeader getEntityHeaderByGuid(String entityGuid); AtlasEntityHeader getEntityHeaderByAttribute(String typeName, Map<String, String> uniqAttributes); List<EntityAuditEventV2> getAuditEvents(String guid, String startKey, EntityAuditEventV2.EntityAuditActionV2 auditAction, short count); EntityMutationResponse createEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse createEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse updateEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntityByAttribute(String typeName, Map<String, String> uniqAttributes, AtlasEntityWithExtInfo entityInfo); EntityMutationResponse partialUpdateEntityByGuid(String entityGuid, Object attrValue, String attrName); EntityMutationResponse deleteEntityByGuid(String guid); EntityMutationResponse deleteEntityByAttribute(String typeName, Map<String, String> uniqAttributes); EntityMutationResponse deleteEntitiesByGuids(List<String> guids); EntityMutationResponse purgeEntitiesByGuids(Set<String> guids); AtlasClassifications getClassifications(String guid); AtlasClassifications getEntityClassifications(String entityGuid, String classificationName); void addClassification(ClassificationAssociateRequest request); void addClassifications(String guid, List<AtlasClassification> classifications); void addClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); void updateClassifications(String guid, List<AtlasClassification> classifications); void updateClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); String setClassifications(AtlasEntityHeaders entityHeaders); void deleteClassification(String guid, String classificationName); void deleteClassifications(String guid, List<AtlasClassification> classifications); void removeClassification(String entityGuid, String classificationName, String associatedEntityGuid); void removeClassification(String typeName, Map<String, String> uniqAttributes, String classificationName); AtlasEntityHeaders getEntityHeaders(long tagUpdateStartTime); void addOrUpdateBusinessAttributes(String entityGuid, boolean isOverwrite, Map<String, Map<String, Object>> businessAttributes); void addOrUpdateBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); String getTemplateForBulkUpdateBusinessAttributes(); BulkImportResponse bulkUpdateBusinessAttributes(String fileName); void addLabels(String entityGuid, Set<String> labels); void addLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void removeLabels(String entityGuid, Set<String> labels); void removeLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void setLabels(String entityGuid, Set<String> labels); void setLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth); AtlasLineageInfo getLineageInfo(String typeName, Map<String, String> attributes, LineageDirection direction, int depth); AtlasSearchResult dslSearch(String query); AtlasSearchResult dslSearchWithParams(String query, int limit, int offset); AtlasSearchResult fullTextSearch(String query); AtlasSearchResult fullTextSearchWithParams(String query, int limit, int offset); AtlasSearchResult basicSearch(String typeName, String classification, String query, boolean excludeDeletedEntities, int limit, int offset); AtlasSearchResult facetedSearch(SearchParameters searchParameters); AtlasSearchResult attributeSearch(String typeName, String attrName, String attrValuePrefix, int limit, int offset); AtlasSearchResult relationshipSearch(String guid, String relation, String sortByAttribute, SortOrder sortOrder, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(String query, String typeName, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(QuickSearchParameters quickSearchParameters); AtlasSuggestionsResult getSuggestions(String prefixString, String fieldName); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); void deleteSavedSearch(String guid); AtlasSearchResult executeSavedSearch(String userName, String searchName); AtlasSearchResult executeSavedSearch(String searchGuid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid, boolean extendedInfo); AtlasRelationship createRelationship(AtlasRelationship relationship); AtlasRelationship updateRelationship(AtlasRelationship relationship); void deleteRelationshipByGuid(String guid); List<AtlasAuditEntry> getAtlasAuditByOperation(AuditSearchParameters auditSearchParameters); List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset); AtlasGlossary getGlossaryByGuid(String glossaryGuid); AtlasGlossary.AtlasGlossaryExtInfo getGlossaryExtInfo(String glossaryGuid); AtlasGlossaryTerm getGlossaryTerm(String termGuid); List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getGlossaryTermHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); AtlasGlossaryCategory getGlossaryCategory(String categoryGuid); List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedCategoryHeader> getGlossaryCategoryHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, String sortByAttribute, int limit, int offset); Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, String sortByAttribute, int limit, int offset); Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, String sortByAttribute, int limit, int offset); AtlasGlossary createGlossary(AtlasGlossary glossary); AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm); List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms); AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory); List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategories); AtlasGlossary updateGlossaryByGuid(String glossaryGuid, AtlasGlossary updatedGlossary); AtlasGlossary partialUpdateGlossaryByGuid(String glossaryGuid, Map<String, String> attributes); AtlasGlossaryTerm updateGlossaryTermByGuid(String termGuid, AtlasGlossaryTerm glossaryTerm); AtlasGlossaryTerm partialUpdateTermByGuid(String termGuid, Map<String, String> attributes); AtlasGlossaryCategory updateGlossaryCategoryByGuid(String categoryGuid, AtlasGlossaryCategory glossaryCategory); AtlasGlossaryCategory partialUpdateCategoryByGuid(String categoryGuid, Map<String, String> attributes); void deleteGlossaryByGuid(String glossaryGuid); void deleteGlossaryTermByGuid(String termGuid); void deleteGlossaryCategoryByGuid(String categoryGuid); List<AtlasRelatedObjectId> getEntitiesAssignedWithTerm(String termGuid, String sortByAttribute, int limit, int offset); void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); void disassociateTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); String getGlossaryImportTemplate(); List<AtlasGlossaryTerm> importGlossary(String fileName); } | AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); AtlasTypesDef getAllTypeDefs(SearchFilter searchFilter); List<AtlasTypeDefHeader> getAllTypeDefHeaders(SearchFilter searchFilter); boolean typeWithGuidExists(String guid); boolean typeWithNameExists(String name); AtlasEnumDef getEnumDefByName(String name); AtlasEnumDef getEnumDefByGuid(String guid); AtlasStructDef getStructDefByName(String name); AtlasStructDef getStructDefByGuid(String guid); AtlasClassificationDef getClassificationDefByName(String name); AtlasClassificationDef getClassificationDefByGuid(String guid); AtlasEntityDef getEntityDefByName(String name); AtlasEntityDef getEntityDefByGuid(String guid); AtlasRelationshipDef getRelationshipDefByName(String name); AtlasRelationshipDef getRelationshipDefByGuid(String guid); AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); AtlasBusinessMetadataDef getBusinessMetadataDefGuid(String guid); @Deprecated AtlasEnumDef createEnumDef(AtlasEnumDef enumDef); @Deprecated AtlasStructDef createStructDef(AtlasStructDef structDef); @Deprecated AtlasEntityDef createEntityDef(AtlasEntityDef entityDef); @Deprecated AtlasClassificationDef createClassificationDef(AtlasClassificationDef classificationDef); AtlasTypesDef createAtlasTypeDefs(AtlasTypesDef typesDef); AtlasTypesDef updateAtlasTypeDefs(AtlasTypesDef typesDef); void deleteAtlasTypeDefs(AtlasTypesDef typesDef); void deleteTypeByName(String typeName); AtlasEntityWithExtInfo getEntityByGuid(String guid); AtlasEntityWithExtInfo getEntityByGuid(String guid, boolean minExtInfo, boolean ignoreRelationships); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes, boolean minExtInfo, boolean ignoreRelationship); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids, boolean minExtInfo, boolean ignoreRelationships); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String,String>> uniqAttributesList); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String, String>> uniqAttributesList, boolean minExtInfo, boolean ignoreRelationship); AtlasEntityHeader getEntityHeaderByGuid(String entityGuid); AtlasEntityHeader getEntityHeaderByAttribute(String typeName, Map<String, String> uniqAttributes); List<EntityAuditEventV2> getAuditEvents(String guid, String startKey, EntityAuditEventV2.EntityAuditActionV2 auditAction, short count); EntityMutationResponse createEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse createEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse updateEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntityByAttribute(String typeName, Map<String, String> uniqAttributes, AtlasEntityWithExtInfo entityInfo); EntityMutationResponse partialUpdateEntityByGuid(String entityGuid, Object attrValue, String attrName); EntityMutationResponse deleteEntityByGuid(String guid); EntityMutationResponse deleteEntityByAttribute(String typeName, Map<String, String> uniqAttributes); EntityMutationResponse deleteEntitiesByGuids(List<String> guids); EntityMutationResponse purgeEntitiesByGuids(Set<String> guids); AtlasClassifications getClassifications(String guid); AtlasClassifications getEntityClassifications(String entityGuid, String classificationName); void addClassification(ClassificationAssociateRequest request); void addClassifications(String guid, List<AtlasClassification> classifications); void addClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); void updateClassifications(String guid, List<AtlasClassification> classifications); void updateClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); String setClassifications(AtlasEntityHeaders entityHeaders); void deleteClassification(String guid, String classificationName); void deleteClassifications(String guid, List<AtlasClassification> classifications); void removeClassification(String entityGuid, String classificationName, String associatedEntityGuid); void removeClassification(String typeName, Map<String, String> uniqAttributes, String classificationName); AtlasEntityHeaders getEntityHeaders(long tagUpdateStartTime); void addOrUpdateBusinessAttributes(String entityGuid, boolean isOverwrite, Map<String, Map<String, Object>> businessAttributes); void addOrUpdateBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); String getTemplateForBulkUpdateBusinessAttributes(); BulkImportResponse bulkUpdateBusinessAttributes(String fileName); void addLabels(String entityGuid, Set<String> labels); void addLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void removeLabels(String entityGuid, Set<String> labels); void removeLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void setLabels(String entityGuid, Set<String> labels); void setLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth); AtlasLineageInfo getLineageInfo(String typeName, Map<String, String> attributes, LineageDirection direction, int depth); AtlasSearchResult dslSearch(String query); AtlasSearchResult dslSearchWithParams(String query, int limit, int offset); AtlasSearchResult fullTextSearch(String query); AtlasSearchResult fullTextSearchWithParams(String query, int limit, int offset); AtlasSearchResult basicSearch(String typeName, String classification, String query, boolean excludeDeletedEntities, int limit, int offset); AtlasSearchResult facetedSearch(SearchParameters searchParameters); AtlasSearchResult attributeSearch(String typeName, String attrName, String attrValuePrefix, int limit, int offset); AtlasSearchResult relationshipSearch(String guid, String relation, String sortByAttribute, SortOrder sortOrder, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(String query, String typeName, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(QuickSearchParameters quickSearchParameters); AtlasSuggestionsResult getSuggestions(String prefixString, String fieldName); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); void deleteSavedSearch(String guid); AtlasSearchResult executeSavedSearch(String userName, String searchName); AtlasSearchResult executeSavedSearch(String searchGuid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid, boolean extendedInfo); AtlasRelationship createRelationship(AtlasRelationship relationship); AtlasRelationship updateRelationship(AtlasRelationship relationship); void deleteRelationshipByGuid(String guid); List<AtlasAuditEntry> getAtlasAuditByOperation(AuditSearchParameters auditSearchParameters); List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset); AtlasGlossary getGlossaryByGuid(String glossaryGuid); AtlasGlossary.AtlasGlossaryExtInfo getGlossaryExtInfo(String glossaryGuid); AtlasGlossaryTerm getGlossaryTerm(String termGuid); List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getGlossaryTermHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); AtlasGlossaryCategory getGlossaryCategory(String categoryGuid); List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedCategoryHeader> getGlossaryCategoryHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, String sortByAttribute, int limit, int offset); Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, String sortByAttribute, int limit, int offset); Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, String sortByAttribute, int limit, int offset); AtlasGlossary createGlossary(AtlasGlossary glossary); AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm); List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms); AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory); List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategories); AtlasGlossary updateGlossaryByGuid(String glossaryGuid, AtlasGlossary updatedGlossary); AtlasGlossary partialUpdateGlossaryByGuid(String glossaryGuid, Map<String, String> attributes); AtlasGlossaryTerm updateGlossaryTermByGuid(String termGuid, AtlasGlossaryTerm glossaryTerm); AtlasGlossaryTerm partialUpdateTermByGuid(String termGuid, Map<String, String> attributes); AtlasGlossaryCategory updateGlossaryCategoryByGuid(String categoryGuid, AtlasGlossaryCategory glossaryCategory); AtlasGlossaryCategory partialUpdateCategoryByGuid(String categoryGuid, Map<String, String> attributes); void deleteGlossaryByGuid(String glossaryGuid); void deleteGlossaryTermByGuid(String termGuid); void deleteGlossaryCategoryByGuid(String categoryGuid); List<AtlasRelatedObjectId> getEntitiesAssignedWithTerm(String termGuid, String sortByAttribute, int limit, int offset); void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); void disassociateTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); String getGlossaryImportTemplate(); List<AtlasGlossaryTerm> importGlossary(String fileName); static final String TYPES_API; static final String ENTITY_API; } |
@Test public void shouldVerifyServerIsReady() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Version\":\"version-rrelease\",\"Name\":\"apache-atlas\"," + "\"Description\":\"Metadata Management and Data Governance Platform over Hadoop\"}"); when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response); assertTrue(atlasClient.isServerReady()); } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void testCreateEntity() throws Exception { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.CREATE_ENTITY, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.CREATED.getStatusCode()); String jsonResponse = AtlasType.toV1Json(new EntityResult(Arrays.asList("id"), null, null)); when(response.getEntity(String.class)).thenReturn(jsonResponse.toString()); when(response.getLength()).thenReturn(jsonResponse.length()); String entityJson = AtlasType.toV1Json(new Referenceable("type")); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); List<String> ids = atlasClient.createEntity(entityJson); assertEquals(ids.size(), 1); assertEquals(ids.get(0), "id"); } | protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } | AtlasClient extends AtlasBaseClient { protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } } | AtlasClient extends AtlasBaseClient { protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldGetAdminStatus() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"Active\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); assertEquals(status, "Active"); } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldReturnStatusAsUnknownIfJSONIsInvalid() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"status\":\"Active\"}"); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); assertEquals(status, AtlasClient.UNKNOWN_STATUS); } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldSelectActiveAmongMultipleServersIfHAIsEnabled() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse firstResponse = mock(ClientResponse.class); when(firstResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String passiveStatus = "{\"Status\":\"PASSIVE\"}"; when(firstResponse.getEntity(String.class)).thenReturn(passiveStatus); when(firstResponse.getLength()).thenReturn(passiveStatus.length()); ClientResponse secondResponse = mock(ClientResponse.class); when(secondResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(secondResponse.getEntity(String.class)).thenReturn(activeStatus); when(secondResponse.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(firstResponse).thenReturn(firstResponse).thenReturn(firstResponse). thenReturn(secondResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[]{"http: client); assertEquals(serviceURL, "http: } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldRetryUntilServiceBecomesActive() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(response).thenReturn(response).thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertEquals(serviceURL, "http: } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldRetryIfCannotConnectToServiceInitially() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); atlasClient.setService(service); atlasClient.setConfiguration(configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertEquals(serviceURL, "http: } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void testEntityTypeDefaultValue() { AtlasEntity defValue = entityType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), entityType.getTypeName()); } | @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } | AtlasEntityType extends AtlasStructType { @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } } | AtlasEntityType extends AtlasStructType { @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); } | AtlasEntityType extends AtlasStructType { @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); } | AtlasEntityType extends AtlasStructType { @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; } |
@Test(expectedExceptions = IllegalArgumentException.class) public void shouldThrowExceptionIfActiveServerIsNotFound() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(response); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertNull(serviceURL); } | public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); } | AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType,
final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName,
final String uniqueAttributeValue,
Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; } |
@Test public void shouldNotCreateAtlasTopicIfNotConfiguredToDoSo() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(false); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final boolean[] topicExistsCalled = new boolean[] {false}; AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { topicExistsCalled[0] = true; return false; } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC); assertFalse(topicExistsCalled[0]); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldNotCreateTopicIfItAlreadyExists() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final boolean[] topicExistsCalled = new boolean[]{false}; final boolean[] createTopicCalled = new boolean[]{false}; AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { topicExistsCalled[0] = true; return true; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { createTopicCalled[0] = true; } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC); assertTrue(topicExistsCalled[0]); assertFalse(createTopicCalled[0]); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldCreateTopicIfItDoesNotExist() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final boolean[] createdTopic = new boolean[]{false}; AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { createdTopic[0] = true; } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC); assertTrue(createdTopic[0]); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldNotFailIfExceptionOccursDuringCreatingTopic() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final boolean[] createTopicCalled = new boolean[]{false}; AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { createTopicCalled[0] = true; throw new RuntimeException("Simulating failure during creating topic"); } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC); assertTrue(createTopicCalled[0]); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldCreateMultipleTopics() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final Map<String, Boolean> createdTopics = new HashMap<>(); createdTopics.put(ATLAS_HOOK_TOPIC, false); createdTopics.put(ATLAS_ENTITIES_TOPIC, false); AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { createdTopics.put(topicName, true); } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC, ATLAS_ENTITIES_TOPIC); assertTrue(createdTopics.get(ATLAS_HOOK_TOPIC)); assertTrue(createdTopics.get(ATLAS_ENTITIES_TOPIC)); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldCreateTopicEvenIfEarlierOneFails() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final Map<String, Boolean> createdTopics = new HashMap<>(); createdTopics.put(ATLAS_ENTITIES_TOPIC, false); AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { if (topicName.equals(ATLAS_HOOK_TOPIC)) { throw new RuntimeException("Simulating failure when creating ATLAS_HOOK topic"); } else { createdTopics.put(topicName, true); } } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC, ATLAS_ENTITIES_TOPIC); assertTrue(createdTopics.get(ATLAS_ENTITIES_TOPIC)); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldCloseResources() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); when(configuration.getString("atlas.authentication.method.kerberos")).thenReturn("false"); final ZkUtils zookeeperUtils = mock(ZkUtils.class); AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC, ATLAS_ENTITIES_TOPIC); verify(zookeeperUtils, times(1)).close(); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test public void shouldNotProcessTopicCreationIfSecurityFails() { Configuration configuration = mock(Configuration.class); when(configuration.getBoolean(AtlasTopicCreator.ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)). thenReturn(true); final ZkUtils zookeeperUtils = mock(ZkUtils.class); final Map<String, Boolean> createdTopics = new HashMap<>(); createdTopics.put(ATLAS_HOOK_TOPIC, false); createdTopics.put(ATLAS_ENTITIES_TOPIC, false); AtlasTopicCreator atlasTopicCreator = new AtlasTopicCreator() { @Override protected boolean ifTopicExists(String topicName, ZkUtils zkUtils) { return false; } @Override protected ZkUtils createZkUtils(Configuration atlasProperties) { return zookeeperUtils; } @Override protected void createTopic(Configuration atlasProperties, String topicName, ZkUtils zkUtils) { createdTopics.put(topicName, true); } @Override protected boolean handleSecurity(Configuration atlasProperties) { return false; } }; atlasTopicCreator.createAtlasTopic(configuration, ATLAS_HOOK_TOPIC, ATLAS_ENTITIES_TOPIC); assertFalse(createdTopics.get(ATLAS_HOOK_TOPIC)); assertFalse(createdTopics.get(ATLAS_ENTITIES_TOPIC)); } | public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); } | AtlasTopicCreator { public void createAtlasTopic(Configuration atlasProperties, String... topicNames) { if (atlasProperties.getBoolean(ATLAS_NOTIFICATION_CREATE_TOPICS_KEY, true)) { if (!handleSecurity(atlasProperties)) { return; } ZkUtils zkUtils = createZkUtils(atlasProperties); for (String topicName : topicNames) { try { LOG.warn("Attempting to create topic {}", topicName); if (!ifTopicExists(topicName, zkUtils)) { createTopic(atlasProperties, topicName, zkUtils); } else { LOG.warn("Ignoring call to create topic {}, as it already exists.", topicName); } } catch (Throwable t) { LOG.error("Failed while creating topic {}", topicName, t); } } zkUtils.close(); } else { LOG.info("Not creating topics {} as {} is false", StringUtils.join(topicNames, ","), ATLAS_NOTIFICATION_CREATE_TOPICS_KEY); } } void createAtlasTopic(Configuration atlasProperties, String... topicNames); static void main(String[] args); static final String ATLAS_NOTIFICATION_CREATE_TOPICS_KEY; } |
@Test (timeOut = 10000) public void testNotifyEntitiesDoesNotHangOnException() throws Exception { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new NotificationException(new Exception())).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 0, null, notificationInterface, false, failedMessagesLogger); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test public void testEntityTypeIsValidValue() { for (Object value : validValues) { assertTrue(entityType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(entityType.isValidValue(value), "value=" + value); } } | @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } | AtlasEntityType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } } | AtlasEntityType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); } | AtlasEntityType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); } | AtlasEntityType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; } |
@Test public void testNotifyEntitiesRetriesOnException() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception())).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, false, failedMessagesLogger); verify(notificationInterface, times(2)). send(NotificationInterface.NotificationType.HOOK, hookNotifications); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test public void testFailedMessageIsLoggedIfRequired() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception(), Arrays.asList("test message"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verify(failedMessagesLogger, times(1)).log("test message"); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test public void testFailedMessageIsNotLoggedIfNotRequired() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new NotificationException(new Exception(), Arrays.asList("test message"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, false, failedMessagesLogger); verifyZeroInteractions(failedMessagesLogger); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test public void testAllFailedMessagesAreLogged() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception(), Arrays.asList("test message1", "test message2"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verify(failedMessagesLogger, times(1)).log("test message1"); verify(failedMessagesLogger, times(1)).log("test message2"); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test public void testFailedMessageIsNotLoggedIfNotANotificationException() throws Exception { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new RuntimeException("test message")).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verifyZeroInteractions(failedMessagesLogger); } | @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); } | AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; } |
@Test(enabled = true) public void testAccessAllowedForUserAndGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("admin", Collections.singleton("ROLE_ADMIN")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(true, isAccessAllowed); } catch (Exception e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } | @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } |
@Test(enabled = true) public void testAccessAllowedForGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("nonmappeduser", Collections.singleton("ROLE_ADMIN")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } | @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } |
@Test(enabled = true) public void testAccessNotAllowedForUserAndGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("nonmappeduser", Collections.singleton("GROUP-NOT-IN-POLICYFILE")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(false, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } | @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } |
@Test(enabled = true) public void testLabels() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_ADD_LABEL); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to add label", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to add label", true, isAccessAllowed); request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_REMOVE_LABEL); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to remove label", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to remove label", true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } | @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } |
@Test(enabled = true) public void testBusinessMetadata() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE_BUSINESS_METADATA); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to update business-metadata", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to update business-metadata", true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } | @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } | AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); } |
@Test public void testEntityTypeGetNormalizedValue() { assertNull(entityType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Object normalizedValue = entityType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(entityType.getNormalizedValue(value), "value=" + value); } } | @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } | AtlasEntityType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } } | AtlasEntityType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); } | AtlasEntityType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); } | AtlasEntityType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; } |
@Test public void testGetTopTermsAsendingInput() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 12, 15); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 2,1,0); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsAsendingInput2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 12, 15, 20, 25, 26, 30, 40); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 7, 6, 5, 4, 3); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsDescendingInput() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 9, 8); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 2); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsDescendingInput2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 9, 8, 7, 6, 5, 4, 3, 2); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 2, 3, 4); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsRandom() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 19, 28, 27, 16, 1, 30, 3, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 8, 6, 2, 3, 1); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsRandom2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 19, 28, 27, 16, 1, 30, 3, 10); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 6, 2, 3, 1); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsRandom3() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 36, 28, 27, 16, 1, 30, 3, 10); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 6, 2, 3); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsRandom4() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 10, 28, 27, 16, 1, 30, 36, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 7, 8, 6, 2, 3); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGetTopTermsRandom5() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 10, 28, 27, 16, 1, 30, 36, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 7, 8, 6, 2); } | @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testGenerateSuggestionString() { List<String> fields = new ArrayList<>(); fields.add("one"); fields.add("two"); fields.add("three"); String generatedString = AtlasJanusGraphIndexClient.generateSuggestionsString(fields); Assert.assertEquals(generatedString, "'one', 'two', 'three'"); } | @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void testEntityTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(entityType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(entityType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } } | @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } | AtlasEntityType extends AtlasStructType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } } | AtlasEntityType extends AtlasStructType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); } | AtlasEntityType extends AtlasStructType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); } | AtlasEntityType extends AtlasStructType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; } |
@Test public void testGenerateSearchWeightString() { Map<String, Integer> fields = new HashMap<>(); fields.put("one", 10); fields.put("two", 1); fields.put("three", 15); String generatedString = AtlasJanusGraphIndexClient.generateSearchWeightString(fields); Assert.assertEquals(generatedString, " one^10 two^1 three^15"); } | @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } | AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); } |
@Test public void vertexFetch() { JsonNode node = getCol1(); MappedElementCache cache = new MappedElementCache(); TinkerGraph tg = TinkerGraph.open(); addVertex(tg, node); Vertex vx = cache.getMappedVertex(tg, 98336); assertNotNull(vx); assertEquals(cache.lruVertexCache.size(), 1); } | public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } | MappedElementCache { public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } } | MappedElementCache { public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } } | MappedElementCache { public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } Vertex getMappedVertex(Graph gr, Object key); void clearAll(); } | MappedElementCache { public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } Vertex getMappedVertex(Graph gr, Object key); void clearAll(); } |
@Test public void idFetch() { JsonNode node = getCol1(); final int EXPECTED_ID = 98336; Object o = GraphSONUtility.getTypedValueFromJsonNode(node.get(GraphSONTokensTP2._ID)); assertNotNull(o); assertEquals((int) o, EXPECTED_ID); } | static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } | GraphSONUtility { static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } } | GraphSONUtility { static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } GraphSONUtility(final ElementProcessors elementProcessors); } | GraphSONUtility { static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } | GraphSONUtility { static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } |
@Test public void verifyReadProperties() { JsonNode node = getCol1(); Map<String, Object> props = GraphSONUtility.readProperties(node); assertEquals(props.get("__superTypeNames").getClass(), ArrayList.class); assertEquals(props.get("Asset.name").getClass(), String.class); assertEquals(props.get("hive_column.position").getClass(), Integer.class); assertEquals(props.get("__timestamp").getClass(), Long.class); assertNotNull(props); } | static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } | GraphSONUtility { static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } } | GraphSONUtility { static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } GraphSONUtility(final ElementProcessors elementProcessors); } | GraphSONUtility { static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } | GraphSONUtility { static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } |
@Test public void dataNodeReadAndVertexAddedToGraph() { JsonNode entityNode = getCol1(); TinkerGraph tg = TinkerGraph.open(); GraphSONUtility gu = new GraphSONUtility(emptyRelationshipCache); Map<String, Object> map = gu.vertexFromJson(tg, entityNode); assertNull(map); assertEquals((long) tg.traversal().V().count().next(), 1L); Vertex v = tg.vertices().next(); assertTrue(v.property(VERTEX_ID_IN_IMPORT_KEY).isPresent()); } | public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } |
@Test public void typeNodeReadAndVertexNotAddedToGraph() { JsonNode entityNode = getDbType(); TinkerGraph tg = TinkerGraph.open(); GraphSONUtility gu = new GraphSONUtility(emptyRelationshipCache); gu.vertexFromJson(tg, entityNode); Assert.assertEquals((long) tg.traversal().V().count().next(), 0L); } | public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } | GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); } |
@Test public void testGenerateSolrQueryString() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2OR.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) OR ( +comment_index:*t10* ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryString2() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters1OR.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryString3() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2AND.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) AND ( +comment_index:*t10* ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryString4() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters1AND.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testReorderDynAttributes() { AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; List<AtlasEntityDef> entityDefs = new ArrayList<>(); String failureMsg = null; entityDefs.add(createTableEntityDefForTopSort()); try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(entityDefs); AtlasEntityType typeTable = ttr.getEntityTypeByName(TYPE_TABLE); assertEquals(typeTable.getDynEvalAttributes().get(0).getName(), ATTR_DESCRIPTION); assertEquals(typeTable.getDynEvalAttributes().get(1).getName(), ATTR_OWNER); assertEquals(typeTable.getDynEvalAttributes().get(2).getName(), ATTR_NAME); assertEquals(typeTable.getDynEvalAttributes().get(3).getName(), ATTR_LOCATION); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg, "failed to create types " + TYPE_TABLE + " and " + TYPE_COLUMN); } | private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } | AtlasEntityType extends AtlasStructType { private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } } | AtlasEntityType extends AtlasStructType { private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); } | AtlasEntityType extends AtlasStructType { private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); } | AtlasEntityType extends AtlasStructType { private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; } |
@Test public void testGenerateSolrQueryString5() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters0.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( +name_index:t10 )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryString6() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters3.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +comment_index:*United States* ) AND ( +descrption__index:*nothing* ) AND ( +name_index:*t100* ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryStringGT() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersGT.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:{ 100 TO * ] ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryStringGTE() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersGTE.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ 100 TO * ] ) AND ( +started__index:[ 100 TO * ] ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryStringLT() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersLT.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ * TO100} ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryStringLE() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersLTE.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ * TO 100 ] ) AND ( +started__index:[ * TO 100 ] ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryStartsWith() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersStartsWith.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), " -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +qualifiedName__index:testdb.t1* ) )"); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGenerateSolrQueryString2TypeNames() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2Types.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParametersForMultipleTypeNames(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table hive_db ) "); } | public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); } | AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; } |
@Test public void testGetFileAsInputStream() throws Exception { Configuration props = ApplicationProperties.get("test.properties"); InputStream inStr = null; try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } props.setProperty("jaas.properties.file", "src/test/resources/atlas-jaas.properties"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "src/test/resources/atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } String originalConfDirSetting = System.setProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY, "src/test/resources"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } if (originalConfDirSetting != null) { System.setProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY, originalConfDirSetting); } else { System.clearProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", null); fail("Expected " + AtlasException.class.getSimpleName() + " but none thrown"); } catch (AtlasException e) { } finally { if (inStr != null) { inStr.close(); } } props.setProperty("jaas.properties.file", "does_not_exist.txt"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); fail("Expected " + AtlasException.class.getSimpleName() + " but none thrown"); } catch (AtlasException e) { } finally { if (inStr != null) { inStr.close(); } } } | public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } | ApplicationProperties extends PropertiesConfiguration { public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } } | ApplicationProperties extends PropertiesConfiguration { public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } private ApplicationProperties(URL url); } | ApplicationProperties extends PropertiesConfiguration { public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } private ApplicationProperties(URL url); static void forceReload(); static Configuration get(); static Configuration set(Configuration configuration); static Configuration get(String fileName); static Configuration getSubsetConfiguration(Configuration inConf, String prefix); static Properties getSubsetAsProperties(Configuration inConf, String prefix); static Class getClass(Configuration configuration, String propertyName, String defaultValue,
Class assignableClass); static Class getClass(String fullyQualifiedClassName, Class assignableClass); static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName); } | ApplicationProperties extends PropertiesConfiguration { public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } private ApplicationProperties(URL url); static void forceReload(); static Configuration get(); static Configuration set(Configuration configuration); static Configuration get(String fileName); static Configuration getSubsetConfiguration(Configuration inConf, String prefix); static Properties getSubsetAsProperties(Configuration inConf, String prefix); static Class getClass(Configuration configuration, String propertyName, String defaultValue,
Class assignableClass); static Class getClass(String fullyQualifiedClassName, Class assignableClass); static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName); static final String ATLAS_CONFIGURATION_DIRECTORY_PROPERTY; static final String APPLICATION_PROPERTIES; static final String GRAPHDB_BACKEND_CONF; static final String STORAGE_BACKEND_CONF; static final String INDEX_BACKEND_CONF; static final String INDEX_MAP_NAME_CONF; static final String SOLR_WAIT_SEARCHER_CONF; static final String ENABLE_FULLTEXT_SEARCH_CONF; static final String ENABLE_FREETEXT_SEARCH_CONF; static final String ATLAS_RUN_MODE; static final String GRAPHBD_BACKEND_JANUS; static final String STORAGE_BACKEND_HBASE; static final String STORAGE_BACKEND_HBASE2; static final String INDEX_BACKEND_SOLR; static final String LDAP_TYPE; static final String LDAP_AD_BIND_PASSWORD; static final String LDAP_BIND_PASSWORD; static final String MASK_LDAP_PASSWORD; static final String DEFAULT_GRAPHDB_BACKEND; static final boolean DEFAULT_SOLR_WAIT_SEARCHER; static final boolean DEFAULT_INDEX_MAP_NAME; static final AtlasRunMode DEFAULT_ATLAS_RUN_MODE; static final String INDEX_SEARCH_MAX_RESULT_SET_SIZE; static final SimpleEntry<String, String> DB_CACHE_CONF; static final SimpleEntry<String, String> DB_CACHE_CLEAN_WAIT_CONF; static final SimpleEntry<String, String> DB_CACHE_SIZE_CONF; static final SimpleEntry<String, String> DB_TX_CACHE_SIZE_CONF; static final SimpleEntry<String, String> DB_CACHE_TX_DIRTY_SIZE_CONF; } |
@Test public void testvalidateAtlasRelationshipDef() throws AtlasBaseException { AtlasRelationshipEndDef ep_single = new AtlasRelationshipEndDef("typeA", "attr1", Cardinality.SINGLE); AtlasRelationshipEndDef ep_single_container = new AtlasRelationshipEndDef("typeB", "attr2", Cardinality.SINGLE); AtlasRelationshipEndDef ep_single_container_2 = new AtlasRelationshipEndDef("typeC", "attr3", Cardinality.SINGLE, true); AtlasRelationshipEndDef ep_single_container_3 = new AtlasRelationshipEndDef("typeD", "attr4", Cardinality.SINGLE, true); AtlasRelationshipEndDef ep_SET = new AtlasRelationshipEndDef("typeD", "attr4", Cardinality.SET,false); AtlasRelationshipEndDef ep_LIST = new AtlasRelationshipEndDef("typeE", "attr5", Cardinality.LIST,true); AtlasRelationshipEndDef ep_SET_container = new AtlasRelationshipEndDef("typeF", "attr6", Cardinality.SET,true); AtlasRelationshipDef relationshipDef1 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.ASSOCIATION, PropagateTags.ONE_TO_TWO, ep_single, ep_SET); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef1); AtlasRelationshipDef relationshipDef2 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef2); AtlasRelationshipDef relationshipDef3 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.AGGREGATION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef3); try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.ASSOCIATION, PropagateTags.ONE_TO_TWO, ep_single_container_2, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_single, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.AGGREGATION, PropagateTags.ONE_TO_TWO, ep_single, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_SET); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_single, ep_LIST); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_LIST, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END)) { fail("This call expected a different error"); } } } | public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } | AtlasRelationshipType extends AtlasStructType { public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } } | AtlasRelationshipType extends AtlasStructType { public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } AtlasRelationshipType(AtlasRelationshipDef relationshipDef); AtlasRelationshipType(AtlasRelationshipDef relationshipDef, AtlasTypeRegistry typeRegistry); } | AtlasRelationshipType extends AtlasStructType { public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } AtlasRelationshipType(AtlasRelationshipDef relationshipDef); AtlasRelationshipType(AtlasRelationshipDef relationshipDef, AtlasTypeRegistry typeRegistry); AtlasRelationshipDef getRelationshipDef(); boolean hasLegacyAttributeEnd(); String getRelationshipLabel(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); AtlasEntityType getEnd1Type(); AtlasEntityType getEnd2Type(); static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef); } | AtlasRelationshipType extends AtlasStructType { public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } AtlasRelationshipType(AtlasRelationshipDef relationshipDef); AtlasRelationshipType(AtlasRelationshipDef relationshipDef, AtlasTypeRegistry typeRegistry); AtlasRelationshipDef getRelationshipDef(); boolean hasLegacyAttributeEnd(); String getRelationshipLabel(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); AtlasEntityType getEnd1Type(); AtlasEntityType getEnd2Type(); static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef); } |
@Test public void createdBasedOnInitialSize() { Spying.resetCounters(); int incrementByFactor = 2; SpyingFixedBufferList fixedBufferList = new SpyingFixedBufferList(incrementByFactor); addElements(fixedBufferList, 0, 3); List<Spying> list = fixedBufferList.toList(); assertSpyingList(list, 3); assertEquals(Spying.callsToCtor.get(), incrementByFactor * 2); } | public List<T> toList() { return this.buffer.subList(0, this.length); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); T next(); List<T> toList(); void reset(); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); T next(); List<T> toList(); void reset(); } |
@Test public void retrieveEmptyList() { int size = 5; SpyingFixedBufferList fixedBufferList = new SpyingFixedBufferList(size); List<Spying> list = fixedBufferList.toList(); assertEquals(list.size(), 0); addElements(fixedBufferList, 0, 3); list = fixedBufferList.toList(); assertEquals(list.size(), 3); } | public List<T> toList() { return this.buffer.subList(0, this.length); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); T next(); List<T> toList(); void reset(); } | FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); T next(); List<T> toList(); void reset(); } |
@Test public void testGetAllTraitsSuperTraits() throws Exception { AtlasTypeRegistry typeSystem = mock(AtlasTypeRegistry.class); String traitName = "MyTrait"; Struct myTrait = new Struct(traitName); String superTraitName = "MySuperTrait"; AtlasClassificationType traitDef = mock(AtlasClassificationType.class); Set<String> superTypeNames = Collections.singleton(superTraitName); AtlasClassificationType superTraitDef = mock(AtlasClassificationType.class); Set<String> superSuperTypeNames = Collections.emptySet(); Referenceable entity = getEntity("id", myTrait); when(typeSystem.getClassificationTypeByName(traitName)).thenReturn(traitDef); when(typeSystem.getClassificationTypeByName(superTraitName)).thenReturn(superTraitDef); when(traitDef.getAllSuperTypes()).thenReturn(superTypeNames); when(superTraitDef.getAllSuperTypes()).thenReturn(superSuperTypeNames); List<Struct> allTraits = NotificationEntityChangeListener.getAllTraits(entity, typeSystem); assertEquals(2, allTraits.size()); for (Struct trait : allTraits) { String typeName = trait.getTypeName(); assertTrue(typeName.equals(traitName) || typeName.equals(superTraitName)); } } | @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } | NotificationEntityChangeListener implements EntityChangeListener { @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } } | NotificationEntityChangeListener implements EntityChangeListener { @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } @Inject NotificationEntityChangeListener(NotificationInterface notificationInterface, AtlasTypeRegistry typeRegistry, Configuration configuration); } | NotificationEntityChangeListener implements EntityChangeListener { @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } @Inject NotificationEntityChangeListener(NotificationInterface notificationInterface, AtlasTypeRegistry typeRegistry, Configuration configuration); @Override void onEntitiesAdded(Collection<Referenceable> entities, boolean isImport); @Override void onEntitiesUpdated(Collection<Referenceable> entities, boolean isImport); @Override void onTraitsAdded(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsDeleted(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsUpdated(Referenceable entity, Collection<? extends Struct> traits); @Override void onEntitiesDeleted(Collection<Referenceable> entities, boolean isImport); @Override void onTermAdded(Collection<Referenceable> entities, AtlasGlossaryTerm term); @Override void onTermDeleted(Collection<Referenceable> entities, AtlasGlossaryTerm term); @VisibleForTesting static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry); } | NotificationEntityChangeListener implements EntityChangeListener { @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } @Inject NotificationEntityChangeListener(NotificationInterface notificationInterface, AtlasTypeRegistry typeRegistry, Configuration configuration); @Override void onEntitiesAdded(Collection<Referenceable> entities, boolean isImport); @Override void onEntitiesUpdated(Collection<Referenceable> entities, boolean isImport); @Override void onTraitsAdded(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsDeleted(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsUpdated(Referenceable entity, Collection<? extends Struct> traits); @Override void onEntitiesDeleted(Collection<Referenceable> entities, boolean isImport); @Override void onTermAdded(Collection<Referenceable> entities, AtlasGlossaryTerm term); @Override void onTermDeleted(Collection<Referenceable> entities, AtlasGlossaryTerm term); @VisibleForTesting static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry); } |
@Test public void testConsumersStartedIfHAIsDisabled() throws Exception { List<NotificationConsumer<Object>> consumers = new ArrayList(); NotificationConsumer notificationConsumerMock = mock(NotificationConsumer.class); consumers.add(notificationConsumerMock); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); when(configuration.getInt(NotificationHookConsumer.CONSUMER_THREADS_PROPERTY, 1)).thenReturn(1); when(notificationInterface.createConsumers(NotificationType.HOOK, 1)).thenReturn(consumers); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry, metricsUtil); notificationHookConsumer.startInternal(configuration, executorService); verify(notificationInterface).createConsumers(NotificationType.HOOK, 1); verify(executorService).submit(any(NotificationHookConsumer.HookConsumer.class)); } | void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void instanceIsActive(); @Override void instanceIsPassive(); @Override int getHandlerOrder(); } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void instanceIsActive(); @Override void instanceIsPassive(); @Override int getHandlerOrder(); static final String DUMMY_DATABASE; static final String DUMMY_TABLE; static final String VALUES_TMP_TABLE_NAME_PREFIX; static final String CONSUMER_THREADS_PROPERTY; static final String CONSUMER_RETRIES_PROPERTY; static final String CONSUMER_FAILEDCACHESIZE_PROPERTY; static final String CONSUMER_RETRY_INTERVAL; static final String CONSUMER_MIN_RETRY_INTERVAL; static final String CONSUMER_MAX_RETRY_INTERVAL; static final String CONSUMER_COMMIT_BATCH_SIZE; static final String CONSUMER_DISABLED; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633_INPUTS_THRESHOLD; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_PRUNE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_CACHE_SIZE; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES; static final String CONSUMER_PREPROCESS_HIVE_PROCESS_UPD_NAME_WITH_QUALIFIED_NAME; static final String CONSUMER_PREPROCESS_HIVE_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_PREPROCESS_RDBMS_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_AUTHORIZE_USING_MESSAGE_USER; static final String CONSUMER_AUTHORIZE_AUTHN_CACHE_TTL_SECONDS; static final int SERVER_READY_WAIT_TIME_MS; } |
@Test public void testConsumersAreNotStartedIfHAIsEnabled() throws Exception { List<NotificationConsumer<Object>> consumers = new ArrayList(); NotificationConsumer notificationConsumerMock = mock(NotificationConsumer.class); consumers.add(notificationConsumerMock); when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getInt(NotificationHookConsumer.CONSUMER_THREADS_PROPERTY, 1)).thenReturn(1); when(notificationInterface.createConsumers(NotificationType.HOOK, 1)).thenReturn(consumers); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry, metricsUtil); notificationHookConsumer.startInternal(configuration, executorService); verifyZeroInteractions(notificationInterface); } | void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void instanceIsActive(); @Override void instanceIsPassive(); @Override int getHandlerOrder(); } | NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore,
ServiceState serviceState, AtlasInstanceConverter instanceConverter,
AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void instanceIsActive(); @Override void instanceIsPassive(); @Override int getHandlerOrder(); static final String DUMMY_DATABASE; static final String DUMMY_TABLE; static final String VALUES_TMP_TABLE_NAME_PREFIX; static final String CONSUMER_THREADS_PROPERTY; static final String CONSUMER_RETRIES_PROPERTY; static final String CONSUMER_FAILEDCACHESIZE_PROPERTY; static final String CONSUMER_RETRY_INTERVAL; static final String CONSUMER_MIN_RETRY_INTERVAL; static final String CONSUMER_MAX_RETRY_INTERVAL; static final String CONSUMER_COMMIT_BATCH_SIZE; static final String CONSUMER_DISABLED; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633_INPUTS_THRESHOLD; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_PRUNE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_CACHE_SIZE; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES; static final String CONSUMER_PREPROCESS_HIVE_PROCESS_UPD_NAME_WITH_QUALIFIED_NAME; static final String CONSUMER_PREPROCESS_HIVE_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_PREPROCESS_RDBMS_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_AUTHORIZE_USING_MESSAGE_USER; static final String CONSUMER_AUTHORIZE_AUTHN_CACHE_TTL_SECONDS; static final int SERVER_READY_WAIT_TIME_MS; } |
@Test public void testStatusOfActiveServerIsReturned() throws IOException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.ACTIVE); AdminResource adminResource = new AdminResource(serviceState, null, null, null, null, null, null, null, null, null, null, null, null); Response response = adminResource.getStatus(); assertEquals(response.getStatus(), HttpServletResponse.SC_OK); JsonNode entity = AtlasJson.parseToV1JsonNode((String) response.getEntity()); assertEquals(entity.get("Status").asText(), "ACTIVE"); } | @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); @GET @Path("stack") @Produces(MediaType.TEXT_PLAIN) String getThreadDump(); @GET @Path("version") @Produces(Servlets.JSON_MEDIA_TYPE) Response getVersion(); @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) Response getStatus(); @GET @Path("session") @Produces(Servlets.JSON_MEDIA_TYPE) Response getUserProfile(); @GET @Path("metrics") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasMetrics getMetrics(); @POST @Path("/export") @Consumes(Servlets.JSON_MEDIA_TYPE) Response export(AtlasExportRequest request); @POST @Path("/import") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) AtlasImportResult importData(@DefaultValue("{}") @FormDataParam("request") String jsonData,
@FormDataParam("data") InputStream inputStream); @PUT @Path("/purge") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) EntityMutationResponse purgeByIds(Set<String> guids); @POST @Path("/importfile") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasImportResult importFile(String jsonData); @GET @Path("/server/{serverName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) AtlasServer getCluster(@PathParam("serverName") String serverName); @GET @Path("/expimp/audit") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<ExportImportAuditEntry> getExportImportAudit(@QueryParam("serverName") String serverName,
@QueryParam("userName") String userName,
@QueryParam("operation") String operation,
@QueryParam("startTime") String startTime,
@QueryParam("endTime") String endTime,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset); @POST @Path("/audits") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasAuditEntry> getAtlasAudits(AuditSearchParameters auditSearchParameters); @GET @Path("/audit/{auditGuid}/details") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasEntityHeader> getAuditDetails(@PathParam("auditGuid") String auditGuid,
@QueryParam("limit") @DefaultValue("10") int limit,
@QueryParam("offset") @DefaultValue("0") int offset); @GET @Path("activeSearches") @Produces(Servlets.JSON_MEDIA_TYPE) Set<String> getActiveSearches(); @DELETE @Path("activeSearches/{id}") @Produces(Servlets.JSON_MEDIA_TYPE) boolean terminateActiveSearch(@PathParam("id") String searchId); @POST @Path("checkstate") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(Servlets.JSON_MEDIA_TYPE) AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @GET @Path("patches") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasPatches getAtlasPatches(); } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); @GET @Path("stack") @Produces(MediaType.TEXT_PLAIN) String getThreadDump(); @GET @Path("version") @Produces(Servlets.JSON_MEDIA_TYPE) Response getVersion(); @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) Response getStatus(); @GET @Path("session") @Produces(Servlets.JSON_MEDIA_TYPE) Response getUserProfile(); @GET @Path("metrics") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasMetrics getMetrics(); @POST @Path("/export") @Consumes(Servlets.JSON_MEDIA_TYPE) Response export(AtlasExportRequest request); @POST @Path("/import") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) AtlasImportResult importData(@DefaultValue("{}") @FormDataParam("request") String jsonData,
@FormDataParam("data") InputStream inputStream); @PUT @Path("/purge") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) EntityMutationResponse purgeByIds(Set<String> guids); @POST @Path("/importfile") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasImportResult importFile(String jsonData); @GET @Path("/server/{serverName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) AtlasServer getCluster(@PathParam("serverName") String serverName); @GET @Path("/expimp/audit") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<ExportImportAuditEntry> getExportImportAudit(@QueryParam("serverName") String serverName,
@QueryParam("userName") String userName,
@QueryParam("operation") String operation,
@QueryParam("startTime") String startTime,
@QueryParam("endTime") String endTime,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset); @POST @Path("/audits") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasAuditEntry> getAtlasAudits(AuditSearchParameters auditSearchParameters); @GET @Path("/audit/{auditGuid}/details") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasEntityHeader> getAuditDetails(@PathParam("auditGuid") String auditGuid,
@QueryParam("limit") @DefaultValue("10") int limit,
@QueryParam("offset") @DefaultValue("0") int offset); @GET @Path("activeSearches") @Produces(Servlets.JSON_MEDIA_TYPE) Set<String> getActiveSearches(); @DELETE @Path("activeSearches/{id}") @Produces(Servlets.JSON_MEDIA_TYPE) boolean terminateActiveSearch(@PathParam("id") String searchId); @POST @Path("checkstate") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(Servlets.JSON_MEDIA_TYPE) AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @GET @Path("patches") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasPatches getAtlasPatches(); } |
@Test public void testResourceGetsValueFromServiceState() throws IOException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); AdminResource adminResource = new AdminResource(serviceState, null, null, null, null, null, null, null, null, null, null, null, null); Response response = adminResource.getStatus(); verify(serviceState).getState(); JsonNode entity = AtlasJson.parseToV1JsonNode((String) response.getEntity()); assertEquals(entity.get("Status").asText(), "PASSIVE"); } | @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); @GET @Path("stack") @Produces(MediaType.TEXT_PLAIN) String getThreadDump(); @GET @Path("version") @Produces(Servlets.JSON_MEDIA_TYPE) Response getVersion(); @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) Response getStatus(); @GET @Path("session") @Produces(Servlets.JSON_MEDIA_TYPE) Response getUserProfile(); @GET @Path("metrics") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasMetrics getMetrics(); @POST @Path("/export") @Consumes(Servlets.JSON_MEDIA_TYPE) Response export(AtlasExportRequest request); @POST @Path("/import") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) AtlasImportResult importData(@DefaultValue("{}") @FormDataParam("request") String jsonData,
@FormDataParam("data") InputStream inputStream); @PUT @Path("/purge") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) EntityMutationResponse purgeByIds(Set<String> guids); @POST @Path("/importfile") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasImportResult importFile(String jsonData); @GET @Path("/server/{serverName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) AtlasServer getCluster(@PathParam("serverName") String serverName); @GET @Path("/expimp/audit") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<ExportImportAuditEntry> getExportImportAudit(@QueryParam("serverName") String serverName,
@QueryParam("userName") String userName,
@QueryParam("operation") String operation,
@QueryParam("startTime") String startTime,
@QueryParam("endTime") String endTime,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset); @POST @Path("/audits") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasAuditEntry> getAtlasAudits(AuditSearchParameters auditSearchParameters); @GET @Path("/audit/{auditGuid}/details") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasEntityHeader> getAuditDetails(@PathParam("auditGuid") String auditGuid,
@QueryParam("limit") @DefaultValue("10") int limit,
@QueryParam("offset") @DefaultValue("0") int offset); @GET @Path("activeSearches") @Produces(Servlets.JSON_MEDIA_TYPE) Set<String> getActiveSearches(); @DELETE @Path("activeSearches/{id}") @Produces(Servlets.JSON_MEDIA_TYPE) boolean terminateActiveSearch(@PathParam("id") String searchId); @POST @Path("checkstate") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(Servlets.JSON_MEDIA_TYPE) AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @GET @Path("patches") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasPatches getAtlasPatches(); } | AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry,
ExportService exportService, ImportService importService, SearchTracker activeSearches,
MigrationProgressService migrationProgressService,
AtlasServerService serverService,
ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore,
AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); @GET @Path("stack") @Produces(MediaType.TEXT_PLAIN) String getThreadDump(); @GET @Path("version") @Produces(Servlets.JSON_MEDIA_TYPE) Response getVersion(); @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) Response getStatus(); @GET @Path("session") @Produces(Servlets.JSON_MEDIA_TYPE) Response getUserProfile(); @GET @Path("metrics") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasMetrics getMetrics(); @POST @Path("/export") @Consumes(Servlets.JSON_MEDIA_TYPE) Response export(AtlasExportRequest request); @POST @Path("/import") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) AtlasImportResult importData(@DefaultValue("{}") @FormDataParam("request") String jsonData,
@FormDataParam("data") InputStream inputStream); @PUT @Path("/purge") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) EntityMutationResponse purgeByIds(Set<String> guids); @POST @Path("/importfile") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasImportResult importFile(String jsonData); @GET @Path("/server/{serverName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) AtlasServer getCluster(@PathParam("serverName") String serverName); @GET @Path("/expimp/audit") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<ExportImportAuditEntry> getExportImportAudit(@QueryParam("serverName") String serverName,
@QueryParam("userName") String userName,
@QueryParam("operation") String operation,
@QueryParam("startTime") String startTime,
@QueryParam("endTime") String endTime,
@QueryParam("limit") int limit,
@QueryParam("offset") int offset); @POST @Path("/audits") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasAuditEntry> getAtlasAudits(AuditSearchParameters auditSearchParameters); @GET @Path("/audit/{auditGuid}/details") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasEntityHeader> getAuditDetails(@PathParam("auditGuid") String auditGuid,
@QueryParam("limit") @DefaultValue("10") int limit,
@QueryParam("offset") @DefaultValue("0") int offset); @GET @Path("activeSearches") @Produces(Servlets.JSON_MEDIA_TYPE) Set<String> getActiveSearches(); @DELETE @Path("activeSearches/{id}") @Produces(Servlets.JSON_MEDIA_TYPE) boolean terminateActiveSearch(@PathParam("id") String searchId); @POST @Path("checkstate") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(Servlets.JSON_MEDIA_TYPE) AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @GET @Path("patches") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasPatches getAtlasPatches(); } |
@Test public void testLeaderElectionIsJoinedOnStart() throws Exception { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS)).thenReturn(new String[] {"id1"}); when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn("127.0.0.1:21000"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); LeaderLatch leaderLatch = mock(LeaderLatch.class); when(curatorFactory.leaderLatchInstance("id1", HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).thenReturn(leaderLatch); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verify(leaderLatch).start(); } | @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testClassificationTypeDefaultValue() { AtlasClassification defValue = classificationType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), classificationType.getTypeName()); } | @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } | AtlasClassificationType extends AtlasStructType { @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } } | AtlasClassificationType extends AtlasStructType { @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); } | AtlasClassificationType extends AtlasStructType { @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); } | AtlasClassificationType extends AtlasStructType { @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; } |
@Test public void testListenerIsAddedForActiveInstanceCallbacks() throws Exception { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS)).thenReturn(new String[] {"id1"}); when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn("127.0.0.1:21000"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); LeaderLatch leaderLatch = mock(LeaderLatch.class); when(curatorFactory.leaderLatchInstance("id1", HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).thenReturn(leaderLatch); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verify(leaderLatch).addListener(activeInstanceElectorService); } | @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testLeaderElectionIsNotStartedIfNotInHAMode() throws AtlasException { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verifyZeroInteractions(curatorFactory); } | @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testNoActionOnStopIfHAModeIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.stop(); verifyZeroInteractions(curatorFactory); } | @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testActiveStateSetOnBecomingLeader() { ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.isLeader(); InOrder inOrder = inOrder(serviceState); inOrder.verify(serviceState).becomingActive(); inOrder.verify(serviceState).setActive(); } | @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testPassiveStateSetOnLoosingLeadership() { ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.notLeader(); InOrder inOrder = inOrder(serviceState); inOrder.verify(serviceState).becomingPassive(); inOrder.verify(serviceState).setPassive(); } | @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } | ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } @Inject ActiveInstanceElectorService(Configuration configuration,
Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders,
CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState,
ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); } |
@Test public void testcanApplyToEntityType() throws AtlasBaseException { AtlasEntityDef entityDefA = new AtlasEntityDef("EntityA"); AtlasEntityDef entityDefB = new AtlasEntityDef("EntityB"); AtlasEntityDef entityDefC = new AtlasEntityDef("EntityC", null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName()))); AtlasEntityDef entityDefD = new AtlasEntityDef("EntityD", null, null, null, new HashSet<>(Arrays.asList(entityDefC.getName()))); AtlasEntityDef entityDefE = new AtlasEntityDef("EntityE"); AtlasEntityDef entityDefF = new AtlasEntityDef("EntityF", null, null, null, new HashSet<>(Arrays.asList(entityDefB.getName(),entityDefE.getName()))); AtlasClassificationDef classifyDef1 = new AtlasClassificationDef("Classify1", null, null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName())), null); AtlasClassificationDef classifyDef2 = new AtlasClassificationDef("Classify2"); AtlasClassificationDef classifyDef3 = new AtlasClassificationDef("Classify3", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName())), null, null); AtlasClassificationDef classifyDef4 = new AtlasClassificationDef("Classify4", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName())), new HashSet<>(Arrays.asList(entityDefD.getName())), null); AtlasClassificationDef classifyDef5 = new AtlasClassificationDef("Classify5", null, null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName(),entityDefC.getName())), null); AtlasClassificationDef classifyDef6 = new AtlasClassificationDef("Classify6", null, null, null, null, new HashSet<>(Arrays.asList(entityDefB.getName())), null); AtlasClassificationDef classifyDef7 = new AtlasClassificationDef("Classify7", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName(),classifyDef6.getName())),null, null); AtlasClassificationDef classifyDef8 = new AtlasClassificationDef("Classify8", null, null, null, new HashSet<>(Arrays.asList(classifyDef6.getName())),new HashSet<>(Arrays.asList(entityDefA.getName())), null); AtlasClassificationDef classifyDef9 = new AtlasClassificationDef("Classify9", null, null, null, null, new HashSet<>(Arrays.asList(entityDefE.getName())), null); AtlasClassificationDef classifyDef10 = new AtlasClassificationDef("Classify10", null, null, null, null, new HashSet<>(Arrays.asList(entityDefC.getName(),entityDefA.getName())), null); AtlasTypeRegistry registry = ModelTestUtil.getTypesRegistry(); AtlasTransientTypeRegistry ttr = registry.lockTypeRegistryForUpdate(); ttr.addType(entityDefA); ttr.addType(entityDefB); ttr.addType(entityDefC); ttr.addType(entityDefD); ttr.addType(entityDefE); ttr.addType(entityDefF); ttr.addType(classifyDef1); ttr.addType(classifyDef2); ttr.addType(classifyDef3); ttr.addType(classifyDef4); ttr.addType(classifyDef5); ttr.addType(classifyDef6); ttr.addType(classifyDef9); ttr.addType(classifyDef10); registry.releaseTypeRegistryForUpdate(ttr, true); ttr = registry.lockTypeRegistryForUpdate(); try { ttr.addType(classifyDef7); fail("Fail disjoined parent case"); } catch (AtlasBaseException ae) { registry.releaseTypeRegistryForUpdate(ttr, false); } ttr = registry.lockTypeRegistryForUpdate(); try { ttr.addType(classifyDef8); fail("Fail trying to add an entity type that is not in the parent"); } catch (AtlasBaseException ae) { registry.releaseTypeRegistryForUpdate(ttr, false); } AtlasEntityType entityTypeA = registry.getEntityTypeByName(entityDefA.getName()); AtlasEntityType entityTypeB = registry.getEntityTypeByName(entityDefB.getName()); AtlasEntityType entityTypeC = registry.getEntityTypeByName(entityDefC.getName()); AtlasEntityType entityTypeD = registry.getEntityTypeByName(entityDefD.getName()); AtlasEntityType entityTypeE = registry.getEntityTypeByName(entityDefE.getName()); AtlasEntityType entityTypeF = registry.getEntityTypeByName(entityDefF.getName()); AtlasClassificationType classifyType1 = registry.getClassificationTypeByName(classifyDef1.getName()); AtlasClassificationType classifyType2 = registry.getClassificationTypeByName(classifyDef2.getName()); AtlasClassificationType classifyType3 = registry.getClassificationTypeByName(classifyDef3.getName()); AtlasClassificationType classifyType4 = registry.getClassificationTypeByName(classifyDef4.getName()); AtlasClassificationType classifyType5 = registry.getClassificationTypeByName(classifyDef5.getName()); AtlasClassificationType classifyType6 = registry.getClassificationTypeByName(classifyDef6.getName()); AtlasClassificationType classifyType9 = registry.getClassificationTypeByName(classifyDef9.getName()); AtlasClassificationType classifyType10 = registry.getClassificationTypeByName(classifyDef10.getName()); assertTrue(classifyType1.canApplyToEntityType(entityTypeA)); assertFalse(classifyType1.canApplyToEntityType(entityTypeB)); assertTrue(classifyType1.canApplyToEntityType(entityTypeC)); assertTrue(classifyType1.canApplyToEntityType(entityTypeD)); assertTrue(classifyType2.canApplyToEntityType(entityTypeA)); assertTrue(classifyType2.canApplyToEntityType(entityTypeB)); assertTrue(classifyType2.canApplyToEntityType(entityTypeC)); assertTrue(classifyType2.canApplyToEntityType(entityTypeD)); assertTrue(classifyType3.canApplyToEntityType(entityTypeA)); assertFalse(classifyType3.canApplyToEntityType(entityTypeB)); assertTrue(classifyType3.canApplyToEntityType(entityTypeC)); assertTrue(classifyType3.canApplyToEntityType(entityTypeD)); assertFalse(classifyType4.canApplyToEntityType(entityTypeA)); assertFalse(classifyType4.canApplyToEntityType(entityTypeB)); assertFalse(classifyType4.canApplyToEntityType(entityTypeC)); assertTrue(classifyType4.canApplyToEntityType(entityTypeD)); assertTrue(classifyType6.canApplyToEntityType(entityTypeF)); assertTrue(classifyType9.canApplyToEntityType(entityTypeF)); assertTrue(classifyType5.canApplyToEntityType(entityTypeA)); assertTrue(classifyType5.canApplyToEntityType(entityTypeC)); assertTrue(classifyType10.canApplyToEntityType(entityTypeA)); assertTrue(classifyType10.canApplyToEntityType(entityTypeC)); } | public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } | AtlasClassificationType extends AtlasStructType { public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } } | AtlasClassificationType extends AtlasStructType { public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); } | AtlasClassificationType extends AtlasStructType { public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); } | AtlasClassificationType extends AtlasStructType { public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; } |
@Test public void testShouldBeActiveIfHAIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ServiceState serviceState = new ServiceState(configuration); assertEquals(ServiceState.ServiceStateValue.ACTIVE, serviceState.getState()); } | public ServiceStateValue getState() { return state; } | ServiceState { public ServiceStateValue getState() { return state; } } | ServiceState { public ServiceStateValue getState() { return state; } ServiceState(); ServiceState(Configuration configuration); } | ServiceState { public ServiceStateValue getState() { return state; } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); } | ServiceState { public ServiceStateValue getState() { return state; } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); } |
@Test(expectedExceptions = IllegalStateException.class) public void testShouldDisallowTransitionIfHAIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ServiceState serviceState = new ServiceState(configuration); serviceState.becomingPassive(); fail("Should not allow transition"); } | public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } | ServiceState { public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } } | ServiceState { public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } ServiceState(); ServiceState(Configuration configuration); } | ServiceState { public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); } | ServiceState { public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); } |
@Test public void testSharedPathIsCreatedIfNotExists() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(null); CreateBuilder createBuilder = mock(CreateBuilder.class); when(curatorFramework.create()).thenReturn(createBuilder); when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder); when(createBuilder.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)).thenReturn(createBuilder); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(createBuilder).forPath(getPath()); } | public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); static final String APACHE_ATLAS_ACTIVE_SERVER_INFO; } |
@Test public void testSharedPathIsCreatedWithRightACLIfNotExists() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(null); CreateBuilder createBuilder = mock(CreateBuilder.class); when(curatorFramework.create()).thenReturn(createBuilder); when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder); ACL expectedAcl = new ACL(ZooDefs.Perms.ALL, new Id("sasl", "[email protected]")); ACL expectedAcl1 = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); when(createBuilder. withACL(Arrays.asList(new ACL[]{expectedAcl,expectedAcl1}))).thenReturn(createBuilder); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(createBuilder).forPath(getPath()); } | public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); static final String APACHE_ATLAS_ACTIVE_SERVER_INFO; } |
@Test public void testDataIsUpdatedWithAtlasServerAddress() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(new Stat()); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(setDataBuilder).forPath( getPath(), SERVER_ADDRESS.getBytes(Charset.forName("UTF-8"))); } | public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); } | ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); static final String APACHE_ATLAS_ACTIVE_SERVER_INFO; } |
@Test public void testShouldPassThroughRequestsIfActive() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.ACTIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldFailIfCannotRetrieveActiveServerAddress() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(null); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testClassificationTypeIsValidValue() { for (Object value : validValues) { assertTrue(classificationType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(classificationType.isValidValue(value), "value=" + value); } } | @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } | AtlasClassificationType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } } | AtlasClassificationType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); } | AtlasClassificationType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); } | AtlasClassificationType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; } |
@Test public void testShouldRedirectRequestToActiveServerAddress() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getRequestURI()).thenReturn("types"); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "types"); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void adminImportRequestsToPassiveServerShouldToActiveServerAddress() throws IOException, ServletException { String importExportUrls[] = {"api/admin/export", "api/admin/import", "api/admin/importfile"}; for (String partialUrl : importExportUrls) { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn(partialUrl); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getRequestURI()).thenReturn(partialUrl); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + partialUrl); } } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testRedirectedRequestShouldContainQueryParameters() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()).thenReturn("types"); when(servletRequest.getQueryString()).thenReturn("query=TRAIT"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "types?query=TRAIT"); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testRedirectedRequestShouldContainEncodeQueryParameters() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()).thenReturn("api/atlas/v2/search/basic"); when(servletRequest.getQueryString()).thenReturn("limit=25&excludeDeletedEntities=true&spaceParam=firstpart secondpart&_=1500969656054&listParam=value1,value2"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "api/atlas/v2/search/basic?limit=25&excludeDeletedEntities=true&spaceParam=firstpart%20secondpart&_=1500969656054&listParam=value1,value2"); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldRedirectPOSTRequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.POST); when(servletRequest.getRequestURI()).thenReturn("types"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "types"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldRedirectPUTRequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.PUT); when(servletRequest.getRequestURI()).thenReturn("types"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "types"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldRedirectDELETERequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.DELETE); when(servletRequest.getRequestURI()). thenReturn("api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldReturnServiceUnavailableIfStateBecomingActive() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.BECOMING_ACTIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
@Test public void testShouldNotRedirectAdminAPIs() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()). thenReturn("api/atlas/admin/asmasn"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); verifyZeroInteractions(activeInstanceState); } | @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } | ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.