Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:com.cs528.style.style.weather.WeatherActivity.java

private void scheduleAndWeatherFilter() {
    //temperature
    temp = todayWeather.getTemperature();
    double temperature = Float.parseFloat(temp) - 273.15;

    if (temperature < COLD) {
        warmness = 2;//from www .  ja  va2s.  com
    } else if (temperature < MODERATE) {
        warmness = 1;
    } else {
        warmness = 0;
    }
    //date
    ScheduleDatabase.init(getApplicationContext());
    Date date = new Date();
    long l = 24 * 60 * 60 * 1000;
    long miliSec = date.getTime() - (date.getTime() % l) + 4 * 60 * 60 * 1000;
    date.setTime(miliSec);
    Schedule schedule = ScheduleDatabase.getSchedule(date);

    // set
    if (schedule == null || schedule.getEvent().ordinal() == 3) {
        style = 0;
    } else {
        style = 1;
    }
    ClothesDatabase.init(getApplicationContext());
    List<Clothes> clothesTopList = ClothesDatabase.getByWarmnessAndStyle(warmness, style, 0);
    List<Clothes> clothesBottomList = ClothesDatabase.getByWarmnessAndStyle(warmness, style, 1);
    List<Clothes> clothesHatList = ClothesDatabase.getByWarmnessAndStyle(warmness, style, 2);
    List<Clothes> clothesShoeList = ClothesDatabase.getByWarmnessAndStyle(warmness, style, 3);
    List<List<Clothes>> allClothes = new ArrayList<>();
    allClothes.add(clothesHatList);
    allClothes.add(clothesTopList);
    allClothes.add(clothesBottomList);
    allClothes.add(clothesShoeList);
    colorFilter(allClothes, 0, 0, 0, new ArrayList<Integer>());
}

From source file:utils.DBManager.java

public ArrayList<Group> getGroups() throws SQLException {
    ArrayList<Group> mGroups = new ArrayList();

    String sql = "SELECT groups.groupid, groupname, creationdate, groups.ownerid, post.date, groups.private "
            + "FROM groups, post WHERE groups.groupid = post.groupid " + "GROUP BY groups.groupid "
            + "ORDER BY post.date DESC";
    PreparedStatement stm = con.prepareStatement(sql);
    ResultSet rs = stm.executeQuery();

    try {/*from w  ww .  j a v a2 s . co  m*/
        while (rs.next()) {

            int i1, i4, i6;
            String s2;
            Date s3, s5;
            i1 = rs.getInt(1);
            s2 = rs.getString(2);
            long d = Long.parseLong(rs.getString(3));
            s3 = new Date();
            s3.setTime(d);
            i4 = rs.getInt(4);
            d = Long.parseLong(rs.getString(5));
            s5 = new Date();
            s5.setTime(d);
            i6 = rs.getInt(6);

            Group aux = new Group();

            aux.setGroupid(i1);
            aux.setTitle(s2);
            aux.setDate(s3);
            aux.setOwner(i4);
            aux.setLastPostDate(s5);
            aux.setPriva(i6 % 2 == 0);
            aux.setNumPost(getNumPost(i1));
            aux.setNumPartecipanti(getNumPartecipanti(i1));

            mGroups.add(aux);
        }
    } finally {
        rs.close();
        stm.close();
    }

    return mGroups;
}

From source file:org.apache.rampart.builder.SymmetricBindingBuilder.java

