Example usage for org.joda.time DateTime plusSeconds

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

Introduction

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

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

Returns a copy of this datetime plus the specified number of seconds.

Usage

From source file:org.apache.cxf.rs.security.saml.sso.SAMLProtocolResponseValidator.java

License:Apache License

/**
 * Validate a SAML 1.1 Protocol Response
 * @param samlResponse//from   www .  j  a  v  a 2  s .  co  m
 * @param sigCrypto
 * @param callbackHandler
 * @throws WSSecurityException
 */
public void validateSamlResponse(org.opensaml.saml.saml1.core.Response samlResponse, Crypto sigCrypto,
        CallbackHandler callbackHandler) throws WSSecurityException {
    // Check the Status Code
    if (samlResponse.getStatus() == null || samlResponse.getStatus().getStatusCode() == null
            || samlResponse.getStatus().getStatusCode().getValue() == null) {
        LOG.fine("Either the SAML Response Status or StatusCode is null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    String statusValue = samlResponse.getStatus().getStatusCode().getValue().getLocalPart();
    if (!SAML1_STATUSCODE_SUCCESS.equals(statusValue)) {
        LOG.fine("SAML Status code of " + samlResponse.getStatus().getStatusCode().getValue()
                + "does not equal " + SAML1_STATUSCODE_SUCCESS);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (samlResponse.getIssueInstant() != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(futureTTL);
        if (samlResponse.getIssueInstant().isAfter(currentTime)) {
            LOG.fine("SAML Response IssueInstant not met");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
    }

    if (SAMLVersion.VERSION_11 != samlResponse.getVersion()) {
        LOG.fine("SAML Version of " + samlResponse.getVersion() + "does not equal " + SAMLVersion.VERSION_11);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    validateResponseSignature(samlResponse, sigCrypto, callbackHandler);

    // Validate Assertions
    for (org.opensaml.saml.saml1.core.Assertion assertion : samlResponse.getAssertions()) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion);
        validateAssertion(wrapper, sigCrypto, callbackHandler, samlResponse.getDOM().getOwnerDocument(),
                samlResponse.isSigned());
    }
}

From source file:org.apache.karaf.cellar.cloud.BlobStoreDiscoveryService.java

License:Apache License

/**
 * Returns a {@link Set} of IPs.//ww  w.  j a  va  2 s .com
 *
 * @return a set of IPs.
 */
@Override
public Set<String> discoverMembers() {

    refresh();

    Set<String> members = new HashSet<String>();
    ListContainerOptions opt = new ListContainerOptions();

    PageSet<? extends StorageMetadata> pageSet = blobStore.list(container, opt);
    LOGGER.debug("CELLAR CLOUD: storage contains a page set of size {}", pageSet.size());
    for (StorageMetadata md : pageSet) {
        if (md.getType() != StorageType.BLOB) {
            //skip everything that isn't of type BLOB ...
            continue;
        }
        String ip = md.getName();
        Object obj = readBlob(container, ip);
        if (obj == null) {
            LOGGER.debug("CELLAR CLOUD: no valid object found, skipping it");
            continue;
        }
        // check if the IP hasn't been updated recently
        if (obj instanceof DateTime) {
            LOGGER.debug("CELLAR CLOUD: retrieved a DateTime from blog store");
            DateTime registeredTime = (DateTime) obj;
            if (registeredTime != null && registeredTime.plusSeconds(validityPeriod).isAfterNow()) {
                LOGGER.debug("CELLAR CLOUD: adding member {}", ip);
                members.add(ip);
            } else {
                LOGGER.debug("CELLAR CLOUD: remove container {}", ip);
                blobStore.removeBlob(container, ip);
            }
        } else if (obj instanceof ServiceContainer) {
            LOGGER.debug("CELLAR CLOUD: retrieved a ServiceContainer from blog store");
            ServiceContainer serviceContainer = (ServiceContainer) obj;
            DateTime registeredTime = serviceContainer.getRegisteredTime();
            if (registeredTime != null && registeredTime.plusSeconds(validityPeriod).isAfterNow()) {
                LOGGER.debug("CELLAR CLOUD: adding member {} for IP {}", serviceContainer.getHostName(), ip);
                members.add(serviceContainer.getHostIp());
            } else {
                LOGGER.debug("CELLAR CLOUD: remove container {}", ip);
                blobStore.removeBlob(container, ip);
            }
        }
    }
    LOGGER.debug("CELLAR CLOUD: returning members {}", members);
    return members;
}

From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java

License:Apache License

Object GetLargerValue(Object v) {
    byte type = DataType.findType(v);

    if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP)
        return null;

    switch (type) {
    case DataType.CHARARRAY:
        return (String) v + "0";
    case DataType.BYTEARRAY:
        String str = ((DataByteArray) v).toString();
        str = str + "0";
        return new DataByteArray(str);
    case DataType.INTEGER:
        return Integer.valueOf((Integer) v + 1);
    case DataType.LONG:
        return Long.valueOf((Long) v + 1);
    case DataType.FLOAT:
        return Float.valueOf((Float) v + 1);
    case DataType.DOUBLE:
        return Double.valueOf((Double) v + 1);
    case DataType.BIGINTEGER:
        return ((BigInteger) v).add(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal) v).add(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.plusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.plusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.plusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.plusHours(1);
        } else {//from   ww w . jav a2 s.  co  m
            return dt.plusDays(1);
        }
    default:
        return null;
    }
}

From source file:org.apache.storm.st.tests.window.WindowVerifier.java

License:Apache License

/**
 * Run the topology and verify that the number and contents of time based windows is as expected
 * once the spout and bolt have emitted sufficient tuples.
 * The spout and bolt are required to log exactly one log line per emit/window using {@link StringDecorator}
 *///  w  w  w  . ja  v a  2 s  . co  m
public void runAndVerifyTime(int windowSec, int slideSec, TestableTopology testable, TopoWrap topo)
        throws IOException, TException, java.net.MalformedURLException {
    topo.submitSuccessfully();
    final int minSpoutEmits = 100;
    final int minBoltEmits = 5;

    String boltName = testable.getBoltName();
    String spoutName = testable.getSpoutName();

    //Waiting for spout tuples isn't strictly necessary since we also wait for bolt emits, but do it anyway
    //Allow two minutes for topology startup, then wait for at most the time it should take to produce 10 windows
    topo.assertProgress(minSpoutEmits, testable.getSpoutExecutors(), spoutName, 180 + 10 * slideSec);
    topo.assertProgress(minBoltEmits, testable.getBoltExecutors(), boltName, 180 + 10 * slideSec);

    final List<TimeData> allSpoutLogLines = topo.getDeserializedDecoratedLogLines(spoutName,
            TimeData::fromJson);
    final List<TimeDataWindow> allBoltLogLines = topo.getDeserializedDecoratedLogLines(boltName,
            TimeDataWindow::fromJson);
    Assert.assertTrue(allBoltLogLines.size() >= minBoltEmits, "Expecting min " + minBoltEmits
            + " bolt emits, found: " + allBoltLogLines.size() + " \n\t" + allBoltLogLines);

    final DateTime firstWindowEndTime = TimeUtil
            .ceil(new DateTime(allSpoutLogLines.get(0).getDate()).withZone(DateTimeZone.UTC), slideSec);
    final int numberOfWindows = allBoltLogLines.size();
    /*
     * Windows should be aligned to the slide size, starting at firstWindowEndTime - windowSec.
     * Because all windows are aligned to the slide size, we can partition the spout emitted timestamps by which window they should fall in.
     * This checks that the partitioned spout emits fall in the expected windows, based on the logs from the spout and bolt.
     */
    for (int i = 0; i < numberOfWindows; ++i) {
        final DateTime windowEnd = firstWindowEndTime.plusSeconds(i * slideSec);
        final DateTime windowStart = windowEnd.minusSeconds(windowSec);
        LOG.info("Comparing window: " + windowStart + " to " + windowEnd + " iter " + (i + 1) + "/"
                + numberOfWindows);

        final List<TimeData> expectedSpoutEmitsInWindow = allSpoutLogLines.stream().filter(spoutLog -> {
            DateTime spoutLogTime = new DateTime(spoutLog.getDate());
            //The window boundaries are )windowStart, windowEnd)
            return spoutLogTime.isAfter(windowStart) && spoutLogTime.isBefore(windowEnd.plusMillis(1));
        }).collect(Collectors.toList());
        TimeDataWindow expectedWindow = new TimeDataWindow(expectedSpoutEmitsInWindow);

        final TimeDataWindow actualWindow = allBoltLogLines.get(i);
        LOG.info("Actual window: " + actualWindow.getDescription());
        LOG.info("Expected window: " + expectedWindow.getDescription());
        for (TimeData oneLog : expectedWindow.getTimeData()) {
            Assertions.assertTrue(actualWindow.getTimeData().contains(oneLog),
                    () -> String.format("Missing: '%s' \n\tActual: '%s' \n\tComputed window: '%s'", oneLog,
                            actualWindow, expectedWindow));
        }
        for (TimeData oneLog : actualWindow.getTimeData()) {
            Assertions.assertTrue(expectedWindow.getTimeData().contains(oneLog),
                    () -> String.format("Extra: '%s' \n\tActual: '%s' \n\tComputed window: '%s'", oneLog,
                            actualWindow, expectedWindow));
        }
    }
}

From source file:org.apache.ws.security.validate.SamlAssertionValidator.java

License:Apache License

/**
 * Check the Conditions of the Assertion.
 *///from  www . j av  a 2 s  .  c  o  m
protected void checkConditions(AssertionWrapper assertion) throws WSSecurityException {
    DateTime validFrom = null;
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
            && assertion.getSaml2().getConditions() != null) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
            && assertion.getSaml1().getConditions() != null) {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validFrom != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(futureTTL);
        if (validFrom.isAfter(currentTime)) {
            LOG.debug("SAML Token condition (Not Before) not met");
            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity");
        }
    }

    if (validTill != null && validTill.isBeforeNow()) {
        LOG.debug("SAML Token condition (Not On Or After) not met");
        throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity");
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletCookieDaoImpl.java

License:Apache License

@Override
@PortalTransactional/* www .j  ava  2s.com*/
public void purgeExpiredCookies(int maxAge) {
    final DateTime now = DateTime.now();

    logger.debug("begin portlet cookie expiration");

    final EntityManager entityManager = this.getEntityManager();
    final Query deletePortletCookieQuery = entityManager.createQuery(this.deletePortletCookieQueryString);
    deletePortletCookieQuery.setParameter(this.nowParameter.getName(), now);
    final int deletedPortletCookies = deletePortletCookieQuery.executeUpdate();
    logger.debug("finished purging {} portlet cookies with expiration before {}", deletedPortletCookies, now);

    final TypedQuery<PortletCookieImpl> expiredByParentCookiesQuery = this
            .createQuery(findExpiredByParentPortletCookiesQuery);
    expiredByParentCookiesQuery.setParameter(this.nowParameter.getName(), now);
    final List<PortletCookieImpl> indirectlyExpiredCookies = expiredByParentCookiesQuery.getResultList();
    for (final PortletCookieImpl portletCookieImpl : indirectlyExpiredCookies) {
        entityManager.remove(portletCookieImpl);
    }
    logger.debug("finished purging {} portlet cookies with parent expiration before {}",
            indirectlyExpiredCookies.size(), now);

    logger.debug("begin portal cookie expiration");

    final Query deletePortalCookieQuery = entityManager.createQuery(this.deletePortalCookieQueryString);
    deletePortalCookieQuery.setParameter(this.nowParameter.getName(), now);
    final int deletedPortalCookies = deletePortalCookieQuery.executeUpdate();
    logger.debug("finished purging {} portal cookies with expiration before {}", deletedPortalCookies, now);

    final Query deleteEmptyPortalCookieQuery = entityManager
            .createQuery(this.deleteEmptyPortalCookieQueryString);
    //Add the maxAge to now and then subtract the emptyCookieMaxAge
    //For example (now + 1 year) - 1 day == the empty-cookie expiration date
    final DateTime emptyExpiration = now.plusSeconds(maxAge).minusSeconds(emptyCookieMaxAge);
    deleteEmptyPortalCookieQuery.setParameter(this.nowParameter.getName(), emptyExpiration);
    final int deletedEmptyPortalCookies = deleteEmptyPortalCookieQuery.executeUpdate();
    logger.debug("finished purging {} empty portal cookies with expiration before {}",
            deletedEmptyPortalCookies, emptyExpiration);
}

From source file:org.bryantd.lightscameraaction.PluginInterface.java

private Boolean initializeImagingJobs() {
    Boolean userInputOK = true;// w ww . j  ava2  s  .c  om
    imageJobsSchedule_ = new ArrayList<DateTime>();

    Double timeBetweenImages = Double.parseDouble((jSpinnerTimeBetween.getValue()).toString().trim());
    Integer timeBetweenImagesMS = timeBetweenImages.intValue();
    Double lightsToImageDelay = Double.parseDouble((jSpinnerDelay.getValue()).toString().trim());
    Integer lightsToImageDelayMS = lightsToImageDelay.intValue();
    Integer numImages = (Integer) jSpinnerNumImages.getValue();

    if (jRadioButtonTimeBetweenMin.isSelected()) {
        Double tempMS = timeBetweenImages * 60.0 * 1000.0;
        timeBetweenImagesMS = tempMS.intValue();
    } else if (jRadioButtonTimeBetweenS.isSelected()) {
        Double tempMS = timeBetweenImages * 1000.0;
        timeBetweenImagesMS = tempMS.intValue();
    }
    System.out.println("Time between images MS: " + timeBetweenImagesMS);

    if (jRadioButtonDelayMin.isSelected()) {
        Double tempMS = lightsToImageDelay * 60.0 * 1000.0;
        lightsToImageDelayMS = tempMS.intValue();
    } else if (jRadioButtonDelayS.isSelected()) {
        Double tempMS = lightsToImageDelay * 1000.0;
        lightsToImageDelayMS = tempMS.intValue();
    }
    System.out.println("Lights to image delay MS: " + lightsToImageDelayMS);

    if (numImages < 1 || timeBetweenImagesMS <= 0 || lightsToImageDelayMS < 0
            || timeBetweenImagesMS < 2 * lightsToImageDelayMS) {
        userInputOK = false;
        if (timeBetweenImagesMS <= 0) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: " + timeBetweenImagesMS + " is not a valid time between images.\n")
                    .toString());
        }
        if (lightsToImageDelayMS < 0) {
            jTextAreaStatus
                    .append(Utilities
                            .timeStamp("Error: " + lightsToImageDelayMS
                                    + "is not a valid lights off to image acquisition time delay.\n")
                            .toString());
        }
        if (timeBetweenImagesMS < 2 * lightsToImageDelayMS) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: time between images (" + timeBetweenImagesMS
                            + " ms) must be at least 2x delay (" + lightsToImageDelayMS + " ms).\n")
                    .toString());
        }
        if (numImages < 1) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: " + numImages + " is not a valid number of images to acquire.\n")
                    .toString());
        }
    }

    if (userInputOK) {
        this.lightsToImageDelayMS_ = lightsToImageDelayMS;
        imageJobsSchedule_.clear();
        DateTime now = new DateTime();
        now = now.plusSeconds(5);
        for (Integer i = 0; i < numImages; i++) {
            DateTime scheduledJob = now.plusMillis(i * timeBetweenImagesMS);
            imageJobsSchedule_.add(scheduledJob);
            System.out.println("Added " + scheduledJob);
        }
        jTextAreaStatus.append(Utilities
                .timeStamp("Added " + imageJobsSchedule_.size() + " image acquisition events to schedule.\n")
                .toString());
    }
    return userInputOK;
}

