Example usage for java.util Calendar compareTo

List of usage examples for java.util Calendar compareTo

Introduction

In this page you can find the example usage for java.util Calendar compareTo.

Prototype

private int compareTo(long t) 

Source Link

Usage

From source file:org.nuxeo.ecm.core.storage.dbs.DBSSession.java

protected Document getLastVersion(String versionSeriesId) throws DocumentException {
    List<DBSDocumentState> docStates = transaction.getKeyValuedStates(KEY_VERSION_SERIES_ID, versionSeriesId);
    if (docStates.isEmpty()) {
        return null;
    }// w w  w .j  av  a2 s  . co m
    // find latest one
    Calendar latest = null;
    DBSDocumentState latestState = null;
    for (DBSDocumentState docState : docStates) {
        Calendar created = (Calendar) docState.get(KEY_VERSION_CREATED);
        if (latest == null || created.compareTo(latest) > 0) {
            latest = created;
            latestState = docState;
        }
    }
    return getDocument(latestState);
}

From source file:com.cjbdev.echo.iss.SpaceStationSpeechlet.java

/**
 * Creates a {@code SpeechletResponse} for the OneshotCityIntent.
 *
 * @return SpeechletResponse spoken and visual response for the given intent
 *///  w  w  w . j  a  v  a  2  s.  c o  m