private void doSignBeforeEncrypt(RampartMessageData rmd) throws RampartException {

    long t0 = 0, t1 = 0, t2 = 0;

    RampartPolicyData rpd = rmd.getPolicyData();
    Document doc = rmd.getDocument();

    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }//from www  .j a v  a2 s.c  o m
    Token sigToken = rpd.getSignatureToken();

    String encrTokId = null;
    String sigTokId = null;

    org.apache.rahas.Token encrTok = null;
    org.apache.rahas.Token sigTok = null;
    WSSecKerberosToken krbToken = null;

    Element sigTokElem = null;

    Vector signatureValues = new Vector();

    if (sigToken != null) {
        if (sigToken instanceof SecureConversationToken) {
            sigTokId = rmd.getSecConvTokenId();
        } else if (sigToken instanceof IssuedToken) {
            sigTokId = rmd.getIssuedSignatureTokenId();
        } else if (sigToken instanceof X509Token) {
            if (rmd.isInitiator()) {
                sigTokId = setupEncryptedKey(rmd, sigToken);
            } else {
                sigTokId = getEncryptedKey(rmd);
            }
        } else if (sigToken instanceof KerberosToken) {
            Date created = new Date();
            Date expires = new Date();
            // TODO make this lifetime configurable ???
            expires.setTime(System.currentTimeMillis() + 300000);
            krbToken = getKerberosTokenBuilder(rmd, sigToken);
            sigTokId = krbToken.getBSTTokenId();
            if (rmd.isInitiator()) {
                sigTokElem = krbToken.getBinarySecurityTokenElement();
            }
            sigTok = new EncryptedKeyToken(sigTokId, created, expires);
            sigTok.setSecret(krbToken.getSessionKey().getEncoded());
        }
    } else {
        throw new RampartException("signatureTokenMissing");
    }

    if (sigTokId == null || sigTokId.length() == 0) {
        throw new RampartException("noSecurityToken");
    }

    if (!(sigToken instanceof KerberosToken)) {

        sigTok = this.getToken(rmd, sigTokId);

        if (SPConstants.INCLUDE_TOEKN_ALWAYS == sigToken.getInclusion()
                || SPConstants.INCLUDE_TOKEN_ONCE == sigToken.getInclusion() || (rmd.isInitiator()
                        && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == sigToken.getInclusion())) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
        } else if ((rmd.isInitiator() && sigToken instanceof X509Token)
                || sigToken instanceof SecureConversationToken) {
            sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
        }
    }

    if (sigTokElem != null) {
        // Set the insertion location
        this.setInsertionLocation(sigTokElem);
    }

    HashMap sigSuppTokMap = null;
    HashMap endSuppTokMap = null;
    HashMap sgndEndSuppTokMap = null;
    HashMap sgndEncSuppTokMap = null;
    HashMap endEncSuppTokMap = null;
    HashMap sgndEndEncSuppTokMap = null;

    Vector sigParts = RampartUtil.getSignedParts(rmd);

    if (this.timestampElement != null) {
        sigParts.add(new WSEncryptionPart(RampartUtil.addWsuIdToElement((OMElement) this.timestampElement)));
    }

    if (rmd.isInitiator()) {
        // Now add the supporting tokens
        SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
        sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

        SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
        endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

        SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
        sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

        SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
        sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

        SupportingToken endorsingEncryptedSuppTokens = rpd.getEndorsingEncryptedSupportingTokens();
        endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

        SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();
        sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

        Vector supportingToks = rpd.getSupportingTokensList();
        for (int i = 0; i < supportingToks.size(); i++) {
            this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
        }

        SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
        this.handleSupportingTokens(rmd, encryptedSupportingToks);

        // Setup signature parts
        sigParts = addSignatureParts(sigSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
        sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

    } else {
        addSignatureConfirmation(rmd, sigParts);
    }

    if (sigParts.size() > 0) {
        if (sigToken instanceof KerberosToken) {
            krbToken.setParts(sigParts);
            try {
                krbToken.signMessage();
            } catch (WSSecurityException e) {
                throw new RampartException("errorInSignatureWithKerberosToken");
            }
            this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                    krbToken.getSignatureElement()));
            signatureValues.add(krbToken.getSignatureValue());
        } else {
            // Sign the message
            signatureValues.add(this.doSymmSignature(rmd, sigToken, sigTok, sigParts));
        }

        this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this.getInsertionLocation());

    }

    if (rmd.isInitiator()) {
        // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
        endSuppTokMap.putAll(endEncSuppTokMap);
        // Do endorsed signatures
        Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);

        for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
            signatureValues.add(iter.next());
        }

        // Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
        sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
        // Do signed endorsing signatures
        Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
        for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
            signatureValues.add(iter.next());
        }
    }

    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    // Encryption
    Token encrToken = rpd.getEncryptionToken();
    boolean isIssuedToken = false;
    if (encrToken instanceof IssuedToken) {
        isIssuedToken = true;
    }
    Element encrTokElem = null;
    if (sigToken.equals(encrToken)) {
        // Use the same token
        encrTokId = sigTokId;
        encrTok = sigTok;
        encrTokElem = sigTokElem;
    } else {
        encrTokId = rmd.getIssuedEncryptionTokenId();
        encrTok = this.getToken(rmd, encrTokId);

        if (SPConstants.INCLUDE_TOEKN_ALWAYS == encrToken.getInclusion()
                || SPConstants.INCLUDE_TOKEN_ONCE == encrToken.getInclusion() || (rmd.isInitiator()
                        && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encrToken.getInclusion())) {
            encrTokElem = (Element) encrTok.getToken();

            // Add the encrToken element before the sigToken element
            RampartUtil.insertSiblingBefore(rmd, sigTokElem, encrTokElem);
        }

    }

    Vector encrParts = RampartUtil.getEncryptedParts(rmd);

    // Check for signature protection
    if (rpd.isSignatureProtection() && this.mainSigId != null) {
        // Now encrypt the signature using the above token
        encrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
    }

    if (rmd.isInitiator()) {
        for (int i = 0; i < encryptedTokensIdList.size(); i++) {
            encrParts.add(new WSEncryptionPart((String) encryptedTokensIdList.get(i), "Element"));
        }
    }

    Element refList = null;
    if (encrParts.size() > 0) {
        // The sec conv token can be used without derived keys
        if (encrToken.isDerivedKeys()) {

            try {
                WSSecDKEncrypt dkEncr = new WSSecDKEncrypt();

                // Check whether it is security policy 1.2 and use the secure conversation
                // accordingly
                if (SPConstants.SP_V12 == encrToken.getVersion()) {
                    dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
                }

                if (encrTokElem != null && encrTok.getAttachedReference() != null) {

                    dkEncr.setExternalKey(encrTok.getSecret(),
                            (Element) doc.importNode((Element) encrTok.getAttachedReference(), true));
                } else if (encrTok.getUnattachedReference() != null) {
                    dkEncr.setExternalKey(encrTok.getSecret(),
                            (Element) doc.importNode((Element) encrTok.getUnattachedReference(), true));
                } else if (!rmd.isInitiator() && encrToken.isDerivedKeys()) {

                    // If the Encrypted key used to create the derived key is not
                    // attached use key identifier as defined in WSS1.1 section
                    // 7.7 Encrypted Key reference
                    SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                    if (encrTok instanceof EncryptedKeyToken) {
                        tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken) encrTok).getSHA1());
                    }
                    dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());

                } else {
                    dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
                }

                if (encrTok instanceof EncryptedKeyToken) {
                    dkEncr.setCustomValueType(
                            WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE);
                }

                dkEncr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                dkEncr.setDerivedKeyLength(rpd.getAlgorithmSuite().getEncryptionDerivedKeyLength() / 8);
                dkEncr.prepare(doc);
                Element encrDKTokenElem = null;
                encrDKTokenElem = dkEncr.getdktElement();
                if (encrTokElem != null) {
                    RampartUtil.insertSiblingAfter(rmd, encrTokElem, encrDKTokenElem);
                } else if (timestampElement != null) {
                    RampartUtil.insertSiblingAfter(rmd, this.timestampElement, encrDKTokenElem);
                } else {
                    RampartUtil.insertSiblingBefore(rmd, this.getInsertionLocation(), encrDKTokenElem);
                }

                refList = dkEncr.encryptForExternalRef(null, encrParts);

                RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, refList);

            } catch (WSSecurityException e) {
                throw new RampartException("errorInDKEncr");
            } catch (ConversationException e) {
                throw new RampartException("errorInDKEncr");
            }
        } else {
            try {

                WSSecEncrypt encr = new WSSecEncrypt();

                encr.setWsConfig(rmd.getConfig());
                // Hack to handle reference id issues
                // TODO Need a better fix
                if (encrTokId.startsWith("#")) {
                    encrTokId = encrTokId.substring(1);
                }
                encr.setEncKeyId(encrTokId);

                if (krbToken == null) {
                    encr.setEphemeralKey(encrTok.getSecret());
                    RampartUtil.setEncryptionUser(rmd, encr);
                    encr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                } else {
                    if (encrTok != null) {
                        byte[] secret = encrTok.getSecret();
                        int factor = 0;
                        if (rmd.getPolicyData().getRampartConfig() != null) {
                            KerberosConfig config = null;
                            String fac = null;
                            config = rmd.getPolicyData().getRampartConfig().getKerberosConfig();
                            if ((fac = config.getProp()
                                    .getProperty(KerberosConfig.KDC_DES_AES_FACTOR)) != null) {
                                try {
                                    factor = Integer.parseInt(fac);
                                } catch (Exception e) {
                                    factor = 0;
                                }
                            }
                        }

                        if (factor > 1) {
                            byte[] newSecret = new byte[secret.length * 4];
                            int j = 0;
                            for (int i = 0; i < newSecret.length; i++) {
                                newSecret[i] = secret[j++];
                                if (j == secret.length)
                                    j = 0;
                            }
                            encr.setEphemeralKey(newSecret);
                            encrTok.setSecret(newSecret);
                        } else {
                            encr.setEphemeralKey(secret);
                            encrTok.setSecret(secret);
                        }
                        ((EncryptedKeyToken) encrTok).setSHA1(krbToken.getKrbSession().getThumbPrintEncoded());
                        try {
                            rmd.getTokenStorage().add(sigTok);
                        } catch (TrustException e) {
                            throw new RampartException("errorAddingKerbTokenToStore");
                        }
                    }
                }

                encr.setDocument(doc);
                encr.setEncryptSymmKey(false);

                // Use key identifier in the KeyInfo in server side
                if (!rmd.isInitiator()) {
                    if (krbToken != null) {
                        encr.setUseKeyIdentifier(true);
                        encr.setKeyIdentifierType(WSConstants.KERBEROS_KEY_IDENTIFIER);
                    } else if (encrTok instanceof EncryptedKeyToken) {
                        encr.setUseKeyIdentifier(true);
                        encr.setCustomReferenceValue(((EncryptedKeyToken) encrTok).getSHA1());
                        encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                    } else if (isIssuedToken) {
                        encr.setUseKeyIdentifier(true);
                        encr.setCustomReferenceValue(encrTokId);
                        encr.setKeyIdentifierType(WSConstants.SAML_ASSERTION_IDENTIFIER);
                        try {
                            // RampartUtil.insertSiblingAfter(rmd,this.timestampElement,getLLOMfromOM(encrTok.getToken()));
                        } catch (Exception e) {
                            log.debug("error while converting SAML issued token to a dom element");
                        }
                    }
                }
                encr.prepare(doc,
                        RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));

                // Encrypt, get hold of the ref list and add it
                refList = encr.encryptForExternalRef(null, encrParts);

                if (encrTokElem != null) {
                    RampartUtil.insertSiblingAfter(rmd, encrTokElem, refList);
                } else {
                    RampartUtil.insertSiblingBeforeOrPrepend(rmd, this.getInsertionLocation(), refList);
                }

            } catch (WSSecurityException e) {
                throw new RampartException("errorInEncryption", e);
            }
        }
    }

    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug("Signature took :" + (t1 - t0) + ", Encryption took :" + (t2 - t1));
    }

}

