Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

In this page you can find the example usage for java.text DecimalFormatSymbols DecimalFormatSymbols.

Prototype

public DecimalFormatSymbols(Locale locale) 

Source Link

Document

Create a DecimalFormatSymbols object for the given locale.

Usage

From source file:org.saiku.reporting.backend.component.ReportContentUtil.java

private static Object convert(final ParameterContext context, final ParameterDefinitionEntry parameter,
        final Class targetType, final Object rawValue) throws ReportProcessingException {
    if (targetType == null) {
        throw new NullPointerException();
    }//from w  ww.  java  2s .c om

    if (rawValue == null) {
        return null;
    }
    if (targetType.isInstance(rawValue)) {
        return rawValue;
    }

    //TODO:    
    //    if (targetType.isAssignableFrom(TableModel.class) && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass()))
    //    {
    //      // wrap IPentahoResultSet to simulate TableModel
    //      return new PentahoTableModel((IPentahoResultSet) rawValue);
    //    }

    final String valueAsString = String.valueOf(rawValue);
    if (StringUtils.isEmpty(valueAsString)) {
        // none of the converters accept empty strings as valid input. So we can return null instead.
        return null;
    }

    if (targetType.equals(Timestamp.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Timestamp(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Time.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Time(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(java.sql.Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new java.sql.Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    }

    final String dataFormat = parameter.getParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.DATA_FORMAT, context);
    if (dataFormat != null) {
        try {
            if (Number.class.isAssignableFrom(targetType)) {
                final DecimalFormat format = new DecimalFormat(dataFormat,
                        new DecimalFormatSymbols(Locale.getDefault()));
                format.setParseBigDecimal(true);
                final Number number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            } else if (Date.class.isAssignableFrom(targetType)) {
                final SimpleDateFormat format = new SimpleDateFormat(dataFormat,
                        new DateFormatSymbols(Locale.getDefault()));
                format.setLenient(false);
                final Date number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            }
        } catch (Exception e) {
            // again, ignore it .
        }
    }

    final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType);
    if (valueConverter != null) {
        try {
            return valueConverter.toPropertyValue(valueAsString);
        } catch (BeanException e) {
            throw new ReportProcessingException(
                    "ReportPlugin.unableToConvertParameter " + parameter.getName() + " " + valueAsString); //$NON-NLS-1$
        }
    }
    return rawValue;
}

From source file:com.rapidminer.tools.Tools.java

public static void setFormatLocale(Locale locale) {
    FORMAT_LOCALE = locale;//from  www  .  j  a  va  2s .c o m
    NUMBER_FORMAT = NumberFormat.getInstance(locale);
    INTEGER_FORMAT = NumberFormat.getIntegerInstance(locale);
    PERCENT_FORMAT = NumberFormat.getPercentInstance(locale);
    FORMAT_SYMBOLS = new DecimalFormatSymbols(locale);
}

From source file:fr.cs.examples.bodies.Phasing.java

private void run(final File input)
        throws IOException, IllegalArgumentException, ParseException, OrekitException {

    // read input parameters
    KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
    parser.parseInput(new FileInputStream(input));
    TimeScale utc = TimeScalesFactory.getUTC();

    // simulation properties
    AbsoluteDate date = parser.getDate(ParameterKey.ORBIT_DATE, utc);
    int nbOrbits = parser.getInt(ParameterKey.PHASING_ORBITS_NUMBER);
    int nbDays = parser.getInt(ParameterKey.PHASING_DAYS_NUMBER);
    double latitude = parser.getAngle(ParameterKey.SUN_SYNCHRONOUS_REFERENCE_LATITUDE);
    boolean ascending = parser.getBoolean(ParameterKey.SUN_SYNCHRONOUS_REFERENCE_ASCENDING);
    double mst = parser.getTime(ParameterKey.SUN_SYNCHRONOUS_MEAN_SOLAR_TIME).getSecondsInDay() / 3600;
    int degree = parser.getInt(ParameterKey.GRAVITY_FIELD_DEGREE);
    int order = parser.getInt(ParameterKey.GRAVITY_FIELD_ORDER);
    String gridOutput = parser.getString(ParameterKey.GRID_OUTPUT);
    double[] gridLatitudes = new double[] { parser.getAngle(ParameterKey.GRID_LATITUDE_1),
            parser.getAngle(ParameterKey.GRID_LATITUDE_2), parser.getAngle(ParameterKey.GRID_LATITUDE_3),
            parser.getAngle(ParameterKey.GRID_LATITUDE_4), parser.getAngle(ParameterKey.GRID_LATITUDE_5) };
    boolean[] gridAscending = new boolean[] { parser.getBoolean(ParameterKey.GRID_ASCENDING_1),
            parser.getBoolean(ParameterKey.GRID_ASCENDING_2), parser.getBoolean(ParameterKey.GRID_ASCENDING_3),
            parser.getBoolean(ParameterKey.GRID_ASCENDING_4),
            parser.getBoolean(ParameterKey.GRID_ASCENDING_5) };

    gravityField = GravityFieldFactory.getNormalizedProvider(degree, order);

    // initial guess for orbit
    CircularOrbit orbit = guessOrbit(date, FramesFactory.getEME2000(), nbOrbits, nbDays, latitude, ascending,
            mst);//  w  w w  .  j a  v  a  2  s  . c  o  m
    System.out.println("initial orbit: " + orbit);
    System.out.println("please wait while orbit is adjusted...");
    System.out.println();

    // numerical model for improving orbit
    double[][] tolerances = NumericalPropagator.tolerances(0.1, orbit, OrbitType.CIRCULAR);
    DormandPrince853Integrator integrator = new DormandPrince853Integrator(1.0e-4 * orbit.getKeplerianPeriod(),
            1.0e-1 * orbit.getKeplerianPeriod(), tolerances[0], tolerances[1]);
    integrator.setInitialStepSize(1.0e-2 * orbit.getKeplerianPeriod());
    NumericalPropagator propagator = new NumericalPropagator(integrator);
    propagator.addForceModel(new HolmesFeatherstoneAttractionModel(
            FramesFactory.getGTOD(IERSConventions.IERS_2010, true), gravityField));
    propagator.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getSun()));
    propagator.addForceModel(new ThirdBodyAttraction(CelestialBodyFactory.getMoon()));

    double deltaP = Double.POSITIVE_INFINITY;
    double deltaV = Double.POSITIVE_INFINITY;

    int counter = 0;
    DecimalFormat f = new DecimalFormat("0.000E00", new DecimalFormatSymbols(Locale.US));
    while (deltaP > 3.0e-1 || deltaV > 3.0e-4) {

        CircularOrbit previous = orbit;

        CircularOrbit tmp1 = improveEarthPhasing(previous, nbOrbits, nbDays, propagator);
        CircularOrbit tmp2 = improveSunSynchronization(tmp1, nbOrbits * tmp1.getKeplerianPeriod(), latitude,
                ascending, mst, propagator);
        orbit = improveFrozenEccentricity(tmp2, nbOrbits * tmp2.getKeplerianPeriod(), propagator);
        double da = orbit.getA() - previous.getA();
        double dex = orbit.getCircularEx() - previous.getCircularEx();
        double dey = orbit.getCircularEy() - previous.getCircularEy();
        double di = FastMath.toDegrees(orbit.getI() - previous.getI());
        double dr = FastMath.toDegrees(
                orbit.getRightAscensionOfAscendingNode() - previous.getRightAscensionOfAscendingNode());
        System.out.println(" iteration " + (++counter) + ": deltaA = " + f.format(da) + " m, deltaEx = "
                + f.format(dex) + ", deltaEy = " + f.format(dey) + ", deltaI = " + f.format(di)
                + " deg, deltaRAAN = " + f.format(dr) + " deg");

        PVCoordinates delta = new PVCoordinates(previous.getPVCoordinates(), orbit.getPVCoordinates());
        deltaP = delta.getPosition().getNorm();
        deltaV = delta.getVelocity().getNorm();

    }

    // final orbit
    System.out.println();
    System.out.println("final orbit (osculating): " + orbit);

    // generate the ground track grid file
    PrintStream output = new PrintStream(new File(input.getParent(), gridOutput));
    for (int i = 0; i < gridLatitudes.length; ++i) {
        printGridPoints(output, gridLatitudes[i], gridAscending[i], orbit, propagator, nbOrbits);
    }
    output.close();

}