private SpeechletResponse handleCityStateIntentRequest(final Intent intent, final Session session) {

    log.debug("Entering handleCityStateIntentRequest");

    boolean hasCountry = false;
    log.debug("hasCountry is: " + hasCountry);

    String cityObject = null;
    String stateObject = null;
    String countryObject = null;
    log.debug("Init city/state/country Objects to null");

    StringBuilder issStrBldr = new StringBuilder();
    StringBuilder issCrdBldr = new StringBuilder();
    log.debug("Init StringBuilders");

    try {

        log.debug("getSlots");

        Slot citySlot = intent.getSlot(SLOT_CITY);
        Slot stateSlot = intent.getSlot(SLOT_STATE);
        Slot countrySlot = intent.getSlot(SLOT_COUNTRY);

        log.debug("Initialized city/state/country Slots");

        KeyValuePair statePair = null;

        log.debug("Checking for a country.");

        if (countrySlot == null || countrySlot.getValue() == null) {

            log.debug("country is null so US is default");
            countryObject = "United States";
        } else {

            countryObject = countrySlot.getValue().trim();
            hasCountry = true;
            log.debug("country is not null: " + countryObject);
        }

        if (!(hasCountry)) {

            log.debug("No country so checking state.");

            if (stateSlot == null || stateSlot.getValue() == null) {

                log.debug("No state or country.");

                StringBuilder rpStrBldr = new StringBuilder();

                issStrBldr.append("<speak>");
                issStrBldr.append("<p>You have not provided a state or country.</p>");
                issStrBldr.append(
                        "<p>For a full list of states within the United States that have sighting information say list states.</p>");
                issStrBldr.append(
                        "<p>Shorten the list by saying list states starting with A or any other letter.</p>");
                issStrBldr.append(
                        "<p>For a full list of countries outside the United states that have sighting information say list countries.</p>");
                issStrBldr.append(
                        "<p>Shorten the list by saying list countries starting with A or any other letter.</p>");
                issStrBldr.append("</speak>");

                rpStrBldr.append("<speak>");
                rpStrBldr.append("<p>For a lists of states say list states.</p>");
                rpStrBldr.append("<p>For a lists of countries say list countries.</p>");
                rpStrBldr.append("</speak>");

                // Create the plain text output.
                SsmlOutputSpeech ssmlspeech = new SsmlOutputSpeech();
                ssmlspeech.setSsml(issStrBldr.toString());

                SsmlOutputSpeech rpssmlspeech = new SsmlOutputSpeech();
                rpssmlspeech.setSsml(rpStrBldr.toString());

                // Create reprompt
                Reprompt reprompt = new Reprompt();
                reprompt.setOutputSpeech(rpssmlspeech);

                return SpeechletResponse.newAskResponse(ssmlspeech, reprompt);

            } else {

                stateObject = stateSlot.getValue().trim();
                log.debug("There is a state: " + stateObject);
            }

        } else {

            log.debug("Have country so setting stateObject to None.");
            stateObject = "None";
        }

        log.debug("Checking city");
        if (citySlot == null || citySlot.getValue() == null) {

            log.debug("City is null so calling handleCity");

            if (hasCountry) {
                return handleCountryLocationList(intent, session, CITY_UNKNOWN);
            } else {
                return handleCityList(intent, session, CITY_UNKNOWN);
            }

        } else {
            // lookup the city. Sample skill uses well known mapping of a few known cities to
            // station id.
            cityObject = citySlot.getValue().trim();
            log.debug("There is a city: " + cityObject);
        }

        if (hasCountry) {

            log.debug("Getting country lookup pair");
            for (KeyValuePair item : COUNTRY_LOOKUP) {

                if (item.getKey().toLowerCase().equals(countryObject.toLowerCase())) {

                    statePair = item;
                    log.debug("pair is: " + statePair.getKey() + ", " + statePair.getValue());
                }
            }

            if ((statePair == null) || (statePair.getValue() == null)) {

                log.debug("Could not find the country in the lookup to get pair");
                return handleCountryList(intent, session, COUNTRY_UNKNOWN);
            }

        } else {

            log.debug("Getting state lookup pair");
            for (KeyValuePair item : STATE_LOOKUP) {

                if (item.getKey().toLowerCase().equals(stateObject.toLowerCase())) {

                    statePair = item;
                    log.debug("pair is: " + statePair.getKey() + ", " + statePair.getValue());
                }
            }

            if ((statePair == null) || (statePair.getValue() == null)) {

                log.debug("Could not find the country in the lookup to get pair");
                return handleStateList(intent, session, STATE_UNKNOWN);
            }
        }

        if (statePair.getKey().equals("National Parks")) {
            log.debug("Dealing with National Parks");
            issStrBldr.append("<speak>");
            issStrBldr.append("<p>The International Space Station will next be visible from ");
            issStrBldr.append(WordUtils.capitalizeFully(cityObject) + " on: </p>");

            issCrdBldr.append("The International Space Station will next be visible from ");
            issCrdBldr.append(WordUtils.capitalizeFully(cityObject) + " on: ");

        } else {
            log.debug("No need for rewording for National Parks");
            issStrBldr.append("<speak>");
            issStrBldr.append("<p>The International Space Station will next be visible from ");
            issStrBldr.append(WordUtils.capitalizeFully(cityObject));
            if (hasCountry) {
                issStrBldr.append(", " + countryObject + " on: </p>");
            } else {
                issStrBldr.append(", " + stateObject + " on: </p>");
            }

            issCrdBldr.append("The International Space Station will next be visible from ");
            issCrdBldr.append(WordUtils.capitalizeFully(cityObject));
            if (hasCountry) {
                issCrdBldr.append(", " + countryObject + " on: ");
            } else {
                issCrdBldr.append(", " + stateObject + " on: ");
            }
        }

        log.debug("Preparing inputStream");
        InputStream in = null;
        if (hasCountry) {
            in = getClass().getResourceAsStream("/speechAssets/countries/" + statePair.getValue());
            log.debug("Got inputStream to: /speechAssets/countries/" + statePair.getValue());
        } else {

            in = getClass().getResourceAsStream("/speechAssets/states/" + statePair.getValue());
            log.debug("Got inputStream to: /speechAssets/states/" + statePair.getValue());
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        log.debug("Created buffered reader");

        List<KeyValuePair> cityList = new ArrayList<KeyValuePair>();

        String sCurrentLine = "";
        while ((sCurrentLine = reader.readLine()) != null) {
            String cityArray[] = sCurrentLine.split(",");
            KeyValuePair cityItem = new KeyValuePair(cityArray[0], cityArray[1]);
            log.debug("Reading in city: " + cityItem.getKey() + ", " + cityItem.getValue());
            cityList.add(cityItem);
        }

        log.debug("cityList created: " + cityList.size());

        KeyValuePair cityPair = null;

        log.debug("Run through list to look for: " + cityObject);

        for (KeyValuePair item : cityList) {
            log.debug("checking :" + cityObject + " against " + item.getKey());
            if (item.getKey().toLowerCase().equals(cityObject.toLowerCase())) {
                cityPair = item;
                log.debug("*************FOUND IT!! " + cityPair.getKey());
            }
        }

        if (cityPair == null) {

            return handleCityList(intent, session, CITY_UNKNOWN);
        }

        log.info("Retrieving data for: " + cityPair.getValue());

        URL url = new URL(
                "https://spotthestation.nasa.gov/sightings/xml_files/" + cityPair.getValue() + ".xml");
        HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();

        // Reading the feed
        SyndFeedInput input = new SyndFeedInput();
        SyndFeed feed = input.build(new XmlReader(httpcon));
        List<SyndEntry> entries = feed.getEntries();

        if (entries.isEmpty()) {

            in.close();

            StringBuilder ndStrBldr = new StringBuilder();
            StringBuilder ndCrdBldr = new StringBuilder();

            ndStrBldr.append("<speak>");
            ndStrBldr.append("<p>There are no sightings for ");
            ndStrBldr.append(WordUtils.capitalizeFully(cityObject));
            if (hasCountry) {
                ndStrBldr.append(", " + countryObject);
            } else {
                ndStrBldr.append(", " + stateObject);
            }
            ndStrBldr.append(" during the current two week period.</p>");
            ndStrBldr.append(
                    "<p>The data lists of space station sightings are updated multiple times a week.</p>");
            ndStrBldr.append(
                    "<p>Please check back in a few days to see if there are any upcoming sighting events for your area.</p>");
            ndStrBldr.append("</speak>");

            ndCrdBldr.append("There are no sightings for ");
            ndCrdBldr.append(WordUtils.capitalizeFully(cityObject));
            if (hasCountry) {
                ndCrdBldr.append(", " + countryObject);
            } else {
                ndCrdBldr.append(", " + stateObject);
            }
            ndCrdBldr.append(" during the current two week period. ");
            ndCrdBldr.append("The data lists of space station sightings are updated multiple times a week.");
            ndCrdBldr.append(
                    "Please check back in a few days to see if there are any upcoming sighting events for your area. ");

            // Create the plain text output.
            SsmlOutputSpeech ssmlspeech = new SsmlOutputSpeech();
            ssmlspeech.setSsml(ndStrBldr.toString());

            // Create the Simple card content.
            SimpleCard card = new SimpleCard();

            if (hasCountry) {
                card.setTitle("ISS - Sighting Information: " + WordUtils.capitalizeFully(cityObject) + ", "
                        + WordUtils.capitalizeFully(countryObject));
            } else {
                card.setTitle("ISS - Sighting Information: " + WordUtils.capitalizeFully(cityObject) + ", "
                        + WordUtils.capitalizeFully(stateObject));
            }

            card.setContent(ndCrdBldr.toString());

            return SpeechletResponse.newTellResponse(ssmlspeech, card);
        }

        Iterator<SyndEntry> itEntries = entries.iterator();

        boolean first = true;
        String firstDesc = "";
        String firstDescMod = "";
        String firstSightDate = "";

        while (itEntries.hasNext()) {
            SyndEntry entry = itEntries.next();
            SyndContent desc = entry.getDescription();
            String descStr = desc.getValue();
            String descStrMod = descStr.replaceAll("<br/>", "");

            String durationSplitArray[] = descStrMod.split("Duration");
            String dateTimeStr = durationSplitArray[0];
            String dateTimeSplitArray[] = dateTimeStr.split("Time:");
            String dateSplitStr = dateTimeSplitArray[0];
            String dateArray[] = dateSplitStr.split("Date:");
            String sightDate = dateArray[1].trim() + " " + dateTimeSplitArray[1].trim();

            SimpleDateFormat formatter = new SimpleDateFormat("EEEE MMM dd, yyyy hh:mm a");

            Calendar cal = Calendar.getInstance();
            Calendar future = Calendar.getInstance();
            future.setTime(formatter.parse(sightDate));

            if ((future.compareTo(cal) > 0) && first) {
                firstDesc = descStr;
                firstDescMod = descStrMod;
                firstSightDate = sightDate;
                first = false;
            }
        }

        firstDesc = firstDesc.replaceAll("\t", "");
        firstDesc = firstDesc.replaceAll("\n", "");

        String descStrArray[] = firstDesc.split("<br/>");

        StringBuilder sightLine = new StringBuilder();

        for (String dStr : descStrArray) {
            String dTkn = dStr;
            dTkn = dTkn.trim();

            if (dTkn.startsWith("Date:")) {

                String sdArray[] = firstSightDate.split(" ");
                String fullMonth = getFullMonth(sdArray[1]);
                String newTkn = dTkn.replace(sdArray[1], fullMonth);
                sightLine.append("<p>" + newTkn + "</p>");
            } else if (dTkn.startsWith("Time:")) {

                sightLine.append("<p>" + dTkn + "</p>");
            } else if (dTkn.startsWith("Duration:")) {

                sightLine.append("<p>" + dTkn + "</p>");
            } else if (dTkn.startsWith("Maximum:")) {

                sightLine.append("<p>" + dTkn + "</p>");
            } else if (dTkn.startsWith("Approach:")) {

                String sStr[] = dTkn.split("above");
                String abrDir = sStr[1].trim();
                String dirStr = getFullDirection(abrDir);
                sightLine.append("<p>" + sStr[0] + "above " + dirStr + "</p>");
            } else if (dTkn.startsWith("Departure:")) {

                String sStr[] = dTkn.split("above");
                String abrDir = sStr[1].trim();
                String dirStr = getFullDirection(abrDir);
                sightLine.append("<p>" + sStr[0] + "above " + dirStr + "</p>");
            }
        }

        issStrBldr.append(sightLine.toString());
        issStrBldr.append("</speak>");

        issCrdBldr.append(firstDescMod);
    } catch (MalformedURLException muex) {
        System.out.println("MalformedURLException" + muex.getMessage());
    } catch (IOException ioex) {
        System.out.println("IOException" + ioex.getMessage());
    } catch (FeedException fex) {
        System.out.println("FeedException" + fex.getMessage());
    } catch (Exception ex) {
        System.out.println("Exeption" + ex.getMessage());
    }

    // Create the Simple card content.
    SimpleCard card = new SimpleCard();

    if (hasCountry) {
        card.setTitle("ISS - Sighting Information: " + WordUtils.capitalizeFully(cityObject) + ", "
                + WordUtils.capitalizeFully(countryObject));
    } else {
        card.setTitle("ISS - Sighting Information: " + WordUtils.capitalizeFully(cityObject) + ", "
                + WordUtils.capitalizeFully(stateObject));
    }

    card.setContent(issCrdBldr.toString());

    // Create the plain text output.
    PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
    speech.setText(issStrBldr.toString());

    // Create the ssmloutput text output.
    SsmlOutputSpeech smlspeech = new SsmlOutputSpeech();
    smlspeech.setSsml(issStrBldr.toString());

    log.debug("Exiting handleCityStateIntentRequest");

    return SpeechletResponse.newTellResponse(smlspeech, card);
}

From source file:org.alfresco.module.org_alfresco_module_rm.record.RecordServiceImpl.java

/**
 * Ensure that the user only updates record properties that they have permission to.
 *
 * @see org.alfresco.repo.node.NodeServicePolicies.OnUpdatePropertiesPolicy#onUpdateProperties(org.alfresco.service.cmr.repository.NodeRef, java.util.Map, java.util.Map)
 *///from   www . j  a  v  a 2s .c o  m
@Override
@Behaviour(name = "onUpdateProperties", kind = BehaviourKind.CLASS, type = "rma:record")
public void onUpdateProperties(final NodeRef nodeRef, final Map<QName, Serializable> before,
        final Map<QName, Serializable> after) {
    if (AuthenticationUtil.getFullyAuthenticatedUser() != null && !AuthenticationUtil.isRunAsUserTheSystemUser()
            && nodeService.exists(nodeRef) && isRecord(nodeRef)
            && !transactionalResourceHelper.getSet(KEY_IGNORE_ON_UPDATE).contains(nodeRef)) {
        for (Map.Entry<QName, Serializable> entry : after.entrySet()) {
            Serializable beforeValue = null;
            QName property = entry.getKey();
            if (before != null) {
                beforeValue = before.get(property);
            }

            Serializable afterValue = entry.getValue();
            boolean propertyUnchanged = false;
            if (beforeValue instanceof Date && afterValue instanceof Date) {
                // deal with date values, remove the seconds and milliseconds for the
                // comparison as they are removed from the submitted for data
                Calendar beforeCal = Calendar.getInstance();
                beforeCal.setTime((Date) beforeValue);
                Calendar afterCal = Calendar.getInstance();
                afterCal.setTime((Date) afterValue);
                beforeCal.set(Calendar.SECOND, 0);
                beforeCal.set(Calendar.MILLISECOND, 0);
                afterCal.set(Calendar.SECOND, 0);
                afterCal.set(Calendar.MILLISECOND, 0);
                propertyUnchanged = (beforeCal.compareTo(afterCal) == 0);
            } else if ((afterValue instanceof Boolean) && (beforeValue == null)
                    && (afterValue.equals(Boolean.FALSE))) {
                propertyUnchanged = true;
            } else {
                // otherwise
                propertyUnchanged = EqualsHelper.nullSafeEquals(beforeValue, afterValue);
            }

            if (!propertyUnchanged && !(ContentModel.PROP_CONTENT.equals(property) && beforeValue == null)
                    && !isPropertyEditable(nodeRef, property)) {
                // the user can't edit the record property
                throw new ModelAccessDeniedException(
                        "The user " + AuthenticationUtil.getFullyAuthenticatedUser()
                                + " does not have the permission to edit the record property "
                                + property.toString() + " on the node " + nodeRef.toString());
            }
        }
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.meta.impl.TimeDimensionMemberServiceImpl.java

/**
 * ??// ww w. j  ava 2 s. c om
 * 
 * @param level
 * @param parentMember
 * @return
 */
private List<MiniCubeMember> genMembersWithQuarterParentForAll(Level level, Member parentMember) {
    List<MiniCubeMember> members = Lists.newArrayList();
    Calendar cal = Calendar.getInstance(); // ?
    cal.set(Calendar.DAY_OF_MONTH, 1); // 1?
    int nowMonth = cal.get(Calendar.MONTH) + 1; // ?
    int quarterIndex = nowMonth / 3; // 
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    for (int i = 0; i <= quarterIndex; i++) {
        cal.set(Calendar.MONTH, i * 3);// 
        cal.set(Calendar.DATE, 1);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(cal.getTime());
        calEnd.add(Calendar.MONTH, 2);
        calEnd.add(Calendar.DATE, calEnd.getActualMaximum(Calendar.DATE) - 1); // 
        String day = sf.format(cal.getTime());
        String year = day.substring(0, 4);
        String caption = year + "" + (i + 1) + "";
        MiniCubeMember firstDayOfQuarter = new MiniCubeMember(day);
        firstDayOfQuarter.setCaption(caption);
        firstDayOfQuarter.setLevel(level);
        firstDayOfQuarter.setParent(parentMember);
        firstDayOfQuarter.setName(day);
        firstDayOfQuarter.setVisible(true);
        while (cal.before(calEnd) || (cal.compareTo(calEnd) == 0)) {
            firstDayOfQuarter.getQueryNodes().add(sf.format(cal.getTime()));
            cal.add(Calendar.DATE, 1);
        }
        members.add(firstDayOfQuarter);
    }
    return members;
}

From source file:org.bedework.notifier.outbound.email.EmailAdaptor.java

private List<TemplateResult> applyTemplates(final Action action) throws NoteException {
    final Note note = action.getNote();
    final NotificationType nt = note.getNotification();
    final EmailSubscription sub = EmailSubscription.rewrap(action.getSub());

    List<TemplateResult> results = new ArrayList<TemplateResult>();
    try {//from ww w.j av a2 s.c o  m
        String prefix = nt.getParsed().getDocumentElement().getPrefix();

        if (prefix == null) {
            prefix = "default";
        }

        final String abstractPath = Util.buildPath(false, Note.DeliveryMethod.email.toString(), "/", prefix,
                "/", nt.getNotification().getElementName().getLocalPart());

        File templateDir = new File(Util.buildPath(false, globalConfig.getTemplatesPath(), "/", abstractPath));
        if (templateDir.isDirectory()) {

            Map<String, Object> root = new HashMap<String, Object>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(nt.toXml(true))));
            Element el = doc.getDocumentElement();
            NodeModel.simplify(el);
            NodeModel.useJaxenXPathSupport();
            root.put("notification", el);

            HashSet<String> recipients = new HashSet<String>();
            for (String email : sub.getEmails()) {
                recipients.add(MAILTO + email);
            }
            root.put("recipients", recipients);

            if (globalConfig.getCardDAVHost() != null && globalConfig.getCardDAVPort() != 0
                    && globalConfig.getCardDAVContextPath() != null) {
                HashMap<String, Object> vcards = new HashMap<String, Object>();
                BasicHttpClient client;
                try {
                    ArrayList<Header> hdrs = new ArrayList<Header>();
                    BasicHeader h = new BasicHeader(HEADER_ACCEPT, globalConfig.getVCardContentType());
                    hdrs.add(h);

                    client = new BasicHttpClient(globalConfig.getCardDAVHost(), globalConfig.getCardDAVPort(),
                            null, 15 * 1000);

                    XPathExpression exp = xPath.compile("//*[local-name() = 'href']");
                    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    HashSet<String> vcardLookups = new HashSet<String>();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        String text = n.getTextContent();

                        text = pMailto.matcher(text).replaceFirst(MAILTO);
                        if (text.startsWith(MAILTO)
                                || text.startsWith(globalConfig.getCardDAVPrincipalsPath())) {
                            vcardLookups.add(text);
                        }
                    }

                    // Get vCards for recipients too. They may not be referenced in the notification.
                    vcardLookups.addAll(recipients);

                    for (String lookup : vcardLookups) {
                        String path = Util.buildPath(false,
                                globalConfig.getCardDAVContextPath() + "/" + lookup.replace(':', '/'));

                        final InputStream is = client.get(path + VCARD_SUFFIX, "application/text", hdrs);
                        if (is != null) {
                            ObjectMapper om = new ObjectMapper();
                            @SuppressWarnings("unchecked")
                            ArrayList<Object> hm = om.readValue(is, ArrayList.class);
                            vcards.put(lookup, hm);
                        }
                    }
                    root.put("vcards", vcards);
                } catch (final Throwable t) {
                    error(t);
                }
            }

            if (nt.getNotification() instanceof ResourceChangeType) {
                ResourceChangeType chg = (ResourceChangeType) nt.getNotification();
                BedeworkConnectorConfig cfg = ((BedeworkConnector) action.getConn()).getConnectorConfig();
                BasicHttpClient cl = getClient(cfg);
                List<Header> hdrs = getHeaders(cfg, new BedeworkSubscription(action.getSub()));

                String href = null;
                if (chg.getCreated() != null) {
                    href = chg.getCreated().getHref();
                } else if (chg.getDeleted() != null) {
                    href = chg.getDeleted().getHref();
                } else if (chg.getUpdated() != null && chg.getUpdated().size() > 0) {
                    href = chg.getUpdated().get(0).getHref();
                }

                if (href != null) {
                    if (chg.getDeleted() == null) {
                        // We only have an event for the templates on a create or update, not on delete.
                        ObjectMapper om = new ObjectMapper();
                        final InputStream is = cl.get(cfg.getSystemUrl() + href, null, hdrs);
                        JsonNode a = om.readValue(is, JsonNode.class);

                        // Check for a recurrence ID on this notification.
                        XPathExpression exp = xPath.compile("//*[local-name() = 'recurrenceid']/text()");
                        String rid = exp.evaluate(doc);
                        if (rid != null && !rid.isEmpty()) {
                            Calendar rcal = Calendar.getInstance();
                            recurIdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                            rcal.setTime(recurIdFormat.parse(rid));

                            // Find the matching recurrence ID in the JSON, and make that the only vevent object.
                            Calendar c = Calendar.getInstance();
                            ArrayNode vevents = (ArrayNode) a.get(2);
                            for (JsonNode vevent : vevents) {
                                if (vevent.size() > 1 && vevent.get(1).size() > 1) {
                                    JsonNode n = vevent.get(1).get(0);
                                    if (n.get(0).asText().equals("recurrence-id")) {
                                        if (n.get(1).size() > 0 && n.get(1).get("tzid") != null) {
                                            jsonIdFormatTZ.setTimeZone(
                                                    TimeZone.getTimeZone(n.get(1).get("tzid").asText()));
                                            c.setTime(jsonIdFormatTZ.parse(n.get(3).asText()));
                                        } else {
                                            jsonIdFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            c.setTime(jsonIdFormatUTC.parse(n.get(3).asText()));
                                        }
                                        if (rcal.compareTo(c) == 0) {
                                            vevents.removeAll();
                                            vevents.add(vevent);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        root.put("vevent", (ArrayList<Object>) om.convertValue(a, ArrayList.class));
                    }

                    // TODO: Provide some calendar information to the templates. This is currently the publisher's
                    // calendar, but needs to be fixed to be the subscriber's calendar.
                    String chref = href.substring(0, href.lastIndexOf("/"));
                    hdrs.add(new BasicHeader(HEADER_DEPTH, "0"));
                    int rc = cl.sendRequest("PROPFIND", cfg.getSystemUrl() + chref, hdrs, "text/xml",
                            CALENDAR_PROPFIND.length(), CALENDAR_PROPFIND.getBytes());
                    if (rc == HttpServletResponse.SC_OK || rc == SC_MULTISTATUS) {
                        Document d = builder.parse(new InputSource(cl.getResponseBodyAsStream()));
                        HashMap<String, String> hm = new HashMap<String, String>();
                        XPathExpression exp = xPath.compile("//*[local-name() = 'href']/text()");
                        hm.put("href", exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'displayname']/text()");
                        hm.put("name", (String) exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'calendar-description']/text()");
                        hm.put("description", (String) exp.evaluate(d));
                        root.put("calendar", hm);
                    }
                }
            }

            if (note.getExtraValues() != null) {
                root.putAll(note.getExtraValues());
            }

            DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(
                    Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            root.put("timezone", (TemplateHashModel) wrapper.getStaticModels().get("java.util.TimeZone"));

            // Sort files so the user can control the order of content types/body parts of the email by template file name.
            File[] templates = templateDir.listFiles(templateFilter);
            Arrays.sort(templates);
            for (File f : templates) {
                Template template = fmConfig.getTemplate(Util.buildPath(false, abstractPath, "/", f.getName()));
                Writer out = new StringWriter();
                Environment env = template.createProcessingEnvironment(root, out);
                env.process();

                TemplateResult r = new TemplateResult(f.getName(), out.toString(), env);
                if (!r.getBooleanVariable("skip")) {
                    results.add(new TemplateResult(f.getName(), out.toString(), env));
                }
            }
        }
    } catch (final Throwable t) {
        throw new NoteException(t);
    }
    return results;
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

private static String coord_latestRange_sync(int startOffset, int endOffset) throws Exception {
    final XLog LOG = XLog.getLog(CoordELFunctions.class);
    final Thread currentThread = Thread.currentThread();
    ELEvaluator eval = ELEvaluator.getCurrent();
    String retVal = "";
    int datasetFrequency = (int) getDSFrequency();// in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1];
    boolean useCurrentTime = Services.get().getConf().getBoolean(LATEST_EL_USE_CURRENT_TIME, false);
    Calendar nominalInstanceCal;
    if (useCurrentTime) {
        nominalInstanceCal = getCurrentInstance(new Date(), instCount);
    } else {/*from  www  . j a  v a 2 s .com*/
        nominalInstanceCal = getCurrentInstance(getActualTime(), instCount);
    }
    StringBuilder resolvedInstances = new StringBuilder();
    StringBuilder resolvedURIPaths = new StringBuilder();
    if (nominalInstanceCal != null) {
        Calendar initInstance = getInitialInstanceCal();
        SyncCoordDataset ds = (SyncCoordDataset) eval.getVariable(DATASET);
        if (ds == null) {
            throw new RuntimeException("Associated Dataset should be defined with key " + DATASET);
        }
        String uriTemplate = ds.getUriTemplate();
        Configuration conf = (Configuration) eval.getVariable(CONFIGURATION);
        if (conf == null) {
            throw new RuntimeException("Associated Configuration should be defined with key " + CONFIGURATION);
        }
        int available = 0;
        boolean resolved = false;
        String user = ParamChecker.notEmpty((String) eval.getVariable(OozieClient.USER_NAME),
                OozieClient.USER_NAME);
        String doneFlag = ds.getDoneFlag();
        URIHandlerService uriService = Services.get().get(URIHandlerService.class);
        URIHandler uriHandler = null;
        Context uriContext = null;
        try {
            while (nominalInstanceCal.compareTo(initInstance) >= 0 && !currentThread.isInterrupted()) {
                ELEvaluator uriEval = getUriEvaluator(nominalInstanceCal);
                String uriPath = uriEval.evaluate(uriTemplate, String.class);
                if (uriHandler == null) {
                    URI uri = new URI(uriPath);
                    uriHandler = uriService.getURIHandler(uri);
                    uriContext = uriHandler.getContext(uri, conf, user, true);
                }
                String uriWithDoneFlag = uriHandler.getURIWithDoneFlag(uriPath, doneFlag);
                if (uriHandler.exists(new URI(uriWithDoneFlag), uriContext)) {
                    XLog.getLog(CoordELFunctions.class)
                            .debug("Found latest(" + available + "): " + uriWithDoneFlag);
                    if (available == startOffset) {
                        LOG.debug("Matched latest(" + available + "): " + uriWithDoneFlag);
                        resolved = true;
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal));
                        resolvedURIPaths.append(uriPath);
                        retVal = resolvedInstances.toString();
                        eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());

                        break;
                    } else if (available <= endOffset) {
                        LOG.debug("Matched latest(" + available + "): " + uriWithDoneFlag);
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal))
                                .append(INSTANCE_SEPARATOR);
                        resolvedURIPaths.append(uriPath).append(INSTANCE_SEPARATOR);
                    }

                    available--;
                }
                // nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), -datasetFrequency);
                nominalInstanceCal = (Calendar) initInstance.clone();
                instCount[0]--;
                nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);
                // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
            }
            if (!StringUtils.isEmpty(resolvedURIPaths.toString())
                    && eval.getVariable(CoordELConstants.RESOLVED_PATH) == null) {
                eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());
            }
        } finally {
            if (uriContext != null) {
                uriContext.destroy();
            }
        }
        if (!resolved) {
            // return unchanged latest function with variable 'is_resolved'
            // to 'false'
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE);
            if (startOffset == endOffset) {
                retVal = "${coord:latest(" + startOffset + ")}";
            } else {
                retVal = "${coord:latestRange(" + startOffset + "," + endOffset + ")}";
            }
        } else {
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE);
        }
    } else {// No feasible nominal time
        eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE);
    }
    return retVal;
}

