Java Code Examples for org.apache.commons.lang3.Validate#isInstanceOf()

The following examples show how to use org.apache.commons.lang3.Validate#isInstanceOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaParserServiceImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Search the method by name in class.
 * </p>
 */
public MethodMetadata getMethodByNameInClass(JavaType serviceClass,
        JavaSymbolName methodName) {
    // Load class details. If class not found an exception will be raised.
    ClassOrInterfaceTypeDetails tmpServiceDetails = typeLocationService
            .getTypeDetails(serviceClass);

    // Checks if it's mutable
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class,
            tmpServiceDetails,
            "Can't modify " + tmpServiceDetails.getName());

    ClassOrInterfaceTypeDetails serviceDetails = (ClassOrInterfaceTypeDetails) tmpServiceDetails;

    List<? extends MethodMetadata> methodList = serviceDetails
            .getDeclaredMethods();

    for (MethodMetadata methodMetadata : methodList) {
        if (methodMetadata.getMethodName().equals(methodName)) {
            return methodMetadata;
        }
    }

    return null;
}
 
Example 2
Source File: PrepHasStepCondition.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Override
public boolean apply(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 2);
    Validate.isInstanceOf(String.class, args[0]);
    Validate.isInstanceOf(String.class, args[1]);

    String preparationId = (String) args[0];
    String headId = (String) args[1];

    PreparationDTO prep = exportParametersUtil.getPreparation(preparationId, headId);

    return prep.getSteps().size() > 1;
}
 
Example 3
Source File: PrepMetadataGetContentUrlGenerator.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 2);
    Validate.isInstanceOf(String.class, args[0]);
    Validate.isInstanceOf(String.class, args[1]);

    String preparationId = (String) args[0];
    String headId = (String) args[1];

    URIBuilder builder = new URIBuilder();
    builder.setPath("/api/preparations/" + preparationId + "/metadata");

    if (StringUtils.isNotEmpty(headId)) {
        builder.setParameter("version", headId);
    }

    return new AsyncExecutionResult(builder.toString());
}
 
Example 4
Source File: WSExportValidationServiceImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get mutable class or interface type details from java type.
 * 
 * @param javaType Java type
 * @return Mutable class or interface type
 */
protected ClassOrInterfaceTypeDetails getTypeDetails(JavaType javaType) {

    // Get mutable class or interface type details from java type
    String id = PhysicalTypeIdentifier.createIdentifier(javaType,
            LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""));
    PhysicalTypeMetadata ptm = (PhysicalTypeMetadata) metadataService
            .get(id);
    Validate.notNull(ptm, "Java source class doesn't exists.");
    PhysicalTypeDetails ptd = ptm.getMemberHoldingTypeDetails();
    Validate.notNull(ptd, "Java source code details unavailable for type "
            + PhysicalTypeIdentifier.getFriendlyName(id));
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class, ptd,
            "Java source code is immutable for type "
                    + PhysicalTypeIdentifier.getFriendlyName(id));

    return (ClassOrInterfaceTypeDetails) ptd;
}
 
Example 5
Source File: MapToStringConverter.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object convertObjectValueToDataValue(Object objectValue, Session session) {
    Validate.isInstanceOf(Map.class, objectValue);
    Map<String, String> map = (Map<String, String>) objectValue;
    if (map.isEmpty()) {
        return null;
    }
    Object dataValue = null;

    if (isPostgresProvider(session)) {
        dataValue = new PGHStore(map);
    } else {
        dataValue = HstoreSupport.toString(map);
    }
    return dataValue;
}
 
Example 6
Source File: JAXBElementCodeGenerator.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Set<JType> getPossibleValueTypes(Collection<JType> possibleTypes) {
	final Set<JType> possibleValueTypes = new HashSet<JType>();

	for (JType possibleType : possibleTypes) {
		Validate.isInstanceOf(JClass.class, possibleType);
		final JClass possibleClass = (JClass) possibleType;
		if (possibleClass.getTypeParameters().size() == 1) {
			possibleValueTypes
					.add(possibleClass.getTypeParameters().get(0));
		} else {
			possibleValueTypes.add(getCodeModel().ref(Object.class));
		}
	}
	return possibleValueTypes;
}
 
