package org.openlowcode.server.data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;
import org.openlowcode.server.data.loader.FlatFileExtractor;
import org.openlowcode.server.data.loader.FlatFileLoader;
import org.openlowcode.server.data.loader.FlatFileLoaderColumn;
import org.openlowcode.server.data.loader.PostUpdateProcessingStore;

public class DecimalDataObjectFieldFlatFileLoaderColumn<E extends DataObject<E>> extends FlatFileLoaderColumn<E> {

    private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());

    private String name;

    private int scale;

    private int precision;

    @SuppressWarnings("unused")
    private ChoiceValue<ApplocaleChoiceDefinition> locale;

    public BigDecimal multiplyatexport = new BigDecimal(1);

    public static class DecimalParser {

        private int scale;

        private int precision;

        private ChoiceValue<ApplocaleChoiceDefinition> locale;

        private DecimalFormat decimalformat;

        private int specialtreatment;

        public static int SPECIAL_TREATMENT_NONE = 0;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;

        public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;

        public int getSpecialTreatment() {
            return this.specialtreatment;
        }

        /**
         * creates a decimal parser
         *
         * @param scale     digits to the right of decimal point (e.g. 533.33 has
         *                  precision on 2)
         * @param precision total number of digits of the number (e.g. 533.33 is 5
         *                  digits)
         * @param locale    locale if CSV import
         */
        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int specialtreatment) {
            this.scale = scale;
            this.precision = precision;
            this.locale = locale;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            if (this.locale != null)
                if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))
                    ;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);
            decimalformat.setParseBigDecimal(true);
            this.specialtreatment = specialtreatment;
        }

        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
            this(scale, precision, locale, SPECIAL_TREATMENT_NONE);
        }

        public BigDecimal parse(String value) {
            try {
                BigDecimal decimal = null;
                if (value != null)
                    if (value.length() > 0) {
                        Number number = decimalformat.parse(value);
                        decimal = (BigDecimal) number;
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)
                            decimal = decimal.multiply(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)
                            decimal = decimal.divide(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)
                            decimal = decimal.multiply(new BigDecimal(100));
                    }
                if (decimal != null)
                    if (decimal.scale() > scale) {
                        decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);
                    }
                if (decimal != null)
                    if (decimal.precision() > precision)
                        throw new RuntimeException("bad format for big decimal, precision is longer than limit " + precision + " for value " + decimal);
                return decimal;
            } catch (ParseException e) {
                throw new RuntimeException("data is supposed to be big decimal but received the following error when parsing '" + value + "'. Exception " + e.getMessage());
            }
        }
    }

    private DecimalParser decimalparser;

    public static BigDecimal parsemultiplierForExport(String multiplier) {
        if (multiplier == null)
            return new BigDecimal(1);
        if (multiplier.length() == 0)
            return new BigDecimal(1);
        if (multiplier.trim().equals("M1000"))
            return new BigDecimal("0.001");
        if (multiplier.trim().equals("M100"))
            return new BigDecimal("0.01");
        if (multiplier.trim().equals("D1000"))
            return new BigDecimal("1000");
        thro

    }

    public static int parseMultiplierForImport(String multiplier) {
        if (multiplier == null)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.length() == 0)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.trim().equals("M1000"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
        if (multiplier.trim().equals("M100"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
        if (multiplier.trim().equals("D1000"))
            return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
        throw new RuntimeException("Invalid multiplier " + multiplier);
    }

    public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition<E> definition, String[] arguments, String name, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
        this.scale = scale;
        this.precision = precision;
        this.name = name;
        this.locale = locale;
        int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;
        if (arguments != null)
            if (arguments.length == 1) {
                String multiplier = arguments[0];
                if (multiplier.trim().equals("M1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
                    multiplyatexport = new BigDecimal("0.001");
                }
                if (multiplier.trim().equals("M100")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M100");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
                    multiplyatexport = new BigDecimal("0.01");
                }
                if (multiplier.trim().equals("D1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of D1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
                    multiplyatexport = new BigDecimal("1000");
                }
                if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)
                    throw new RuntimeException("Decimal DataObjectFieldFlatFileLoader invalid modifier " + multiplier);
            }
        if (arguments != null)
            if (arguments.length > 1)
                throw new RuntimeException("Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)");
        decimalparser = new DecimalParser(scale, precision, locale, modifier);
    }

    @Override
    public boolean load(E object, Object value, PostUpdateProcessingStore<E> postupdateprocessingstore) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = object.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + object.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) object.payload.lookupSimpleFieldOnName(name);
        BigDecimal oldbigdecimal = decimalfield.getValue();
        BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, "Flat file loader for column " + decimalfield.getName(), decimalparser);
        if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {
            return false;
        } else {
            decimalfield.setValue(newbigdecimal);
            return true;
        }
    }

    @Override
    protected boolean putContentInCell(E currentobject, Cell cell, String context) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = currentobject.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + currentobject.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) currentobject.payload.lookupSimpleFieldOnName(name);
        BigDecimal decimal = decimalfield.getValue();
        if (decimal != null) {
            decimal = decimal.multiply(this.multiplyatexport);
            cell.setCellValue(decimal.doubleValue());
        }
        if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {
            logger.finest("special treatment for cell percentage");
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * puts a big decimal in cell, formatting as percentage if needed
     *
     * @param cell       cell
     * @param value      value
     * @param multiplier multiplier in the sense of DecimalFlatFileLoader
     * @return true if formatting was done, false if formatting was not done
     */
    public static <F extends FieldChoiceDefinition<F>> boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {
        BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);
        if (value != null)
            cell.setCellValue(value.multiply(multiplierforexport).doubleValue());
        if (multiplierforexport.equals(new BigDecimal("0.01"))) {
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * gets a BigDecimal from cell
     *
     * @param value           value to parse
     * @param scale           number of digits right of the decimal point (e.g.
     *                        533.33 is 2 digits
     * @param precision       total number of digits of the number (e.g. 533.33 is 5
     *                        digits)
     * @param locale          locale for import from text (comma or dot as decimal)
     * @param modifier        String modifier in the sense of
     *                        DecimalDataObjectFieldFlatFileLoader
     * @param contextforerror context used in exceptions
     * @return
     */
    public static <F extends FieldChoiceDefinition<F>> BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int modifier, String contextforerror) {
        return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));
    }
}