From source file:org.finra.dm.dao.AbstractDaoTest.java

/**
 * Creates a list of expected partition value process dates for a specified range. Weekends are excluded.
 *
 * @param partitionKeyGroupName the partition key group name
 * @param startDate the start date of the range
 * @param endDate the end date of the range
 *
 * @return the list of expected partition value process dates
 *//*from   ww  w . j a v  a  2 s.c  o m*/
protected List<ExpectedPartitionValueEntity> createExpectedPartitionValueProcessDates(
        String partitionKeyGroupName, Calendar startDate, Calendar endDate) {
    // Initialize the list of expected partition values.
    List<String> expectedPartitionValues = new ArrayList<>();

    // Keep incrementing the start date until it is greater than the end date, or until we have 1000 dates to protect against having too many dates or an
    // infinite loop in case the end date is before the start date.
    for (int i = 0; i < 1000 && startDate.compareTo(endDate) <= 0; i++) {
        // Create and persist a new entity for the date if it does not fall on the weekend.
        if ((startDate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)
                && (startDate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)) {
            expectedPartitionValues
                    .add(new SimpleDateFormat(DmDao.DEFAULT_SINGLE_DAY_DATE_MASK).format(startDate.getTime()));
        }

        // Add one day to the calendar.
        startDate.add(Calendar.DAY_OF_MONTH, 1);
    }

    // Return the list of entities.
    return createExpectedPartitionValueEntities(partitionKeyGroupName, expectedPartitionValues);
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Cleans the directory containing old files.
 * <p/>//from w  w  w . j  a  va2 s  . c om
 * This method does not throw any exception.
 *
 * @param toCleanDirectory The directory containing old files to clean.
 */
private void cleanOutOldFiles(File toCleanDirectory) {
    if (!toCleanDirectory.exists() || !toCleanDirectory.isDirectory() || !toCleanDirectory.canRead()
            || !toCleanDirectory.canWrite()) {
        logger.warn("Can not clean directory:" + toCleanDirectory);
        return;
    }

    int numberDeletedFiles = 0;

    final String regex = wildCardToClean.replace("?", ".?").replace("*", ".*?");

    final Calendar currentCalendar = Calendar.getInstance();
    currentCalendar.setTime(new Date());

    try {

        File[] candidateFiles = toCleanDirectory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File inputFile) {
                Calendar lastModifiedCalendar = Calendar.getInstance();
                lastModifiedCalendar.setTime(new Date(inputFile.lastModified()));
                lastModifiedCalendar.add(Calendar.DAY_OF_MONTH, ageToCleanInDays);

                return lastModifiedCalendar.compareTo(currentCalendar) < 0 && inputFile.getName().matches(regex)
                        && inputFile.isFile() && inputFile.canWrite();
            }
        });

        for (File candidateFile : candidateFiles) {
            candidateFile.delete();
            numberDeletedFiles++;
        }

        logger.info("Old files cleaned: " + numberDeletedFiles);
    } catch (Exception e) {
        // Ignore any error, just log it
        logger.error("Error while cleaning old files", e);
    }
}