Example 7
Source File: PrepMetadataExecutionIdGenerator.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public String getExecutionId(ProceedingJoinPoint pjp) {

    // look for AsyncParameter param
    Object[] args = AnnotationUtils.extractAsyncParameter(pjp);

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 2);
    Validate.isInstanceOf(String.class, args[0]);
    Validate.isInstanceOf(String.class, args[1]);

    return DigestUtils.sha1Hex(args[0] + "_" + args[1]);
}
 
Example 8
Source File: CacheCondition.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(ContentCacheKey.class, args[0]);

    ContentCacheKey cacheKey = (ContentCacheKey) args[0];

    return contentCache.has(cacheKey);
}
 
Example 9
Source File: PreparationExportCondition.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(ExportParameters.class, args[0]);

    return StringUtils.isNotEmpty(((ExportParameters) args[0]).getPreparationId());
}
 
Example 10
Source File: PrepMetadataCacheCondition.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 2);
    Validate.isInstanceOf(String.class, args[0]);
    Validate.isInstanceOf(String.class, args[1]);

    try {
        String preparationId = (String) args[0];
        String headId = (String) args[1];

        ExportParameters exportParameters = new ExportParameters();
        exportParameters.setPreparationId(preparationId);
        exportParameters.setStepId(headId);
        exportParameters = exportParametersUtil.populateFromPreparationExportParameter(exportParameters);

        final TransformationMetadataCacheKey cacheKey = cacheKeyGenerator
                .generateMetadataKey(exportParameters.getPreparationId(), exportParameters.getStepId(), HEAD);

        return cacheCondition.apply(cacheKey);

    } catch (IOException e) {
        LOGGER.error("Cannot get all information from export parameters", e);
    }

    return false;
}
 
Example 11
Source File: PreparationGetContentUrlGenerator.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(ExportParameters.class, args[0]);

    ExportParameters param = (ExportParameters) args[0];

    URIBuilder builder = new URIBuilder();
    builder.setPath("/api/preparations/" + param.getPreparationId() + "/content");

    if (StringUtils.isNotEmpty(param.getStepId())) {
        builder.setParameter("version", param.getStepId());
    }

    if (param.getFrom() != null) {
        builder.setParameter("from", param.getFrom().name());
    }

    if (StringUtils.isNotEmpty(param.getFilter())) {
        builder.setParameter("filter", param.getFilter());
    }

    return new AsyncExecutionResult(builder.toString());
}
 
Example 12
Source File: MockResultUrlGenerator.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {

    // check pre-condition
    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(Integer.class, args[0]);

    Integer index = (Integer) args[0];

    return new AsyncExecutionResult("/url/result/" + index);
}
 
Example 13
Source File: JavaParserServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Updates the class with the new method created with selected attributes.
 * </p>
 */
public void createMethod(JavaSymbolName methodName, JavaType returnType,
        JavaType targetType, int modifier, List<JavaType> throwsTypes,
        List<AnnotationMetadata> annotationList,
        List<AnnotatedJavaType> paramTypes,
        List<JavaSymbolName> paramNames, String body) {

    Validate.notNull(paramTypes, "Param type mustn't be null");
    Validate.notNull(paramNames, "Param name mustn't be null");

    // MetadataID
    String targetId = PhysicalTypeIdentifier.createIdentifier(targetType,
            LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""));

    // Obtain the physical type and itd mutable details
    PhysicalTypeMetadata ptm = (PhysicalTypeMetadata) metadataService
            .get(targetId);
    Validate.notNull(ptm, "Java source class doesn't exists.");

    PhysicalTypeDetails ptd = ptm.getMemberHoldingTypeDetails();

    Validate.notNull(ptd, "Java source code details unavailable for type "
            + PhysicalTypeIdentifier.getFriendlyName(targetId));
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class, ptd,
            "Java source code is immutable for type "
                    + PhysicalTypeIdentifier.getFriendlyName(targetId));
    ClassOrInterfaceTypeDetails mutableTypeDetails = (ClassOrInterfaceTypeDetails) ptd;

    // create method
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine(body);
    MethodMetadataBuilder operationMetadata = new MethodMetadataBuilder(
            targetId, modifier, methodName,
            (returnType == null ? JavaType.VOID_PRIMITIVE : returnType),
            paramTypes, paramNames, bodyBuilder);
    for (AnnotationMetadata annotationMetadata : annotationList) {
        operationMetadata.addAnnotation(annotationMetadata);
    }
    for (JavaType javaType : throwsTypes) {
        operationMetadata.addThrowsType(javaType);
    }

    ClassOrInterfaceTypeDetailsBuilder mutableTypeDetailsBuilder = new ClassOrInterfaceTypeDetailsBuilder(
            mutableTypeDetails);
    mutableTypeDetailsBuilder.addMethod(operationMetadata.build());
    typeManagementService
            .createOrUpdateTypeOnDisk(mutableTypeDetailsBuilder.build());
}
 
