<commit_before>/*
 * Copyright (C) 2015 Systematic A/S
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.systematic.healthcare.fhir.generator;

import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.dstu2.composite.BoundCodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.ElementDefinitionDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.resource.StructureDefinition;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.util.ElementUtil;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.FluentIterable;
import org.apache.commons.lang3.StringUtils;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.Type;
import org.jboss.forge.roaster.model.source.*;

import javax.annotation.Nullable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;

import static org.reflections.ReflectionUtils.getAllFields;
import static org.reflections.ReflectionUtils.withAnnotation;

public class Generator {

    private static final String DSTU2_PACKAGE = "ca.uhn.fhir.model.dstu2";
    private static final String DSTU2_RESOURCE_PACKAGE = DSTU2_PACKAGE + ".resource";
    private static final String DSTU2_COMPOSITE_PACKAGE = DSTU2_PACKAGE + ".composite";
    private static final String DSTU2_PRIMITIVE_PACKAGE = "ca.uhn.fhir.model.primitive";
    public static final String HL7_FHIR_REFERENCE_URL_START = "http://hl7.org/fhir";

    public JavaClassSource convertDefinitionToJavaFile(StructureDefinitionProvider resolver) throws Exception {
        StructureDefinition def = resolver.getDefinition();
        final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
        Class<?> classType = Class.forName(DSTU2_RESOURCE_PACKAGE + "." + def.getConstrainedType());
        javaClass.setPackage(resolver.getOutPackage()).setName(convertNameToValidJavaIdentifier(def.getName())).extendSuperType(classType);
        addClassResourceDefAnnotation(def, javaClass);

        Set<Field> fields = getAllFields(classType, withAnnotation(Child.class));
        Map<String, Field> nameToField = new HashMap<>();
        for (Field f : fields) {
            Child annotation = f.getAnnotation(Child.class);
            nameToField.put(annotation.name(), f);
        }

        StructureDefinition.Differential dif = def.getDifferential();
        List<ElementDefinitionDt> elements = dif.getElement();
        for (ElementDefinitionDt element : elements) {
            if (element.getPath().indexOf('.') != -1) {
                //Element name is (path minus the constrained name). E.g. Path for field Subject on Observations is Observation.subject, which we resolve to subject
                String elementName = element.getPath().substring(def.getConstrainedType().length() + 1);
                if (elementName.endsWith("[x]")) {
                    elementName = elementName.substring(0, elementName.indexOf("[x]"));
                }
                if (elementName.equals("extension")) {
                    addExtensionField(javaClass, element, resolver);
                } else {
                    addField(javaClass, nameToField, element, elementName);
                }
            }
        }
        addSliceFields(resolver, javaClass);
        List<FieldSource<JavaClassSource>> allFields = new ArrayList<>();
        allFields.addAll(existingFieldsChanged);
        allFields.addAll(extensionFieldsAdded);
        addIsEmptyMethod(javaClass, allFields);
        addSettersAndGettersForFields(javaClass, existingFieldsChanged, false);
        addSettersAndGettersForFields(javaClass, extensionFieldsAdded, true);
        return javaClass;
    }

    private void addSettersAndGettersForFields(JavaClassSource javaClass, List<FieldSource<JavaClassSource>> fieldsAdded, boolean isExtension) {
        for (FieldSource<JavaClassSource> field : fieldsAdded) {
            String fieldName = StringUtils.capitalize(field.getName().substring(2)); // Remove my
            String type = field.getType().getName();
            String genericTypes = Joiner.on(',').join(FluentIterable.from(field.getType().getTypeArguments()).transform(new Function<Type<JavaClassSource>, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Type<JavaClassSource> input) {
                    return input.getName();
                }
            }));
            String getFieldName = fieldName;
            String fieldTypeName = field.getType().getName();
            if (fieldTypeName.equals("DateDt") || fieldTypeName.equals("StringDt") || fieldTypeName.equals("BoundCodeDt") || fieldTypeName.equals("BoundCodeableConceptDt")) {
                getFieldName = getFieldName + "Element";
            }
            String bodyGet = "return " + field.getName() + ";";
            if (field.getType().isType(List.class)) {
                bodyGet = "if (" + field.getName() + " == null) {\n" +
                        "   " + field.getName() + " = new java.util.ArrayList<>();\n" +
                        "}\n" +
                        bodyGet;

                type = type + "<" + genericTypes + ">";
            }
            MethodSource<JavaClassSource> methodGet = javaClass.addMethod().setName("get" + getFieldName).setPublic().setReturnType(type).setBody(bodyGet);
            if (!isExtension) {
                methodGet.addAnnotation(Override.class);
            }

            String bodySet = field.getName() + " = theValue;\nreturn this;";
            MethodSource<JavaClassSource> methodSet = javaClass.addMethod().setName("set" + fieldName).setPublic()
                    .setReturnType(javaClass.getName()).setBody(bodySet);
            methodSet.addParameter(type, "theValue");
            if (!isExtension) {
                // TODO: add support for overrride
                //methodSet.addAnnotation(Override.class);
            }
            AnnotationSource<JavaClassSource> childAnnotation = field.getAnnotation(Child.class);
            String min = childAnnotation.getStringValue("min");
            String max = childAnnotation.getStringValue("max");
            if ("0".equals(min) && "0".equals(max)) {
                field.addAnnotation(Deprecated.class);
                // TODO: add deprecation on getter and setter.
                //methodGet.addAnnotation(Deprecated.class);
                //methodSet.addAnnotation(Deprecated.class);
            }

        }
    }

    private void addIsEmptyMethod(JavaClassSource javaClass, List<FieldSource<JavaClassSource>> fieldsAdded) {
        String types = Joiner.on(',').join(FluentIterable.from(fieldsAdded).transform(new FieldSourceGetNameFunction()));<commit_msg>Add support for deprecation of fields<commit_after>/*
 * Copyright (C) 2015 Systematic A/S
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.systematic.healthcare.fhir.generator;

import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.dstu2.composite.BoundCodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.ElementDefinitionDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.resource.StructureDefinition;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.util.ElementUtil;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.FluentIterable;
import org.apache.commons.lang3.StringUtils;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.Type;
import org.jboss.forge.roaster.model.source.*;

import javax.annotation.Nullable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;

import static org.reflections.ReflectionUtils.getAllFields;
import static org.reflections.ReflectionUtils.withAnnotation;

public class Generator {

    private static final String DSTU2_PACKAGE = "ca.uhn.fhir.model.dstu2";
    private static final String DSTU2_RESOURCE_PACKAGE = DSTU2_PACKAGE + ".resource";
    private static final String DSTU2_COMPOSITE_PACKAGE = DSTU2_PACKAGE + ".composite";
    private static final String DSTU2_PRIMITIVE_PACKAGE = "ca.uhn.fhir.model.primitive";
    public static final String HL7_FHIR_REFERENCE_URL_START = "http://hl7.org/fhir";

    public JavaClassSource convertDefinitionToJavaFile(StructureDefinitionProvider resolver) throws Exception {
        StructureDefinition def = resolver.getDefinition();
        final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
        Class<?> classType = Class.forName(DSTU2_RESOURCE_PACKAGE + "." + def.getConstrainedType());
        javaClass.setPackage(resolver.getOutPackage()).setName(convertNameToValidJavaIdentifier(def.getName())).extendSuperType(classType);
        addClassResourceDefAnnotation(def, javaClass);

        Set<Field> fields = getAllFields(classType, withAnnotation(Child.class));
        Map<String, Field> nameToField = new HashMap<>();
        for (Field f : fields) {
            Child annotation = f.getAnnotation(Child.class);
            nameToField.put(annotation.name(), f);
        }

        StructureDefinition.Differential dif = def.getDifferential();
        List<ElementDefinitionDt> elements = dif.getElement();
        for (ElementDefinitionDt element : elements) {
            if (element.getPath().indexOf('.') != -1) {
                //Element name is (path minus the constrained name). E.g. Path for field Subject on Observations is Observation.subject, which we resolve to subject
                String elementName = element.getPath().substring(def.getConstrainedType().length() + 1);
                if (elementName.endsWith("[x]")) {
                    elementName = elementName.substring(0, elementName.indexOf("[x]"));
                }
                if (elementName.equals("extension")) {
                    addExtensionField(javaClass, element, resolver);
                } else {
                    addField(javaClass, nameToField, element, elementName);
                }
            }
        }
        addSliceFields(resolver, javaClass);
        List<FieldSource<JavaClassSource>> allFields = new ArrayList<>();
        allFields.addAll(existingFieldsChanged);
        allFields.addAll(extensionFieldsAdded);
        addIsEmptyMethod(javaClass, allFields);
        addSettersAndGettersForFields(javaClass, existingFieldsChanged, false);
        addSettersAndGettersForFields(javaClass, extensionFieldsAdded, true);
        return javaClass;
    }

    private void addSettersAndGettersForFields(JavaClassSource javaClass, List<FieldSource<JavaClassSource>> fieldsAdded, boolean isExtension) {
        for (FieldSource<JavaClassSource> field : fieldsAdded) {
            String fieldName = StringUtils.capitalize(field.getName().substring(2)); // Remove my
            String type = field.getType().getName();
            String genericTypes = Joiner.on(',').join(FluentIterable.from(field.getType().getTypeArguments()).transform(new Function<Type<JavaClassSource>, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Type<JavaClassSource> input) {
                    return input.getName();
                }
            }));
            String getFieldName = fieldName;
            String fieldTypeName = field.getType().getName();
            if (fieldTypeName.equals("DateDt") || fieldTypeName.equals("StringDt") || fieldTypeName.equals("BoundCodeDt") || fieldTypeName.equals("BoundCodeableConceptDt")) {
                getFieldName = getFieldName + "Element";
            }
            String bodyGet = "return " + field.getName() + ";";
            if (field.getType().isType(List.class)) {
                bodyGet = "if (" + field.getName() + " == null) {\n" +
                        "   " + field.getName() + " = new java.util.ArrayList<>();\n" +
                        "}\n" +
                        bodyGet;

                type = type + "<" + genericTypes + ">";
            }
            MethodSource<JavaClassSource> methodGet = javaClass.addMethod().setName("get" + getFieldName).setPublic().setReturnType(type).setBody(bodyGet);
            if (!isExtension) {
                // TODO: add support for overrride
                //methodGet.addAnnotation(Override.class);
            }

            String bodySet = field.getName() + " = theValue;\nreturn this;";
            MethodSource<JavaClassSource> methodSet = javaClass.addMethod().setName("set" + fieldName).setPublic()
                    .setReturnType(javaClass.getName()).setBody(bodySet);
            methodSet.addParameter(type, "theValue");
            if (!isExtension) {
                methodSet.addAnnotation(Override.class);
            }
            AnnotationSource<JavaClassSource> childAnnotation = field.getAnnotation(Child.class);
            String min = childAnnotation.getStringValue("min");
            String max = childAnnotation.getStringValue("max");
            if ("0".equals(min) && "0".equals(max)) {
                field.addAnnotation(Deprecated.class);
                // TODO: add deprecation on getter and setter.
                //methodGet.addAnnotation(Deprecated.class);
                //methodSet.addAnnotation(Deprecated.class);
            }

        }
    }

    private void addIsEmptyMethod(JavaClassSource javaClass, List<FieldSource<JavaClassSource>> fieldsAdded) {
        String types = Joiner.on(',').join(FluentIterable.from(fieldsAdded).transform(new FieldSourceGetNameFunction()));
{'fraction_non_alphanumeric': 0.11134592524105139, 'fraction_numerical': 0.0038304054946506406, 'mean_word_length': 2.972455403987408, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2017787', 'n_tokens_mistral': 4158, 'n_tokens_neox': 4044, 'n_words': 822}