From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java

/**
 * create a subjob for each day in the date range, using first parameter as a template.
 * Then transfer all the rinex files for each subjob. 
 * @param strDateFrom/*ww w .j  ava 2s.c om*/
 * @param strDateTo
 * @param param
 * @return array of strings
 */
private String[] createSubjobs(String strDateFrom, String strDateTo, String param, HttpServletRequest request,
        List<GeodesyGridInputFile> gpsFiles) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<String> paramList = new ArrayList<String>();
    // Save in session to use it when submitting job
    String jobInputDir = (String) request.getSession().getAttribute("jobInputDir");

    //Use the first parameter from GUI as template for generating param for each day in the date range
    String paramTemp = param.substring(param.indexOf("-expt", 0), param.length());

    try {
        Date dateFrom = df.parse(strDateFrom);
        Date dateTo = df.parse(strDateTo);

        Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(dateFrom);

        Calendar calTo = Calendar.getInstance();
        calTo.setTime(dateTo);

        //String gpsFiles = (String)request.getSession().getAttribute("gridInputFiles");   
        //List<String> urlsList = GeodesyUtil.getSelectedGPSFiles(gpsFiles);

        //while dateFrom is less than or equal to dateTo
        int jobCount = 0;
        while ((calFrom.compareTo(calTo)) <= 0) {
            //TO-DO check if this subJob has renix files available
            int year = calFrom.get(Calendar.YEAR);
            int doy = calFrom.get(Calendar.DAY_OF_YEAR);
            String strParam = "-d " + year + " " + doy + " " + paramTemp;
            paramList.add(strParam);

            String[] rinexOfDay = getRinexFilesOfDate(calFrom, gpsFiles);
            if (rinexOfDay.length > 0) {
                //First create subJob/rinex/ directories path for this subJob
                //Then urlcopy relevent rinex files for this sub job
                String subJobId = "subJob_" + jobCount;
                String subJobDir = jobInputDir + subJobId + File.separator;
                if (createGridDir(request, subJobDir)) {
                    String rinexSubJobDir = subJobDir + GridSubmitController.RINEX_DIR + File.separator;
                    if (createGridDir(request, rinexSubJobDir)) {
                        // Full URL
                        // e.g. "gsiftp://pbstore.ivec.org:2811//pbstore/au01/grid-auscope/Abdi.Jama@csiro.au-20091103_163322/"
                        //       +"rinex/" + filename
                        String toURL = gridAccess.getGridFtpServer() + File.separator + rinexSubJobDir;
                        urlCopy(rinexOfDay, request, toURL);

                        Hashtable subJobStageInDir = (Hashtable) request.getSession()
                                .getAttribute("subJobStageInDir");

                        if (subJobStageInDir == null)
                            subJobStageInDir = new Hashtable();

                        if (!subJobStageInDir.containsKey(subJobId)) {
                            String gridSubjobDir = gridAccess.getGridFtpServer() + subJobDir;
                            subJobStageInDir.put(subJobId, gridSubjobDir);
                            request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                            logger.info("Added gridStageInDir: " + gridSubjobDir);
                        }
                    }
                    /*Hashtable subJobStageInDir = (Hashtable) request.getSession().getAttribute("subJobStageInDir");
                            
                    if(subJobStageInDir == null)
                       subJobStageInDir = new Hashtable();
                            
                    if(!subJobStageInDir.containsKey(subJobId)){
                       String gridSubjobDir = gridAccess.getGridFtpServer()+subJobDir;
                       subJobStageInDir.put(subJobId, gridSubjobDir);
                       request.getSession().setAttribute("subJobStageInDir", subJobStageInDir);
                       logger.info("Added gridStageInDir: "+gridSubjobDir);
                    }*/
                }
            } else {
                logger.info("No rinex files found for this day: " + year + "-" + doy);
            }

            calFrom.add(Calendar.DATE, 1);
            jobCount++;
            logger.debug("Added param: " + strParam);
        }
    } catch (ParseException e) {
        //do we need to pass this to the gui
        logger.error("Error casting date: " + e.getMessage());
    }
    String[] paramArray = new String[paramList.size()];
    paramArray = paramList.toArray(paramArray);
    return paramArray;
}

