Example usage for java.lang.reflect Field getAnnotations

List of usage examples for java.lang.reflect Field getAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect Field getAnnotations.

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }/* w  w  w .  j a va  2s  .  co m*/
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:org.diorite.cfg.system.ConfigField.java

/**
 * Construct new config field for given {@link Field}.
 *
 * @param field source field.//from  w ww  .jav  a  2 s . co  m
 * @param index index of field in class. Used to set priority of field.
 */
public ConfigField(final Field field, final int index) {
    this.field = field;
    {
        getAllPossibleTypes(field).forEach(TemplateCreator::checkTemplate);
    }
    this.index = index;

    final String[] comments = TemplateCreator.readComments(field);
    this.header = comments[0];
    this.footer = comments[1];
    {
        final CfgName annotation = field.getAnnotation(CfgName.class);
        this.name = (annotation != null) ? annotation.value() : field.getName();
    }
    {
        final CfgPriority annotation = field.getAnnotation(CfgPriority.class);
        this.priority = (annotation != null) ? (annotation.value() * -1) : index;
    }

    for (final FieldOptions option : FieldOptions.values()) {
        if (!option.contains(field)) {
            continue;
        }
        this.options.put(option, option.get(this, field));
    }

    final Class<?> type = DioriteReflectionUtils.getPrimitive(field.getType());
    Supplier<Object> def = null;
    annotation: {
        {
            final CfgBooleanDefault annotation = field.getAnnotation(CfgBooleanDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgBooleanArrayDefault annotation = field.getAnnotation(CfgBooleanArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgByteDefault annotation = field.getAnnotation(CfgByteDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgShortDefault annotation = field.getAnnotation(CfgShortDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgIntDefault annotation = field.getAnnotation(CfgIntDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgLongDefault annotation = field.getAnnotation(CfgLongDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgFloatDefault annotation = field.getAnnotation(CfgFloatDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgDoubleDefault annotation = field.getAnnotation(CfgDoubleDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }

        {
            final CfgByteArrayDefault annotation = field.getAnnotation(CfgByteArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgCharDefault annotation = field.getAnnotation(CfgCharDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgCharArrayDefault annotation = field.getAnnotation(CfgCharArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgShortArrayDefault annotation = field.getAnnotation(CfgShortArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgIntArrayDefault annotation = field.getAnnotation(CfgIntArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgLongArrayDefault annotation = field.getAnnotation(CfgLongArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgFloatArrayDefault annotation = field.getAnnotation(CfgFloatArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgDoubleArrayDefault annotation = field.getAnnotation(CfgDoubleArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgStringDefault annotation = field.getAnnotation(CfgStringDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgStringArrayDefault annotation = field.getAnnotation(CfgStringArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }

        if (type.isEnum()) {
            for (final Annotation a : field.getAnnotations()) {
                if (a.annotationType().isAnnotationPresent(CfgCustomDefault.class)) {
                    final Annotation annotation = field.getAnnotation(a.annotationType());
                    this.invoker = DioriteReflectionUtils.getMethod(annotation.getClass(), "value");
                    def = () -> this.invoker.invoke(annotation);
                    break annotation;
                }
            }
        }
    }
    final CfgDelegateDefault annotation = field.getAnnotation(CfgDelegateDefault.class);
    if (annotation != null) {
        final String path = annotation.value();
        final Supplier<Object> basicDelegate = getBasicDelegate(path);
        if (basicDelegate != null) {
            def = basicDelegate;
        } else if (path.equalsIgnoreCase("{new}")) {
            final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(field.getType());
            def = constructor::invoke;
        } else {
            final int sepIndex = path.indexOf("::");
            final Class<?> clazz;
            final String methodName;
            if (sepIndex == -1) {
                clazz = field.getDeclaringClass();
                methodName = path;
            } else {
                try {
                    Class<?> tmpClass = DioriteReflectionUtils
                            .tryGetCanonicalClass(path.substring(0, sepIndex));
                    if (tmpClass == null) {
                        tmpClass = DioriteReflectionUtils
                                .tryGetCanonicalClass(field.getDeclaringClass().getPackage().getName() + "."
                                        + path.substring(0, sepIndex));
                        if (tmpClass == null) {
                            tmpClass = DioriteReflectionUtils.getNestedClass(field.getDeclaringClass(),
                                    path.substring(0, sepIndex));
                        }
                    }
                    clazz = tmpClass;
                } catch (final Exception e) {
                    throw new RuntimeException("Can't find class for: " + path, e);
                }
                methodName = path.substring(sepIndex + 2);
            }
            if (clazz == null) {
                throw new RuntimeException("Can't find class for delegate: " + path);
            }
            final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(clazz, methodName, false);
            if (methodInvoker == null) {
                final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils.getReflectGetter(methodName,
                        clazz);
                def = () -> reflectGetter.get(null);
            } else {
                def = () -> methodInvoker.invoke(null);
            }
        }
    }
    this.def = def;
}

From source file:ca.oson.json.Oson.java

private <E> Enum<?> json2Enum(FieldData objectDTO) {
    objectDTO.valueToProcess = StringUtil.unquote(objectDTO.valueToProcess, isEscapeHtml());
    Object valueToProcess = objectDTO.valueToProcess;
    Class<E> returnType = objectDTO.returnType;
    boolean required = objectDTO.required();
    Enum defaultValue = (Enum) objectDTO.defaultValue;
    boolean json2Java = objectDTO.json2Java;

    if (returnType == null || valueToProcess == null) {
        if (required) {
            return defaultValue;
        }//  ww w  .j  a v  a2s  .c o  m

        return null;
    }

    String value = (String) valueToProcess;

    Class<Enum> enumType = (Class<Enum>) returnType;

    try {
        Function function = objectDTO.getDeserializer();

        if (function != null) {

            Object returnedValue = null;

            if (function instanceof Json2DataMapperFunction) {
                DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper, objectDTO.level,
                        getPrettyIndentation());
                returnedValue = ((Json2DataMapperFunction) function).apply(classData);

            } else if (function instanceof Json2FieldDataFunction) {
                Json2FieldDataFunction f = (Json2FieldDataFunction) function;
                FieldData fieldData = objectDTO.clone();

                returnedValue = f.apply(fieldData);

            } else if (function instanceof Json2EnumFunction) {
                return (Enum<?>) ((Json2EnumFunction) function).apply(value);
            } else {
                returnedValue = function.apply(value);
            }

            if (returnedValue instanceof Optional) {
                returnedValue = ObjectUtil.unwrap(returnedValue);
            }

            if (returnedValue == null) {
                return null;
            }

            Class type = returnedValue.getClass();

            if (Enum.class.isAssignableFrom(type)) {
                return (Enum<?>) returnedValue;

            } else if (Number.class.isAssignableFrom(type)) {
                int ordinal = ((Number) returnedValue).intValue();

                for (Enum enumValue : enumType.getEnumConstants()) {
                    if (enumValue.ordinal() == ordinal) {
                        return enumValue;
                    }
                }

            } else {
                String name = returnedValue.toString();

                for (Enum enumValue : enumType.getEnumConstants()) {
                    if (enumValue.toString().equalsIgnoreCase(name)
                            || enumValue.name().equalsIgnoreCase(name)) {
                        return enumValue;
                    }
                }
            }

        }

    } catch (Exception ex) {
    }

    for (Method method : enumType.getDeclaredMethods()) {
        for (Annotation annotation : method.getDeclaredAnnotations()) {
            String aname = annotation.annotationType().getName();

            switch (aname) {
            case "com.fasterxml.jackson.annotation.JsonCreator":
            case "org.codehaus.jackson.annotate.JsonCreator":
                return ObjectUtil.getMethodValue(null, method, value);

            case "ca.oson.json.annotation.FieldMapper":
                ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation;
                if (fieldMapper.jsonCreator() != null && fieldMapper.jsonCreator() == BOOLEAN.TRUE) {
                    return ObjectUtil.getMethodValue(null, method, value);
                }
            }
        }

    }

    String fieldName = null;
    for (Field field : enumType.getDeclaredFields()) {
        String name = null;
        ca.oson.json.annotation.FieldMapper fieldMapper = field
                .getAnnotation(ca.oson.json.annotation.FieldMapper.class);
        if (fieldMapper != null) {
            name = fieldMapper.name();

            if (value.equalsIgnoreCase(name)) {
                fieldName = field.getName();
                break;
            }

        } else {
            for (Annotation annotation : field.getAnnotations()) {
                name = ObjectUtil.getName(annotation);
                if (value.equalsIgnoreCase(name)) {
                    fieldName = field.getName();
                    break;
                }
            }
        }
    }
    if (fieldName != null) {
        try {
            return Enum.valueOf(enumType, fieldName.toUpperCase());
        } catch (IllegalArgumentException ex) {
        }
    }

    try {
        return Enum.valueOf(enumType, value.toUpperCase());
    } catch (IllegalArgumentException ex) {
    }

    for (Enum enumValue : enumType.getEnumConstants()) {
        if (enumValue.toString().equalsIgnoreCase(value) || enumValue.name().equalsIgnoreCase(value)) {
            return enumValue;
        }
    }

    FieldData fieldData = new FieldData(value, Integer.class, true);
    Integer ordinal = json2Integer(fieldData);

    if (ordinal != null) {
        for (Enum enumValue : enumType.getEnumConstants()) {
            if (enumValue.ordinal() == ordinal) {
                return enumValue;
            }
        }
    }

    return null;
}

From source file:ca.oson.json.Oson.java

private <E> String enum2Json(FieldData objectDTO) {
    Object value = objectDTO.valueToProcess;
    Class<E> valueType = objectDTO.returnType;
    EnumType enumType = objectDTO.getEnumType();

    if (value == null) {
        return null;
    }//from   w  w  w .  j a  v a2 s  . c  o m

    Enum en = (Enum) value;

    try {
        Function function = objectDTO.getSerializer();
        if (function != null) {
            try {
                if (function instanceof DataMapper2JsonFunction) {
                    DataMapper classData = new DataMapper(objectDTO.returnType, value, objectDTO.classMapper,
                            objectDTO.level, getPrettyIndentation());
                    return ((DataMapper2JsonFunction) function).apply(classData);

                } else if (function instanceof Enum2JsonFunction) {
                    return ((Enum2JsonFunction) function).apply(en);

                } else {

                    Object returnedValue = null;
                    if (function instanceof FieldData2JsonFunction) {
                        FieldData2JsonFunction f = (FieldData2JsonFunction) function;
                        FieldData fieldData = objectDTO.clone();
                        returnedValue = f.apply(fieldData);
                    } else {
                        returnedValue = function.apply(value);
                    }

                    if (returnedValue instanceof Optional) {
                        returnedValue = ObjectUtil.unwrap(returnedValue);
                    }

                    if (returnedValue == null) {
                        return null; // just ignore it, right?
                    } else if (Enum.class.isAssignableFrom(returnedValue.getClass())) {
                        en = (Enum) returnedValue;

                    } else {
                        objectDTO.valueToProcess = returnedValue;
                        return object2String(objectDTO);
                    }

                }

            } catch (Exception e) {
            }
        }
    } catch (Exception ex) {
    }

    String name = en.name();

    if (enumType == null || enumType == EnumType.STRING) {

        for (Method method : valueType.getDeclaredMethods()) {
            for (Annotation annotation : method.getDeclaredAnnotations()) {
                String aname = annotation.annotationType().getName();

                switch (aname) {
                case "com.fasterxml.jackson.annotation.JsonValue":
                case "org.codehaus.jackson.annotate.JsonValue":
                    return ObjectUtil.getMethodValue(en, method);

                case "ca.oson.json.annotation.FieldMapper":
                    ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation;
                    if (fieldMapper.jsonValue() != null && fieldMapper.jsonValue() == BOOLEAN.TRUE) {
                        return ObjectUtil.getMethodValue(en, method);
                    }
                }
            }

        }

        for (Field field : valueType.getDeclaredFields()) {
            if (name.equalsIgnoreCase(field.getName())) {
                ca.oson.json.annotation.FieldMapper fieldMapper = field
                        .getAnnotation(ca.oson.json.annotation.FieldMapper.class);
                if (fieldMapper != null) {
                    String aname = fieldMapper.name();
                    if (!StringUtil.isEmpty(aname)) {
                        return aname;
                    }

                } else {
                    for (Annotation annotation : field.getAnnotations()) {
                        String aname = ObjectUtil.getName(annotation);
                        if (!StringUtil.isEmpty(aname)) {
                            return aname;
                        }
                    }
                }
            }
        }

        return name;
    }

    switch (enumType) {
    case STRING:
        return en.name();
    case ORDINAL:
    default:
        return "" + en.ordinal();
    }
}