From source file:org.efaps.esjp.accounting.report.TrialBalanceDS_Base.java

License:Apache License

@Override
public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource,
        final Map<String, Object> _jrParameters) throws EFapsException {
    super.init(_jasperReport, _parameter, _parentSource, _jrParameters);

    final Map<Instance, DataBean> mapping = new HashMap<>();
    final List<Instance> instances = new ArrayList<>();

    final DateTime dateFrom = new DateTime(
            _parameter.getParameterValue(CIFormAccounting.Accounting_PReportTrialBalanceForm.dateFrom.name));
    final DateTime dateTo = new DateTime(
            _parameter.getParameterValue(CIFormAccounting.Accounting_PReportTrialBalanceForm.dateTo.name));
    final boolean includeInit = Boolean.parseBoolean(
            _parameter.getParameterValue(CIFormAccounting.Accounting_PReportTrialBalanceForm.includeInit.name));
    int level = 2;
    final String levelStr = _parameter
            .getParameterValue(CIFormAccounting.Accounting_PReportTrialBalanceForm.level.name);
    if (levelStr != null && !levelStr.isEmpty()) {
        level = Integer.parseInt(levelStr);
    }//from   w  w  w. ja  v a 2 s.  com

    _jrParameters.put("IncludeInit", includeInit);
    _jrParameters.put("DateFrom", dateFrom);
    _jrParameters.put("DateTo", dateTo);

    final String[] oids = (String[]) Context.getThreadContext().getSessionAttribute("selectedOIDs");
    for (final String oid : oids) {
        final Instance instancetmp = Instance.get(oid);
        if (instancetmp.isValid()) {
            instances.addAll(getAccountInst(_parameter, instancetmp, false));
        }
    }

    final QueryBuilder attrQueryBldr = new QueryBuilder(CIAccounting.TransactionAbstract);
    attrQueryBldr.addWhereAttrLessValue(CIAccounting.TransactionAbstract.Date, dateTo.plusDays(1));
    if (!includeInit) {
        attrQueryBldr.addWhereAttrGreaterValue(CIAccounting.TransactionAbstract.Date, dateFrom.minusSeconds(1));
    }
    final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
    queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink,
            attrQueryBldr.getAttributeQuery(CIAccounting.TransactionAbstract.ID));
    queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, instances.toArray());
    final MultiPrintQuery multi = queryBldr.getPrint();
    final SelectBuilder selTrans = SelectBuilder.get()
            .linkto(CIAccounting.TransactionPositionAbstract.TransactionLink);
    final SelectBuilder selTransDate = new SelectBuilder(selTrans)
            .attribute(CIAccounting.TransactionAbstract.Date);
    final SelectBuilder selAcc = SelectBuilder.get()
            .linkto(CIAccounting.TransactionPositionAbstract.AccountLink);
    final SelectBuilder selAccInst = new SelectBuilder(selAcc).instance();
    final SelectBuilder selAccName = new SelectBuilder(selAcc).attribute(CIAccounting.AccountAbstract.Name);
    final SelectBuilder selAccDescr = new SelectBuilder(selAcc)
            .attribute(CIAccounting.AccountAbstract.Description);
    multi.addSelect(selTransDate, selAccInst, selAccName, selAccDescr);
    multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount);
    multi.execute();
    while (multi.next()) {
        final DateTime date = multi.<DateTime>getSelect(selTransDate);
        final BigDecimal amount = multi
                .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
        final Instance accInst = multi.getSelect(selAccInst);
        DataBean bean;
        if (mapping.containsKey(accInst)) {
            bean = mapping.get(accInst);
        } else {
            bean = new DataBean();
            mapping.put(accInst, bean);
            bean.setAccName(multi.<String>getSelect(selAccName));
            bean.setAccDescr(multi.<String>getSelect(selAccDescr));
        }
        if (multi.getCurrentInstance().getType().isKindOf(CIAccounting.TransactionPositionDebit.getType())) {
            if (includeInit && date.isBefore(dateFrom.plusSeconds(1))) {
                bean.addInitDebit(amount);
            } else {
                bean.addDebit(amount);
            }
        } else {
            if (includeInit && date.isBefore(dateFrom.plusSeconds(1))) {
                bean.addInitCredit(amount);
            } else {
                bean.addCredit(amount);
            }
        }
    }
    final List<DataBean> values;
    if (level > 0) {
        values = new ArrayList<>();
        final Map<Instance, Leveler> accMap = new HashMap<>();
        for (final Entry<Instance, DataBean> entry : mapping.entrySet()) {
            final Leveler accInfo = getLeveler(_parameter).setInstance(entry.getKey()).setLevel(level);
            if (accMap.containsKey(accInfo.getInstance())) {
                accMap.get(accInfo.getInstance()).addBean(entry.getValue());
            } else {
                accInfo.addBean(entry.getValue());
                accMap.put(accInfo.getInstance(), accInfo);
            }
        }
        for (final Leveler leveler : accMap.values()) {
            values.add(leveler.getDataBean());
        }
    } else {
        values = new ArrayList<>(mapping.values());
    }

    final ComparatorChain<DataBean> chain = new ComparatorChain<>();
    chain.addComparator(new Comparator<DataBean>() {

        @Override
        public int compare(final DataBean _arg0, final DataBean _arg1) {
            return _arg0.getAccName().compareTo(_arg1.getAccName());
        }
    });
    Collections.sort(values, chain);
    setData(values);
}

