Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

License:Open Source License

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);
    }//from ww  w  .j a v a  2 s . com

    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);
}

From source file:com.esofthead.mycollab.common.service.ibatis.TimelineTrackingServiceImpl.java

License:Open Source License

@Override
public Map<String, List<GroupItem>> findTimelineItems(String fieldGroup, List<String> groupVals, Date start,
        Date end, TimelineTrackingSearchCriteria criteria) {
    try {//from  w ww. ja  v  a  2s  .  c  o m
        DateTime startDate = new DateTime(start);
        final DateTime endDate = new DateTime(end);
        if (startDate.isAfter(endDate)) {
            throw new UserInvalidInputException("Start date must be greater than end date");
        }
        List<Date> dates = boundDays(startDate, endDate.minusDays(1));
        Map<String, List<GroupItem>> items = new HashMap<>();
        criteria.setFieldgroup(StringSearchField.and(fieldGroup));
        List<GroupItem> cacheTimelineItems = timelineTrackingCachingMapperExt.findTimelineItems(groupVals,
                dates, criteria);

        DateTime calculatedDate = startDate.toDateTime();
        if (cacheTimelineItems.size() > 0) {
            GroupItem item = cacheTimelineItems.get(cacheTimelineItems.size() - 1);
            String dateValue = item.getGroupname();
            calculatedDate = DateTime.parse(dateValue, DateTimeFormat.forPattern("yyyy-MM-dd"));

            for (GroupItem map : cacheTimelineItems) {
                String groupVal = map.getGroupid();
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(map);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(map);
                }
            }
        }

        dates = boundDays(calculatedDate.plusDays(1), endDate);
        if (dates.size() > 0) {
            boolean isValidForBatchSave = true;
            final String type = criteria.getType().getValue();
            SetSearchField<Integer> extraTypeIds = criteria.getExtraTypeIds();
            Integer tmpExtraTypeId = null;
            if (extraTypeIds != null) {
                if (extraTypeIds.getValues().size() == 1) {
                    tmpExtraTypeId = extraTypeIds.getValues().iterator().next();
                } else {
                    isValidForBatchSave = false;
                }
            }
            final Integer extraTypeId = tmpExtraTypeId;

            final List<Map> timelineItems = timelineTrackingMapperExt.findTimelineItems(groupVals, dates,
                    criteria);
            if (isValidForBatchSave) {
                final Integer sAccountId = (Integer) criteria.getSaccountid().getValue();
                final String itemFieldGroup = criteria.getFieldgroup().getValue();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

                final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                final List<Map> filterCollections = new ArrayList<>(
                        Collections2.filter(timelineItems, new Predicate<Map>() {
                            @Override
                            public boolean apply(Map input) {
                                String dateStr = (String) input.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                return !dt.equals(endDate);
                            }
                        }));
                jdbcTemplate.batchUpdate(
                        "INSERT INTO `s_timeline_tracking_cache`(type, fieldval,extratypeid,sAccountId,"
                                + "forDay, fieldgroup,count) VALUES(?,?,?,?,?,?,?)",
                        new BatchPreparedStatementSetter() {
                            @Override
                            public void setValues(PreparedStatement preparedStatement, int i)
                                    throws SQLException {
                                Map item = filterCollections.get(i);
                                preparedStatement.setString(1, type);
                                String fieldVal = (String) item.get("groupid");
                                preparedStatement.setString(2, fieldVal);
                                preparedStatement.setInt(3, extraTypeId);
                                preparedStatement.setInt(4, sAccountId);
                                String dateStr = (String) item.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                preparedStatement.setDate(5, new java.sql.Date(dt.toDate().getTime()));
                                preparedStatement.setString(6, itemFieldGroup);
                                int value = ((BigDecimal) item.get("value")).intValue();
                                preparedStatement.setInt(7, value);
                            }

                            @Override
                            public int getBatchSize() {
                                return filterCollections.size();
                            }
                        });
            }

            for (Map map : timelineItems) {
                String groupVal = (String) map.get("groupid");
                GroupItem item = new GroupItem();
                item.setValue(((BigDecimal) map.get("value")).doubleValue());
                item.setGroupid((String) map.get("groupid"));
                item.setGroupname((String) map.get("groupname"));
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(item);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(item);
                }
            }
        }

        return items;
    } catch (Exception e) {
        LOG.error("Error", e);
        return null;
    }
}