Example 14
Source File: WSExportOperationsImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String getAvailableServiceOperationsToExport(JavaType serviceClass) {

    StringBuilder methodListStringBuilder = new StringBuilder();

    if (!isWebServiceClass(serviceClass)) {

        // If class is not defined as web service.
        methodListStringBuilder
                .append("Class '"
                        + serviceClass.getFullyQualifiedTypeName()
                        + "' is not defined as Web Service.\nUse the command 'service define ws --class "
                        + serviceClass.getFullyQualifiedTypeName()
                        + "' to export as web service.");

        return methodListStringBuilder.toString();
    }

    String id = typeLocationService.getPhysicalTypeIdentifier(serviceClass);

    Validate.notNull(
            id,
            "Cannot locate source for '"
                    + serviceClass.getFullyQualifiedTypeName() + "'.");

    // Get service class details
    ClassOrInterfaceTypeDetails tmpServiceDetails = typeLocationService
            .getTypeDetails(serviceClass);
    MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(
            serviceClass.getFullyQualifiedTypeName(), tmpServiceDetails);

    // Checks if it's mutable
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class,
            tmpServiceDetails,
            "Can't modify " + tmpServiceDetails.getName());

    List<? extends MethodMetadata> methodList = memberDetails.getMethods();

    // If there aren't any methods in class.
    if (methodList == null || methodList.isEmpty()) {

        methodListStringBuilder.append("Class '"
                + serviceClass.getFullyQualifiedTypeName()
                + "' has not defined any method.");

        return methodListStringBuilder.toString();
    }

    boolean isAnnotationIntroduced;

    // for every method
    for (MethodMetadata methodMetadata : methodList) {

        // already has @GvNIXWebMethod
        isAnnotationIntroduced = javaParserService
                .isAnnotationIntroducedInMethod(
                        GvNIXWebMethod.class.getName(), methodMetadata);

        // if ! has @GvNIXWebMethod
        if (!isAnnotationIntroduced) {
            if (!StringUtils.isNotBlank(methodListStringBuilder.toString())) {
                methodListStringBuilder
                        .append("Method list to export as web service operation in '"
                                + serviceClass.getFullyQualifiedTypeName()
                                + "':\n");
            }
            // add method name to list
            methodListStringBuilder
                    .append("\t* "
                            + methodMetadata.getMethodName()
                                    .getSymbolName() + "\n");
        }

    }

    // If there aren't defined any methods available to export.
    if (!StringUtils.isNotBlank(methodListStringBuilder.toString())) {
        methodListStringBuilder
                .append("Class '"
                        + serviceClass.getFullyQualifiedTypeName()
                        + "' hasn't got any available method to export as web service operations.");
    }

    return methodListStringBuilder.toString();
}
 