public static <F extends FieldChoiceDefinition<F>> BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int modifier, String contextforerror) {
        return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));
    }

package org.openlowcode.server.data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;
import org.openlowcode.server.data.loader.FlatFileExtractor;
import org.openlowcode.server.data.loader.FlatFileLoader;
import org.openlowcode.server.data.loader.FlatFileLoaderColumn;
import org.openlowcode.server.data.loader.PostUpdateProcessingStore;

public class DecimalDataObjectFieldFlatFileLoaderColumn<E extends DataObject<E>> extends FlatFileLoaderColumn<E> {

    private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());

    private String name;

    private int scale;

    private int precision;

    @SuppressWarnings("unused")
    private ChoiceValue<ApplocaleChoiceDefinition> locale;

    public BigDecimal multiplyatexport = new BigDecimal(1);

    public static class DecimalParser {

        private int scale;

        private int precision;

        private ChoiceValue<ApplocaleChoiceDefinition> locale;

        private DecimalFormat decimalformat;

        private int specialtreatment;

        public static int SPECIAL_TREATMENT_NONE = 0;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;

        public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;

        public int getSpecialTreatment() {
            return this.specialtreatment;
        }

        /**
         * creates a decimal parser
         *
         * @param scale     digits to the right of decimal point (e.g. 533.33 has
         *                  precision on 2)
         * @param precision total number of digits of the number (e.g. 533.33 is 5
         *                  digits)
         * @param locale    locale if CSV import
         */
        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int specialtreatment) {
            this.scale = scale;
            this.precision = precision;
            this.locale = locale;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            if (this.locale != null)
                if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))
                    ;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);
            decimalformat.setParseBigDecimal(true);
            this.specialtreatment = specialtreatment;
        }

        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
            this(scale, precision, locale, SPECIAL_TREATMENT_NONE);
        }

        public BigDecimal parse(String value) {
            try {
                BigDecimal decimal = null;
                if (value != null)
                    if (value.length() > 0) {
                        Number number = decimalformat.parse(value);
                        decimal = (BigDecimal) number;
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)
                            decimal = decimal.multiply(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)
                            decimal = decimal.divide(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)
                            decimal = decimal.multiply(new BigDecimal(100));
                    }
                if (decimal != null)
                    if (decimal.scale() > scale) {
                        decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);
                    }
                if (decimal != null)
                    if (decimal.precision() > precision)
                        throw new RuntimeException("bad format for big decimal, precision is longer than limit " + precision + " for value " + decimal);
                return decimal;
            } catch (ParseException e) {
                throw new RuntimeException("data is supposed to be big decimal but received the following error when parsing '" + value + "'. Exception " + e.getMessage());
            }
        }
    }

    private DecimalParser decimalparser;

    public static BigDecimal parsemultiplierForExport(String multiplier) {
        if (multiplier == null)
            return new BigDecimal(1);
        if (multiplier.length() == 0)
            return new BigDecimal(1);
        if (multiplier.trim().equals("M1000"))
            return new BigDecimal("0.001");
        if (multiplier.trim().equals("M100"))
            return new BigDecimal("0.01");
        if (multiplier.trim().equals("D1000"))
            return new BigDecimal("1000");
        throw new RuntimeException("Invalid multiplier " + multiplier);
    }

    public static int parseMultiplierForImport(String multiplier) {
        if (multiplier == null)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.length() == 0)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.trim().equals("M1000"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
        if (multiplier.trim().equals("M100"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
        if (multiplier.trim().equals("D1000"))
            return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
        throw new RuntimeException("Invalid multiplier " + multiplier);
    }

    public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition<E> definition, String[] arguments, String name, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
        this.scale = scale;
        this.precision = precision;
        this.name = name;
        this.locale = locale;
        int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;
        if (arguments != null)
            if (arguments.length == 1) {
                String multiplier = arguments[0];
                if (multiplier.trim().equals("M1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
                    multiplyatexport = new BigDecimal("0.001");
                }
                if (multiplier.trim().equals("M100")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M100");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
                    multiplyatexport = new BigDecimal("0.01");
                }
                if (multiplier.trim().equals("D1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of D1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
                    multiplyatexport = new BigDecimal("1000");
                }
                if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)
                    throw new RuntimeException("Decimal DataObjectFieldFlatFileLoader invalid modifier " + multiplier);
            }
        if (arguments != null)
            if (arguments.length > 1)
                throw new RuntimeException("Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)");
        decimalparser = new DecimalParser(scale, precision, locale, modifier);
    }

    @Override
    public boolean load(E object, Object value, PostUpdateProcessingStore<E> postupdateprocessingstore) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = object.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + object.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) object.payload.lookupSimpleFieldOnName(name);
        BigDecimal oldbigdecimal = decimalfield.getValue();
        BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, "Flat file loader for column " + decimalfield.getName(), decimalparser);
        if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {
            return false;
        } else {
            decimalfield.setValue(newbigdecimal);
            return true;
        }
    }

    @Override
    protected boolean putContentInCell(E currentobject, Cell cell, String context) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = currentobject.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + currentobject.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) currentobject.payload.lookupSimpleFieldOnName(name);
        BigDecimal decimal = decimalfield.getValue();
        if (decimal != null) {
            decimal = decimal.multiply(this.multiplyatexport);
            cell.setCellValue(decimal.doubleValue());
        }
        if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {
            logger.finest("special treatment for cell percentage");
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * puts a big decimal in cell, formatting as percentage if needed
     *
     * @param cell       cell
     * @param value      value
     * @param multiplier multiplier in the sense of DecimalFlatFileLoader
     * @return true if formatting was done, false if formatting was not done
     */
    public static <F extends FieldChoiceDefinition<F>> boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {
        BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);
        if (value != null)
            cell.setCellValue(value.multiply(multiplierforexport).doubleValue());
        if (multiplierforexport.equals(new BigDecimal("0.01"))) {
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * gets a BigDecimal from cell
     *
     * @param value           value to parse
     * @param scale           number of digits right of the decimal point (e.g.
     *                        533.33 is 2 digits
     * @param precision       total number of digits of the number (e.g. 533.33 is 5
     *                        digits)
     * @param locale          locale for import from text (comma or dot as decimal)
     * @param modifier        String modifier in the sense of
     *                        DecimalDataObjectFieldFlatFileLoader
     * @param contextforerror context used in exceptions
     * @return
     */


if (multiplier.trim().equals("D1000"))
            return new BigDecimal("1000");

package org.openlowcode.server.data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.openlowcode.module.system.data.choice.ApplocaleChoiceDefinition;
import org.openlowcode.server.data.loader.FlatFileExtractor;
import org.openlowcode.server.data.loader.FlatFileLoader;
import org.openlowcode.server.data.loader.FlatFileLoaderColumn;
import org.openlowcode.server.data.loader.PostUpdateProcessingStore;

public class DecimalDataObjectFieldFlatFileLoaderColumn<E extends DataObject<E>> extends FlatFileLoaderColumn<E> {

    private static Logger logger = Logger.getLogger(DecimalDataObjectFieldFlatFileLoaderColumn.class.getName());

    private String name;

    private int scale;

    private int precision;

    @SuppressWarnings("unused")
    private ChoiceValue<ApplocaleChoiceDefinition> locale;

    public BigDecimal multiplyatexport = new BigDecimal(1);

    public static class DecimalParser {

        private int scale;

        private int precision;

        private ChoiceValue<ApplocaleChoiceDefinition> locale;

        private DecimalFormat decimalformat;

        private int specialtreatment;

        public static int SPECIAL_TREATMENT_NONE = 0;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_1000 = 1;

        public static int SPECIAL_TREATMENT_DIVIDE_BY_1000 = 2;

        public static int SPECIAL_TREATMENT_MULTIPLY_BY_100 = 3;

        public int getSpecialTreatment() {
            return this.specialtreatment;
        }

        /**
         * creates a decimal parser
         *
         * @param scale     digits to the right of decimal point (e.g. 533.33 has
         *                  precision on 2)
         * @param precision total number of digits of the number (e.g. 533.33 is 5
         *                  digits)
         * @param locale    locale if CSV import
         */
        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int specialtreatment) {
            this.scale = scale;
            this.precision = precision;
            this.locale = locale;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            if (this.locale != null)
                if (this.locale.getStorageCode().equals(ApplocaleChoiceDefinition.get().FR))
                    ;
            decimalformat = (DecimalFormat) NumberFormat.getInstance(Locale.FRENCH);
            decimalformat.setParseBigDecimal(true);
            this.specialtreatment = specialtreatment;
        }

        public DecimalParser(int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
            this(scale, precision, locale, SPECIAL_TREATMENT_NONE);
        }

        public BigDecimal parse(String value) {
            try {
                BigDecimal decimal = null;
                if (value != null)
                    if (value.length() > 0) {
                        Number number = decimalformat.parse(value);
                        decimal = (BigDecimal) number;
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_1000)
                            decimal = decimal.multiply(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_DIVIDE_BY_1000)
                            decimal = decimal.divide(new BigDecimal(1000));
                        if (specialtreatment == SPECIAL_TREATMENT_MULTIPLY_BY_100)
                            decimal = decimal.multiply(new BigDecimal(100));
                    }
                if (decimal != null)
                    if (decimal.scale() > scale) {
                        decimal = decimal.setScale(scale, RoundingMode.HALF_DOWN);
                    }
                if (decimal != null)
                    if (decimal.precision() > precision)
                        throw new RuntimeException("bad format for big decimal, precision is longer than limit " + precision + " for value " + decimal);
                return decimal;
            } catch (ParseException e) {
                throw new RuntimeException("data is supposed to be big decimal but received the following error when parsing '" + value + "'. Exception " + e.getMessage());
            }
        }
    }

    private DecimalParser decimalparser;

    public static BigDecimal parsemultiplierForExport(String multiplier) {
        if (multiplier == null)
            return new BigDecimal(1);
        if (multiplier.length() == 0)
            return new BigDecimal(1);
        if (multiplier.trim().equals("M1000"))
            return new BigDecimal("0.001");
        if (multiplier.trim().equals("M100"))
            return new BigDecimal("0.01");

        throw new RuntimeException("Invalid multiplier " + multiplier);
    }

    public static int parseMultiplierForImport(String multiplier) {
        if (multiplier == null)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.length() == 0)
            return DecimalParser.SPECIAL_TREATMENT_NONE;
        if (multiplier.trim().equals("M1000"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
        if (multiplier.trim().equals("M100"))
            return DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
        if (multiplier.trim().equals("D1000"))
            return DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
        throw new RuntimeException("Invalid multiplier " + multiplier);
    }

    public DecimalDataObjectFieldFlatFileLoaderColumn(DataObjectDefinition<E> definition, String[] arguments, String name, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale) {
        this.scale = scale;
        this.precision = precision;
        this.name = name;
        this.locale = locale;
        int modifier = DecimalParser.SPECIAL_TREATMENT_NONE;
        if (arguments != null)
            if (arguments.length == 1) {
                String multiplier = arguments[0];
                if (multiplier.trim().equals("M1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_1000;
                    multiplyatexport = new BigDecimal("0.001");
                }
                if (multiplier.trim().equals("M100")) {
                    logger.finer(" ---> For field " + name + ", special treatment of M100");
                    modifier = DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100;
                    multiplyatexport = new BigDecimal("0.01");
                }
                if (multiplier.trim().equals("D1000")) {
                    logger.finer(" ---> For field " + name + ", special treatment of D1000");
                    modifier = DecimalParser.SPECIAL_TREATMENT_DIVIDE_BY_1000;
                    multiplyatexport = new BigDecimal("1000");
                }
                if (modifier == DecimalParser.SPECIAL_TREATMENT_NONE)
                    throw new RuntimeException("Decimal DataObjectFieldFlatFileLoader invalid modifier " + multiplier);
            }
        if (arguments != null)
            if (arguments.length > 1)
                throw new RuntimeException("Decimal DataObjetFieldFlatFileLoader only supports 1 modifier ( M100, M1000 or D1000)");
        decimalparser = new DecimalParser(scale, precision, locale, modifier);
    }

    @Override
    public boolean load(E object, Object value, PostUpdateProcessingStore<E> postupdateprocessingstore) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = object.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + object.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) object.payload.lookupSimpleFieldOnName(name);
        BigDecimal oldbigdecimal = decimalfield.getValue();
        BigDecimal newbigdecimal = FlatFileLoader.parseDecimal(value, precision, scale, "Flat file loader for column " + decimalfield.getName(), decimalparser);
        if (FlatFileLoader.isTheSame(oldbigdecimal, newbigdecimal)) {
            return false;
        } else {
            decimalfield.setValue(newbigdecimal);
            return true;
        }
    }

    @Override
    protected boolean putContentInCell(E currentobject, Cell cell, String context) {
        @SuppressWarnings("unchecked")
        DataObjectField<?, E> field = currentobject.payload.lookupSimpleFieldOnName(name);
        if (field == null)
            throw new RuntimeException("field " + name + " could not be looked-up on " + currentobject.getName());
        if (!(field instanceof DecimalDataObjectField))
            throw new RuntimeException("Expected field " + name + " would be of type DecimalDataObjectField but in reality, it is " + field.getClass().toString());
        DecimalDataObjectField<?> decimalfield = (DecimalDataObjectField<?>) currentobject.payload.lookupSimpleFieldOnName(name);
        BigDecimal decimal = decimalfield.getValue();
        if (decimal != null) {
            decimal = decimal.multiply(this.multiplyatexport);
            cell.setCellValue(decimal.doubleValue());
        }
        if (this.decimalparser.getSpecialTreatment() == DecimalParser.SPECIAL_TREATMENT_MULTIPLY_BY_100) {
            logger.finest("special treatment for cell percentage");
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * puts a big decimal in cell, formatting as percentage if needed
     *
     * @param cell       cell
     * @param value      value
     * @param multiplier multiplier in the sense of DecimalFlatFileLoader
     * @return true if formatting was done, false if formatting was not done
     */
    public static <F extends FieldChoiceDefinition<F>> boolean putContentInCell(Cell cell, BigDecimal value, String multiplier) {
        BigDecimal multiplierforexport = parsemultiplierForExport(multiplier);
        if (value != null)
            cell.setCellValue(value.multiply(multiplierforexport).doubleValue());
        if (multiplierforexport.equals(new BigDecimal("0.01"))) {
            CellStyle percentagecellstyle = FlatFileExtractor.createBorderedStyle(cell.getSheet().getWorkbook());
            percentagecellstyle.setDataFormat(cell.getSheet().getWorkbook().createDataFormat().getFormat("0.0%"));
            cell.setCellStyle(percentagecellstyle);
            return true;
        }
        return false;
    }

    /**
     * gets a BigDecimal from cell
     *
     * @param value           value to parse
     * @param scale           number of digits right of the decimal point (e.g.
     *                        533.33 is 2 digits
     * @param precision       total number of digits of the number (e.g. 533.33 is 5
     *                        digits)
     * @param locale          locale for import from text (comma or dot as decimal)
     * @param modifier        String modifier in the sense of
     *                        DecimalDataObjectFieldFlatFileLoader
     * @param contextforerror context used in exceptions
     * @return
     */
    public static <F extends FieldChoiceDefinition<F>> BigDecimal getContentFromCell(Object value, int scale, int precision, ChoiceValue<ApplocaleChoiceDefinition> locale, int modifier, String contextforerror) {
        return FlatFileLoader.parseDecimal(value, precision, scale, contextforerror, new DecimalParser(scale, precision, locale, modifier));
    }
}


package com.sun.s1asdev.ejb.ejb30.hello.session3;

import jakarta.persistence.*;

@Entity
@Table(name = "EJB30_HELLO_SESSION3_PERSON")
public class Person implements java.io.Serializable {

    @Id
    String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

{
        return "Person: {" + "(name = " + name + ")}";
    }
}


{
        return "Person: {" + "(name = " + name + ")}";
    }

package com.sun.s1asdev.ejb.ejb30.hello.session3;

import jakarta.persistence.*;

@Entity
@Table(name = "EJB30_HELLO_SESSION3_PERSON")
public class Person implements java.io.Serializable {

    @Id
    String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString()


package com.sun.s1asdev.ejb.ejb30.hello.session3;

import jakarta.persistence.*;

@Entity
@Table(name = "EJB30_HELLO_SESSION3_PERSON")
public class Person implements java.io.Serializable {

    @Id
    String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person: {" + "(nam


private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception

package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

{
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }
    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }
}


{
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }

package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

    private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }
    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception


package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

    private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {

        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }
    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }
}


try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }

    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }
}


