Example usage for org.joda.time DateTime getDayOfYear

List of usage examples for org.joda.time DateTime getDayOfYear

Introduction

In this page you can find the example usage for org.joda.time DateTime getDayOfYear.

Prototype

public int getDayOfYear() 

Source Link

Document

Get the day of year field value.

Usage

From source file:org.efaps.esjp.common.uitable.MultiPrint_Base.java

License:Apache License

/**
 * @param _field Field the date is wanted for
 * @return datetime array/*from ww  w.j  ava  2 s .  c om*/
 * @throws EFapsException on error
 */
protected Object[] getFilter(final Field _field) throws EFapsException {
    Object[] ret = null;
    final String filter = _field.getFilter().getDefaultValue();
    if (filter != null) {
        final String[] parts = filter.split(":");
        final String range = parts[0];
        final int fromSub = parts.length > 1 ? Integer.parseInt(parts[1]) : 0;
        final int rangeCount = parts.length > 2 ? Integer.parseInt(parts[2]) : 1;
        DateTime dateFrom = new DateTime();
        DateTime dateTo = new DateTime();
        if (range != null) {
            final FilterDefault def = FilterDefault.valueOf(range.toUpperCase());
            // to get a timezone dependent DateTim
            DateTime tmp = DateTimeUtil.translateFromUI(new DateTime()).withTimeAtStartOfDay();
            switch (def) {
            case TODAY:
                dateFrom = tmp.toDateTime().minusDays(fromSub).minusMinutes(1);
                dateTo = dateFrom.plusDays(rangeCount).plusSeconds(1);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case WEEK:
                // the first of the current week
                tmp = tmp.minusDays(tmp.getDayOfWeek() - 1);
                dateFrom = tmp.minusWeeks(fromSub).minusMinutes(1);
                dateTo = tmp.plusWeeks(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case MONTH:
                // the first of the current month
                tmp = tmp.minusDays(tmp.getDayOfMonth() - 1);
                // substract the month and a minute before
                dateFrom = tmp.minusMonths(fromSub).minusMinutes(1);
                // add the month
                dateTo = tmp.plusMonths(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case YEAR:
                tmp = tmp.minusDays(tmp.getDayOfYear() - 1);
                dateFrom = tmp.minusYears(fromSub).minusMinutes(1);
                dateTo = tmp.plusYears(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case ALL:
                ret = new String[] { "*" };
                break;
            case NONE:
                break;
            default:
                ret = new String[] { range + "*" };
                break;
            }
        }
    }
    return ret;
}

From source file:org.everit.jira.core.util.TimetrackerUtil.java

License:Apache License

/**
 * Check the date is contains the dates or not.
 *
 * @param dates/*  w ww  . j  ava2s . co m*/
 *          the dates set.
 * @param date
 *          the date that check contains.
 * @return true if contains, otherwise false.
 */
public static boolean containsSetTheSameDay(final Set<DateTime> dates, final DateTime date) {
    for (DateTime d : dates) {
        if ((d.getYear() == date.getYear()) && (d.getDayOfYear() == date.getDayOfYear())) {
            return true;
        }
    }
    return false;
}

From source file:org.jahia.modules.portal.service.PortalService.java

License:Open Source License

public PortalContext buildPortalContext(RenderContext renderContext, JCRNodeWrapper portalTabNode,
        JCRSessionWrapper sessionWrapper, final boolean updateLastPortalUsed) throws RepositoryException {
    final String currentPath = portalTabNode.getPath();
    final boolean isEditable = portalTabNode.hasPermission("jcr:write_live");
    final Locale mainResourceLocale = renderContext.getMainResourceLocale();
    final String siteKey = renderContext.getSite().getSiteKey();

    PortalContext portalContext = JCRTemplate.getInstance().doExecuteWithSystemSession(
            sessionWrapper.getUser().getUsername(), sessionWrapper.getWorkspace().getName(),
            sessionWrapper.getLocale(), new JCRCallback<PortalContext>() {
                @Override/*from   www . jav a 2  s.  co  m*/
                public PortalContext doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    JCRNodeWrapper portalTabNode = session.getNode(currentPath);
                    JCRNodeWrapper portalNode = JCRContentUtils.getParentOfType(portalTabNode,
                            PortalConstants.JMIX_PORTAL);

                    PortalContext portalContext = new PortalContext();
                    boolean isModel = portalNode.isNodeType(PortalConstants.JNT_PORTAL_MODEL);
                    portalContext.setEditable(isEditable);
                    portalContext.setPath(portalNode.getPath());
                    portalContext.setIdentifier(portalNode.getIdentifier());
                    portalContext.setTabPath(portalTabNode.getPath());
                    portalContext.setTabIdentifier(portalTabNode.getIdentifier());
                    portalContext.setFullTemplate(
                            portalNode.getProperty(PortalConstants.J_FULL_TEMPLATE).getString());
                    portalContext.setLock(portalNode.hasProperty(PortalConstants.J_LOCKED)
                            && portalNode.getProperty(PortalConstants.J_LOCKED).getBoolean());
                    portalContext.setModel(isModel);
                    portalContext.setCustomizable(isModel
                            && portalNode.hasProperty(PortalConstants.J_ALLOW_CUSTOMIZATION)
                            && portalNode.getProperty(PortalConstants.J_ALLOW_CUSTOMIZATION).getBoolean());
                    JCRSiteNode site = JahiaSitesService.getInstance().getSiteByKey(siteKey, session);

                    JCRNodeWrapper modelNode = null;
                    boolean modelDeleted = false;
                    if (isModel) {
                        portalContext.setEnabled(portalNode.hasProperty(PortalConstants.J_ENABLED)
                                && portalNode.getProperty(PortalConstants.J_ENABLED).getBoolean());
                    } else {
                        try {
                            modelNode = (JCRNodeWrapper) portalNode.getProperty(PortalConstants.J_MODEL)
                                    .getNode();
                        } catch (Exception e) {
                            // model deleted
                        }
                        if (modelNode != null) {
                            portalContext.setModelPath(modelNode.getPath());
                            portalContext.setModelIdentifier(modelNode.getIdentifier());
                            portalContext.setEnabled(modelNode.hasProperty(PortalConstants.J_ENABLED)
                                    && modelNode.getProperty(PortalConstants.J_ENABLED).getBoolean());
                        } else {
                            portalContext.setEnabled(false);
                            modelDeleted = true;
                        }
                    }

                    portalContext.setSiteKey(site.getSiteKey());
                    portalContext.setPortalTabTemplates(new ArrayList<PortalKeyNameObject>());
                    portalContext.setPortalTabSkins(new ArrayList<PortalKeyNameObject>());
                    portalContext.setPortalWidgetTypes(new TreeSet<PortalWidgetType>(WIDGET_TYPES_COMPARATOR));
                    if (isEditable) {

                        // Templates for portal tabs
                        List<JCRNodeWrapper> templates = getPortalTabTemplates(
                                portalNode.getProperty(PortalConstants.J_TEMPLATE_ROOT_PATH).getString(),
                                session);
                        for (JCRNodeWrapper template : templates) {
                            PortalKeyNameObject portalTabTemplate = new PortalKeyNameObject();
                            portalTabTemplate.setName(template.getDisplayableName());
                            portalTabTemplate.setKey(template.getName());
                            portalContext.getPortalTabTemplates().add(portalTabTemplate);
                        }

                        // Widget skins
                        SortedSet<View> widgetSkins = getViewSet(PortalConstants.JMIX_PORTAL_WIDGET, site);
                        for (View widgetView : widgetSkins) {
                            if (widgetView.getKey().startsWith("box")) {
                                PortalKeyNameObject portalTabSkin = new PortalKeyNameObject();
                                try {
                                    portalTabSkin.setName(Messages.get(widgetView.getModule(),
                                            widgetView.getKey(), mainResourceLocale));
                                } catch (MissingResourceException e) {
                                    // no resourceBundle for skin
                                    portalTabSkin.setName(widgetView.getKey());
                                }

                                portalTabSkin.setKey(widgetView.getKey());
                                portalContext.getPortalTabSkins().add(portalTabSkin);
                            }
                        }

                        // Widget types
                        Collection<ExtendedNodeType> widgetTypes = getPortalWidgetNodeTypes(portalNode);
                        Collection<ExtendedNodeType> modelWidgetTypes = !isModel && !modelDeleted
                                ? getPortalWidgetNodeTypes(modelNode)
                                : null;

                        for (ExtendedNodeType widgetType : widgetTypes) {
                            if (!isModel && !modelDeleted) {
                                if (modelWidgetTypes.contains(widgetType)) {
                                    PortalWidgetType portalWidgetType = buildPortalWidgetType(widgetType, site,
                                            mainResourceLocale, false);
                                    portalContext.getPortalWidgetTypes().add(portalWidgetType);
                                    modelWidgetTypes.remove(widgetType);
                                }
                            } else {
                                PortalWidgetType portalWidgetType = buildPortalWidgetType(widgetType, site,
                                        mainResourceLocale, false);
                                portalContext.getPortalWidgetTypes().add(portalWidgetType);
                            }
                        }
                        if (!isModel && !modelDeleted) {
                            for (ExtendedNodeType modelWidgetType : modelWidgetTypes) {
                                PortalWidgetType portalWidgetType = buildPortalWidgetType(modelWidgetType, site,
                                        mainResourceLocale, true);
                                portalContext.getPortalWidgetTypes().add(portalWidgetType);
                            }
                        }
                    }

                    if (updateLastPortalUsed) {
                        DateTime currentDateTime = new DateTime();
                        String lastViewed = portalNode.getPropertyAsString(PortalConstants.J_LASTVIEWED);

                        boolean firstView = StringUtils.isEmpty(lastViewed);
                        if (firstView || currentDateTime.getDayOfYear() != ISODateTimeFormat
                                .dateOptionalTimeParser().parseDateTime(lastViewed).getDayOfYear()) {
                            portalNode.setProperty(PortalConstants.J_LASTVIEWED,
                                    currentDateTime.toCalendar(mainResourceLocale));
                            portalNode.saveSession();
                        }
                    }

                    return portalContext;
                }
            });

    portalContext.setBaseUrl(StringUtils.isNotEmpty(renderContext.getURLGenerator().getContext())
            ? renderContext.getURLGenerator().getContext() + renderContext.getURLGenerator().getBaseLive()
            : renderContext.getURLGenerator().getBaseLive());

    return portalContext;
}

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.adige.SnowMelting.java

License:Open Source License

private double[] calcMelting(int i, int j, WritableRaster enWR, WritableRaster demWR, double tem, double pio,
        double sol, double ore, DateTime time, double minimoEI, double condiniI, double condiniL, double lll)
        throws IOException {

    double[] risultato = new double[5];
    double melting = 0;
    double prain = 0;
    double psnow = 0;

    int day = time.getDayOfYear();

    double dayangb = (360 / 365.25) * (day - 79.436);

    dayangb = Math.toRadians(dayangb);

    // Evaluate the declination of the sun.
    double delta = getDeclination(dayangb);
    // Evaluate the radiation in this day.
    double ss = Math.acos(-Math.tan(delta) * Math.tan(lll));

    // double ssDaniele = Math.acos(-Math.tan(delta) * Math.tan(lambda));
    double sunrise = 12 * (1.0 - ss / Math.PI);
    double sunset = 12 * (1.0 + ss / Math.PI);
    double hhh = (double) time.getMillisOfDay() / (1000 * 60 * 60);
    // System.out.println(time+"  day=" + day + "  delta=  " +
    // delta+"  sunrise= "+sunrise+"  sunset="+sunset);
    if (doDaily == false) {

        if ((hhh >= (sunrise) && hhh <= (sunset))) {
            if (skyviewfactorWR.getSampleDouble(i, j, 0) != -9999.0) {

                double ei = 0;
                if (pMode == 0) {
                    ei = enWR.getSampleDouble(i, j, 0) / (ore / 24);
                }/*from  www.j a  va  2s. com*/

                double temp = tem;

                if (isNovalue(tem)) {
                    double zzz = demwr.getSampleDouble(i, j, 0);
                    temp = 273 + pLapse * (zzz - 4000);
                }
                if (isNovalue(pio) || pio < 0) {
                    pio = 0;
                }
                if (pMode == 0) {

                    if (temp > pTmelt) {

                        melting = ei * pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                        melting = Math.min(melting, (condiniI + condiniL));
                    } else {
                        melting = 0;
                    }

                } else if (pMode == 1) {
                    if (temp > pTmelt) {

                        melting = pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                    } else {
                        melting = 0;
                    }
                    melting = Math.max(melting, 0);

                } else if (pMode == 2) {
                    if (temp > pTmelt) {
                        melting = (pCmf + sol * pCrf) * (temp - pTmelt)
                                * skyviewfactorWR.getSampleDouble(i, j, 0);
                    } else {
                        melting = 0;
                    }
                    melting = Math.max(melting, 0);

                }

                else {
                    System.out.println("ERROREEEE");
                }

                prain = (pio / Math.PI) * Math.atan((temp - pTmelt) / pm1) + pio * 0.5;

                psnow = pio - prain;
                prain = prain * pCr;
                psnow = pCs * psnow;

                // freezing
                double freezing = 0;

                if (temp < pTmelt) {
                    freezing = pCff * (pTmelt - temp);
                } else {
                    freezing = 0;
                }

                double I = 0;
                double deltat = 1.0;
                // if (temp > pTmelt) {
                I = condiniI + deltat * (psnow + freezing - melting);
                // } else {
                // I = condiniI + deltat * (psnow + freezing);
                // }
                if (I < 0) {
                    I = 0;
                    melting = 0;
                }

                double L = 0;
                L = condiniL + deltat * (prain + melting - freezing);
                double L_max = pR * I;
                double melting_discharge = 0;
                if (L < 0)
                    L = 0.0;
                if (L > L_max) {
                    melting_discharge = L - L_max;
                    L = L_max;
                }
                risultato[0] = L + I;
                risultato[1] = I;
                risultato[2] = L;
                risultato[3] = melting_discharge;
                risultato[4] = freezing;

            }

            else {

                risultato[0] = -9999;
                risultato[1] = condiniI;
                risultato[2] = condiniL;
                risultato[3] = -9999;
                risultato[4] = -9999;

            }
        } else {

            if (skyviewfactorWR.getSampleDouble(i, j, 0) != -9999.0) {

                double z = 0;
                if (pMode == 0) {
                    z = minimoEI / ore;
                }

                double temp = tem;

                if (isNovalue(tem)) {
                    double zzz = demWR.getSampleDouble(i, j, 0);
                    temp = pLapse * (zzz - 4000);
                }

                if (pMode == 0) {
                    if (temp > pTmelt) {
                        melting = z * pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                        melting = Math.min(melting, (condiniI + condiniL));

                    } else {
                        melting = 0;
                    }
                    // melting = Math.max(melting, 0);

                } else if (pMode == 1) {
                    if (temp > pTmelt) {
                        melting = pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                    } else {
                        melting = 0;
                    }
                    melting = Math.max(melting, 0);

                }

                else if (pMode == 2) {
                    if (temp > pTmelt) {
                        melting = (pCmf + sol * pCrf) * (temp - pTmelt)
                                * skyviewfactorWR.getSampleDouble(i, j, 0);
                    } else {
                        melting = 0;
                    }
                    melting = Math.max(melting, 0);

                } else {
                    System.out.println("ERROREEEE");
                }

                if (isNovalue(pio) || pio < 0) {
                    pio = 0;
                }

                prain = (pio / Math.PI) * Math.atan((temp - pTmelt) / pm1) + pio * 0.5;

                psnow = pio - prain;
                prain = prain * pCr;
                psnow = pCs * psnow;

                // freezing
                double freezing = 0;

                if (temp < pTmelt) {
                    freezing = pCff * (pTmelt - temp);

                } else {
                    freezing = 0;
                }

                double I = 0;
                double deltat = 1.0;
                // if (temp > pTmelt) {
                I = condiniI + deltat * (psnow + freezing - melting);
                // } else {
                // I = condiniI + deltat * (psnow + freezing);
                // }
                if (I < 0) {
                    I = 0;
                    melting = 0;
                }

                double L = 0;
                L = condiniL + deltat * (prain + melting - freezing);
                double L_max = pR * I;
                double melting_discharge = 0;
                if (L < 0)
                    L = 0.0;
                if (L > L_max) {
                    melting_discharge = L - L_max;
                    L = L_max;
                }
                risultato[0] = L + I;
                risultato[1] = I;
                risultato[2] = L;
                risultato[3] = melting_discharge;
                risultato[4] = freezing;

            }

            else {

                risultato[0] = -9999;
                risultato[1] = condiniI;
                risultato[2] = condiniL;
                risultato[3] = -9999;
                risultato[4] = -9999;

            }

        }

    } else {

        if (skyviewfactorWR.getSampleDouble(i, j, 0) != -9999.0) {
            double ei = 0;
            if (pMode == 0) {
                ei = enWR.getSampleDouble(i, j, 0) / (ore / 24);
            }
            double temp = tem;

            if (isNovalue(tem)) {
                double zzz = demWR.getSampleDouble(i, j, 0);
                temp = 273 + pLapse * (zzz - 4000);
            }
            if (isNovalue(pio)) {
                pio = 0;
            }
            if (pMode == 0) {
                if ((temp > pTmelt)) {
                    melting = ei * pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                } else {
                    melting = 0;
                }
                melting = Math.max(melting, 0);

            } else if (pMode == 1) {
                if ((temp > pTmelt)) {
                    melting = pCmf * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                } else {
                    melting = 0;
                }
                melting = Math.max(melting, 0);

            }

            else if (pMode == 2) {
                if (temp > pTmelt) {
                    melting = (pCmf + sol * pCrf) * (temp - pTmelt) * skyviewfactorWR.getSampleDouble(i, j, 0);
                } else {
                    melting = 0;
                }
                melting = Math.max(melting, 0);

            }

            else {
                System.out.println("ERROREEEE");
            }

            prain = (pio / Math.PI) * Math.atan((temp - pTmelt) / pm1) + pio * 0.5;

            psnow = pio - prain;
            prain = prain * pCr;
            psnow = pCs * psnow;

            // freezing
            double freezing = 0;

            if (temp < pTmelt) {
                freezing = pCff * (pTmelt - temp);
            } else {
                freezing = 0;
            }

            double I = 0;
            double deltat = 1.0;
            // if (temp > pTmelt) {
            I = condiniI + deltat * (psnow + freezing - melting);
            // } else {
            // I = condiniI + deltat * (psnow + freezing);
            // }
            if (I < 0) {
                I = 0;
                melting = 0;
            }

            double L = 0;
            L = condiniL + deltat * (prain + melting - freezing);
            double L_max = pR * I;
            double melting_discharge = 0;
            if (L < 0)
                L = 0.0;
            if (L > L_max) {
                melting_discharge = L - L_max;
                L = L_max;
            }
            risultato[0] = L + I;
            risultato[1] = I;
            risultato[2] = L;
            risultato[3] = melting_discharge;
            risultato[4] = freezing;

        }

        else {

            risultato[0] = -9999;
            risultato[1] = condiniI;
            risultato[2] = condiniL;
            risultato[3] = -9999;
            risultato[4] = -9999;

        }

    }

    return risultato;

}

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.insolation.OmsInsolation.java

License:Open Source License

@Execute
public void process() throws Exception { // transform the
    checkNull(inElev, tStartDate, tEndDate);
    // extract some attributes of the map
    HashMap<String, Double> attribute = CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    double dx = attribute.get(CoverageUtilities.XRES);

    /*/*from   w  ww.  j a  va 2  s . c o m*/
     * The models use only one value of the latitude. So I have decided to
     * set it to the center of the raster. Extract the CRS of the
     * GridCoverage and transform the value of a WGS84 latitude.
     */
    CoordinateReferenceSystem sourceCRS = inElev.getCoordinateReferenceSystem2D();
    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;

    double srcPts[] = new double[] { attribute.get(CoverageUtilities.EAST),
            attribute.get(CoverageUtilities.SOUTH) };

    Coordinate source = new Coordinate(srcPts[0], srcPts[1]);
    Point[] so = new Point[] { GeometryUtilities.gf().createPoint(source) };
    CrsUtilities.reproject(sourceCRS, targetCRS, so);
    // the latitude value
    lambda = Math.toRadians(so[0].getY());

    /*
     * transform the start and end date in an int value (the day in the
     * year, from 1 to 365)
     */
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd").withZone(DateTimeZone.UTC);
    DateTime currentDatetime = formatter.parseDateTime(tStartDate);
    int startDay = currentDatetime.getDayOfYear();
    currentDatetime = formatter.parseDateTime(tEndDate);
    int endDay = currentDatetime.getDayOfYear();
    CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    RenderedImage pitTmpRI = inElev.getRenderedImage();
    int width = pitTmpRI.getWidth();
    int height = pitTmpRI.getHeight();
    WritableRaster pitWR = CoverageUtilities.replaceNovalue(pitTmpRI, -9999.0);
    pitTmpRI = null;

    WritableRaster insolationWR = CoverageUtilities.createDoubleWritableRaster(width, height, null,
            pitWR.getSampleModel(), 0.0);
    WritableRandomIter insolationIterator = RandomIterFactory.createWritable(insolationWR, null);

    WritableRaster gradientWR = normalVector(pitWR, dx);

    pm.beginTask(msg.message("insolation.calculating"), endDay - startDay);

    for (int i = startDay; i <= endDay; i++) {
        calcInsolation(lambda, pitWR, gradientWR, insolationWR, i, dx);
        pm.worked(i - startDay);
    }
    pm.done();
    for (int y = 2; y < height - 2; y++) {
        for (int x = 2; x < width - 2; x++) {
            if (pitWR.getSampleDouble(x, y, 0) == -9999.0) {
                insolationIterator.setSample(x, y, 0, Double.NaN);

            }
        }
    }

    outIns = CoverageUtilities.buildCoverage("insolation", insolationWR, attribute,
            inElev.getCoordinateReferenceSystem());
}

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.lwrb.OmsLongwaveRadiationBalance.java

License:Open Source License

/**
 * Evaluate the radiation.//www .j  a  v  a2s .c  o m
 * 
 * @param lambda
 *            the latitude.
 * @param demWR
 *            the raster of elevation
 * @param gradientWR
 *            the raster of the gradient value of the dem.
 * @param insolationWR
 *            the wr where to store the result.
 * @param the
 *            day in the year.
 * @throws Exception
 * @paradx the resolutiono of the dem.
 */
private void calcInsolation(double lambda, WritableRaster demWR, WritableRaster gradientWR,
        WritableRaster insolationWR, WritableRaster staoWR, WritableRaster diffuseWR, double dx, DateTime time)
        throws Exception {

    int day = time.getDayOfYear();

    double dayangb = (360 / 365.25) * (day - 79.436);

    dayangb = Math.toRadians(dayangb);

    // Evaluate the declination of the sun.
    delta = getDeclination(dayangb);
    // Evaluate the radiation in this day.
    double ss = Math.acos(-Math.tan(delta) * Math.tan(lambda));
    double sunrise = 12 * (1.0 - ss / Math.PI);
    double sunset = 12 * (1.0 + ss / Math.PI);
    double hhh = (double) time.getMillisOfDay() / (1000 * 60 * 60);

    double tetaj = 2 * Math.PI * (day - 1.0) / 365.0;
    double ecccorr = 1.00011 + 0.034221 * Math.cos(tetaj) + 0.00128 * Math.sin(tetaj)
            + 0.000719 * Math.cos(2 * tetaj) + 0.000077 * Math.sin(2 * tetaj);

    double hourangle = (hhh / 12.0 - 1.0) * Math.PI;

    // CoverageUtilities.getRegionParamsFromGridCoverage(inskyview);
    // RenderedImage SkyTmpRI = inskyview.getRenderedImage();
    // int width = SkyTmpRI.getWidth();
    // int height = SkyTmpRI.getHeight();

    if (workWithRaster) {

        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {

                if (hhh <= (sunrise)) {

                    insolationWR.setSample(i, j, 0, 0);
                    staoWR.setSample(i, j, 0, 0);
                    diffuseWR.setSample(i, j, 0, 0);

                }
                if (hhh >= (sunset)) {
                    // System.out.println(0);
                    vetgio[contaore] = 0;
                    insolationWR.setSample(i, j, 0, 0);
                    staoWR.setSample(i, j, 0, 0);
                    diffuseWR.setSample(i, j, 0, 0);

                }
                if (hhh > (sunrise) && hhh < (sunset)) {
                    if (demWR.getSampleDouble(i, j, 0) != -9999.0) {
                        omega = hourangle;
                        // calculating the vector related to the sun
                        double sunVector[] = calcSunVector();
                        double zenith = calcZenith(sunVector[2]);

                        double[] inverseSunVector = calcInverseSunVector(sunVector);
                        double[] normalSunVector = calcNormalSunVector(sunVector);

                        height = demWR.getHeight();
                        width = demWR.getWidth();
                        WritableRaster sOmbraWR = calculateFactor(height, width, sunVector, inverseSunVector,
                                normalSunVector, demWR, dx);

                        double mr = 1
                                / (sunVector[2] + 0.15 * Math.pow((93.885 - (zenith * 180 / 3.14)), (-1.253)));

                        double temp = doubleNovalue;
                        double umi = doubleNovalue;
                        // evaluate the radiation.
                        // double[] aaa = calcRadiation(i, j, demWR,
                        // sOmbraWR,
                        // insolationWR, sunVector, gradientWR, mr,
                        // ecccorr, temp, umi);
                        // vetgio[contaore] = aaa * 0.0864 / 24;
                        // System.out.println(aaa);
                        // staoWR.setSample(i, j, 0, aaa[0] * 0.0864 / 24);
                        // insolationWR.setSample(i, j, 0,
                        // aaa[1] * 0.0864 / 24);
                        // diffuseWR.setSample(i, j, 0, aaa[2] * 0.0864 /
                        // 24);

                    }

                    else {
                        staoWR.setSample(i, j, 0, -9999);
                        insolationWR.setSample(i, j, 0, -9999);
                        diffuseWR.setSample(i, j, 0, -9999);

                    }
                }
            }
        }
        //
    } else {

        for (int contastaz = 0; contastaz < xStation.length; contastaz++) {
            System.out.println("STAZIONE N. ========> " + contastaz);
            int colnuber = colnumvetVect[contastaz];
            int rownumber = rownumvetVect[contastaz];
            int i = colnuber;
            int j = rownumber;
            int id = idStation[contastaz];

            // evaluate the radiation.
            double temperatura = doubleNovalue;
            if (tempvalues != null) {
                temperatura = tempvalues.get(id)[0];
            }

            double temperaturaSuolo = doubleNovalue;
            if (soiltempvalues != null) {
                temperaturaSuolo = soiltempvalues.get(id)[0];
            } else {
                temperaturaSuolo = temperatura;
            }

            double clearness = doubleNovalue;
            if (clearindexvalue != null) {
                clearness = clearindexvalue.get(id)[0];
            }

            double umidita = doubleNovalue;
            if (umivalues != null) {
                umidita = umivalues.get(id)[0];
            }
            System.out.println("ID===" + id);
            double[] aaa = calcLongwaveRadiation(i, j, demWR, insolationWR, gradientWR, ecccorr, temperatura,
                    umidita, clearness, temperaturaSuolo);
            outSimulated[contaconta] = aaa[1];
            contaconta++;
            outHMlongwaveUpwelling.put(id, new double[] { aaa[2] });
            outHMlongwaveDownwelling.put(id, new double[] { aaa[1] });
            outHMlongwave.put(id, new double[] { aaa[2] + aaa[1] });

        }
    }

    //
    System.out.println("========contaora========= " + contaore);
    contaore += 1;
    if (workWithRaster) {
        printmap(insolationWR, staoWR, diffuseWR, cumulationTime, contaore);
    }
    // System.out.println("___________________");
}

From source file:org.jmxtrans.embedded.samples.graphite.CocktailAppMetricsSimulator.java

License:Open Source License

public void generateLoad(GraphiteDataInjector graphiteDataInjector) throws Exception {

    TimeSeries rawIntegratedTimeSeries = new TimeSeries("sales.integrated.raw");
    TimeSeries rawTimeSeries = new TimeSeries("sales.raw");

    DateTime now = new DateTime();
    DateTime end = now.plusDays(3);//from w ww. jav a 2 s.  c o  m

    DateTime date = now.minusDays(15);
    DateTime twoDaysAfterBegin = date.plusDays(2);
    double serverFairness = 1.05;

    int integratedValue = 0;

    MathContext mathContext = new MathContext(1, RoundingMode.CEILING);

    int randomFactor = 0;

    while (date.isBefore(end)) {
        if (rawIntegratedTimeSeries.getItemCount() % 120 == 0) {
            randomFactor = 10 + random.nextInt(2);
        }
        int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear());
        int value = new BigDecimal(randomFactor) // random factor
                .multiply(new BigDecimal(10)) // go to cents of USD
                .multiply(new BigDecimal(weekGrowthFactor))
                .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()]))
                .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()]))
                .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes

        integratedValue += value;
        for (int i1 = 0; i1 < 3; i1++) {
            Second period = new Second(date.toDate());
            rawTimeSeries.add(period, value);
            rawIntegratedTimeSeries.add(period, integratedValue);
            date = date.plusSeconds(30);
        }
    }

    rawIntegratedTimeSeries = MovingAverage.createMovingAverage(rawIntegratedTimeSeries,
            rawIntegratedTimeSeries.getKey().toString(), 60 * 7, 0);
    rawTimeSeries = MovingAverage.createMovingAverage(rawTimeSeries, rawTimeSeries.getKey().toString(), 60 * 7,
            0);

    // SALES - REVENUE

    TimeSeries salesRevenueInCentsCounter = new TimeSeries("sales.revenueInCentsCounter");
    TimeSeries salesRevenueInCentsCounterSrv1 = new TimeSeries("srv1.sales.revenueInCentsCounter");
    TimeSeries salesRevenueInCentsCounterSrv2 = new TimeSeries("srv2.sales.revenueInCentsCounter");
    int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics
    for (int i = 0; i < rawIntegratedTimeSeries.getItemCount(); i++) {
        TimeSeriesDataItem dataItem = rawIntegratedTimeSeries.getDataItem(i);
        int value = dataItem.getValue().intValue();
        // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing
        int value1 = Math.min((int) (value * serverFairness / 2), value);

        {
            // simulate srv2 restart
            DateTime currentDate = new DateTime(dataItem.getPeriod().getStart());
            boolean shouldResetValue2 = resetValue2ToZeroOffset == 0
                    && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear();
            if (shouldResetValue2) {
                resetValue2ToZeroOffset = value - value1;
                System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate);
            }
        }

        int value2 = value - value1 - resetValue2ToZeroOffset;
        salesRevenueInCentsCounter.add(dataItem.getPeriod(), value);
        salesRevenueInCentsCounterSrv1.add(dataItem.getPeriod(), value1);
        salesRevenueInCentsCounterSrv2.add(dataItem.getPeriod(), value2);
    }
    graphiteDataInjector.exportMetrics(salesRevenueInCentsCounter, salesRevenueInCentsCounterSrv1,
            salesRevenueInCentsCounterSrv2);

    // SALES - ITEMS
    TimeSeries salesItemsCounter = new TimeSeries("sales.itemsCounter");
    TimeSeries salesItemsCounterSrv1 = new TimeSeries("srv1.sales.itemsCounter");
    TimeSeries salesItemsCounterSrv2 = new TimeSeries("srv2.sales.itemsCounter");

    for (int i = 0; i < rawIntegratedTimeSeries.getItemCount(); i++) {
        RegularTimePeriod period = salesRevenueInCentsCounter.getDataItem(i).getPeriod();
        int ordersPriceInCents1 = salesRevenueInCentsCounterSrv1.getDataItem(i).getValue().intValue();
        int ordersPriceInCents2 = salesRevenueInCentsCounterSrv2.getDataItem(i).getValue().intValue();

        int value1 = ordersPriceInCents1 / 600;
        int value2 = ordersPriceInCents2 / 600;

        salesItemsCounter.add(period, value1 + value2);
        salesItemsCounterSrv1.add(period, value1);
        salesItemsCounterSrv2.add(period, value2);

    }

    graphiteDataInjector.exportMetrics(salesItemsCounter, salesItemsCounterSrv1, salesItemsCounterSrv2);

    // WEBSITE - VISITORS
    TimeSeries newVisitorsCounterSrv1 = new TimeSeries("srv1.website.visitors.newVisitorsCounter");
    TimeSeries newVisitorsCounterSrv2 = new TimeSeries("srv1.website.visitors.newVisitorsCounter");

    TimeSeries activeVisitorsGaugeSrv1 = new TimeSeries("srv1.website.visitors.activeGauge");
    TimeSeries activeVisitorsGaugeSrv2 = new TimeSeries("srv2.website.visitors.activeGauge");
    int integratedValue1 = 0;
    int integratedValue2 = 0;
    float activeVisitorsFactor = 1;
    for (int i = 0; i < rawTimeSeries.getItemCount(); i++) {

        TimeSeriesDataItem dataItem = rawTimeSeries.getDataItem(i);
        RegularTimePeriod period = dataItem.getPeriod();
        int value = dataItem.getValue().intValue() / 20;
        integratedValue += value;

        int value1 = Math.min((int) (value * serverFairness / 2), value);
        integratedValue1 += value1;

        int value2 = value - value1;
        integratedValue2 += value2;

        newVisitorsCounterSrv1.add(period, integratedValue1);
        newVisitorsCounterSrv2.add(period, integratedValue2);

        if (i % 120 == 0) {
            activeVisitorsFactor = (10 + random.nextInt(3)) / 10;
        }

        activeVisitorsGaugeSrv1.add(period, Math.floor(value1 * activeVisitorsFactor));
        activeVisitorsGaugeSrv2.add(period, Math.floor(value2 * activeVisitorsFactor));
    }

    graphiteDataInjector.exportMetrics(newVisitorsCounterSrv1, newVisitorsCounterSrv2, activeVisitorsGaugeSrv1,
            activeVisitorsGaugeSrv2);

}