From source file:com.ethercis.servicemanager.common.IsoDateJoda.java

License:Apache License

/**
 * Calculate the difference from the given time to now. 
 * ISO 8601 states: Durations are represented by the format P[n]Y[n]M[n]DT[n]H[n]M[n]S
 * @param utc Given time, e.g. "1997-07-16T19:20:30.45+01:00"
 * @return The ISO 8601 Period like "P3Y6M4DT12H30M17S"
 *//* w ww. ja  v  a  2  s.  c  o  m*/
public static String getDifferenceToNow(String utc) {
    if (utc == null)
        return "";
    utc = ReplaceVariable.replaceAll(utc, " ", "T");
    DateTime now = new DateTime();
    DateTimeFormatter f = ISODateTimeFormat.dateTimeParser();
    DateTime other = f.parseDateTime(utc);
    Period period = new Period(other, now); // Period(ReadableInstant startInstant, ReadableInstant endInstant)
    return period.toString();
}

From source file:com.etouch.auth.SamlCallbackHandler.java

License:Apache License

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    Message m = PhaseInterceptorChain.getCurrentMessage();

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];

            if (saml2) {
                callback.setSamlVersion(SAMLVersion.VERSION_20);
            } else {
                callback.setSamlVersion(SAMLVersion.VERSION_11);
            }/*  w ww  .ja va2s .  c om*/

            callback.setIssuer(HtppResponseHelper.integratorKey);

            /*String subjectName = (String)m.getContextualProperty("saml.subject.name");
            if (subjectName == null) {
            subjectName = "uid=sts-client,o=mock-sts.com";
            }*/

            String subjectQualifier = "www.mock-sts.com";

            if (!saml2 && SAML2Constants.CONF_SENDER_VOUCHES.equals(confirmationMethod)) {
                confirmationMethod = SAML1Constants.CONF_SENDER_VOUCHES;
            }

            DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
            DateTime notAfter = formatter.parseDateTime(HtppResponseHelper.samlExpireDate);

            SubjectBean subjectBean = new SubjectBean(HtppResponseHelper.username,
                    SAML2Constants.NAMEID_FORMAT_EMAIL_ADDRESS, confirmationMethod);
            subjectBean.setSubjectNameIDFormat(SAML2Constants.NAMEID_FORMAT_EMAIL_ADDRESS);
            SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
            subjectConfirmationData.setRecipient(HtppResponseHelper.samlRecipient);
            subjectConfirmationData.setNotAfter(notAfter);
            subjectBean.setSubjectConfirmationData(subjectConfirmationData);

            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {

                try {
                    CryptoLoader loader = new CryptoLoader();
                    Crypto crypto = (Crypto) loader.getCrypto(m, SecurityConstants.SIGNATURE_CRYPTO,
                            SecurityConstants.SIGNATURE_PROPERTIES);
                    X509Certificate cert = SecurityUtils.getCertificates(
                            (org.apache.ws.security.components.crypto.Crypto) crypto,
                            SecurityUtils.getUserName(m,
                                    (org.apache.ws.security.components.crypto.Crypto) crypto,
                                    "ws-security.signature.username"))[0];

                    KeyInfoBean keyInfo = new KeyInfoBean();
                    keyInfo.setCertificate(cert);
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
            callback.setSubject(subjectBean);

            //SubjectConfirmationData SubjectConfirmationData

            ConditionsBean conditions = new ConditionsBean();

            //System.out.println("notAfter:"+notAfter);
            conditions.setNotAfter(notAfter);
            conditions.setAudienceURI(HtppResponseHelper.samlAudienceURI);
            callback.setConditions(conditions);

            /*AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
            authDecBean.setDecision(Decision.INDETERMINATE);
            authDecBean.setResource("https://sp.example.com/SAML2");
            ActionBean actionBean = new ActionBean();
            actionBean.setContents("Read");
            authDecBean.setActions(Collections.singletonList(actionBean));
            callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));*/

            AuthenticationStatementBean authBean = new AuthenticationStatementBean();
            authBean.setSubject(subjectBean);
            authBean.setAuthenticationInstant(new DateTime());
            authBean.setSessionIndex("123456");
            // AuthnContextClassRef is not set
            authBean.setAuthenticationMethod("urn:oasis:names:tc:SAML:2.0:ac:classes:X509");
            callback.setAuthenticationStatementData(Collections.singletonList(authBean));

            AttributeStatementBean attrBean = new AttributeStatementBean();
            attrBean.setSubject(subjectBean);

            /*List<String> roles = CastUtils.cast((List<?>)m.getContextualProperty("saml.roles"));
            if (roles == null) {
            roles = Collections.singletonList("user");
            }
            List<AttributeBean> claims = new ArrayList<AttributeBean>();
            AttributeBean roleClaim = new AttributeBean();
            roleClaim.setSimpleName("subject-role");
            roleClaim.setQualifiedName(Claim.DEFAULT_ROLE_NAME);
            roleClaim.setNameFormat(Claim.DEFAULT_NAME_FORMAT);
            roleClaim.setCustomAttributeValues(new ArrayList<Object>(roles));
            claims.add(roleClaim);
                    
            List<String> authMethods = CastUtils.cast((List<?>)m.getContextualProperty("saml.auth"));
            if (authMethods == null) {
            authMethods = Collections.singletonList("password");
            }
            */

            AttributeBean authClaim = new AttributeBean();
            authClaim.setSimpleName("http://claims/authentication");
            authClaim.setQualifiedName("http://claims/authentication");
            authClaim.setNameFormat("http://claims/authentication-format");
            //authClaim.setCustomAttributeValues(new ArrayList<Object>(authMethods));
            //claims.add(authClaim);

            //attrBean.setSamlAttributes(claims);
            callback.setAttributeStatementData(Collections.singletonList(attrBean));
        }
    }
}