package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

    private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }
}


if (superClass == null) {
                throw e;
            }

package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

    private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();

            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }
    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }
    }
}


try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredField(superClass, fieldName);
        }

package org.glowroot.agent.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Reflections {

    private static final Logger logger = LoggerFactory.getLogger(Reflections.class);

    private Reflections() {
    }

    public static Method getAnyMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getMethod(name, parameterTypes);
            // even though getMethod() above only returns public method, still need to
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredMethod(clazz, name, parameterTypes);
        }
    }

    public static Field getAnyField(Class<?> clazz, String fieldName) throws Exception {
        try {
            Field field = clazz.getField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            return getAnyDeclaredField(clazz, fieldName);
        }
    }

    private static Method getAnyDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws Exception {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);
            method.setAccessible(true);
            return method;
        } catch (NoSuchMethodException e) {
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        } catch (NoClassDefFoundError e) {
            // NoClassDefFoundError is thrown if any method signature in clazz references a missing
            // seems best to treat same as NoSuchMethodException
            // log exception at trace level
            logger.trace(e.getMessage(), e);
            Class<?> superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw new NoSuchMethodException();
            }
            return getAnyDeclaredMethod(superClass, name, parameterTypes);
        }
    }

    private static Field getAnyDeclaredField(Class<?> clazz, String fieldName) throws Exception {


public static boolean isAsynchronousFlowRequest()

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }
    }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

