Example usage for org.apache.commons.lang StringUtils trimToNull

List of usage examples for org.apache.commons.lang StringUtils trimToNull

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils trimToNull.

Prototype

public static String trimToNull(String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null.

Usage

From source file:adalid.util.i18n.Merger.java

private static String locale(String name) {
    String substringBeforeLast = StringUtils.substringBeforeLast(name, ".");
    String substringAfter = StringUtils.substringAfter(substringBeforeLast, "_");
    return StringUtils.trimToNull(substringAfter);
}

From source file:net.sf.eclipsecs.core.config.ConfigurationWriter.java

/**
 * Writes a module to the transformer handler.
 *
 * @param module//  w  w w  . j a  v a  2 s.c  o  m
 *            the module to write
 * @param parent
 *            the parent element
 * @param parentSeverity
 *            the severity of the parent module
 * @param remainingModules
 *            the list of remaining (possibly child) modules
 */
private static void writeModule(Module module, Branch parent, Severity parentSeverity,
        List<Module> remainingModules) {

    Severity severity = parentSeverity;

    // remove this module from the list of modules to write
    remainingModules.remove(module);

    List<Module> childs = getChildModules(module, remainingModules);

    // Start the module
    Element moduleEl = parent.addElement(XMLTags.MODULE_TAG);
    moduleEl.addAttribute(XMLTags.NAME_TAG, module.getMetaData().getInternalName());

    // Write comment
    if (StringUtils.trimToNull(module.getComment()) != null) {

        Element metaEl = moduleEl.addElement(XMLTags.METADATA_TAG);
        metaEl.addAttribute(XMLTags.NAME_TAG, XMLTags.COMMENT_ID);
        metaEl.addAttribute(XMLTags.VALUE_TAG, module.getComment());
    }

    // Write severity only if it differs from the parents severity
    if (module.getSeverity() != null && !Severity.inherit.equals(module.getSeverity())) {

        Element propertyEl = moduleEl.addElement(XMLTags.PROPERTY_TAG);
        propertyEl.addAttribute(XMLTags.NAME_TAG, XMLTags.SEVERITY_TAG);
        propertyEl.addAttribute(XMLTags.VALUE_TAG, module.getSeverity().name());

        // set the parent severity for child modules
        severity = module.getSeverity();
    }

    // write module id
    if (StringUtils.trimToNull(module.getId()) != null) {

        Element propertyEl = moduleEl.addElement(XMLTags.PROPERTY_TAG);
        propertyEl.addAttribute(XMLTags.NAME_TAG, XMLTags.ID_TAG);
        propertyEl.addAttribute(XMLTags.VALUE_TAG, module.getId());
    }

    // write properties of the module
    for (ConfigProperty property : module.getProperties()) {

        // write property only if it differs from the default value
        String value = StringUtils.trimToNull(property.getValue());
        if (value != null && !ObjectUtils.equals(value, property.getMetaData().getDefaultValue())) {

            Element propertyEl = moduleEl.addElement(XMLTags.PROPERTY_TAG);
            propertyEl.addAttribute(XMLTags.NAME_TAG, property.getMetaData().getName());
            propertyEl.addAttribute(XMLTags.VALUE_TAG, property.getValue());
        }
    }

    // write custom messages
    for (Map.Entry<String, String> entry : module.getCustomMessages().entrySet()) {

        Element metaEl = moduleEl.addElement(XMLTags.MESSAGE_TAG);
        metaEl.addAttribute(XMLTags.KEY_TAG, entry.getKey());
        metaEl.addAttribute(XMLTags.VALUE_TAG, entry.getValue());
    }

    // write custom metadata
    for (Map.Entry<String, String> entry : module.getCustomMetaData().entrySet()) {

        Element metaEl = moduleEl.addElement(XMLTags.METADATA_TAG);
        metaEl.addAttribute(XMLTags.NAME_TAG, entry.getKey());
        metaEl.addAttribute(XMLTags.VALUE_TAG, entry.getValue());
    }

    // Write last enabled severity level
    if (module.getLastEnabledSeverity() != null) {

        Element metaEl = moduleEl.addElement(XMLTags.METADATA_TAG);
        metaEl.addAttribute(XMLTags.NAME_TAG, XMLTags.LAST_ENABLED_SEVERITY_ID);
        metaEl.addAttribute(XMLTags.VALUE_TAG, module.getLastEnabledSeverity().name());
    }

    // write child modules recursivly
    for (Module child : childs) {
        writeModule(child, moduleEl, severity, remainingModules);
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java

private String getExpectedMediaType(HttpServletRequest request) {
    String mediaType = null;//  w  w w  .  ja va 2  s.c o  m
    String acceptHeader = request.getHeader("Accept");
    if (acceptHeader != null) {
        mediaType = StringUtils
                .trimToNull(MIMEParse.bestMatch(Collections.singleton(MEDIA_TYPE_JSON), acceptHeader));
    }

    return mediaType;
}

From source file:eionet.meta.imp.VocabularyCSVImportHandler.java

/**
 * In this method, beans are generated (either created or updated) according to values in CSV file.
 *
 * @throws eionet.meta.service.ServiceException
 *             if there is the input is invalid
 *///from  w w  w .j av  a2s.c  om
public void generateUpdatedBeans() throws ServiceException {
    // content.
    CSVReader reader = new CSVReader(this.content);
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    try {
        String[] header = reader.readNext();

        // first check if headers contains fix columns
        String[] fixedHeaders = new String[VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT];
        VocabularyCSVOutputHelper.addFixedEntryHeaders(fixedHeaders);

        // compare if it has URI
        boolean isEqual = StringUtils.equalsIgnoreCase(header[VocabularyCSVOutputHelper.URI_INDEX],
                fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX]);

        if (!isEqual) {
            reader.close();
            throw new ServiceException("Missing header! CSV file should start with header: '"
                    + fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX] + "'");
        }

        List<String> fixedHeadersList = new ArrayList<String>(
                Arrays.asList(Arrays.copyOf(fixedHeaders, VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT)));
        // remove uri from header
        fixedHeadersList.remove(VocabularyCSVOutputHelper.URI_INDEX);
        Map<String, Integer> fixedHeaderIndices = new HashMap<String, Integer>();
        for (int i = VocabularyCSVOutputHelper.URI_INDEX + 1; i < header.length; i++) {
            String elementHeader = StringUtils.trimToNull(header[i]);
            if (StringUtils.isBlank(elementHeader)) {
                throw new ServiceException("Header for column (" + (i + 1) + ") is empty!");
            }

            int headerIndex = -1;
            boolean headerFound = false;
            for (headerIndex = 0; headerIndex < fixedHeadersList.size(); headerIndex++) {
                if (StringUtils.equalsIgnoreCase(elementHeader, fixedHeadersList.get(headerIndex))) {
                    headerFound = true;
                    break;
                }
            }

            // if it is a fixed header value (concept property), add to map and continue
            if (headerFound) {
                String headerValue = fixedHeadersList.remove(headerIndex);
                fixedHeaderIndices.put(headerValue, i);
                continue;
            }

            // it is not a concept attribute and but a data element identifier
            // if there is language appended, split it
            String[] tempStrArray = elementHeader.split("[@]");
            if (tempStrArray.length == 2) {
                elementHeader = tempStrArray[0];
            }

            // if bound elements do not contain header already, add it (if possible)
            if (!this.boundElementsIds.containsKey(elementHeader)) {
                // search for data element
                this.elementsFilter.setIdentifier(elementHeader);
                DataElementsResult elementsResult = this.dataService.searchDataElements(this.elementsFilter);
                // if there is one and only one element check if header and identifer exactly matches!
                if (elementsResult.getTotalResults() < 1) {
                    throw new ServiceException("Cannot find any data element for column: " + elementHeader
                            + ". Please bind element manually then upload CSV.");
                } else if (elementsResult.getTotalResults() > 1) {
                    throw new ServiceException("Cannot find single data element for column: " + elementHeader
                            + ". Search returns: " + elementsResult.getTotalResults()
                            + " elements. Please bind element manually then upload CSV.");
                } else {
                    DataElement elem = elementsResult.getDataElements().get(0);
                    if (StringUtils.equals(elementHeader, elem.getIdentifier())) {
                        // found it, add to list and map
                        this.boundElementsIds.put(elementHeader,
                                elementsResult.getDataElements().get(0).getId());
                        this.newBoundElement.add(elem);
                    } else {
                        throw new ServiceException("Found data element did not EXACTLY match with column: "
                                + elementHeader + ", found: " + elem.getIdentifier());
                    }
                }
            }
        } // end of for loop iterating on headers

        String[] lineParams;
        // first row is header so start from 2
        for (int rowNumber = 2; (lineParams = reader.readNext()) != null; rowNumber++) {
            if (lineParams.length != header.length) {
                StringBuilder message = new StringBuilder();
                message.append("Row (").append(rowNumber).append(") ");
                message.append("did not have same number of columns with header, it was skipped.");
                message.append(" It should have have same number of columns (empty or filled).");
                this.logMessages.add(message.toString());
                continue;
            }

            // do line processing
            String uri = lineParams[VocabularyCSVOutputHelper.URI_INDEX];
            if (StringUtils.isEmpty(uri)) {
                this.logMessages.add("Row (" + rowNumber + ") was skipped (Base URI was empty).");
                continue;
            } else if (StringUtils.startsWith(uri, "//")) {
                this.logMessages.add("Row (" + rowNumber
                        + ") was skipped (Concept was excluded by user from update operation).");
                continue;
            } else if (!StringUtils.startsWith(uri, this.folderContextRoot)) {
                this.logMessages
                        .add("Row (" + rowNumber + ") was skipped (Base URI did not match with Vocabulary).");
                continue;
            }

            String conceptIdentifier = uri.replace(this.folderContextRoot, "");
            if (StringUtils.contains(conceptIdentifier, "/") || !Util.isValidIdentifier(conceptIdentifier)) {
                this.logMessages.add("Row (" + rowNumber + ") did not contain a valid concept identifier.");
                continue;
            }

            // now we have a valid row
            Pair<VocabularyConcept, Boolean> foundConceptWithFlag = findOrCreateConcept(conceptIdentifier);

            // if vocabulary concept duplicated with another row, importer will ignore it not to repeat
            if (foundConceptWithFlag == null || foundConceptWithFlag.getRight()) {
                this.logMessages
                        .add("Row (" + rowNumber + ") duplicated with a previous concept, it was skipped.");
                continue;
            }

            VocabularyConcept lastFoundConcept = foundConceptWithFlag.getLeft();
            // vocabulary concept found or created
            this.toBeUpdatedConcepts.add(lastFoundConcept);

            Integer conceptPropertyIndex = null;
            // check label
            conceptPropertyIndex = fixedHeaderIndices.get(fixedHeaders[VocabularyCSVOutputHelper.LABEL_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setLabel(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check definition
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.DEFINITION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setDefinition(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check notation
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.NOTATION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setNotation(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // TODO: update - with merging flexible csv import
            // check start date
            // ignore status and accepteddate changes

            // now it is time iterate on rest of the columns, here is the tricky part
            List<DataElement> elementsOfConcept = null;
            List<DataElement> elementsOfConceptByLang = null;
            String prevHeader = null;
            String prevLang = null;
            for (int k = VocabularyCSVOutputHelper.URI_INDEX + 1; k < lineParams.length; k++) {
                if (StringUtils.isEmpty(lineParams[k])) {
                    // value is empty, no need to proceed
                    continue;
                }

                if (fixedHeaderIndices.containsValue(k)) {
                    // concept property, already handled
                    continue;
                }

                String elementHeader = header[k];
                String lang = null;
                String[] tempStrArray = elementHeader.split("[@]");
                if (tempStrArray.length == 2) {
                    elementHeader = tempStrArray[0];
                    lang = tempStrArray[1];
                }

                if (!StringUtils.equals(elementHeader, prevHeader)) {
                    elementsOfConcept = getDataElementValuesByName(elementHeader,
                            lastFoundConcept.getElementAttributes());
                    if (elementsOfConcept == null) {
                        elementsOfConcept = new ArrayList<DataElement>();
                        lastFoundConcept.getElementAttributes().add(elementsOfConcept);
                    }
                }

                if (!StringUtils.equals(elementHeader, prevHeader) || !StringUtils.equals(lang, prevLang)) {
                    elementsOfConceptByLang = getDataElementValuesByNameAndLang(elementHeader, lang,
                            lastFoundConcept.getElementAttributes());
                }

                prevLang = lang;
                prevHeader = elementHeader;

                VocabularyConcept foundRelatedConcept = null;
                if (Util.isValidUri(lineParams[k])) {
                    foundRelatedConcept = findRelatedConcept(lineParams[k]);
                }

                // check for pre-existence of the VCE by attribute value or related concept id
                Integer relatedId = null;
                if (foundRelatedConcept != null) {
                    relatedId = foundRelatedConcept.getId();
                }
                boolean returnFromThisPoint = false;
                for (DataElement elemByLang : elementsOfConceptByLang) {
                    String elementValueByLang = elemByLang.getAttributeValue();
                    if (StringUtils.equals(lineParams[k], elementValueByLang)) {
                        // vocabulary concept element already in database, no need to continue, return
                        returnFromThisPoint = true;
                        break;
                    }

                    if (relatedId != null) {
                        Integer relatedConceptId = elemByLang.getRelatedConceptId();
                        if (relatedConceptId != null && relatedConceptId.intValue() == relatedId.intValue()) {
                            // vocabulary concept element already in database, no need to continue, return
                            returnFromThisPoint = true;
                            break;
                        }
                    }
                }
                // check if an existing VCE found or not
                if (returnFromThisPoint) {
                    continue;
                }

                // create VCE
                DataElement elem = new DataElement();
                elementsOfConcept.add(elem);
                elem.setAttributeLanguage(lang);
                elem.setIdentifier(elementHeader);
                elem.setId(this.boundElementsIds.get(elementHeader));
                // check if there is a found related concept
                if (foundRelatedConcept != null) {
                    elem.setRelatedConceptIdentifier(foundRelatedConcept.getIdentifier());
                    int id = foundRelatedConcept.getId();
                    elem.setRelatedConceptId(id);
                    elem.setAttributeValue(null);
                    if (id < 0) {
                        addToElementsReferringNotCreatedConcepts(id, elem);
                    }
                } else {
                    elem.setAttributeValue(lineParams[k]);
                    elem.setRelatedConceptId(null);
                }
            } // end of for loop iterating on rest of the columns (for data elements)
        } // end of row iterator (while loop on rows)
        processUnseenConceptsForRelatedElements();
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sf.firemox.clickable.ability.Ability.java

/**
 * Create an instance of Ability//  w  w w. ja  v a 2 s  .c o  m
 * 
 * @param name
 *          Name of card used to display this ability in a stack
 * @param optimizer
 *          the optimizer to use.
 * @param priority
 *          the resolution type.
 * @param pictureName
 *          the picture name of this ability. If <code>null</code> the card
 *          picture will be used instead.
 */
protected Ability(String name, Optimization optimizer, Priority priority, String pictureName) {
    // name of this ability
    this.name = StringUtils.trimToNull(name);
    this.optimizer = optimizer;
    this.priority = priority;
    this.pictureName = pictureName;
}

From source file:com.bluexml.side.forms.generator.alfresco.chiba.FormGenerator.java

@Override
public void initialize(Map<String, String> generationParameters_, Map<String, Boolean> generatorOptions_,
        Map<String, String> configurationParameters_, DependencesManager dm, ComponentMonitor monitor)
        throws Exception {
    super.initialize(generationParameters_, generatorOptions_, configurationParameters_, dm, monitor);

    this.monitor = monitor;

    successfulInit = false;//from www . j av a  2s  .  c  o m
    setTEMP_FOLDER("generator_" + getClass().getName() + File.separator + defaultModelID);
    File webappFolder = new File(getTemporarySystemFile(), "webapps" + File.separator + webappName);
    xformGenerationFolder = new File(webappFolder.getAbsolutePath() + File.separator + "forms");
    String classesPathname = webappFolder.getAbsolutePath() + File.separator + "WEB-INF" + File.separator
            + "classes";
    mappingGenerationFolder = new File(classesPathname);

    FileUtils.forceMkdir(xformGenerationFolder);
    FileUtils.forceMkdir(mappingGenerationFolder);

    String baseDir = xformGenerationFolder.getAbsolutePath();
    String resDir = mappingGenerationFolder.getAbsolutePath();

    File generateMappingFile = new File(resDir + File.separator + "mapping.xml");
    File generateRedirectFile = new File(resDir + File.separator + "redirect.xml");
    File generateCSSFile = new File(resDir + File.separator + "styles.css");

    XFormsGenerator xformsGenerator = new XFormsGenerator();
    MappingGenerator mappingGenerator = new MappingGenerator();
    generators.add(mappingGenerator);
    generators.add(xformsGenerator);

    xformsGenerator.setOutputFolder(baseDir);
    mappingGenerator.setOutputMappingFile(generateMappingFile.getAbsolutePath());
    mappingGenerator.setOutputCSSFile(generateCSSFile.getAbsolutePath());
    mappingGenerator.setOutputRedirectFile(generateRedirectFile.getAbsolutePath());

    // deal with messages.properties file
    String messagesFilePath = generationParameters
            .get("com.bluexml.side.Form.generator.xforms.chiba.messagesFilePath");
    if (StringUtils.trimToNull(messagesFilePath) != null) {
        File file = new File(messagesFilePath);
        if (file.exists()) {
            setMessagesFilePath(messagesFilePath);
        } else {
            monitor.addWarningText("The specified messages file does not exist. Will generate defaults.");
            messagesFilePath = null;
        }
    }
    if (StringUtils.trimToNull(messagesFilePath) == null) {
        String filePath = classesPathname + File.separator + "messages.properties";
        if (DefaultMessages.generateMessagesFile(filePath)) {
            setMessagesFilePath(filePath);
        } else {
            monitor.addWarningText("Could not generate and set the messages file.");
        }
    }

    // generate the forms.properties file
    String filePath = resDir + File.separator + "forms.properties";

    if (DefaultMessages.generateFormsFile(filePath, generationParameters) == false) {
        monitor.addWarningText("Could not generate and set the 'forms.properties' file.");
    }

    // deal with the webapp address (protocol, host, port, context)
    webappContext = generationParameters.get(COM_BLUEXML_SIDE_FORM_GENERATOR_XFORMS_CHIBA_WEBAPP_CONTEXT);
    if (StringUtils.trimToNull(webappContext) != null) {
        // we check that the context is not 'forms'
        int pos = webappContext.lastIndexOf('/');
        int len = webappContext.length();
        // if there's a trailing "/", remove it
        if (pos == (len - 1)) {
            webappContext = webappContext.substring(0, len - 1);
        }
        len = webappContext.length();
        pos = webappContext.lastIndexOf('/');
        String context = webappContext.substring(pos + 1, len);
        if (context.equals("forms")) {
            throw new Exception("The context of your webapp SHOULD NOT be 'forms'!");
        }
    }
    successfulInit = true;
}

From source file:com.hmsinc.epicenter.classifier.util.ClassifierUtils.java

public static CharSequence filterAllowNumbers(final CharSequence complaint, final Set<String> stopwords) {
    String ret = "";
    if (complaint != null) {

        // Lowercase, alphabetic only, remove extra spaces..
        final String cleaned = StringUtils.trimToNull(complaint.toString().toLowerCase(Locale.getDefault())
                .replaceAll("h/a", "headache").replaceAll("n/v", "nausea vomiting").replaceAll("[/,]", " ")
                .replaceAll("[^a-z\\s\\d]", " "));

        if (cleaned != null) {

            final StringBuilder buf = new StringBuilder();

            final String[] sp = cleaned.split("\\s");

            for (int i = 0; i < sp.length; i++) {
                if (sp[i] != null && sp[i].length() > 1 && !stopwords.contains(sp[i])) {
                    if (buf.length() > 0) {
                        buf.append(" ");
                    }/*  ww  w.ja  v a  2s .  co  m*/
                    buf.append(sp[i]);
                }
            }
            if (buf.length() > 0) {
                ret = buf.toString();
            }
        }
    }
    return ret;
}

From source file:com.hmsinc.epicenter.integrator.service.PatientService.java

private PatientDetail parseDetails(final HL7Message message, final Patient patient) throws HL7Exception {

    final Terser t = message.getTerser();

    // Create new set of Details
    PatientDetail patientDetail = new PatientDetail();
    patientDetail.setPatient(patient);/*from w  w  w . jav  a2s .c o  m*/

    // Zipcode
    String zipcode = t.get("/PID-11-5");

    try {
        if (zipcode == null) {
            throw new InvalidZipcodeException("No patient zipcode provided.");
        }
        patientDetail.setZipcode(zipcode);
    } catch (InvalidZipcodeException ize) {
        logger.error(ize.getMessage());
        statisticsService.updateProviderStats(message, StatisticsService.StatsType.INCOMPLETE,
                "missing: " + IncompleteDataException.IncompleteDataType.ZIPCODE);
    }

    // Date of Birth
    final String dob = StringUtils.trimToNull(t.get("/PID-7"));
    if (dob == null) {
        logger.warn("No date of birth set in message");
    } else {
        patientDetail.setDateOfBirth(ER7Utils.fromER7Date(dob));
    }

    // Gender
    String genderAbbr = StringUtils.trimToNull(t.get("/PID-8"));
    if (genderAbbr == null) {
        genderAbbr = "U";
        logger.warn("No gender set in message");
        statisticsService.updateProviderStats(message, StatisticsService.StatsType.INCOMPLETE,
                "missing: " + IncompleteDataException.IncompleteDataType.GENDER);
    }

    patientDetail.setGender(attributeRepository.getGenderByAbbreviation(genderAbbr));

    final SortedSet<PatientDetail> sortedDetails = patient.getPatientDetails();

    if (patient.getPatientId() == null) {

        // Just save it.
        logger.debug("Saving details without patientID");
        sortedDetails.add(patientDetail);

    } else if (sortedDetails.size() == 0) {

        // Just save it.
        logger.debug("Creating initial detail record");
        sortedDetails.add(patientDetail);

    } else {

        final PatientDetail latestDetail = sortedDetails.last();
        if (patientDetail.equals(latestDetail)) {

            patientDetail = latestDetail;
            logger.debug("Using existing detail record: {}", latestDetail.getId());

        } else {

            logger.debug("Creating updated detail record");
            logger.debug("Old: {}  New: {}", latestDetail, patientDetail);
            sortedDetails.add(patientDetail);

        }
    }

    return patientDetail;
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopAbstractTextField.java

@Override
public <V> V getValue() {
    String text = getImpl().getText();
    Object rawValue = validateRawValue(text);
    if (rawValue instanceof String) {
        rawValue = StringUtils.trimToNull((String) rawValue);
    }//from w  w  w.j  a v a2s.co m

    //noinspection unchecked
    return (V) rawValue;
}

From source file:com.bluexml.xforms.generator.forms.renderable.forms.RenderableModelChoiceField.java

/**
 * Instantiates a new renderable model choice field.
 * //  w ww  . j ava  2  s .  c  o  m
 * @param generationManager
 *            the generation manager
 * @param parent
 *            the parent
 * @param formElement
 *            the form element
 */
public RenderableModelChoiceField(XFormsGenerator generationManager, FormElement parent,
        ModelChoiceField formElement) {
    super(generationManager, parent, formElement);

    AssociationProperties properties = new AssociationProperties();

    properties.setAssocTitle(formElement.getLabel());
    Clazz formElt_realClass = (Clazz) generationManager.getFormGenerator()
            .getRealObject(formElement.getReal_class());
    properties.setDestination(formElt_realClass);
    String defaultFormName = ModelTools.getCompleteName(formElt_realClass);
    properties.setCreateEditDefaultFormName(defaultFormName);
    properties.setHiBound(formElement.getMax_bound());
    properties.setLoBound(formElement.getMin_bound());
    properties.setUniqueName(FormGeneratorsManager.getUniqueName(formElement));
    properties.setHint(formElement.getHelp_text());
    properties.setStyle(formElement.getStyle());
    properties.setWidgetType(formElement.getWidget());

    properties.setCreateEditFormType(FormTypeRendered.formForm);
    int targetsNb = formElement.getTarget().size();
    if (targetsNb > 0) {
        // we want to allow several targets in the XHTML file
        for (FormContainer targetedForm : formElement.getTarget()) {
            // we need to get the real object, in case the target form is from another file.
            FormContainer realTargetedForm = (FormContainer) getFormGenerator().getRealObject(targetedForm);
            if (realTargetedForm instanceof FormClass) {
                if (formElement.getWidget() == ModelChoiceWidgetType.INLINE) {
                    properties.setInline(true);
                    RenderableFormContainer renderableForm = generationManager
                            .getRenderableForm(realTargetedForm);
                    properties.setDestinationRenderable(renderableForm);
                    properties.addCreateEditFormName(realTargetedForm.getId());
                    break; // only one target allowed if inline
                }

                properties.addCreateEditFormName(realTargetedForm.getId());
            }
        }
    }
    // add support for hiding/displaying action buttons
    boolean showingActions = formElement.isShow_actions();
    properties.setShowingActions(showingActions);
    properties.setDisabled(formElement.isDisabled());
    properties.setMandatory(formElement.isMandatory());

    // set maximum number of items to display
    String lsize = "" + formElement.getField_size();
    if (StringUtils.trimToNull(lsize) != null) {
        properties.setFieldSize(lsize);
    }

    String pattern = formElement.getFormat_pattern();
    try {
        if (StringUtils.trimToNull(pattern) != null) {
            pattern = URLEncoder.encode(pattern, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        logger.fatal("Unsupported encoding scheme: UTF-8");
        throw new RuntimeException("Unsupported encoding scheme: UTF-8");
    }
    properties.setFormatPattern(pattern);
    properties.setLabelLength("" + formElement.getLabel_length());

    boolean filtered = false;
    boolean isComposition = false;
    Association association = (Association) getFormGenerator().getRealObject(formElement.getRef());

    try {
        filtered = getFormGenerator().isAssociationFilterable(formElt_realClass, association);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("The class selected on '" + formElement.getLabel()
                + "' is not compatible with the association.");
    }
    // AssociationType associationType = ;
    isComposition = (association.getAssociationType() == AssociationType.COMPOSITION);

    if (filtered) {
        // retrieve the association name
        String alfrescoName = getFormGenerator().getAlfrescoName(formElt_realClass, association);
        properties.setFilterAssoc(alfrescoName);
    }
    properties.setComposition(isComposition);

    // custom configuration parameters
    FormGeneratorsManager formGenerator = getFormGenerator();
    properties.setDataSourceUri(formGenerator.getXtensionDataSourceUri(formElement));
    properties.setFeatureMode(formGenerator.getXtensionFeatureMode(formElement));
    properties.setLuceneQuery(formGenerator.getXtensionLuceneQuery(formElement));
    properties.setNoAutoSearch(formGenerator.getXtensionNoAutoSearch(formElement));
    properties.setNoStatsOutput(formGenerator.getXtensionNoStatsOutput(formElement));

    add(new CommonRenderableAssociation(properties));
}