From source file:com.facebook.presto.operator.scalar.DateTimeFunctions.java

License:Apache License

private static DateTime parseDateTimeHelper(DateTimeFormatter formatter, String datetimeString) {
    try {/*w  w w  .  j a  v  a  2 s .c o m*/
        return formatter.parseDateTime(datetimeString);
    } catch (IllegalArgumentException e) {
        throw new PrestoException(INVALID_FUNCTION_ARGUMENT.toErrorCode(), e);
    }
}

From source file:com.fatboyindustrial.gsonjodatime.DateMidnightConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>//from w ww.  j a v  a  2 s.  c o m
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link com.google.gson.JsonDeserializationContext#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws com.google.gson.JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public DateMidnight deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    return new DateMidnight(fmt.parseDateTime(json.getAsString()));
}

From source file:com.fatboyindustrial.gsonjodatime.DateTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>/*  www .  j  av  a 2  s .  com*/
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    return fmt.parseDateTime(json.getAsString());
}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

/**
 * Gets the required parameters parameters
 *
 * @throws IOException/* w ww  . j a  va  2  s  . co  m*/
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    response.setContentType("application/json");
    final JSONObject json = new JSONObject();

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");
    final DateTimeFormatter formatterbis = DateTimeFormat.forPattern("dd/MM/yyyy/ HH:mm");

    try {
        json.put("on", AlertsConfiguration.getProperty(AlertsConfiguration.ALERTS_ON_OFF));
        json.put("hourlyDate", AlertsConfiguration.getProperty(AlertsConfiguration.HOURLY_DELAY));
        json.put("dailyDate", AlertsConfiguration.getProperty(AlertsConfiguration.DAILY_DELAY));
        json.put("weeklyDate", AlertsConfiguration.getProperty(AlertsConfiguration.WEEKLY_DELAY));
        json.put("host", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_HOST));
        json.put("port", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_PORT));
        json.put("database", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_NAME));
        json.put("collection", AlertsConfiguration.getProperty(AlertsConfiguration.DATABASE_COLLECTION));

        json.put("nextHourly",
                getNextEvent("hourly", AlertsConfiguration.getProperty(AlertsConfiguration.HOURLY_DELAY)));
        json.put("hourly",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_HOURLY_EXEC)))
                                .toString(formatterbis));

        json.put("nextDaily",
                getNextEvent("daily", AlertsConfiguration.getProperty(AlertsConfiguration.DAILY_DELAY)));
        json.put("daily",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_DAILY_EXEC)))
                                .toString(formatterbis));

        json.put("nextWeekly",
                getNextEvent("weekly", AlertsConfiguration.getProperty(AlertsConfiguration.WEEKLY_DELAY)));
        json.put("weekly",
                new DateTime(formatter
                        .parseDateTime(AlertsConfiguration.getProperty(AlertsConfiguration.LAST_WEEKLY_EXEC)))
                                .toString(formatterbis));

        json.put("smtp", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_ADDRESS));
        json.put("from", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_FROM));
        json.put("user", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_USER));
        json.put("pass", AlertsConfiguration.getProperty(AlertsConfiguration.SMTP_PASSWORD));

        json.put(OutputConstants.CODE, CodesReturned.ALLOK.getValue());
    } catch (final JSONException e) {
        LOGGER.error(
                "Error while building the JSON answer in the doGet of the alerts administration servlets, make sure the fields are filled correctly and that datafari.properties have the correct encoding charset(UTF_8). Error 69021",
                e);
        json.put("message",
                "Error while getting the parameters, please retry, if the problem persists contact your system administrator. Error code : 69021");
        json.put(OutputConstants.CODE, CodesReturned.PROBLEMQUERY.getValue());
    } catch (final IOException e) {
        LOGGER.error(
                "Error while reading the datafari.properties file in the doGet of the alerts administration Servlet . Error 69020 ",
                e);
        json.put("message",
                "Error while reading the datafari.properties file, please make sure the file exists and retry, if the problem persists contact your system administrator. Error code : 69020");
        json.put(OutputConstants.CODE, CodesReturned.GENERALERROR.getValue());
    }

    final PrintWriter out = response.getWriter();
    out.print(json);

}

