Search in sources :

Example 1 with DTO

use of org.eclipse.che.dto.shared.DTO in project che by eclipse.

the class FactoryBuilder method validateCompatibility.

/**
     * Validate compatibility of factory parameters.
     *
     * @param object
     *         - object to validate factory parameters
     * @param parent
     *         - parent object
     * @param methodsProvider
     *         - class that provides methods with {@link org.eclipse.che.api.core.factory.FactoryParameter}
     *         annotations
     * @param allowedMethodsProvider
     *         - class that provides allowed methods
     * @param version
     *         - version of factory
     * @param parentName
     *         - parent parameter queryParameterName
     * @throws org.eclipse.che.api.core.ConflictException
     */
void validateCompatibility(Object object, Object parent, Class methodsProvider, Class allowedMethodsProvider, Version version, String parentName, boolean isUpdate) throws ConflictException {
    // validate source
    if (SourceStorageDto.class.equals(methodsProvider) && !hasSubprojectInPath(parent)) {
        sourceStorageParametersValidator.validate((SourceStorage) object, version);
    }
    // get all methods recursively
    for (Method method : methodsProvider.getMethods()) {
        FactoryParameter factoryParameter = method.getAnnotation(FactoryParameter.class);
        if (factoryParameter == null) {
            continue;
        }
        String fullName = (parentName.isEmpty() ? "" : (parentName + ".")) + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, method.getName().startsWith("is") ? method.getName().substring(2) : method.getName().substring(3).toLowerCase());
        // check that field is set
        Object parameterValue;
        try {
            parameterValue = method.invoke(object);
        } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
            // should never happen
            LOG.error(e.getLocalizedMessage(), e);
            throw new ConflictException(FactoryConstants.INVALID_PARAMETER_MESSAGE);
        }
        // if value is null or empty collection or default value for primitives
        if (ValueHelper.isEmpty(parameterValue)) {
            // field must not be a mandatory, unless it's ignored or deprecated or doesn't suit to the version
            if (Obligation.MANDATORY.equals(factoryParameter.obligation()) && factoryParameter.deprecatedSince().compareTo(version) > 0 && factoryParameter.ignoredSince().compareTo(version) > 0 && method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
                throw new ConflictException(String.format(FactoryConstants.MISSING_MANDATORY_MESSAGE, method.getName()));
            }
        } else if (!method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) {
            throw new ConflictException(String.format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
        } else {
            // is parameter deprecated
            if (factoryParameter.deprecatedSince().compareTo(version) <= 0 || (!isUpdate && factoryParameter.setByServer())) {
                throw new ConflictException(String.format(FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version));
            }
            // use recursion if parameter is DTO object
            if (method.getReturnType().isAnnotationPresent(DTO.class)) {
                // validate inner objects such Git ot ProjectAttributes
                validateCompatibility(parameterValue, object, method.getReturnType(), method.getReturnType(), version, fullName, isUpdate);
            } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[1];
                Class secMapParamClass = (tp instanceof ParameterizedType) ? (Class) ((ParameterizedType) tp).getRawType() : (Class) tp;
                if (!String.class.equals(secMapParamClass) && !List.class.equals(secMapParamClass)) {
                    if (secMapParamClass.isAnnotationPresent(DTO.class)) {
                        Map<Object, Object> map = (Map) parameterValue;
                        for (Map.Entry<Object, Object> entry : map.entrySet()) {
                            validateCompatibility(entry.getValue(), object, secMapParamClass, secMapParamClass, version, fullName + "." + entry.getKey(), isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            } else if (List.class.isAssignableFrom(method.getReturnType())) {
                Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
                Class secListParamClass = (tp instanceof ParameterizedType) ? (Class) ((ParameterizedType) tp).getRawType() : (Class) tp;
                if (!String.class.equals(secListParamClass) && !List.class.equals(secListParamClass)) {
                    if (secListParamClass.isAnnotationPresent(DTO.class)) {
                        List<Object> list = (List) parameterValue;
                        for (Object entry : list) {
                            validateCompatibility(entry, object, secListParamClass, secListParamClass, version, fullName, isUpdate);
                        }
                    } else {
                        throw new RuntimeException("This type of fields is not supported by factory.");
                    }
                }
            }
        }
    }
}
Also used : ConflictException(org.eclipse.che.api.core.ConflictException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) FactoryParameter(org.eclipse.che.api.core.factory.FactoryParameter) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SourceStorageDto(org.eclipse.che.api.workspace.shared.dto.SourceStorageDto) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) DTO(org.eclipse.che.dto.shared.DTO)

Example 2 with DTO

use of org.eclipse.che.dto.shared.DTO in project che by eclipse.

the class TypeScriptDtoGenerator method init.

/**
     * Init stuff is responsible to grab all DTOs found in classpath (classloader) and setup model for String Template
     */
protected void init() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    if (useClassPath) {
        configurationBuilder.setUrls(forJavaClassPath());
    } else {
        configurationBuilder.setUrls(forClassLoader());
    }
    // keep only DTO interfaces
    Reflections reflections = new Reflections(configurationBuilder);
    List<Class<?>> annotatedWithDtos = new ArrayList<>(reflections.getTypesAnnotatedWith(DTO.class));
    List<Class<?>> interfacesDtos = annotatedWithDtos.stream().filter(clazz -> clazz.isInterface()).collect(Collectors.toList());
    interfacesDtos.stream().forEach(this::analyze);
}
Also used : Resources(com.google.common.io.Resources) URL(java.net.URL) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) Reflections(org.reflections.Reflections) Collectors(java.util.stream.Collectors) SubTypesScanner(org.reflections.scanners.SubTypesScanner) ArrayList(java.util.ArrayList) List(java.util.List) DtoModel(org.eclipse.che.plugin.typescript.dto.model.DtoModel) TypeAnnotationsScanner(org.reflections.scanners.TypeAnnotationsScanner) ST(org.stringtemplate.v4.ST) ClasspathHelper.forJavaClassPath(org.reflections.util.ClasspathHelper.forJavaClassPath) DTO(org.eclipse.che.dto.shared.DTO) ClasspathHelper.forClassLoader(org.reflections.util.ClasspathHelper.forClassLoader) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) SubTypesScanner(org.reflections.scanners.SubTypesScanner) TypeAnnotationsScanner(org.reflections.scanners.TypeAnnotationsScanner) ArrayList(java.util.ArrayList) DTO(org.eclipse.che.dto.shared.DTO) Reflections(org.reflections.Reflections)