From source file:kolacer.Kolacer.java

private String[] ziskejDatumyPodleDne(String den) {
    String[] nedele = new String[2];

    Date date = new Date();
    int style = DateFormat.LONG;
    DateFormat df = DateFormat.getDateInstance(style, Locale.forLanguageTag("sk"));
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    int pocitadlo = 0;
    while (!den.equals(df.format(date).split(",")[0])) {
        date.setTime(date.getTime() - 1000 * 60 * 60 * 24);
        pocitadlo++;/*from w ww . j  a v a2  s .  co  m*/
        if (pocitadlo == 7)
            break;
    }
    nedele[1] = sdf.format(date);
    date.setTime(date.getTime() - 14000 * 60 * 60 * 24);
    nedele[0] = sdf.format(date);
    return nedele;
}

From source file:utils.DBManager.java

public ArrayList<Group> getGroups(int status, String user) throws SQLException, ParseException {
    String sql = "select groups.groupid,groupname,creationdate,groups.ownerid,post.date,groups.private "
            + "from groups,users,user_groups,post " + "WHERE groups.groupid = user_groups.groupid "
            + "AND users.userid= user_groups.userid " + "AND post.groupid= groups.groupid "
            + "AND username = ? AND user_groups.status = ? AND (groups.private =0 OR groups.private=2)  "
            + "GROUP BY groups.groupid " + "ORDER by post.date DESC ";
    PreparedStatement stm = con.prepareStatement(sql);
    stm.setString(1, user);/*from  www  .  j a va2s  . co m*/
    stm.setInt(2, status);
    ResultSet rs;
    rs = stm.executeQuery();
    ArrayList<Group> mGroups = new ArrayList<>();
    try {
        while (rs.next()) {
            int i1, i4, i6;
            String s2;
            Date s3, s5;
            i1 = rs.getInt(1);
            s2 = rs.getString(2);
            long d = Long.parseLong(rs.getString(3));
            s3 = new Date();
            s3.setTime(d);
            i4 = rs.getInt(4);
            d = Long.parseLong(rs.getString(5));
            s5 = new Date();
            s5.setTime(d);
            i6 = rs.getInt(6);

            Group aux = new Group();

            aux.setGroupid(i1);
            aux.setTitle(s2);
            aux.setDate(s3);
            aux.setOwner(i4);
            aux.setLastPostDate(s5);
            aux.setPriva(i6 % 2 == 0);
            aux.setNumPost(getNumPost(i1));
            aux.setNumPartecipanti(getNumPartecipanti(i1));

            mGroups.add(aux);
        }

        if (status != 2) {
            sql = "SELECT groups.groupid,groupname,creationdate,groups.ownerid,post.date,groups.private "
                    + "FROM groups,post " + "WHERE post.groupid = groups.groupid "
                    + "AND (groups.private = 1 OR groups.private = 3) " + "GROUP BY groups.groupid "
                    + "ORDER by post.date DESC ";

            stm = con.prepareStatement(sql);
            rs = stm.executeQuery();

            while (rs.next()) {
                int i1, i4, i6;
                String s2;
                Date s3, s5;
                i1 = rs.getInt(1);
                s2 = rs.getString(2);
                long d = Long.parseLong(rs.getString(3));
                s3 = new Date();
                s3.setTime(d);
                i4 = rs.getInt(4);
                d = Long.parseLong(rs.getString(5));
                s5 = new Date();
                s5.setTime(d);
                i6 = rs.getInt(6);

                Group aux = new Group();

                aux.setGroupid(i1);
                aux.setTitle(s2);
                aux.setDate(s3);
                aux.setOwner(i4);
                aux.setLastPostDate(s5);
                aux.setPriva(i6 % 2 == 0);
                aux.setNumPost(getNumPost(i1));
                aux.setNumPartecipanti(getNumPartecipanti(i1));

                mGroups.add(aux);
            }
        }

    } finally {
        rs.close();
        stm.close();
    }
    Collections.sort(mGroups);
    return mGroups;
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

/** Method that lists all users with certificate's that expires within given days. */
public UserView[] filterByExpiringCertificates(String days, int index, int size) throws NumberFormatException {
    ArrayList<EndEntityInformation> userlist = new ArrayList<EndEntityInformation>();
    UserView[] returnval = null;//  w  w w  .ja  va 2  s  .c om
    long d = Long.parseLong(days);
    Date finddate = new Date();
    long millis = (d * 86400000); // One day in milliseconds.
    finddate.setTime(finddate.getTime() + millis);
    Collection<String> usernames = certificatesession.findUsernamesByExpireTimeWithLimit(finddate);
    if (!usernames.isEmpty()) {
        Iterator<String> i = usernames.iterator();
        while (i.hasNext() && userlist.size() <= EndEntityManagementConstants.MAXIMUM_QUERY_ROWCOUNT + 1) {
            EndEntityInformation user = null;
            try {
                user = endEntityAccessSession.findUser(administrator, (String) i.next());
                if (user != null) {
                    userlist.add(user);
                }
            } catch (AuthorizationDeniedException e) {
            }
        }
        usersView.setUsers(userlist, informationmemory.getCAIdToNameMap());
        returnval = usersView.getUsers(index, size);
    }
    return returnval;
}

From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java

@Override
public DublinCoreCatalogList findConflictingEvents(String captureDeviceID, String rrule, Date startDate,
        Date endDate, long duration, String timezone) throws SchedulerException {
    RRule rule;//from  ww w.ja  v  a  2 s.c  om
    try {
        rule = new RRule(rrule);
        rule.validate();
    } catch (Exception e) {
        logger.error("Could not create rule for finding conflicting events: {}", e.getMessage());
        throw new SchedulerException(e);
    }
    Recur recur = rule.getRecur();
    TimeZone tz = TimeZone.getTimeZone(timezone);
    DateTime seed = new DateTime(true);
    DateTime period = new DateTime(true);
    if (tz.inDaylightTime(startDate) && !tz.inDaylightTime(endDate)) {
        seed.setTime(startDate.getTime() + 3600000);
        period.setTime(endDate.getTime());
    } else if (!tz.inDaylightTime(startDate) && tz.inDaylightTime(endDate)) {
        seed.setTime(startDate.getTime());
        period.setTime(endDate.getTime() + 3600000);
    } else {
        seed.setTime(startDate.getTime());
        period.setTime(endDate.getTime());
    }
    DateList dates = recur.getDates(seed, period, Value.DATE_TIME);
    List<DublinCoreCatalog> events = new ArrayList<DublinCoreCatalog>();

    for (Object date : dates) {
        // Date filterStart = (Date) d;
        Date d = (Date) date;
        // Adjust for DST, if start of event
        if (tz.inDaylightTime(seed)) { // Event starts in DST
            if (!tz.inDaylightTime(d)) { // Date not in DST?
                d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour
            }
        } else { // Event doesn't start in DST
            if (tz.inDaylightTime(d)) {
                d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour
            }
        }
        // TODO optimize: create only one query and execute it
        List<DublinCoreCatalog> filterEvents = findConflictingEvents(captureDeviceID, d,
                new Date(d.getTime() + duration)).getCatalogList();
        events.addAll(filterEvents);
    }

    return new DublinCoreCatalogList(events, events.size());
}

From source file:org.etudes.mneme.impl.AssessmentServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w. j  a v  a  2 s. co  m*/
 */
public void clearStaleMintAssessments() {
    // give it a day
    Date stale = new Date();
    stale.setTime(stale.getTime() - (1000l * 60l * 60l * 24l));

    if (M_log.isDebugEnabled())
        M_log.debug("clearStaleMintAssessments");

    List<String> ids = this.storage.clearStaleMintAssessments(stale);

    // events
    for (String id : ids) {
        eventTrackingService.post(eventTrackingService.newEvent(MnemeService.ASSESSMENT_DELETE,
                getAssessmentReference(id), true));
    }
}

From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java

/**
 * Given recurrence pattern and template DublinCore, DublinCores for multiple events are generated. Each event will
 * have template's title plus sequential number. Spatial property of DublinCore is set to represent time period in
 * which event will take place.//from   w  w w.  j a va  2  s  .  c om
 * 
 * @param template
 *          {@link DublinCoreCatalog} used as template
 * @return list of {@link DublinCoreCatalog}s
 * @throws ParseException
 *           if recurrence pattern cannot be parsed
 */
protected List<DublinCoreCatalog> createEventCatalogsFromReccurence(DublinCoreCatalog template)
        throws ParseException, IllegalArgumentException {

    if (!template.hasValue(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)) {
        throw new IllegalArgumentException("Event has no recurrence pattern.");
    }

    DCMIPeriod temporal = EncodingSchemeUtils
            .decodeMandatoryPeriod(template.getFirst(DublinCore.PROPERTY_TEMPORAL));
    if (!temporal.hasEnd() || !temporal.hasStart()) {
        throw new IllegalArgumentException(
                "Dublin core field dc:temporal does not contain information about start and end of event");
    }

    Date start = temporal.getStart();
    Date end = temporal.getEnd();
    Long duration = 0L;

    TimeZone tz = null; // Create timezone based on CA's reported TZ.
    if (template.hasValue(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE)) {
        tz = TimeZone.getTimeZone(template.getFirst(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE));
    } else { // No timezone was present, assume the serve's local timezone.
        tz = TimeZone.getDefault();
    }

    Recur recur = new RRule(template.getFirst(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)).getRecur();
    DateTime seed = new DateTime(true);
    DateTime period = new DateTime(true);
    if (tz.inDaylightTime(start) && !tz.inDaylightTime(end)) {
        seed.setTime(start.getTime() + 3600000);
        period.setTime(end.getTime());
        duration = (end.getTime() - (start.getTime() + 3600000)) % (24 * 60 * 60 * 1000);
    } else if (!tz.inDaylightTime(start) && tz.inDaylightTime(end)) {
        seed.setTime(start.getTime());
        period.setTime(end.getTime() + 3600000);
        duration = ((end.getTime() + 3600000) - start.getTime()) % (24 * 60 * 60 * 1000);
    } else {
        seed.setTime(start.getTime());
        period.setTime(end.getTime());
        duration = (end.getTime() - start.getTime()) % (24 * 60 * 60 * 1000);
    }
    DateList dates = recur.getDates(seed, period, Value.DATE_TIME);
    logger.debug("DateList: {}", dates);

    List<DublinCoreCatalog> events = new LinkedList<DublinCoreCatalog>();
    int i = 1;
    int length = Integer.toString(dates.size()).length();
    for (Object date : dates) {
        Date d = (Date) date;
        // Adjust for DST, if start of event
        if (tz.inDaylightTime(seed)) { // Event starts in DST
            if (!tz.inDaylightTime(d)) { // Date not in DST?
                d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour
            }
        } else { // Event doesn't start in DST
            if (tz.inDaylightTime(d)) {
                d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour
            }
        }
        DublinCoreCatalog event = (DublinCoreCatalog) ((DublinCoreCatalogImpl) template).clone();
        int numZeros = length - Integer.toString(i).length();
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < numZeros; j++) {
            sb.append(0);
        }
        sb.append(i);
        event.set(DublinCore.PROPERTY_TITLE,
                template.getFirst(DublinCore.PROPERTY_TITLE) + " " + sb.toString());

        DublinCoreValue eventTime = EncodingSchemeUtils
                .encodePeriod(new DCMIPeriod(d, new Date(d.getTime() + duration)), Precision.Second);
        event.set(DublinCore.PROPERTY_TEMPORAL, eventTime);
        events.add(event);
        i++;
    }
    return events;
}