From source file:com.francelabs.datafari.servlets.admin.alertsAdmin.java

License:Apache License

private String getNextEvent(final String frequency, final String initialDate) {
    final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy/HH:mm");
    final DateTime scheduledDate = new DateTime(formatter.parseDateTime(initialDate));
    final Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.SECOND, 0);//from  w  ww .ja v  a 2 s. co  m
    cal.set(Calendar.MILLISECOND, 0);
    final DateTime currentDateTime = new DateTime(cal.getTime());
    DateTime scheduledDateTimeUpdate = new DateTime(cal.getTime());

    switch (frequency.toLowerCase()) {
    case "hourly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.HOUR_OF_DAY, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "daily":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    case "weekly":
        // Create what would be the current scheduled date
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_WEEK, scheduledDate.getDayOfWeek() + 1); // +1
        // =
        // diff
        // between
        // Joda
        // and
        // Calendar
        cal.set(Calendar.HOUR_OF_DAY, scheduledDate.getHourOfDay());
        cal.set(Calendar.MINUTE, scheduledDate.getMinuteOfHour());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        scheduledDateTimeUpdate = new DateTime(cal.getTime());

        // Compare the current date with the current scheduled one, if the
        // current date is later than the scheduled one then create the next
        // scheduled date
        if (!currentDateTime.isBefore(scheduledDateTimeUpdate)) {
            cal.add(Calendar.WEEK_OF_YEAR, 1);
            scheduledDateTimeUpdate = new DateTime(cal.getTime());
        }
        break;

    default:
        break;
    }
    return scheduledDateTimeUpdate.toString(formatter);
}

From source file:com.github.fge.jsonschema.format.helpers.AbstractDateFormatAttribute.java

License:LGPL

@Override
public final void validate(final ProcessingReport report, final MessageBundle bundle, final FullData data)
        throws ProcessingException {
    final DateTimeFormatter formatter = getFormatter();
    final String value = data.getInstance().getNode().textValue();

    try {// w ww  .  ja  va  2 s.  c om
        formatter.parseDateTime(value);
    } catch (IllegalArgumentException ignored) {
        report.error(newMsg(data, bundle, "err.format.invalidDate").putArgument("value", value)
                .putArgument("expected", format));
    }
}