{
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


{
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }
    }

    public static boolean isFlowRequest()

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {

        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }
    }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);

    }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new


@SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }
        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }
    }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.afterPhase(afterPhaseEvent);
            }

package org.springframework.faces.webflow;

import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.component.visit.VisitContextFactory;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.PartialViewContextFactory;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.render.RenderKitFactory;
import javax.faces.view.ViewDeclarationLanguageFactory;
import javax.faces.view.facelets.FaceletCacheFactory;
import javax.faces.view.facelets.TagHandlerDelegateFactory;
import org.springframework.util.Assert;
import org.springframework.webflow.execution.RequestContextHolder;

/**
 * Common support for the JSF integration with Spring Web Flow.
 *
 * @author Jeremy Grelle
 * @author Phillip Webb
 */
public class JsfUtils {

    public static void notifyAfterListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent afterPhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = (lifecycle.getPhaseListeners().length - 1); i >= 0; i--) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];

        }
    }

    public static void notifyBeforeListeners(PhaseId phaseId, Lifecycle lifecycle, FacesContext context) {
        PhaseEvent beforePhaseEvent = new PhaseEvent(context, phaseId, lifecycle);
        for (int i = 0; i < lifecycle.getPhaseListeners().length; i++) {
            PhaseListener listener = lifecycle.getPhaseListeners()[i];
            if (listener.getPhaseId() == phaseId || listener.getPhaseId() == PhaseId.ANY_PHASE) {
                listener.beforePhase(beforePhaseEvent);
            }
        }
    }

    public static boolean isFlowRequest() {
        if (RequestContextHolder.getRequestContext() != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAsynchronousFlowRequest() {
        if (isFlowRequest() && RequestContextHolder.getRequestContext().getExternalContext().isAjaxRequest()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Find a factory of the specified class using JSFs {@link FactoryFinder} class.
     * @param factoryClass the factory class to find
     * @return the factory instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T findFactory(Class<T> factoryClass) {
        Assert.notNull(factoryClass, "FactoryClass must not be null");
        String name = FACTORY_NAMES.get(factoryClass);
        Assert.state(name != null, "Unknown factory class " + factoryClass.getName());
        return (T) FactoryFinder.getFactory(name);
    }

    private static final Map<Class<?>, String> FACTORY_NAMES;

    static {
        FACTORY_NAMES = new HashMap<>();
        FACTORY_NAMES.put(ApplicationFactory.class, FactoryFinder.APPLICATION_FACTORY);
        FACTORY_NAMES.put(ExceptionHandlerFactory.class, FactoryFinder.EXCEPTION_HANDLER_FACTORY);
        FACTORY_NAMES.put(ExternalContextFactory.class, FactoryFinder.EXTERNAL_CONTEXT_FACTORY);
        FACTORY_NAMES.put(FaceletCacheFactory.class, FactoryFinder.FACELET_CACHE_FACTORY);
        FACTORY_NAMES.put(FacesContextFactory.class, FactoryFinder.FACES_CONTEXT_FACTORY);
        FACTORY_NAMES.put(LifecycleFactory.class, FactoryFinder.LIFECYCLE_FACTORY);
        FACTORY_NAMES.put(PartialViewContextFactory.class, FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
        FACTORY_NAMES.put(RenderKitFactory.class, FactoryFinder.RENDER_KIT_FACTORY);
        FACTORY_NAMES.put(TagHandlerDelegateFactory.class, FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY);
        FACTORY_NAMES.put(ViewDeclarationLanguageFactory.class, FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
        FACTORY_NAMES.put(VisitContextFactory.class, FactoryFinder.VISIT_CONTEXT_FACTORY);
    }
}


public float getScore(float sx, float sy, float tx, float ty)

/**
 * @project loon
 * @author cping
 * @email：example@nnthink.com
 * @version 0.3.3
 */
package loon.action.map.heuristics;

import loon.action.map.AStarFindHeuristic;
import loon.utils.MathUtils;

public class DiagonalShort implements AStarFindHeuristic {

{
        float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));
        float straight = (MathUtils.abs(sx - tx) + MathUtils.abs(sy - ty));
        return 2 * diagonal + (straight - 2 * diagonal);
    }

    public int getType() {
        return DIAGONAL_SHORT;
    }
}


/**
 * @project loon
 * @author cping
 * @email：example@nnthink.com
 * @version 0.3.3
 */
package loon.action.map.heuristics;

import loon.action.map.AStarFindHeuristic;
import loon.utils.MathUtils;

public class DiagonalShort implements AStarFindHeuristic {

    public float getScore(float sx, float sy, float tx, float ty) {
        float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));
        float straight = (MathUtils.abs(sx - tx) + MathUtils.abs(sy - ty));
        return 2 * diagonal + (straight - 2 * diagonal);
    }

    public int getType()


/**
 * @project loon
 * @author cping
 * @email：example@nnthink.com
 * @version 0.3.3
 */
package loon.action.map.heuristics;

import loon.action.map.AStarFindHeuristic;
import loon.utils.MathUtils;

public class DiagonalShort implements AStarFindHeuristic {

    public float getScore(float sx, float sy, float tx, float ty) {
        float diagonal = MathUtils.min(MathUtils.abs(sx - tx), MathUtils.abs(sy - ty));
        float straight = (MathUtils.

        return 2 * diagonal + (straight - 2 * diagonal);
    }

    public int getType() {
        return DIAGONAL_SHORT;
    }
}


package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

{
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        return config;
    }

    public String toXML() {
        StringWriter writer = new StringWriter();
        writer.write("<avatar");
        writeXML(writer);
        writer.write("</avatar>");
        return writer.toString();
    }

    public void parseXML(Element element) {
        super.parseXML(element);
    }
}


{
        super.parseXML(element);
    }

package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

    public WebMediumConfig credentials() {
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        return config;
    }

    public String toXML() {
        StringWriter writer = new StringWriter();
        writer.write("<avatar");
        writeXML(writer);
        writer.write("</avatar>");
        return writer.toString();
    }

    public void parseXML(Element element)


        StringWriter writer = new StringWriter();
        writer.write("<avatar");

package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

    public WebMediumConfig credentials() {
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        return config;
    }

    public String toXML() {

        writeXML(writer);
        writer.write("</avatar>");
        return writer.toString();
    }

    public void parseXML(Element element) {
        super.parseXML(element);
    }
}


writeXML(writer);
        writer.write("</avatar>");

package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

    public WebMediumConfig credentials() {
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        return config;
    }

    public String toXML() {
        StringWriter writer = new StringWriter();
        writer.write("<avatar");

        return writer.toString();
    }

    public void parseXML(Element element) {
        super.parseXML(element);
    }
}


package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

    public WebMediumConfig credentials() {
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        return config;
    }

    public String toXML() {
        StringWriter writer = new StringWriter();
        writer.write("<avatar");
        writeXML(writer);
        writer.write("</avatar>");

    public void parseXML(Element element) {
        super.parseXML(element);
    }
}


package org.botlibre.sdk.config;

import java.io.StringWriter;
import org.w3c.dom.Element;

/**
 * DTO for XML avatar config.
 */
public class AvatarConfig extends WebMediumConfig {

    public String getType() {
        return "avatar";
    }

    public WebMediumConfig credentials() {
        AvatarConfig config = new AvatarConfig();
        config.id = this.id;
        ret

    }

    public String toXML() {
        StringWriter writer = new StringWriter();
        writer.write("<avatar");
        writeXML(writer);
        writer.write("</avatar>");
        return writer.toString();
    }

    public void parseXML(Element element) {
        super.parseXML(element);
    }
}