Example usage for java.lang Class getPackage

List of usage examples for java.lang Class getPackage

Introduction

In this page you can find the example usage for java.lang Class getPackage.

Prototype

public Package getPackage() 

Source Link

Document

Gets the package of this class.

Usage

From source file:hu.bme.mit.sette.tools.spf.SpfGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }//from   w w  w. j av a 2 s. c  o  m

        for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // create .jpf descriptor
            JPFConfig jpfConfig = new JPFConfig();
            jpfConfig.target = javaClass.getName() + '_' + method.getName();

            String symbMethod = javaClass.getName() + '.' + method.getName() + '('
                    + StringUtils.repeat("sym", "#", parameterTypes.length) + ')';

            jpfConfig.symbolicMethod.add(symbMethod);

            jpfConfig.classpath = "build/";

            for (File libraryFile : getSnippetProject().getFiles().getLibraryFiles()) {
                jpfConfig.classpath += ',' + getSnippetProjectSettings().getLibraryDirectoryPath() + '/'
                        + libraryFile.getName();
            }

            jpfConfig.listener = JPFConfig.SYMBOLIC_LISTENER;
            jpfConfig.symbolicDebug = JPFConfig.ON;

            jpfConfig.searchMultipleErrors = JPFConfig.TRUE;
            jpfConfig.decisionProcedure = JPFConfig.DP_CORAL;

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());

            String[] parameterLiterals = new String[parameterTypes.length];

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                parameterLiterals[i] = SpfGenerator.getParameterLiteral(parameterType);
                i++;
            }

            main.codeLines().add(javaClass.getSimpleName() + '.' + method.getName() + '('
                    + StringUtils.join(parameterLiterals, ", ") + ");");

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathJPF = relativePath + '.' + JPFConfig.JPF_CONFIG_EXTENSION;
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetJPFFile = new File(getRunnerProjectSettings().getGeneratedDirectory(), relativePathJPF);
            FileUtils.forceMkdir(targetJPFFile.getParentFile());
            FileUtils.write(targetJPFFile, jpfConfig.generate().toString());

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

protected JavaDocBuilder getJavaDocBuilder(final Class clz) throws URISyntaxException {
    final String projectPath = new File("").getAbsolutePath();
    final String packagePath = clz.getPackage().getName().replaceAll("\\.", "/");
    if (builder == null) {
        builder = new JavaDocBuilder();

        final URL resource = Thread.currentThread().getContextClassLoader().getResource(packagePath);
        final File src = new File(resource.toURI());
        builder.addSourceTree(src);/*from  ww w . j  a  va 2s.c o  m*/

        // project source folder
        final File realFolder = new File(projectPath + "/src/main/java/" + packagePath);
        if (realFolder.exists()) {
            builder.addSourceTree(realFolder);
        }
    }

    return builder;
}

From source file:org.apache.axis2.description.java2wsdl.DocLitBareSchemaGenerator.java

private QName generateSchemaForType(XmlSchemaSequence sequence, Class<?> type, String partName)
        throws Exception {

    boolean isArrayType = false;
    if (type != null) {
        isArrayType = type.isArray();/*from  w  w w.j a v  a  2  s.  c o m*/
    }
    if (isArrayType) {
        type = type.getComponentType();
    }
    if (AxisFault.class.getName().equals(type)) {
        return null;
    }
    String classTypeName;
    if (type == null) {
        classTypeName = "java.lang.Object";
    } else {
        classTypeName = type.getName();
    }
    if (isArrayType && "byte".equals(classTypeName)) {
        classTypeName = "base64Binary";
        isArrayType = false;
    }
    if (isDataHandler(type)) {
        classTypeName = "base64Binary";
    }
    QName schemaTypeName = typeTable.getSimpleSchemaTypeName(classTypeName);
    if (schemaTypeName == null && type != null) {
        schemaTypeName = generateSchema(type);
        addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        String schemaNamespace = resolveSchemaNamespace(getQualifiedName(type.getPackage()));
        addImport(getXmlSchema(schemaNamespace), schemaTypeName);
        if (sequence == null) {
            generateSchemaForSingleElement(schemaTypeName, partName, isArrayType);
        }
    } else {
        if (sequence == null) {
            generateSchemaForSingleElement(schemaTypeName, partName, isArrayType);
        } else {
            addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        }
    }
    addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
    return schemaTypeName;
}