From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java

License:Open Source License

public void generateLoad() throws Exception {
    System.out.println("Inject data on Graphite server " + this.graphiteHost);

    TimeSeries timeSeries = new TimeSeries("shopping-cart.raw");

    DateTime now = new DateTime();
    DateTime end = now.plusDays(1);//w ww .  jav  a 2s  .c o  m

    DateTime date = now.minusDays(15);
    DateTime twoDaysAfterBegin = date.plusDays(2);

    int integratedValue = 0;

    MathContext mathContext = new MathContext(1, RoundingMode.CEILING);

    int randomFactor = 0;

    while (date.isBefore(end)) {
        if (timeSeries.getItemCount() % 120 == 0) {
            randomFactor = 10 + random.nextInt(2);
        }
        int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear());
        int value = new BigDecimal(randomFactor) // random factor
                .multiply(new BigDecimal(10)) // go to cents of USD
                .multiply(new BigDecimal(weekGrowthFactor))
                .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()]))
                .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()]))
                .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes

        integratedValue += value;
        for (int i1 = 0; i1 < 3; i1++) {
            timeSeries.add(new Minute(date.toDate()), integratedValue);
            date = date.plusMinutes(1);
        }
    }

    TimeSeries ordersPriceInCentsTimeSeries = MovingAverage.createMovingAverage(timeSeries,
            "shopping-cart.OrdersPriceInCents", 60 * 7, 0);

    TimeSeries ordersPriceInCentsSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrdersPriceInCents");
    TimeSeries ordersPriceInCentsSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrdersPriceInCents");
    int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics
    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        TimeSeriesDataItem dataItem = ordersPriceInCentsTimeSeries.getDataItem(i);
        int value = dataItem.getValue().intValue();
        // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing
        int value1 = Math.min((int) (value * 1.05 / 2), value);

        {
            // simulate srv2 restart
            DateTime currentDate = new DateTime(dataItem.getPeriod().getStart());
            boolean shouldResetValue2 = resetValue2ToZeroOffset == 0
                    && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear();
            if (shouldResetValue2) {
                resetValue2ToZeroOffset = value - value1;
                System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate);
            }
        }

        int value2 = value - value1 - resetValue2ToZeroOffset;
        // System.out.println("value=" + value + ", value1=" + value1 + ", value2=" + value2);
        ordersPriceInCentsSrv1TimeSeries.add(dataItem.getPeriod(), value1);
        ordersPriceInCentsSrv2TimeSeries.add(dataItem.getPeriod(), value2);
    }

    TimeSeries orderItemsCountTimeSeries = new TimeSeries("shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrderItemsCount");

    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        RegularTimePeriod period = ordersPriceInCentsTimeSeries.getDataItem(i).getPeriod();
        int ordersPriceInCents1 = ordersPriceInCentsSrv1TimeSeries.getDataItem(i).getValue().intValue();
        int ordersPriceInCents2 = ordersPriceInCentsSrv2TimeSeries.getDataItem(i).getValue().intValue();

        int value1 = ordersPriceInCents1 / 600;
        int value2 = ordersPriceInCents2 / 600;

        orderItemsCountTimeSeries.add(period, value1 + value2);
        orderItemsCountSrv1TimeSeries.add(period, value1);
        orderItemsCountSrv2TimeSeries.add(period, value2);

    }

    exportMetrics(ordersPriceInCentsTimeSeries, ordersPriceInCentsSrv1TimeSeries,
            ordersPriceInCentsSrv2TimeSeries, ordersPriceInCentsTimeSeries, orderItemsCountTimeSeries,
            orderItemsCountSrv1TimeSeries, orderItemsCountSrv2TimeSeries);

    TimeSeries activeSrv1Visitors = new TimeSeries("srv1.visitors.currentActive");
    TimeSeries activeSrv2Visitors = new TimeSeries("srv1.visitors.currentActive");

}

From source file:org.jpos.qi.components.DateRange.java

License:Open Source License

public String toString() {
    if (getRange() != null)
        return getRange();
    DateTime from = new DateTime(getStart());
    DateTime to = new DateTime(getEnd());
    String format = ((QI) UI.getCurrent()).getMessage("daterange.format");
    if (from.getDayOfYear() == to.getDayOfYear())
        return from.toString(format);
    return from.toString(format) + " - " + to.toString(format);

}

From source file:org.jpos.transaction.TxnId.java

License:Open Source License

/**
 * Creates new TxnId object/* w  ww .  j  av a 2 s  . c  o  m*/
 *
 * @param dt Transaction's TIMESTAMP DateTime
 * @param node node id
 * @param transactionId TransactionManager's ID
 */
public static TxnId create(DateTime dt, int node, long transactionId) {
    TxnId id = new TxnId();
    if (dt.getZone() != DateTimeZone.UTC)
        dt = dt.toDateTime(DateTimeZone.UTC);

    return id.init(dt.getYear() - 2000, dt.getDayOfYear(), dt.getSecondOfDay(), node, transactionId);
}