Java Examples for org.joda.time.format.DateTimeFormat

The following java examples will help you to understand the usage of org.joda.time.format.DateTimeFormat. These source code samples are taken from different open source projects.

Example 1
Project: flare-spork-master  File: CustomFormatToISO.java View source code
@Override
public String exec(Tuple input) throws IOException {
    if (input == null || input.size() < 2) {
        return null;
    }
    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);
    String date = input.get(0).toString();
    String format = input.get(1).toString();
    // See http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
    DateTimeFormatter parser = DateTimeFormat.forPattern(format);
    DateTime result;
    try {
        result = parser.parseDateTime(date);
    } catch (Exception e) {
        return null;
    }
    return result.toString();
}
Example 2
Project: jtotus-master  File: FetcherOsuusPankki.java View source code
public static void main(String[] av) {
    String patternString = "yyyy-MM-dd";
    DateTimeFormatter formatter = DateTimeFormat.forPattern(patternString);
    String name = "Metso Oyj";
    DateTime fromDate = formatter.parseDateTime("2009-05-01");
    DateTime toDate = formatter.parseDateTime("2011-05-05");
    ;
    int type = 0;
    FetcherOsuusPankki instance = new FetcherOsuusPankki();
    Map<String, Double> result = instance.fetchDataPeriod(name, fromDate, toDate, type);
//        
//        for (Entry<String,Double> entry:result.entrySet()) {
//            System.out.printf("%s, %f\n", entry.getKey(), entry.getValue());
//        }
}
Example 3
Project: eGov-master  File: DashboardService.java View source code
public List<Map<String, Object>> getOpenComplaintSLA() {
    final DateTime startOfTheYear = new LocalDate().minusYears(1).toDateTimeAtStartOfDay();
    final DateTime tillDate = new LocalDate().toDateTimeAtCurrentTime();
    final List<Object[]> openComplaints = dashboardRepository.fetchOpenComplaintAggregateBetween(startOfTheYear, tillDate);
    final List<Map<String, Object>> compAggrData = new ArrayList<Map<String, Object>>();
    final Map<String, Object> complaintData = new HashMap<String, Object>();
    String lastZone = null;
    double regComplaint = 0;
    double openFrm90Days = 0;
    double totalOpen = 0;
    double pecentage = 0;
    final Date dateBefore90Days = new LocalDate().minusDays(90).toDateTimeAtStartOfDay().toDate();
    final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyy");
    final String formattedFrm = startOfTheYear.toString(dtf);
    final String formattedTo = tillDate.toString(dtf);
    for (final Object[] compData : openComplaints) {
        final String statusName = String.valueOf(compData[4]);
        final long count = Long.valueOf(String.valueOf(compData[5]));
        if ("REGISTERED FORWARDED PROCESSING REOPENED".contains(statusName)) {
            if (((Date) compData[6]).before(dateBefore90Days))
                openFrm90Days += count;
            totalOpen += count;
        }
        regComplaint += count;
        complaintData.put("lat", compData[3]);
        complaintData.put("lng", compData[2]);
        complaintData.put("startDt", formattedFrm);
        complaintData.put("endDt", formattedTo);
        complaintData.put("zoneID", compData[1]);
        final String currentZone = String.valueOf(compData[0]);
        if (openComplaints.size() == 1 || lastZone != null && !currentZone.equals(lastZone)) {
            pecentage = Math.round(100 * (totalOpen / regComplaint));
            complaintData.put("pecentage", pecentage);
            complaintData.put("regComp", regComplaint);
            complaintData.put("open90Comp", openFrm90Days);
            complaintData.put("openComp", totalOpen);
            complaintData.put("zone", lastZone);
            compAggrData.add(new HashMap<String, Object>(complaintData));
            pecentage = 0;
            regComplaint = 0;
            totalOpen = 0;
            openFrm90Days = 0;
        }
        lastZone = currentZone;
    }
    // SORT BASED ON TOTAL NO. OF OPEN COMP > 90
    sortData(compAggrData, "open90Comp");
    return compAggrData;
}
Example 4
Project: financius-public-master  File: BaseInterval.java View source code
public static String getTitle(Context context, Interval interval, Type type) {
    switch(type) {
        case DAY:
            return DateTimeFormat.mediumDate().print(interval.getStart());
        case WEEK:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_ABBREV_ALL) + " - " + DateUtils.formatDateTime(context, interval.getEnd().minusMillis(1), DateUtils.FORMAT_ABBREV_ALL);
        case MONTH:
            return DateUtils.formatDateTime(context, interval.getStart(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY);
        case YEAR:
            return interval.getStart().year().getAsText();
        default:
            throw new IllegalArgumentException("Type " + type + " is not supported.");
    }
}
Example 5
Project: lucene-solr-master  File: ParsingFieldUpdateProcessorsTest.java View source code
public void testParseDateNonUTCdefaultTimeZoneRoundTrip() throws Exception {
    IndexSchema schema = h.getCore().getLatestSchema();
    // should match "*_dt" dynamic field
    assertNotNull(schema.getFieldOrNull("date_dt"));
    String dateStringNoTimeZone = "2010-11-12T13:14:15.168";
    String dateStringUTC = dateStringNoTimeZone + "Z";
    // dateStringNoTimeZone interpreted as being in timeZone America/New_York, then printed as UTC
    String dateStringUSEasternTimeAsUTC = "2010-11-12T18:14:15.168Z";
    SolrInputDocument d = processAdd("parse-date-non-UTC-defaultTimeZone", doc(f("id", "99"), f("dateUTC_dt", dateStringUTC), f("dateNoTimeZone_dt", dateStringNoTimeZone)));
    assertNotNull(d);
    String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    DateTimeFormatter dateTimeFormatterUTC = DateTimeFormat.forPattern(pattern);
    DateTime dateTimeUTC = dateTimeFormatterUTC.parseDateTime(dateStringUTC);
    assertTrue(d.getFieldValue("dateUTC_dt") instanceof Date);
    assertTrue(d.getFieldValue("dateNoTimeZone_dt") instanceof Date);
    assertEquals(dateTimeUTC.getMillis(), ((Date) d.getFieldValue("dateUTC_dt")).getTime());
    assertU(commit());
    assertQ(req("id:99"), "//date[@name='dateUTC_dt'][.='" + dateStringUTC + "']", "//date[@name='dateNoTimeZone_dt'][.='" + dateStringUSEasternTimeAsUTC + "']");
}
Example 6
Project: richfaces-master  File: TestAddAndDeleteAlbumGroup.java View source code
@Test
public void addAlbumGroup() {
    login();
    DateTime dt = new DateTime();
    DateTimeFormatter pattern = DateTimeFormat.forPattern("EEE MMM dd");
    // open and cancel
    Graphene.guardAjax(getPage().getHeaderPanel().getToolbar().getAddAlbumGroupLink()).click();
    AddAlbumGroupPanel panel = getPage().getAddAlbumGroupPanel();
    panel.advanced().waitUntilPopupIsVisible().perform();
    panel.cancel();
    // open and close
    Graphene.guardAjax(getPage().getHeaderPanel().getToolbar().getAddAlbumGroupLink()).click();
    panel = getPage().getAddAlbumGroupPanel();
    panel.advanced().waitUntilPopupIsVisible().perform();
    panel.cancel();
    // check initial state
    RichFacesTree myGroupsTree = getPage().getLeftPanel().getMyGroupsTree();
    assertEquals(2, myGroupsTree.advanced().getNodes().size());
    assertEquals(0, myGroupsTree.advanced().getLeafNodes().size());
    addGroup();
    // check changed state in left panel
    myGroupsTree = getPage().getLeftPanel().getMyGroupsTree();
    assertEquals(3, myGroupsTree.advanced().getNodes().size());
    assertEquals(0, myGroupsTree.advanced().getNodes().get(2).advanced().getNodes().size());
    // check changed state in groups view
    GroupsView ownAlbumGroups = getPage().getLeftPanel().openOwnGroups(3);
    ownAlbumGroups.checkHeader("My album groups (3)");
    ownAlbumGroups.getGroups().get(2).checkAll(GROUP_NAME, "Created " + dt.toString(pattern) + ".*" + dt.getYear() + ", contains 0 images into 0 albums", "", true);
    // open group
    GroupView groupView = getPage().getLeftPanel().openOwnGroup(GROUP_NAME);
    // check data
    groupView.checkGroupHeader(GROUP_NAME, "Created " + dt.toString(pattern) + ".*" + dt.getYear() + ", contains 0 images into 0 albums");
    assertEquals(0, groupView.getAlbumPreviews().size());
    groupView.checkUserOwnsGroup(true);
}
Example 7
Project: ews-java-api-master  File: DateTimeUtils.java View source code
private static DateTimeFormatter[] createDateTimeFormats() {
    return new DateTimeFormatter[] { DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-ddZ").withZoneUTC(), DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC() };
}
Example 8
Project: cms-ce-master  File: ContentBaseHandlerServlet.java View source code
public void handlerBrowse(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems, ExtendedMap parameters, User oldUser, Document verticalDoc) throws VerticalAdminException {
    UserEntity user = securityService.getUser(oldUser);
    String op = formItems.getString("op");
    String subop = formItems.getString("subop", "browse");
    String contenthandler = formItems.getString("contenthandler", "");
    int submittetCategoryKey = formItems.getInt("categorykey", -1);
    if (submittetCategoryKey == -1) {
        submittetCategoryKey = formItems.getInt("cat", -1);
    }
    CategoryKey categoryKey = CategoryKey.parse(submittetCategoryKey);
    boolean categoryDisabled_which_means_user_do_not_have_read_access = formItems.getBoolean("disabled", false);
    String[] contentTypeStringArray = formItems.getStringArray("contenttypestring");
    int[] contentTypes = resolveContentTypes(contentTypeStringArray);
    StringBuffer contentTypesString = createContentTypesString(contentTypes);
    if (!"browse".equals(subop)) {
        String deploymentPath = DeploymentPathResolver.getAdminDeploymentPath(request);
        CookieUtil.setCookie(response, getPopupCookieName(contentTypesString.toString()), categoryKey != null ? categoryKey.toString() : "-1", COOKIE_TIMEOUT, deploymentPath);
    }
    ContentTypeKey contentTypeKey = null;
    boolean hasAdminReadOnCategory = true;
    boolean hasCategoryRead = false;
    boolean hasCategoryCreate = false;
    boolean hasCategoryPublish = false;
    boolean hasCategoryAdministrate = false;
    CategoryAccessResolver categoryAccessResolver = new CategoryAccessResolver(groupDao);
    if (categoryKey != null) {
        CategoryEntity category = categoryDao.findByKey(categoryKey);
        hasAdminReadOnCategory = categoryAccessResolver.hasAdminBrowseCategoryAccess(user, category);
        hasCategoryRead = categoryAccessResolver.hasReadCategoryAccess(user, category);
        hasCategoryCreate = categoryAccessResolver.hasCreateContentAccess(user, category);
        hasCategoryPublish = categoryAccessResolver.hasApproveContentAccess(user, category);
        hasCategoryAdministrate = categoryAccessResolver.hasAdministrateCategoryAccess(user, category);
        ContentTypeEntity contentType = category.getContentType();
        if (contentType != null) {
            contentTypeKey = contentType.getContentTypeKey();
        }
    }
    String sortBy = formItems.getString("sortby", "@timestamp");
    String sortByDirection = formItems.getString("sortby-direction", "DESC");
    StringBuffer orderBy = new StringBuffer();
    orderBy.append(sortBy);
    orderBy.append(" ");
    orderBy.append(sortByDirection);
    final String cookieName = "archiveBrowseItemsPerPage";
    int index = formItems.getInt("index", 0);
    int count = ListCountResolver.resolveCount(request, formItems, cookieName);
    CookieUtil.setCookie(response, cookieName, Integer.toString(count), COOKIE_TIMEOUT, DeploymentPathResolver.getAdminDeploymentPath(request));
    XMLDocument xmlContent = null;
    String searchType = formItems.getString("searchtype", null);
    // Get contents
    if (searchType != null) {
        if (searchType.equals("simple")) {
            xmlContent = new SearchUtility(userDao, groupDao, securityService, contentService).simpleSearch(oldUser, formItems, categoryKey, contentTypes, orderBy.toString(), index, count);
            parameters.put("searchtext", formItems.getString("searchtext", ""));
            parameters.put("scope", formItems.getString("scope"));
        } else {
            String ownerGroupKey = formItems.getString("owner", "");
            if (!"".equals(ownerGroupKey)) {
                User ownerUser = getUserFromUserGroupKey(ownerGroupKey);
                parameters.put("owner.uid", ownerUser.getName());
                parameters.put("owner.fullName", ownerUser.getDisplayName());
                parameters.put("owner.qualifiedName", ownerUser.getQualifiedName());
                addUserKeyToFormItems(formItems, "owner.key", ownerUser);
            }
            String modifierGroupKey = formItems.getString("modifier", "");
            if (!"".equals(modifierGroupKey)) {
                User modifierUser = getUserFromUserGroupKey(modifierGroupKey);
                parameters.put("modifier.uid", modifierUser.getName());
                parameters.put("modifier.fullName", modifierUser.getDisplayName());
                parameters.put("modifier.qualifiedName", modifierUser.getQualifiedName());
                addUserKeyToFormItems(formItems, "modifier.key", modifierUser);
            }
            String assignee = formItems.getString("_assignee", "");
            if (!"".equals(assignee)) {
                User assigneeUser = getUserFromUserKey(assignee);
                if (assigneeUser == null) {
                    assigneeUser = getUserFromUserGroupKey(assignee);
                }
                parameters.put("assignment.assigneeUserKey", assignee);
                parameters.put("assignment.assigneeDisplayName", assigneeUser.getDisplayName());
                parameters.put("assignment.assigneeQualifiedName", assigneeUser.getQualifiedName().toString());
            }
            String assigner = formItems.getString("_assigner", "");
            if (!"".equals(assigner)) {
                User assignerUser = getUserFromUserKey(assigner);
                if (assignerUser == null) {
                    assignerUser = getUserFromUserGroupKey(assigner);
                }
                parameters.put("assignment.assignerUserKey", assigner);
                parameters.put("assignment.assignerDisplayName", assignerUser.getDisplayName());
                parameters.put("assignment.assignerQualifiedName", assignerUser.getQualifiedName().toString());
            }
            String assignmentDueDate = formItems.getString("date_assignmentDueDate", "");
            if (!"".equals(assignmentDueDate)) {
                DateTimeFormatter norwegianDateFormatter = DateTimeFormat.forPattern("dd.MM.yyyy");
                DateMidnight assignmentDueDateAsDateTime = norwegianDateFormatter.parseDateTime(assignmentDueDate).toDateMidnight();
                DateTimeFormatter isoDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                String assignmentDueDateAsStringIsoFormatted = isoDateFormatter.print(assignmentDueDateAsDateTime);
                parameters.put("assignment.dueDate", assignmentDueDateAsStringIsoFormatted);
                parameters.put("assignment.dueDate.op", formItems.getString("_assignmentDueDate.op", ""));
            }
            xmlContent = new SearchUtility(userDao, groupDao, securityService, contentService).advancedSearch(oldUser, formItems, contentTypes, orderBy.toString(), index, count);
            parameters.put("asearchtext", formItems.getString("asearchtext", ""));
            parameters.put("ascope", formItems.getString("ascope"));
            parameters.put("subcategories", formItems.getString("subcategories"));
            parameters.put("state", formItems.getString("state", ""));
            parameters.put("owner", ownerGroupKey);
            parameters.put("modifier", modifierGroupKey);
            parameters.put("created.op", formItems.getString("created.op", ""));
            parameters.put("created", formItems.getString("datecreated", ""));
            parameters.put("modified.op", formItems.getString("modified.op", ""));
            parameters.put("modified", formItems.getString("datemodified", ""));
            parameters.put("acontentkey", formItems.getString("acontentkey", ""));
            parameters.put("filter", formItems.getString("filter", ""));
            parameters.put("selectedtabpage", formItems.getString("selectedtabpage", ""));
            parameters.put("duedate", assignmentDueDate);
        }
        parameters.put("searchtype", searchType);
    } else if (hasAdminReadOnCategory) {
        xmlContent = admin.getContent(oldUser, categoryKey, false, orderBy.toString(), index, count, 0, 0, 0);
    }
    if (xmlContent != null) {
        Document contentDoc = xmlContent.getAsDOMDocument();
        XMLTool.mergeDocuments(verticalDoc, contentDoc, true);
        // Find all content types and categories in this list
        Element[] contentElems = XMLTool.getElements(contentDoc.getDocumentElement(), "content");
        Set<ContentTypeKey> contentTypeKeys = new HashSet<ContentTypeKey>();
        Set<Integer> categoryKeys = new HashSet<Integer>();
        for (Element contentElem : contentElems) {
            contentTypeKeys.add(new ContentTypeKey(contentElem.getAttribute("contenttypekey")));
            Element categoryElem = XMLTool.getElement(contentElem, "categoryname");
            categoryKeys.add(Integer.parseInt(categoryElem.getAttribute("key")));
        }
        if (contentTypeKeys.size() == 0 && searchType == null && contentTypeKey != null) {
            // This is a normal listing of an empty category
            contentTypeKeys.add(contentTypeKey);
        }
        if (contentTypeKeys.size() > 0) {
            XMLDocument ctyDoc = admin.getContentTypes(ContentTypeKey.convertToIntArray(contentTypeKeys), true);
            XMLTool.mergeDocuments(verticalDoc, ctyDoc.getAsDOMDocument(), true);
        }
        // Get content types for this site
        XMLDocument siteContentTypesDoc = admin.getContentTypes(false);
        final Document siteContentTypesDocument = siteContentTypesDoc.getAsDOMDocument();
        XMLTool.renameElement(siteContentTypesDocument.getDocumentElement(), "sitecontenttypes");
        XMLTool.mergeDocuments(verticalDoc, siteContentTypesDocument, true);
        // Get all categories
        if (categoryKeys.size() > 0) {
            Integer[] keyArray = new Integer[categoryKeys.size()];
            keyArray = categoryKeys.toArray(keyArray);
            CategoryCriteria categoryCriteria = new CategoryCriteria();
            categoryCriteria.addCategoryKeys(Arrays.asList(keyArray));
            Document categoriesDoc = admin.getMenu(oldUser, categoryCriteria).getAsDOMDocument();
            XMLTool.mergeDocuments(verticalDoc, categoriesDoc, false);
        }
    }
    Document headerDoc = admin.getCategoryPathXML(categoryKey, contentTypes).getAsDOMDocument();
    XMLTool.mergeDocuments(verticalDoc, headerDoc, true);
    // Default browse config
    Document defaultBrowseConfig = AdminStore.getXml(session, "defaultbrowseconfig.xml").getAsDOMDocument();
    XMLTool.mergeDocuments(verticalDoc, defaultBrowseConfig, true);
    // Feedback
    if (formItems.containsKey("feedback")) {
        addFeedback(verticalDoc, formItems.getInt("feedback"));
    }
    // Category header
    if (categoryKey != null) {
        // Category
        // Small hack: we put the current category on /data/category, all categories
        // used are also present in /data/categories/category, but without contentcount and accessrights
        Document categoryDoc = admin.getCategory(oldUser, categoryKey.toInt()).getAsDOMDocument();
        XMLTool.mergeDocuments(verticalDoc, categoryDoc, false);
        int superCategoryKey = admin.getSuperCategoryKey(categoryKey.toInt());
        if (superCategoryKey != -1) {
            CategoryAccessRight supercar = admin.getCategoryAccessRight(oldUser, superCategoryKey);
            parameters.put("parentcategoryadministrate", supercar.getAdministrate());
        }
        // Trenger indexparametre for å vite hvilke felt det kan sorteres på.. list.xsl
        Document indexingDoc = XMLTool.domparse(admin.getIndexingParametersXML(contentTypeKey));
        XMLTool.mergeDocuments(verticalDoc, indexingDoc, true);
        parameters.put("cat", categoryKey.toString());
        parameters.put("contenttypekey", Integer.toString(contentTypeKey != null ? contentTypeKey.toInt() : -1));
        parameters.put("selectedunitkey", Integer.toString(admin.getUnitKey(categoryKey.toInt())));
    } else {
        parameters.putInt("cat", -1);
        parameters.putInt("selectedunitkey", -1);
    }
    if (categoryDisabled_which_means_user_do_not_have_read_access) {
        parameters.put("searchonly", "true");
    }
    parameters.put("index", index);
    parameters.put("count", count);
    parameters.put("op", op);
    parameters.put("subop", subop);
    parameters.put("hasAdminBrowse", hasAdminReadOnCategory);
    parameters.put("hasCategoryRead", hasCategoryRead);
    parameters.put("hasCategoryCreate", hasCategoryCreate);
    parameters.put("hasCategoryPublish", hasCategoryPublish);
    parameters.put("hasCategoryAdministrate", hasCategoryAdministrate);
    parameters.put("fieldname", formItems.getString("fieldname", ""));
    parameters.put("fieldrow", formItems.getString("fieldrow", ""));
    parameters.put("contenttypestring", contentTypesString.toString());
    parameters.put("sortby", sortBy);
    parameters.put("sortby-direction", sortByDirection);
    parameters.put("contenthandler", contenthandler);
    parameters.put("minoccurrence", formItems.getString("minoccurrence", ""));
    parameters.put("maxoccurrence", formItems.getString("maxoccurrence", ""));
    if (formItems.containsKey("reload")) {
        parameters.put("reload", formItems.getString("reload"));
    }
    addPageTemplatesOfUserSitesToDocument(admin, user, PageTemplateType.CONTENT, verticalDoc);
    transformXML(request, response, verticalDoc, "content_list.xsl", parameters);
}
Example 9
Project: aokp-gerrit-master  File: ScheduleConfig.java View source code
private static long initialDelay(Config rc, String section, String subsection, String keyStartTime, DateTime now, long interval) {
    long delay = MISSING_CONFIG;
    String start = rc.getString(section, subsection, keyStartTime);
    try {
        if (start != null) {
            DateTimeFormatter formatter;
            MutableDateTime startTime = now.toMutableDateTime();
            try {
                formatter = ISODateTimeFormat.hourMinute();
                LocalTime firstStartTime = formatter.parseLocalTime(start);
                startTime.hourOfDay().set(firstStartTime.getHourOfDay());
                startTime.minuteOfHour().set(firstStartTime.getMinuteOfHour());
            } catch (IllegalArgumentException e1) {
                formatter = DateTimeFormat.forPattern("E HH:mm");
                LocalDateTime firstStartDateTime = formatter.parseLocalDateTime(start);
                startTime.dayOfWeek().set(firstStartDateTime.getDayOfWeek());
                startTime.hourOfDay().set(firstStartDateTime.getHourOfDay());
                startTime.minuteOfHour().set(firstStartDateTime.getMinuteOfHour());
            }
            startTime.secondOfMinute().set(0);
            startTime.millisOfSecond().set(0);
            long s = startTime.getMillis();
            long n = now.getMillis();
            delay = (s - n) % interval;
            if (delay <= 0) {
                delay += interval;
            }
        } else {
            log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section, keyStartTime));
        }
    } catch (IllegalArgumentException e2) {
        log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, keyStartTime), e2);
        delay = INVALID_CONFIG;
    }
    return delay;
}
Example 10
Project: extdirectspring-master  File: ApiControllerTest.java View source code
private void testGroup1(Configuration config, String fingerprint) throws Exception {
    ApiRequestParams params = ApiRequestParams.builder().apiNs("Ext.ns").actionNs("actionns").group("group1").configuration(config).build();
    doTest("/api-debug-doc.js", params, group1Apis("actionns"));
    doTest("/api-debug.js", params, group1Apis("actionns"));
    if (fingerprint == null) {
        doTest("/api.js", params, group1Apis("actionns"));
    } else {
        MvcResult result = doTest("/api" + fingerprint + ".js", params, group1Apis("actionns"));
        MockHttpServletResponse response = result.getResponse();
        assertThat(response.getHeaderNames()).hasSize(5);
        assertThat(response.getHeader("ETag")).isNotNull();
        assertThat(response.getHeader("Cache-Control")).isEqualTo("public, max-age=" + 6 * 30 * 24 * 60 * 60);
        String expiresHeader = (String) response.getHeaderValue("Expires");
        DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss z");
        DateTime expires = DateTime.parse(expiresHeader, fmt);
        DateTime inSixMonths = DateTime.now(DateTimeZone.UTC).plusSeconds(6 * 30 * 24 * 60 * 60);
        assertThat(expires.getYear()).isEqualTo(inSixMonths.getYear());
        assertThat(expires.getMonthOfYear()).isEqualTo(inSixMonths.getMonthOfYear());
        assertThat(expires.getDayOfMonth()).isEqualTo(inSixMonths.getDayOfMonth());
        assertThat(expires.getHourOfDay()).isEqualTo(inSixMonths.getHourOfDay());
        assertThat(expires.getMinuteOfDay()).isEqualTo(inSixMonths.getMinuteOfDay());
    }
}
Example 11
Project: beowulf-master  File: DateUtils.java View source code
/**
	 * Converts a date string with zone information to the default host's time
	 * zone 2012-03-21 19:37:54+0230. Ignore the timzone information in the date
	 * object. Its a bug in Date/Time utils to display local zone only
	 * 
	 * @param dateString
	 *            should be of the form "yyyy-MM-dd HH:mm:ssZ"
	 * @return
	 */