Example 15
Source File: WSExportValidationServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String getWebServiceDefaultNamespace(JavaType javaType) {

    // Get and validate mutable type details
    ClassOrInterfaceTypeDetails typeDetails = typeLocationService
            .getTypeDetails(javaType);
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class, typeDetails,
            "Can't modify ".concat(typeDetails.getName().toString()));

    // Get and validate gvNIX web service annotation
    AnnotationMetadata annotation = typeDetails
            .getTypeAnnotation(new JavaType(GvNIXWebService.class.getName()));
    Validate.isTrue(
            annotation != null,
            "Launch command 'service define ws --class ".concat(
                    javaType.getFullyQualifiedTypeName()).concat(
                    "' to export class to Web Service."));

    // Get and validate gvNIX web service annotation target namespace attr
    StringAttributeValue targetNamespace = (StringAttributeValue) annotation
            .getAttribute(new JavaSymbolName("targetNamespace"));

    Validate.notNull(
            targetNamespace,
            "You must define 'targetNamespace' annotation attribute in @GvNIXWebService in class: '"
                    .concat(javaType.getFullyQualifiedTypeName()).concat(
                            "'."));

    Validate.isTrue(
            StringUtils.isNotBlank(targetNamespace.getValue()),
            "You must define 'targetNamespace' annotation attribute in @GvNIXWebService in class: '"
                    .concat(javaType.getFullyQualifiedTypeName()).concat(
                            "'."));

    // Get and validate gvNIX web service annotation target namespace value
    String targetNamespaceValue = targetNamespace.getValue();
    Validate.isTrue(
            checkNamespaceFormat(targetNamespaceValue),
            "Attribute 'targetNamespace' in @GvNIXWebService for Web Service class '"
                    .concat(javaType.getFullyQualifiedTypeName())
                    .concat("'has to start with 'http://'.\ni.e.: http://name.of.namespace/"));

    return targetNamespaceValue;
}
 
Example 16
Source File: OCCChecksumMetadata.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Add checksum field (plus getter/setter) to builder
 * 
 * @param field
 * @param getter
 * @param setter
 * @param typeManagementService
 */
private void addChecksumFieldToEntity(FieldMetadata field,
        MethodMetadata getter, MethodMetadata setter,
        TypeManagementService typeManagementService) {

    PhysicalTypeDetails ptd = governorPhysicalTypeMetadata
            .getMemberHoldingTypeDetails();

    Validate.isInstanceOf(
            ClassOrInterfaceTypeDetails.class,
            ptd,
            "Java source code is immutable for type "
                    + PhysicalTypeIdentifier
                            .getFriendlyName(governorPhysicalTypeMetadata
                                    .getId()));

    ClassOrInterfaceTypeDetailsBuilder mutableTypeDetails = new ClassOrInterfaceTypeDetailsBuilder(
            (ClassOrInterfaceTypeDetails) ptd);

    // Try to locate an existing field with @javax.persistence.Version

    try {
        if (!fieldExist(mutableTypeDetails, field)) {
            mutableTypeDetails.addField(new FieldMetadataBuilder(
                    governorTypeDetails.getDeclaredByMetadataId(), field));
        }
        if (!methodExists(mutableTypeDetails, getter)) {
            mutableTypeDetails.addMethod(getter);
        }
        if (!methodExists(mutableTypeDetails, setter)) {
            mutableTypeDetails.addMethod(setter);
        }
        typeManagementService.createOrUpdateTypeOnDisk(mutableTypeDetails
                .build());

    }
    catch (IllegalArgumentException e) {
        // TODO In some cases, one element is added more than one time
        LOGGER.finest("Problem adding version field: ".concat(e.toString()));
    }

}
 
Example 17
Source File: JavaParserServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Adds Web Service annotation to selected method.
 * </p>
 */