From source file:pcgen.io.PCGVer2Creator.java

private static void appendSourceInTaggedFormat(StringBuilder buffer, CDOMObject source) {
    buffer.append(IOConstants.TAG_SOURCE).append(':');
    buffer.append('[');
    buffer.append(IOConstants.TAG_TYPE).append(':');

    // I love reflection :-)
    final Class<? extends CDOMObject> srcClass = source.getClass();
    final String pckName = srcClass.getPackage().getName();
    final String srcName = srcClass.getName().substring(pckName.length() + 1);

    buffer.append(srcName.toUpperCase());
    buffer.append('|');
    buffer.append(IOConstants.TAG_NAME).append(':');
    buffer.append(source.getKeyName());//  ww w. j  a v a  2 s . com
    buffer.append(']');
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method updates existing Spring bean definitions in a XML application context file. Bean definition is
 * identified by its type defining class.
 *
 * @param project/*from w  w  w . j  a va  2 s  .c  o m*/
 * @param type
 * @param jaxbElement
 */
public void updateBeanDefinitions(File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
        xsltSource.setSystemId("update-bean");

        List<File> configFiles = new ArrayList<>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile, project));

        LSParser parser = XMLUtils.createLSParser();
        GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
        parser.setFilter(getBeanFilter);

        for (File file : configFiles) {
            parser.parseURI(file.toURI().toString());
            if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
                xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

                String beanElement = type.getAnnotation(XmlRootElement.class).name();
                String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

                //create transformer
                Transformer transformer = transformerFactory.newTransformer(xsltSource);
                transformer.setParameter("bean_element", beanElement);
                transformer.setParameter("bean_namespace", beanNamespace);
                transformer.setParameter("bean_content", getXmlContent(jaxbElement)
                        .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                        .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

                //transform
                StringResult result = new StringResult();
                transformer.transform(xmlSource, result);
                FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
                return;
            }
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
        throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
}

From source file:com.github.gekoh.yagen.hst.CreateEntities.java