public static Date convertDateStringWithZoneToGMT(String dateString) {
    SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT_WITH_ZONE);
    Date date = null;
    try {
        DateTime jodaDateTime = new DateTime(format.parse(dateString));
        DateTime dtGMT = jodaDateTime.withZone(DateTimeZone.forID("Etc/GMT"));
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DEFAULT_DATE_FORMAT);
        date = convertToDate(dtGMT.toString(fmt), DEFAULT_DATE_FORMAT);
    } catch (ParseException e) {
        logger.error("Date parsing failed for the string {} with format {}", dateString, DEFAULT_DATE_FORMAT_WITH_ZONE);
    }
    return date;
}
Example 12
Project: The-Digital-Parrot-master  File: Timeline.java View source code
public String extractLabel(int slice) {
    Interval interval;
    try {
        interval = convertSliceToInterval(slice);
    } catch (IllegalArgumentException iae) {
        iae.printStackTrace();
        return "";
    }
    DateTimeFormatter format = DateTimeFormat.shortDate();
    if (incrementMode == Mode.Days) {
        return interval.getStart().toString(format);
    } else {
        String incrementString = "";
        switch(incrementMode) {
            case Years:
                incrementString = "Year " + sliceLabelExtractor.extractLabel(interval.getStart()) + " (";
                break;
            case Months:
                incrementString = "Month " + sliceLabelExtractor.extractLabel(interval.getStart()) + " (";
                break;
            case Weeks:
                incrementString = "Week " + sliceLabelExtractor.extractLabel(interval.getStart()) + " (";
                break;
        }
        return incrementString + interval.getStart().toString(format) + " to " + interval.getEnd().toString(format) + ")";
    }
}
Example 13
Project: expenditures-master  File: MissionResponsibilityController.java View source code
@RequestMapping(value = "/prepareRelationshipType/{accountId}", method = RequestMethod.GET)
public String prepareRelationshipType(@PathVariable String accountId, final Model model) throws Exception {
    final MissionSystem mission = MissionSystem.getInstance();
    final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
    final LocalDate local = new LocalDate();
    final SortedSet<AccountabilityType> set = new TreeSet<>(AccountabilityType.COMPARATORY_BY_NAME);
    final Set<AccountabilityType> workingPlaceAccountabilities = mission.getAccountabilityTypesRequireingAuthorization();
    set.addAll(workingPlaceAccountabilities);
    final Set<AccountabilityType> authorityAccountabilities = mission.getAccountabilityTypesThatAuthorize();
    set.addAll(authorityAccountabilities);
    model.addAttribute("accountabilityTypes", set);
    model.addAttribute("invalidData", false);
    model.addAttribute("notActive", false);
    model.addAttribute("iniDate", local.toString(formatter));
    if (FenixFramework.getDomainObject(accountId) instanceof User) {
        model.addAttribute("user", FenixFramework.getDomainObject(accountId));
    } else if (FenixFramework.getDomainObject(accountId) instanceof Unit) {
        model.addAttribute("unit", FenixFramework.getDomainObject(accountId));
    }
    if (ExpenditureTrackingSystem.getInstance().getAcquisitionsUnitManagerGroup().isMember(Authenticate.getUser())) {
        model.addAttribute("Allowed", true);
        return "expenditure-tracking/addMissionResponsability";
    }
    return search(accountId, model);
}
Example 14
Project: abmash-master  File: HtmlElement.java View source code
/**
	 * Selects the specified date.
	 * 
	 * TODO
	 * 
	 * @param dateTime
	 * @return this [email protected] HtmlElement}
	 */
public HtmlElement chooseDate(DateTime dateTime) {
    // TODO detect datepicker type
    // TODO detect date format in input field
    // TODO detect time format and input field
    // TODO detect if sendkeys work for one or the other
    // TODO convert date to string 08/22/2013 and check if sendkeys worked
    //type(dateTime.getDateString());
    click();
    // TODO Ajax Wait condition
    // TODO year
    // TODO exception handler if no element was found
    // TODO first try with month name
    browser.query(QueryFactory.choosable("datepicker"), QueryFactory.below(this)).findFirst().choose(String.valueOf(dateTime.getMonthOfYear() - 1));
    // TODO exception handler if no element was found
    browser.query(QueryFactory.clickable(String.valueOf(dateTime.getDayOfMonth())), QueryFactory.select("*:attrMatch(CONTAINS, *, \"datepicker\") > a"), QueryFactory.below(this)).findFirst().click();
    // TODO time
    DateTimeFormatter fmt = DateTimeFormat.forPattern("h:mm aa");
    // TODO exception handler if no element was found
    browser.query(QueryFactory.choosable("time"), QueryFactory.rightOf(this)).findFirst().choose(fmt.print(dateTime));
    return this;
}