public void updateMethodAnnotations(JavaType className,
        JavaSymbolName method,
        List<AnnotationMetadata> annotationMetadataUpdateList,
        List<AnnotatedJavaType> annotationWebParamMetadataList) {

    // MetadataID
    String targetId = PhysicalTypeIdentifier.createIdentifier(className,
            LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""));

    // Obtain the physical type and itd mutable details
    PhysicalTypeMetadata ptm = (PhysicalTypeMetadata) metadataService
            .get(targetId);

    PhysicalTypeDetails ptd = ptm.getMemberHoldingTypeDetails();

    Validate.notNull(ptd, "Java source code details unavailable for type "
            + PhysicalTypeIdentifier.getFriendlyName(targetId));
    Validate.isInstanceOf(ClassOrInterfaceTypeDetails.class, ptd,
            "Java source code is immutable for type "
                    + PhysicalTypeIdentifier.getFriendlyName(targetId));

    ClassOrInterfaceTypeDetails mutableTypeDetails = (ClassOrInterfaceTypeDetails) ptd;

    List<MethodMetadata> updatedMethodList = new ArrayList<MethodMetadata>();

    // Add to list required method and all methods in Java

    // Search one method in all (Java and AspectJ)
    updatedMethodList.addAll(searchMethodInAll(className, method,
            annotationMetadataUpdateList, annotationWebParamMetadataList,
            targetId));

    // Search methods in Java, excepts one method
    updatedMethodList.addAll(searchMethodsInJava(method, targetId,
            mutableTypeDetails));

    ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetails = createTypeDetails(
            mutableTypeDetails, updatedMethodList);
    // Add old class imports into new class to avoid undefined imports
    // Example: Not included HashSet import when exporting method in
    // petclinic Owner
    classOrInterfaceTypeDetails.setRegisteredImports(mutableTypeDetails
            .getRegisteredImports());

    // Updates the class in file system.
    updateClass(classOrInterfaceTypeDetails.build());
}
 
Example 18
Source File: ListCodeGenerator.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void generate(JBlock block, JType type,
		Collection<JType> possibleTypes, boolean isAlwaysSet, A arguments) {
	Validate.isInstanceOf(JClass.class, type);
	final JClass _class = (JClass) type;

	final JClass jaxbElementClass = getCodeModel().ref(JAXBElement.class);
	final Set<JType> arrays = new HashSet<JType>();
	final Collection<JClass> jaxbElements = new HashSet<JClass>();
	final Set<JType> otherTypes = new HashSet<JType>();
	for (final JType possibleType : possibleTypes) {
		if (possibleType.isArray()) {
			arrays.add(possibleType);
		} else if (possibleType instanceof JClass
				&& jaxbElementClass
						.isAssignableFrom(((JClass) possibleType).erasure())) {
			jaxbElements.add((JClass) possibleType);
		} else {
			otherTypes.add(possibleType);
		}
	}
	// If list items are not arrays or JAXBElements, just delegate to the
	// hashCode of the list
	if (arrays.isEmpty() && jaxbElements.isEmpty()) {
		getImplementor().onObject(arguments, block, false);
	} else {
		final JClass elementType = getElementType(_class);

		block = arguments.ifHasSetValue(block, isAlwaysSet, true);

		final A iterator = arguments.iterator(block, elementType);

		// while(e1.hasNext() && e2.hasNext()) {
		final JBlock whileBlock = iterator._while(block);
		// E o1 = e1.next();
		// Object o2 = e2.next();
		final boolean isElementAlwaysSet = elementType.isPrimitive();
		getCodeGenerator().generate(whileBlock, elementType, possibleTypes,
				isElementAlwaysSet,
				iterator.element(whileBlock, elementType));
		// }
		// return !(e1.hasNext() || e2.hasNext());
	}
}
 
Example 19
Source File: PairConditionalAsyncTest.java    From data-prep with Apache License 2.0 3 votes vote down vote up
@Override
public boolean apply(Object... args) {

    // check pre-condition

    Validate.notNull(args);
    Validate.isTrue(args.length == 1);
    Validate.isInstanceOf(Integer.class, args[0]);

    Integer index = (Integer) args[0];

    return (index & 1) == 0;
}
 
Example 20
Source File: DynamicPlugin.java    From rheem with Apache License 2.0 3 votes vote down vote up
/**
 * Checks and casts the given {@link Object}. If it is not {@code null}, feed it to a {@link Consumer}.
 *
 * @param o        to be casted
 * @param t        to that should be casted
 * @param consumer accepts the casted {@code o} unless it is {@code null}
 */
@SuppressWarnings("unchecked")
public static <T> void ifPresent(Object o, Class<? super T> t, Consumer<T> consumer) {
    if (o == null) return;
    Validate.isInstanceOf(t, o, "Expected %s to be of type %s (is %s).", o, t, o.getClass());
    consumer.accept((T) o);
}