From source file:org.entcore.feeder.timetable.edt.EDTImporter.java

License:Open Source License

private JsonObject generateCourse(int startCourseWeek, int endCourseWeek, BitSet enabledItems,
        List<JsonObject> items, JsonObject entity) {
    final int day = Integer.parseInt(entity.getString("Jour"));
    final int startPlace = Integer.parseInt(entity.getString("NumeroPlaceDebut"));
    final int placesNumber = Integer.parseInt(entity.getString("NombrePlaces"));
    DateTime startDate = startDateWeek1.plusWeeks(startCourseWeek - 1).plusDays(day - 1);
    DateTime endDate = startDate.plusWeeks(endCourseWeek - startCourseWeek);
    startDate = startDate.plusSeconds(slots.get(entity.getString("NumeroPlaceDebut")).getStart());
    endDate = endDate.plusSeconds(slots.get(String.valueOf((startPlace + placesNumber - 1))).getEnd());
    final JsonObject c = new JsonObject().put("structureId", structureId)
            .put("subjectId", subjects.get(entity.getJsonArray("Matiere").getJsonObject(0).getString(IDENT)))
            .put("startDate", startDate.toString()).put("endDate", endDate.toString())
            .put("dayOfWeek", startDate.getDayOfWeek());

    for (int i = 0; i < enabledItems.size(); i++) {
        if (enabledItems.get(i)) {
            final JsonObject item = items.get(i);
            final String ident = item.getString(IDENT);
            switch (item.getString("itemType")) {
            case "Professeur":
                JsonArray teachersArray = c.getJsonArray("teacherIds");
                if (teachersArray == null) {
                    teachersArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("teacherIds", teachersArray);
                }/*from  w  w  w  .  ja v  a  2  s .  c  om*/
                final String tId = teachers.get(ident);
                if (isNotEmpty(tId)) {
                    teachersArray.add(tId);
                }
                break;
            case "Classe":
                JsonArray classesArray = c.getJsonArray("classes");
                if (classesArray == null) {
                    classesArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("classes", classesArray);
                }
                JsonObject ci = classes.get(ident);
                if (ci != null) {
                    classesArray.add(ci.getString("className"));
                }
                break;
            case "Groupe":
                JsonArray groupsArray = c.getJsonArray("groups");
                if (groupsArray == null) {
                    groupsArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("groups", groupsArray);
                }
                JsonObject g = groups.get(ident);
                if (g != null) {
                    groupsArray.add(g.getString("Nom"));
                }
                break;
            case "Materiel":
                JsonArray equipmentsArray = c.getJsonArray("equipmentLabels");
                if (equipmentsArray == null) {
                    equipmentsArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("equipmentLabels", equipmentsArray);
                }
                final String eId = equipments.get(ident);
                if (isNotEmpty(eId)) {
                    equipmentsArray.add(eId);
                }

                break;
            case "Salle":
                JsonArray roomsArray = c.getJsonArray("roomLabels");
                if (roomsArray == null) {
                    roomsArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("roomLabels", roomsArray);
                }
                final String rId = rooms.get(ident);
                if (isNotEmpty(rId)) {
                    roomsArray.add(rId);
                }
                break;
            case "Personnel":
                JsonArray personnelsArray = c.getJsonArray("personnelIds");
                if (personnelsArray == null) {
                    personnelsArray = new fr.wseduc.webutils.collections.JsonArray();
                    c.put("personnelIds", personnelsArray);
                }
                final String pId = personnels.get(ident);
                if (isNotEmpty(pId)) {
                    personnelsArray.add(pId);
                }
                break;
            }
        }
    }
    try {
        c.put("_id", JsonUtil.checksum(c));
    } catch (NoSuchAlgorithmException e) {
        log.error("Error generating course checksum", e);
    }
    return c;
}