From source file:info.raack.appliancelabeler.web.MainController.java

@RequestMapping(value = "/energy/{frequency}", method = RequestMethod.GET)
public void getEnergyData(@PathVariable("frequency") String frequency,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis,
        @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // need to get latest values from stepgreen service

    EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response);

    Date start = new Date();
    Date end = new Date();

    if (startMillis != null && endMillis != null) {
        start = new Date(startMillis.longValue());
        end = new Date(endMillis.longValue());
    } else if (startMillis != null && endMillis == null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(startMillis.longValue());
        start = new Date();
        start.setTime(startMillis.longValue());

        c.add(Calendar.DATE, 1);//from   w w w . j  av  a  2  s  . c o  m
        end = c.getTime();
    } else if (startMillis == null && endMillis != null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(endMillis.longValue());
        end = new Date();
        end.setTime(endMillis.longValue());

        c.add(Calendar.DATE, -1);
        start = c.getTime();

    } else {
        createOneDaySpan(energyMonitor, start, end);
    }

    if (ticks == null) {
        ticks = 300;
    }

    Date queryStart = null;
    Date queryEnd = null;

    // if the time window is less than 5 minutes, then just take the window as is; otherwise, enlarge the window to the 5 minute interval requested
    if (end.getTime() - start.getTime() > (5 * 60 * 1000)) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(start);
        queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime();

        cal = new GregorianCalendar();
        cal.setTime(end);
        queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime();
    } else {
        queryStart = start;
        queryEnd = end;
    }

    List<SecondData> data = getEnergyDataWithLimits(energyMonitor,
            DataService.DataFrequency.valueOf(frequency.toUpperCase()), queryStart, queryEnd, ticks);
    Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService
            .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd);
    Map<UserAppliance, List<ApplianceStateTransition>> predictedApplianceStateTransitions = dataService
            .getPredictedApplianceStateTransitionsForMonitor(energyMonitor, algorithm.getId(), queryStart,
                    queryEnd);

    JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() {
        // serialize date to milliseconds since epoch
        public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) {
            JsonArray object = new JsonArray();
            object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime()));
            object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed()));
            return object;
        }
    };

    EnergyWrapper energyWrapper = new EnergyWrapper(data, predictedEnergyUsage,
            predictedApplianceStateTransitions, database.getEnergyCost(energyMonitor));

    String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer)
            .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() {

                // skip logger
                public boolean shouldSkipClass(Class<?> clazz) {
                    return clazz.equals(Logger.class);
                }

                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    // skip endTime of energytimestep
                    return (fieldAttributes.getName().equals("endTime")
                            && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) ||
                    // skip userAppliance, detectionAlgorithmId of appliance state transition
                    ((fieldAttributes.getName().equals("userAppliance")
                            || fieldAttributes.getName().equals("detectionAlgorithmId"))
                            && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class);
                }
            }).create().toJson(energyWrapper);

    response.getWriter().write(dataJS);

    // set appropriate JSON response type
    response.setContentType("application/json");
}