From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java

private String[] getRinexFilesOfDate(Calendar currentDate, List<GeodesyGridInputFile> gpsFiles) {

    List<String> rinexFilesOfDate = new ArrayList<String>();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar fileDate = Calendar.getInstance();
    for (GeodesyGridInputFile rinexUrl : gpsFiles) {
        try {//from w  w  w .j av a 2s  .  c  om
            Date date = df.parse(rinexUrl.getFileDate());
            fileDate.setTime(date);

            //now check if the file if for the current date, we don't care about which station
            if (currentDate.compareTo(fileDate) == 0) {
                logger.debug(
                        "Date: " + currentDate.get(Calendar.YEAR) + "-" + currentDate.get(Calendar.DAY_OF_YEAR)
                                + " is matched to rinex file: " + rinexUrl.getFileUrl());
                rinexFilesOfDate.add(rinexUrl.getFileUrl());
                //TO-DO it would be nice for performance if we could remove processed urls from the list
                //somehow this fails.
                //gpsFiles.remove(rinexUrl);
            }
        } catch (Exception e) {
            //do we need to pass this to the gui
            logger.error("Error casting date of the rinex file: " + e.getMessage());
        }

    }

    String[] rinexArray = new String[rinexFilesOfDate.size()];
    rinexArray = rinexFilesOfDate.toArray(rinexArray);
    return rinexArray;
}