From source file:org.pentaho.reporting.platform.plugin.ReportContentUtil.java

private static Object convert(final ParameterContext context, final ParameterDefinitionEntry parameter,
        final Class targetType, final Object rawValue) throws ReportProcessingException {
    if (targetType == null) {
        throw new NullPointerException();
    }//from w w  w.  ja  v a2s. c  o m

    if (rawValue == null) {
        return null;
    }
    if (targetType.isInstance(rawValue)) {
        return rawValue;
    }

    if (targetType.isAssignableFrom(TableModel.class)
            && IPentahoResultSet.class.isAssignableFrom(rawValue.getClass())) {
        // wrap IPentahoResultSet to simulate TableModel
        return new PentahoTableModel((IPentahoResultSet) rawValue);
    }

    final String valueAsString = String.valueOf(rawValue);
    if (StringUtils.isEmpty(valueAsString)) {
        // none of the converters accept empty strings as valid input. So we can return null instead.
        return null;
    }

    if (targetType.equals(Timestamp.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Timestamp(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Time.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Time(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(java.sql.Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new java.sql.Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    } else if (targetType.equals(Date.class)) {
        try {
            final Date date = parseDate(parameter, context, valueAsString);
            return new Date(date.getTime());
        } catch (ParseException pe) {
            // ignore, we try to parse it as real date now ..
        }
    }

    final String dataFormat = parameter.getParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.DATA_FORMAT, context);
    if (dataFormat != null) {
        try {
            if (Number.class.isAssignableFrom(targetType)) {
                final DecimalFormat format = new DecimalFormat(dataFormat,
                        new DecimalFormatSymbols(LocaleHelper.getLocale()));
                format.setParseBigDecimal(true);
                final Number number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            } else if (Date.class.isAssignableFrom(targetType)) {
                final SimpleDateFormat format = new SimpleDateFormat(dataFormat,
                        new DateFormatSymbols(LocaleHelper.getLocale()));
                format.setLenient(false);
                final Date number = format.parse(valueAsString);
                final String asText = ConverterRegistry.toAttributeValue(number);
                return ConverterRegistry.toPropertyValue(asText, targetType);
            }
        } catch (Exception e) {
            // again, ignore it .
        }
    }

    final ValueConverter valueConverter = ConverterRegistry.getInstance().getValueConverter(targetType);
    if (valueConverter != null) {
        try {
            return valueConverter.toPropertyValue(valueAsString);
        } catch (BeanException e) {
            throw new ReportProcessingException(Messages.getInstance()
                    .getString("ReportPlugin.unableToConvertParameter", parameter.getName(), valueAsString)); //$NON-NLS-1$
        }
    }
    return rawValue;
}

From source file:jsdp.app.inventory.univariate.CapacitatedStochasticLotSizing.java

static void simulate(Distribution[] distributions, double fixedOrderingCost, double holdingCost,
        double penaltyCost, double proportionalOrderingCost, double initialInventory,
        BackwardRecursionImpl recursion, double confidence, double errorTolerance) {

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
    DecimalFormat df = new DecimalFormat("#.00", otherSymbols);

    double[] results = SimulatePolicies.simulateStochaticLotSizing(distributions, fixedOrderingCost,
            holdingCost, penaltyCost, proportionalOrderingCost, initialInventory, recursion, confidence,
            errorTolerance);/* ww  w  .j a v  a  2s  . com*/
    System.out.println();
    System.out.println("Simulated cost: " + df.format(results[0]) + " Confidence interval=("
            + df.format(results[0] - results[1]) + "," + df.format(results[0] + results[1]) + ")@"
            + df.format(confidence * 100) + "% confidence");
    System.out.println();
}

From source file:jsdp.app.lotsizing.sS_jsdp.java

public static void solveSampleInstanceForwardRecursion(Distribution[] distributions, double minDemand,
        double maxDemand, double fixedOrderingCost, double proportionalOrderingCost, double holdingCost,
        double penaltyCost, double initialInventory, double confidence, double errorTolerance) {

    sS_ForwardRecursion recursion = new sS_ForwardRecursion(distributions, minDemand, maxDemand,
            fixedOrderingCost, proportionalOrderingCost, holdingCost, penaltyCost);

    sS_StateDescriptor initialState = new sS_StateDescriptor(0, sS_State.inventoryToState(initialInventory));

    /**//  www  .j a v a 2s. co m
     * Replace parallelStream with stream in "runForwardRecursion" to prevent deadlock
     */
    StopWatch timer = new StopWatch();
    timer.start();
    recursion.runForwardRecursion(
            ((sS_StateSpace) recursion.getStateSpace()[initialState.getPeriod()]).getState(initialState));
    timer.stop();
    double ETC = recursion.getExpectedCost(initialInventory);
    double action = sS_State.stateToInventory(recursion.getOptimalAction(initialState).getIntAction());
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();

    double[][] optimalPolicy = recursion.getOptimalPolicy(initialInventory);
    double[] s = optimalPolicy[0];
    double[] S = optimalPolicy[1];
    for (int i = 0; i < distributions.length; i++) {
        System.out.println("S[" + (i + 1) + "]:" + S[i] + "\ts[" + (i + 1) + "]:" + s[i]);
    }
    System.out.println("Note that (s,S) values for period 0 have been set on best effort basis.");

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
    DecimalFormat df = new DecimalFormat("#.00", otherSymbols);

    double[] results = SimulatePolicies.simulate_sS(distributions, fixedOrderingCost, holdingCost, penaltyCost,
            proportionalOrderingCost, initialInventory, recursion, confidence, errorTolerance);
    System.out.println("Simulated cost: " + df.format(results[0]) + " Confidence interval=("
            + df.format(results[0] - results[1]) + "," + df.format(results[0] + results[1]) + ")@"
            + df.format(confidence * 100) + "% confidence");
    System.out.println();
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * Format {@link String} as a Volume//from ww w  .j a va 2  s . c  om
 *  
 * WARNING: Only use this method to present data to the screen
 * 
 * @param locale {@link Locale}
 * @param stringToFormat  {@link String} to format
 * @return a string formatted as a volume with group separators (eg, 131.224.000) assuming the receiver is an int string read from XML
 */
public static String formatVolume(Locale locale, String stringToFormat) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));

    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
    formatter.setMaximumFractionDigits(0);

    result = formatter.format(Double.parseDouble(stringToFormat));

    return result;
}

From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java

/**
 * Formats a number into a string.//from  w  w  w. ja  v a2  s .  c  o m
 * 
 * @param d
 *            the decimal number being formatted.
 * @param pattern
 *            the pattern describing the string format.
 * @return the formatted string.
 */
public static String formatNumber(double d, String pattern) {
    DecimalFormat format = new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.US));
    return format.format(d);
}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat integetFormat(ConfigPriceFormat priceFormat) {
    // khi to interger format
    String pattern = "###,###";
    Locale locale = new Locale("vi", "VN");
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setGroupingSeparator(priceFormat.getGroupSymbol().charAt(0));
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    format.setGroupingSize(priceFormat.getGroupLength());
    return format;
}