Example 3 with DTO

use of org.eclipse.che.dto.shared.DTO in project che by eclipse.

the class DtoGenerator method generate.

public void generate() {
    Set<URL> urls = getClasspathForPackages(dtoPackages);
    genFileName = genFileName.replace('/', File.separatorChar);
    String outputFilePath = genFileName;
    // Extract the name of the output file that will contain all the DTOs and its package.
    String myPackageBase = packageBase;
    if (!myPackageBase.endsWith("/")) {
        myPackageBase += "/";
    }
    myPackageBase = myPackageBase.replace('/', File.separatorChar);
    int packageStart = outputFilePath.lastIndexOf(myPackageBase) + myPackageBase.length();
    int packageEnd = outputFilePath.lastIndexOf(File.separatorChar);
    String fileName = outputFilePath.substring(packageEnd + 1);
    String className = fileName.substring(0, fileName.indexOf(".java"));
    String packageName = outputFilePath.substring(packageStart, packageEnd).replace(File.separatorChar, '.');
    File outFile = new File(outputFilePath);
    try {
        DtoTemplate dtoTemplate = new DtoTemplate(packageName, className, impl);
        Reflections reflection = new Reflections(new ConfigurationBuilder().setUrls(urls).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
        List<Class<?>> dtos = new ArrayList<>(reflection.getTypesAnnotatedWith(DTO.class));
        // We sort alphabetically to ensure deterministic order of routing types.
        Collections.sort(dtos, new ClassesComparator());
        for (Class<?> clazz : dtos) {
            // DTO are interface
            if (clazz.isInterface()) {
                dtoTemplate.addInterface(clazz);
            }
        }
        reflection = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
        List<Class<?>> dtosDependencies = new ArrayList<>(reflection.getTypesAnnotatedWith(DTO.class));
        dtosDependencies.removeAll(dtos);
        reflection = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()).setScanners(new SubTypesScanner()));
        for (Class<?> clazz : dtosDependencies) {
            for (Class impl : reflection.getSubTypesOf(clazz)) {
                if (!(impl.isInterface() || urls.contains(impl.getProtectionDomain().getCodeSource().getLocation()))) {
                    if ("client".equals(dtoTemplate.getImplType())) {
                        if (isClientImpl(impl)) {
                            dtoTemplate.addImplementation(clazz, impl);
                        }
                    } else if ("server".equals(dtoTemplate.getImplType())) {
                        if (isServerImpl(impl)) {
                            dtoTemplate.addImplementation(clazz, impl);
                        }
                    }
                }
            }
        }
        // Emit the generated file.
        Files.createDirectories(outFile.toPath().getParent());
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) {
            writer.write(dtoTemplate.toString());
        }
        if ("server".equals(impl)) {
            // Create file in META-INF/services/
            File outServiceFile = new File(myPackageBase + "META-INF/services/" + DtoFactoryVisitor.class.getCanonicalName());
            Files.createDirectories(outServiceFile.toPath().getParent());
            try (BufferedWriter serviceFileWriter = new BufferedWriter(new FileWriter(outServiceFile))) {
                serviceFileWriter.write(packageName + "." + className);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) SubTypesScanner(org.reflections.scanners.SubTypesScanner) TypeAnnotationsScanner(org.reflections.scanners.TypeAnnotationsScanner) File(java.io.File) DTO(org.eclipse.che.dto.shared.DTO) Reflections(org.reflections.Reflections)

Aggregations

ArrayList (java.util.ArrayList)3 DTO (org.eclipse.che.dto.shared.DTO)3 IOException (java.io.IOException)2 URL (java.net.URL)2 List (java.util.List)2 Reflections (org.reflections.Reflections)2 SubTypesScanner (org.reflections.scanners.SubTypesScanner)2 TypeAnnotationsScanner (org.reflections.scanners.TypeAnnotationsScanner)2 ConfigurationBuilder (org.reflections.util.ConfigurationBuilder)2 Resources (com.google.common.io.Resources)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileWriter (java.io.FileWriter)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1