From source file:org.entcore.feeder.timetable.udt.UDTImporter.java

License:Open Source License

private JsonObject generateCourse(String start, String end, JsonObject entity, int periodWeek,
        int endPeriodWeek, boolean theoretical) {
    JsonObject ficheTStart = fichesT.get(start);
    JsonObject ficheTEnd = fichesT.get(end);
    if (ficheTStart == null || ficheTEnd == null) {
        report.addError("invalid.ficheT");
        return null;
    }//  w ww.j  a v  a2 s . c  om
    final Slot slotStart = slots.get(ficheTStart.getString("jour")
            + padLeft(ficheTStart.getString("demi_seq"), 2, '0') + ficheTStart.getString("site"));
    final Slot slotEnd = slots.get(ficheTEnd.getString("jour")
            + padLeft(ficheTEnd.getString("demi_seq"), 2, '0') + ficheTEnd.getString("site"));
    if (slotStart == null || slotEnd == null) {
        report.addError("invalid.slot");
        return null;
    }
    final int day = Integer.parseInt(ficheTStart.getString("jour"));
    final int cpw = (periodWeek < startDateWeek1.getWeekOfWeekyear()) ? periodWeek + maxYearWeek : periodWeek;
    DateTime startDate = startDateWeek1.plusWeeks(cpw - startDateWeek1.getWeekOfWeekyear()).plusDays(day - 1);
    while (holidays.contains(startDate)) {
        startDate = startDate.plusWeeks(1);
    }
    startDate = startDate.plusSeconds(slotStart.getStart());
    //final int epw = periods.get(periodWeek);
    final int cepw = (endPeriodWeek < startDateWeek1.getWeekOfWeekyear()) ? endPeriodWeek + maxYearWeek
            : endPeriodWeek;
    DateTime endDate = startDateWeek1.plusWeeks(cepw - startDateWeek1.getWeekOfWeekyear()).plusDays(day - 1);
    while (holidays.contains(endDate)) {
        endDate = endDate.minusWeeks(1);
    }
    endDate = endDate.plusSeconds(slotEnd.getEnd());
    if (endDate.isBefore(startDate)) {
        log.error("endDate before start date. cpw : " + cpw + ", cepw : " + cepw + ", startDateWeek1 : "
                + startDateWeek1 + ", endPeriodOfWeek : " + endPeriodWeek);
    }
    final Set<String> ce = coens.get(start);
    JsonArray teacherIds;
    if (ce != null && ce.size() > 0) {
        teacherIds = new fr.wseduc.webutils.collections.JsonArray(new ArrayList<>(ce));
    } else {
        teacherIds = new fr.wseduc.webutils.collections.JsonArray();
    }
    final String pId = teachers.get(entity.getString("prof"));
    if (isNotEmpty(pId)) {
        teacherIds.add(pId);
    }

    final JsonObject c = new JsonObject().put("structureId", structureId).put("startDate", startDate.toString())
            .put("endDate", endDate.toString()).put("dayOfWeek", day).put("teacherIds", teacherIds)
            .put("theoretical", theoretical);
    final String sId = subjects.get(entity.getString("mat"));
    if (isNotEmpty(sId)) {
        c.put("subjectId", sId);
    }
    final String rId = rooms.get(entity.getString("salle"));
    if (isNotEmpty(rId)) {
        c.put("roomLabels", new fr.wseduc.webutils.collections.JsonArray().add(rId));
    }
    final JsonObject cId = classes.get(entity.getString("div"));
    if (cId != null && isNotEmpty(cId.getString("className"))) {
        c.put("classes", new fr.wseduc.webutils.collections.JsonArray().add(cId.getString("className")));
    }

    JsonArray groups;
    if (isNotEmpty(entity.getString("rgpmt")) || isNotEmpty(entity.getString("gpe"))) {
        groups = new fr.wseduc.webutils.collections.JsonArray();
        c.put("groups", groups);
        String name = regroup.get(entity.getString("rgpmt"));
        if (isNotEmpty(name)) {
            groups.add(name);
        }
        String gName = entity.getString("gpe");
        if (isNotEmpty(gName)) {
            groups.add(entity.getString("div") + " Gr " + gName);
        }
    }
    try {
        c.put("_id", JsonUtil.checksum(c));
    } catch (NoSuchAlgorithmException e) {
        log.error("Error generating course checksum", e);
    }
    return c;
}