From source file:fr.cs.examples.attitude.EarthObservation_day_night_switch_with_spinned_transitions.java

/** Program entry point.
 * @param args program arguments (unused here)
 *//*from w  ww  .  ja  v a 2s .c  om*/
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //----------------------------------------
        //  Initial state definition : date, orbit
        //----------------------------------------
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 02, 00, 00, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        //------------------------------
        // Attitudes sequence definition
        //------------------------------
        final AttitudesSequence attitudesSequence = new AttitudesSequence();

        // Attitude laws definition
        final double settingRate = FastMath.toRadians(1.0);
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);
        final AttitudeProvider transitionLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);
        final AttitudeProvider rollSetUpLaw = new SpinStabilized(nightRestingLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_I, settingRate);
        final AttitudeProvider pitchSetUpLaw = new SpinStabilized(transitionLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_J, settingRate);
        final AttitudeProvider pitchTearDownLaw = new SpinStabilized(dayObservationLaw,
                AbsoluteDate.J2000_EPOCH, Vector3D.PLUS_J, -settingRate);
        final AttitudeProvider rollTearDownLaw = new SpinStabilized(transitionLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_I, -settingRate);

        // Event detectors definition
        //---------------------------
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();

        // Detectors : end day-night rdv 2
        final DateDetector endDayNightRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end day-night rdv 1
        final DateDetector endDayNightRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse entry
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-entry day-night-rdv1-mode");
                            endDayNightRdV1Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endDayNightRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 2
        final DateDetector endNightDayRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 1
        final DateDetector endNightDayRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse exit
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-exit night-day-rdv1-mode");
                            endNightDayRdV1Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endNightDayRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Attitude sequences definition
        //------------------------------
        attitudesSequence.addSwitchingCondition(dayObservationLaw, dayNightEvent, false, true,
                pitchTearDownLaw);
        attitudesSequence.addSwitchingCondition(pitchTearDownLaw, endDayNightRdV1Event_increase, true, false,
                rollTearDownLaw);
        attitudesSequence.addSwitchingCondition(pitchTearDownLaw, endDayNightRdV1Event_decrease, false, true,
                rollTearDownLaw);
        attitudesSequence.addSwitchingCondition(rollTearDownLaw, endDayNightRdV2Event_increase, true, false,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(rollTearDownLaw, endDayNightRdV2Event_decrease, false, true,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, nightDayEvent, true, false, rollSetUpLaw);
        attitudesSequence.addSwitchingCondition(rollSetUpLaw, endNightDayRdV1Event_increase, true, false,
                pitchSetUpLaw);
        attitudesSequence.addSwitchingCondition(rollSetUpLaw, endNightDayRdV1Event_decrease, false, true,
                pitchSetUpLaw);
        attitudesSequence.addSwitchingCondition(pitchSetUpLaw, endNightDayRdV2Event_increase, true, false,
                dayObservationLaw);
        attitudesSequence.addSwitchingCondition(pitchSetUpLaw, endNightDayRdV2Event_decrease, false, true,
                dayObservationLaw);

        // Initialisation
        //---------------
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with day law");
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with night law");
        }

        //----------------------
        // Propagator definition
        //----------------------

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);
        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(10.0, new OrekitFixedStepHandler() {
            private DecimalFormat f1 = new DecimalFormat("0.0000000000000000E00",
                    new DecimalFormatSymbols(Locale.US));
            private Vector3DFormat f2 = new Vector3DFormat(" ", " ", " ", f1);
            private PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            private PVCoordinatesProvider moon = CelestialBodyFactory.getMoon();
            private Frame eme2000 = FramesFactory.getEME2000();
            private Frame itrf2005 = FramesFactory.getITRF(IERSConventions.IERS_2010, true);

            private String printVector3D(final String name, final Vector3D v) {
                return name + " " + f2.format(v);
            }

            private String printRotation(final String name, final Rotation r) {
                return name + " " + f1.format(r.getQ1()) + " " + f1.format(r.getQ2()) + " "
                        + f1.format(r.getQ3()) + " " + f1.format(r.getQ0());
            }

            private String printRotation2(final String name, final Rotation r) {
                return name + " " + f1.format(-r.getQ1()) + " " + f1.format(-r.getQ2()) + " "
                        + f1.format(-r.getQ3()) + " " + f1.format(-r.getQ0());
            }

            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    // the Earth position in spacecraft should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    final double endNightDayTimer1 = endNightDayRdV1Event_decrease.g(currentState);
                    final double endNightDayTimer2 = endNightDayRdV2Event_decrease.g(currentState);
                    final double endDayNightTimer1 = endDayNightRdV1Event_decrease.g(currentState);
                    final double endDayNightTimer2 = endDayNightRdV2Event_decrease.g(currentState);

                    output.add(currentState.getDate() + " " + FastMath.toDegrees(eclipseAngle) + " "
                            + endNightDayTimer1 + " " + endNightDayTimer2 + " " + endDayNightTimer1 + " "
                            + endDayNightTimer2 + " " + FastMath.toDegrees(pointingOffset));
                    final AbsoluteDate date = currentState.getDate();
                    final PVCoordinates pv = currentState.getPVCoordinates(eme2000);
                    final Rotation lvlhRot = new Rotation(pv.getPosition(), pv.getMomentum(), Vector3D.MINUS_K,
                            Vector3D.MINUS_J);
                    final Rotation earthRot = eme2000.getTransformTo(itrf2005, date).getRotation();
                    System.out.println("Scenario::setVectorMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printVector3D("sun", sun.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("moon", moon.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("satPos", pv.getPosition()) + " "
                            + printVector3D("satVel", pv.getVelocity()) + " "
                            + printVector3D("orbMom", pv.getMomentum()));
                    System.out.println("Scenario::setQuatMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printRotation("earthFrame", earthRot) + " "
                            + printRotation("LVLHFrame", lvlhRot));
                    System.out.println("Scenario::computeStep 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY));
                    System.out.println("  -> " + printRotation2("", currentState.getAttitude().getRotation())
                            + " " + printVector3D("", currentState.getAttitude().getSpin()));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        //----------
        // Propagate
        //----------

        // Propagate from the initial date for the fixed duration
        propagator.propagate(initialDate.shiftedBy(1.75 * 3600.));

        //--------------
        // Print results
        //--------------

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}