private String createHistoryEntity(String baseClassPackageName, AccessibleObject fieldOrMethod,
        Reader template) {//from ww  w. java 2s.  com
    TemporalEntity temporalEntity = fieldOrMethod.getAnnotation(TemporalEntity.class);
    JoinTable joinTable = fieldOrMethod.getAnnotation(JoinTable.class);
    Class targetEntity = null;
    Class declaringClass;
    String packageName;
    String hstEntityClassSimpleName = FieldInfo.toCamelCase(joinTable.name()) + HISTORY_ENTITY_SUFFIX;
    hstEntityClassSimpleName = hstEntityClassSimpleName.substring(0, 1).toUpperCase()
            + hstEntityClassSimpleName.substring(1);

    if (fieldOrMethod.isAnnotationPresent(ManyToMany.class)) {
        targetEntity = MappingUtils.determineTargetEntity(fieldOrMethod,
                fieldOrMethod.getAnnotation(ManyToMany.class).targetEntity());
    } else if (fieldOrMethod.isAnnotationPresent(ManyToOne.class)) {
        targetEntity = MappingUtils.determineTargetEntity(fieldOrMethod,
                fieldOrMethod.getAnnotation(ManyToOne.class).targetEntity());
    } else {
        throw new UnsupportedOperationException(
                "when generating history entity for relation on " + fieldOrMethod);
    }

    if (fieldOrMethod instanceof Field) {
        declaringClass = ((Field) fieldOrMethod).getDeclaringClass();
    } else {
        declaringClass = ((Method) fieldOrMethod).getDeclaringClass();
    }
    packageName = declaringClass.getPackage().getName();

    List<FieldInfo> fieldInfos = new ArrayList<FieldInfo>();

    //      add join columns to both sides of the relation (assumes we have only one each)
    fieldInfos.add(FieldInfo.getIdFieldInfo(declaringClass,
            getFieldNameFromReferencingClassName(declaringClass.getSimpleName()),
            joinTable.joinColumns()[0].name()));
    fieldInfos.add(FieldInfo.getIdFieldInfo(targetEntity,
            getFieldNameFromReferencingClassName(targetEntity.getSimpleName()),
            joinTable.inverseJoinColumns()[0].name()));

    return createHistoryEntity(baseClassPackageName, packageName, hstEntityClassSimpleName,
            temporalEntity.historyTableName(), null, null, template, fieldInfos);
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static String[] classToPackages(Class clss) {
    if (null != clss && null != clss.getPackage() && null != clss.getPackage().getName()) {
        return clss.getPackage().getName().split("\\.");
    }/*from www  .ja  v  a 2 s  .c  om*/
    return emptypkgs;
    //        return Optional.ofNullable(clss)
    //                .map(Class::getPackage)
    //                .map(Package::getName)
    //                .map(s -> s.split("\\."))
    //                .orElse(emptypkgs);
}

From source file:hivemall.docs.FuncsListGenerator.java

private void generate(@Nonnull File outputFile, @Nonnull String preface,
        @Nonnull Map<String, List<String>> headers) throws MojoExecutionException {
    Reflections reflections = new Reflections("hivemall");
    Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(Description.class);

    StringBuilder sb = new StringBuilder();
    Map<String, Set<String>> packages = new HashMap<>();

    Pattern func = Pattern.compile("_FUNC_(\\(.*?\\))(.*)", Pattern.DOTALL);

    for (Class<?> annotatedClass : annotatedClasses) {
        Deprecated deprecated = annotatedClass.getAnnotation(Deprecated.class);
        if (deprecated != null) {
            continue;
        }//ww w. j a va 2 s  . co m

        Description description = annotatedClass.getAnnotation(Description.class);

        String value = description.value().replaceAll("\n", " ");
        Matcher matcher = func.matcher(value);
        if (matcher.find()) {
            value = asInlineCode(description.name() + matcher.group(1)) + escapeHtml(matcher.group(2));
        }
        sb.append(asListElement(value));

        StringBuilder sbExtended = new StringBuilder();
        if (!description.extended().isEmpty()) {
            sbExtended.append(description.extended());
            sb.append("\n");
        }

        String extended = sbExtended.toString();
        if (extended.isEmpty()) {
            sb.append("\n");
        } else {
            if (extended.toLowerCase().contains("select")) { // extended description contains SQL statements
                sb.append(indent(asCodeBlock(extended, "sql")));
            } else {
                sb.append(indent(asCodeBlock(extended)));
            }
        }

        String packageName = annotatedClass.getPackage().getName();
        if (!packages.containsKey(packageName)) {
            Set<String> set = new TreeSet<>();
            packages.put(packageName, set);
        }
        Set<String> List = packages.get(packageName);
        List.add(sb.toString());

        StringUtils.clear(sb);
    }

    try (PrintWriter writer = new PrintWriter(outputFile)) {
        // license header
        writer.println("<!--");
        try {
            File licenseFile = new File(basedir, "resources/license-header.txt");
            FileReader fileReader = new FileReader(licenseFile);

            try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    writer.println(indent(line));
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read license file");
        }
        writer.println("-->\n");

        writer.println(preface);

        writer.println("\n<!-- toc -->\n");

        for (Map.Entry<String, List<String>> e : headers.entrySet()) {
            writer.println(e.getKey() + "\n");
            List<String> packageNames = e.getValue();
            for (String packageName : packageNames) {
                for (String desc : packages.get(packageName)) {
                    writer.println(desc);
                }
            }
        }

        writer.flush();
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Output file is not found");
    }
}

From source file:com.angkorteam.framework.swagger.factory.SwaggerFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    Swagger swagger = new Swagger();
    io.swagger.models.Info info = new io.swagger.models.Info();
    swagger.setInfo(info);/*  w w  w . ja v  a2  s.c  om*/
    info.setTitle(title);
    info.setLicense(license);
    info.setContact(contact);
    info.setTermsOfService(termsOfService);
    info.setVersion(version);
    info.setDescription(description);

    swagger.setConsumes(consumes);
    swagger.setProduces(produces);
    swagger.setSchemes(schemes);
    swagger.setBasePath(basePath);
    swagger.setHost(host);
    swagger.setExternalDocs(externalDocs);

    ConfigurationBuilder config = new ConfigurationBuilder();
    Set<String> acceptablePackages = new HashSet<>();

    boolean allowAllPackages = false;

    if (resourcePackages != null && resourcePackages.length > 0) {
        for (String resourcePackage : resourcePackages) {
            if (resourcePackage != null && !"".equals(resourcePackage)) {
                acceptablePackages.add(resourcePackage);
                config.addUrls(ClasspathHelper.forPackage(resourcePackage));
            }
        }
    }

    config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());

    Reflections reflections = new Reflections(config);
    Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class);

    Set<Class<?>> output = new HashSet<Class<?>>();
    for (Class<?> cls : controllers) {
        if (allowAllPackages) {
            output.add(cls);
        } else {
            for (String pkg : acceptablePackages) {
                if (cls.getPackage().getName().startsWith(pkg)) {
                    output.add(cls);
                }
            }
        }
    }

    Map<String, Path> paths = new HashMap<>();
    swagger.setPaths(paths);
    Map<String, Model> definitions = new HashMap<>();
    swagger.setDefinitions(definitions);
    Stack<Class<?>> modelStack = new Stack<>();
    for (Class<?> controller : controllers) {
        List<String> clazzPaths = new ArrayList<>();
        RequestMapping clazzRequestMapping = controller.getDeclaredAnnotation(RequestMapping.class);
        Api api = controller.getDeclaredAnnotation(Api.class);
        if (clazzRequestMapping != null) {
            clazzPaths = lookPaths(clazzRequestMapping);
        }
        if (clazzPaths.isEmpty()) {
            clazzPaths.add("");
        }
        if (api != null) {
            if (!"".equals(api.description())) {
                for (String name : api.tags()) {
                    if (!"".equals(name)) {
                        io.swagger.models.Tag tag = new io.swagger.models.Tag();
                        tag.setDescription(api.description());
                        tag.setName(name);
                        swagger.addTag(tag);
                    }
                }
            }
        } else {
            io.swagger.models.Tag tag = new io.swagger.models.Tag();
            tag.setDescription("Unknown");
            tag.setName("Unknown");
            swagger.addTag(tag);
        }
        Method[] methods = null;
        try {
            methods = controller.getDeclaredMethods();
        } catch (NoClassDefFoundError e) {
        }
        if (methods != null && methods.length > 0) {
            for (Method method : methods) {
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                ApiResponses apiResponses = method.getAnnotation(ApiResponses.class);
                ApiHeaders apiHeaders = method.getAnnotation(ApiHeaders.class);
                List<String> methodPaths = new ArrayList<>();
                if (requestMapping != null && apiOperation != null && apiResponses != null) {
                    methodPaths = lookPaths(requestMapping);
                }
                if (methodPaths.isEmpty()) {
                    methodPaths.add("");
                }
                if (requestMapping != null && apiOperation != null && apiResponses != null) {
                    for (String classPath : clazzPaths) {
                        for (String methodPath : methodPaths) {
                            RequestMethod[] requestMethods = requestMapping.method();
                            if (requestMethods == null || requestMethods.length == 0) {
                                requestMethods = RequestMethod.values();
                            }
                            Path path = new Path();
                            paths.put(classPath + methodPath, path);
                            for (RequestMethod requestMethod : requestMethods) {
                                Operation operation = new Operation();
                                operation.setDescription(apiOperation.description());
                                for (String consume : requestMapping.consumes()) {
                                    operation.addConsumes(consume);
                                }
                                for (String produce : requestMapping.produces()) {
                                    operation.addProduces(produce);
                                }
                                if (api != null) {
                                    if (!"".equals(api.description())) {
                                        for (String name : api.tags()) {
                                            if (!"".equals(name)) {
                                                operation.addTag(name);
                                            }
                                        }
                                    }
                                } else {
                                    io.swagger.models.Tag tag = new io.swagger.models.Tag();
                                    operation.addTag("Unknown");
                                }

                                if (requestMethod == RequestMethod.DELETE) {
                                    path.delete(operation);
                                } else if (requestMethod == RequestMethod.GET) {
                                    path.get(operation);
                                } else if (requestMethod == RequestMethod.HEAD) {
                                    path.head(operation);
                                } else if (requestMethod == RequestMethod.OPTIONS) {
                                    path.options(operation);
                                } else if (requestMethod == RequestMethod.PATCH) {
                                    path.patch(operation);
                                } else if (requestMethod == RequestMethod.POST) {
                                    path.post(operation);
                                } else if (requestMethod == RequestMethod.PUT) {
                                    path.put(operation);
                                }

                                if (apiHeaders != null && apiHeaders.value() != null
                                        && apiHeaders.value().length > 0) {
                                    for (ApiHeader header : apiHeaders.value()) {
                                        HeaderParameter parameter = new HeaderParameter();
                                        parameter.setName(header.name());
                                        parameter.setType("string");
                                        parameter.setDescription(header.description());
                                        parameter.setRequired(header.required());
                                        operation.addParameter(parameter);
                                    }
                                }

                                for (Parameter parameter : method.getParameters()) {
                                    PathVariable pathVariable = parameter.getAnnotation(PathVariable.class);
                                    RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
                                    RequestBody requestBody = parameter.getAnnotation(RequestBody.class);
                                    RequestPart requestPart = parameter.getAnnotation(RequestPart.class);
                                    ApiParam apiParam = parameter.getAnnotation(ApiParam.class);
                                    if (apiParam != null && pathVariable != null
                                            && isSimpleScalar(parameter.getType())) {
                                        PathParameter pathParameter = new PathParameter();
                                        pathParameter.setRequired(true);
                                        pathParameter.setDescription(apiParam.description());
                                        pathParameter.setType(lookupType(parameter.getType()));
                                        pathParameter.setFormat(lookupFormat(parameter.getType(), apiParam));
                                        pathParameter.setName(pathVariable.value());
                                        operation.addParameter(pathParameter);
                                        continue;
                                    }

                                    if (requestMethod == RequestMethod.DELETE
                                            || requestMethod == RequestMethod.GET
                                            || requestMethod == RequestMethod.HEAD
                                            || requestMethod == RequestMethod.OPTIONS
                                            || requestMethod == RequestMethod.PATCH
                                            || requestMethod == RequestMethod.PUT) {
                                        if (apiParam != null && requestParam != null
                                                && isSimpleArray(parameter.getType())) {
                                            QueryParameter param = new QueryParameter();
                                            param.setRequired(requestParam.required());
                                            param.setDescription(apiParam.description());
                                            param.setType("array");
                                            if (!"".equals(requestParam.value())) {
                                                param.setName(requestParam.value());
                                            }
                                            if (!"".equals(requestParam.name())) {
                                                param.setName(requestParam.name());
                                            }
                                            param.setItems(lookupProperty(parameter.getType(), requestParam,
                                                    apiParam));
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestParam != null
                                                && isSimpleScalar(parameter.getType())) {
                                            QueryParameter param = new QueryParameter();
                                            param.setRequired(requestParam.required());
                                            param.setDescription(apiParam.description());
                                            param.setType(lookupType(parameter.getType()));
                                            param.setFormat(lookupFormat(parameter.getType(), apiParam));
                                            if (!"".equals(requestParam.value())) {
                                                param.setName(requestParam.value());
                                            }
                                            if (!"".equals(requestParam.name())) {
                                                param.setName(requestParam.name());
                                            }
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestBody != null
                                                && parameter.getType() == MultipartFile.class) {
                                            FormParameter param = new FormParameter();
                                            param.setRequired(true);
                                            param.setIn("body");
                                            param.setName("body");
                                            param.setType("file");
                                            param.setDescription(apiParam.description());
                                            operation.addConsumes("application/octet-stream");
                                            //                                                BodyParameter param = new BodyParameter();
                                            //                                                param.setRequired(requestBody.required());
                                            //                                                param.setDescription(apiParam.description());
                                            //                                                param.setName("body");
                                            //                                                ModelImpl model = new ModelImpl();
                                            //                                                model.setType("file");
                                            //                                                param.setSchema(model);
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestBody != null
                                                && isSimpleArray(parameter.getType())) {
                                            BodyParameter param = new BodyParameter();
                                            param.setRequired(requestBody.required());
                                            param.setDescription(apiParam.description());
                                            param.setName("body");
                                            ArrayModel model = new ArrayModel();
                                            StringProperty property = new StringProperty();
                                            property.setType(lookupType(parameter.getType()));
                                            property.setFormat(lookupFormat(parameter.getType(), apiParam));
                                            model.setItems(property);
                                            param.setSchema(model);
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestBody != null
                                                && isSimpleScalar(parameter.getType())) {
                                            BodyParameter param = new BodyParameter();
                                            param.setRequired(requestBody.required());
                                            param.setDescription(apiParam.description());
                                            param.setName("body");
                                            ModelImpl model = new ModelImpl();
                                            model.setType(lookupType(parameter.getType()));
                                            model.setFormat(lookupFormat(parameter.getType(), apiParam));
                                            param.setSchema(model);
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestBody != null
                                                && isModelArray(parameter.getType())) {
                                            BodyParameter param = new BodyParameter();
                                            param.setRequired(requestBody.required());
                                            param.setDescription(apiParam.description());
                                            param.setName("body");
                                            ArrayModel model = new ArrayModel();
                                            RefProperty property = new RefProperty();
                                            property.setType(lookupType(parameter.getType()));
                                            property.set$ref("#/definitions/"
                                                    + parameter.getType().getComponentType().getSimpleName());
                                            if (!modelStack.contains(parameter.getType().getComponentType())) {
                                                modelStack.push(parameter.getType().getComponentType());
                                            }
                                            model.setItems(property);
                                            param.setSchema(model);
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestBody != null
                                                && isModelScalar(parameter.getType())) {
                                            BodyParameter param = new BodyParameter();
                                            param.setRequired(requestBody.required());
                                            param.setDescription(apiParam.description());
                                            param.setName("body");
                                            RefModel model = new RefModel();
                                            model.set$ref(
                                                    "#/definitions/" + parameter.getType().getSimpleName());
                                            if (!modelStack.contains(parameter.getType())) {
                                                modelStack.push(parameter.getType());
                                            }
                                            param.setSchema(model);
                                            operation.addParameter(param);
                                            continue;
                                        }
                                    } else if (requestMethod == RequestMethod.POST) {
                                        if (apiParam != null && requestParam != null
                                                && isSimpleArray(parameter.getType())) {
                                            FormParameter param = new FormParameter();
                                            param.setRequired(requestParam.required());
                                            param.setDescription(apiParam.description());
                                            param.setType("array");
                                            if (!"".equals(requestParam.value())) {
                                                param.setName(requestParam.value());
                                            }
                                            if (!"".equals(requestParam.name())) {
                                                param.setName(requestParam.name());
                                            }
                                            param.setItems(lookupProperty(parameter.getType(), requestParam,
                                                    apiParam));
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestParam != null
                                                && isSimpleScalar(parameter.getType())) {
                                            FormParameter param = new FormParameter();
                                            param.setRequired(requestParam.required());
                                            param.setDescription(apiParam.description());
                                            param.setType(lookupType(parameter.getType()));
                                            param.setFormat(lookupFormat(parameter.getType(), apiParam));
                                            if (!"".equals(requestParam.value())) {
                                                param.setName(requestParam.value());
                                            }
                                            if (!"".equals(requestParam.name())) {
                                                param.setName(requestParam.name());
                                            }
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestPart != null
                                                && isSimpleArray(parameter.getType())) {
                                            FormParameter param = new FormParameter();
                                            param.setRequired(requestPart.required());
                                            param.setDescription(apiParam.description());
                                            param.setType("array");
                                            if (!"".equals(requestPart.value())) {
                                                param.setName(requestPart.value());
                                            }
                                            if (!"".equals(requestPart.name())) {
                                                param.setName(requestPart.name());
                                            }
                                            param.setItems(lookupProperty(parameter.getType(), requestParam,
                                                    apiParam));
                                            operation.addParameter(param);
                                            continue;
                                        }
                                        if (apiParam != null && requestPart != null
                                                && isSimpleScalar(parameter.getType())) {
                                            FormParameter param = new FormParameter();
                                            param.setRequired(requestPart.required());
                                            param.setDescription(apiParam.description());
                                            param.setType(lookupType(parameter.getType()));
                                            param.setFormat(lookupFormat(parameter.getType(), apiParam));
                                            if (!"".equals(requestPart.value())) {
                                                param.setName(requestPart.value());
                                            }
                                            if (!"".equals(requestPart.name())) {
                                                param.setName(requestPart.name());
                                            }
                                            operation.addParameter(param);
                                            continue;
                                        }
                                    }
                                }

                                for (ApiResponse apiResponse : apiResponses.value()) {
                                    if (isSimpleScalar(apiResponse.response())) {
                                        if (apiResponse.array()) {
                                            Response response = new Response();
                                            if (!"".equals(apiResponse.description())) {
                                                response.setDescription(
                                                        apiResponse.httpStatus().getReasonPhrase());
                                            } else {
                                                response.setDescription(apiResponse.description());
                                            }
                                            ArrayProperty property = new ArrayProperty();
                                            property.setItems(
                                                    lookupProperty(apiResponse.response(), apiResponse));
                                            response.setSchema(property);
                                            operation.addResponse(
                                                    String.valueOf(apiResponse.httpStatus().value()), response);
                                        } else {
                                            Response response = new Response();
                                            if ("".equals(apiResponse.description())) {
                                                response.setDescription(
                                                        apiResponse.httpStatus().getReasonPhrase());
                                            } else {
                                                response.setDescription(apiResponse.description());
                                            }
                                            response.setSchema(
                                                    lookupProperty(apiResponse.response(), apiResponse));
                                            operation.addResponse(
                                                    String.valueOf(apiResponse.httpStatus().value()), response);
                                        }
                                    } else if (isModelScalar(apiResponse.response())) {
                                        if (apiResponse.array()) {
                                            Response response = new Response();
                                            if (!"".equals(apiResponse.description())) {
                                                response.setDescription(
                                                        apiResponse.httpStatus().getReasonPhrase());
                                            } else {
                                                response.setDescription(apiResponse.description());
                                            }
                                            RefProperty property = new RefProperty();
                                            property.set$ref(
                                                    "#/definitions/" + apiResponse.response().getSimpleName());
                                            if (!modelStack.contains(apiResponse.response())) {
                                                modelStack.push(apiResponse.response());
                                            }
                                            ArrayProperty array = new ArrayProperty();
                                            array.setItems(property);
                                            response.setSchema(array);
                                            operation.addResponse(
                                                    String.valueOf(apiResponse.httpStatus().value()), response);
                                        } else {
                                            Response response = new Response();
                                            if (!"".equals(apiResponse.description())) {
                                                response.setDescription(
                                                        apiResponse.httpStatus().getReasonPhrase());
                                            } else {
                                                response.setDescription(apiResponse.description());
                                            }
                                            RefProperty property = new RefProperty();
                                            property.set$ref(
                                                    "#/definitions/" + apiResponse.response().getSimpleName());
                                            if (!modelStack.contains(apiResponse.response())) {
                                                modelStack.push(apiResponse.response());
                                            }
                                            response.setSchema(property);
                                            operation.addResponse(
                                                    String.valueOf(apiResponse.httpStatus().value()), response);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    while (!modelStack.isEmpty()) {
        Class<?> scheme = modelStack.pop();
        if (definitions.containsKey(scheme.getSimpleName())) {
            continue;
        }
        java.lang.reflect.Field[] fields = scheme.getDeclaredFields();
        if (fields != null && fields.length > 0) {
            ModelImpl model = new ModelImpl();
            model.setType("object");
            for (Field field : fields) {
                ApiProperty apiProperty = field.getDeclaredAnnotation(ApiProperty.class);
                if (apiProperty != null) {
                    if (apiProperty.array()) {
                        Class<?> type = apiProperty.model();
                        ArrayProperty property = new ArrayProperty();
                        if (isSimpleScalar(type)) {
                            property.setItems(lookupProperty(type, apiProperty));
                        } else if (isModelScalar(type)) {
                            if (!definitions.containsKey(type.getSimpleName())) {
                                modelStack.push(type);
                            }
                            RefProperty ref = new RefProperty();
                            ref.set$ref("#/definitions/" + type.getSimpleName());
                            property.setItems(ref);
                        }
                        model.addProperty(field.getName(), property);
                    } else {
                        Class<?> type = field.getType();
                        if (isSimpleScalar(type)) {
                            model.addProperty(field.getName(), lookupProperty(type, apiProperty));
                        } else if (isModelScalar(type)) {
                            if (!definitions.containsKey(type.getSimpleName())) {
                                modelStack.push(type);
                            }
                            RefProperty ref = new RefProperty();
                            ref.set$ref("#/definitions/" + type.getSimpleName());
                            model.addProperty(field.getName(), ref);
                        }
                    }
                }
            }
            definitions.put(scheme.getSimpleName(), model);
        }
    }

    this.swagger = swagger;
}

From source file:com.evolveum.midpoint.prism.schema.SchemaRegistryImpl.java

@Override
public PrismSchema findSchemaByCompileTimeClass(@NotNull Class<?> compileTimeClass) {
    Package compileTimePackage = compileTimeClass.getPackage();
    if (compileTimePackage == null) {
        return null; // e.g. for arrays
    }// w  w w .j a v  a 2 s .c om
    for (SchemaDescription desc : schemaDescriptions) {
        if (compileTimePackage.equals(desc.getCompileTimeClassesPackage())) {
            return desc.getSchema();
        }
    }
    return null;
}