Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.mycollab.common.service.impl.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   www.j  a va 2  s .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 greaterThan 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 Set<String> types = criteria.getTypes().getValues();
            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, 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, types);
                                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.mycollab.core.utils.DateTimeUtils.java

License:Open Source License

public static String formatDate(Date date, String dateFormat, Locale locale, TimeZone timezone) {
    if (date == null) {
        return "";
    }//w  ww  . ja v a2 s.c o  m

    DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale);
    if (timezone != null) {
        formatter = formatter.withZone(DateTimeZone.forTimeZone(timezone));
    }

    return formatter.print(new DateTime(date));
}

From source file:com.mycollab.module.project.view.ticket.CreatedDateOrderComponent.java

License:Open Source License

@Override
public void insertTickets(List<ProjectTicket> tickets) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern(MyCollabUI.getLongDateFormat())
            .withLocale(UserUIContext.getUserLocale());
    for (ProjectTicket ticket : tickets) {
        if (ticket.getCreatedTime() != null) {
            Date createdDate = ticket.getCreatedTime();
            DateTime jodaTime = new DateTime(createdDate, DateTimeZone.UTC);
            DateTime monDay = jodaTime.dayOfWeek().withMinimumValue();
            String monDayStr = formatter.print(monDay);
            Long time = new LocalDate(monDay).toDate().getTime();
            if (createdDateAvailables.containsKey(time)) {
                DefaultTicketGroupComponent groupComponent = createdDateAvailables.get(time);
                groupComponent.insertTicket(ticket);
            } else {
                DateTime maxValue = monDay.dayOfWeek().withMaximumValue();
                String sundayStr = formatter.print(maxValue);
                String titleValue = String.format("%s - %s", monDayStr, sundayStr);

                DefaultTicketGroupComponent groupComponent = new DefaultTicketGroupComponent(titleValue);
                createdDateAvailables.put(time, groupComponent);
                addComponent(groupComponent);
                groupComponent.insertTicket(ticket);
            }//from w w w .  j  a va 2s.  co  m
        } else {
            if (unspecifiedTasks == null) {
                unspecifiedTasks = new DefaultTicketGroupComponent(
                        UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED));
                addComponent(unspecifiedTasks, 0);
            }
            unspecifiedTasks.insertTicket(ticket);
        }
    }
}

From source file:com.mycollab.module.project.view.ticket.DueDateOrderComponent.java

License:Open Source License

@Override
public void insertTickets(List<ProjectTicket> tickets) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern(MyCollabUI.getLongDateFormat())
            .withLocale(UserUIContext.getUserLocale());
    for (ProjectTicket ticket : tickets) {
        if (ticket.getDueDate() != null) {
            Date dueDate = ticket.getDueDate();
            DateTime jodaTime = new DateTime(dueDate, DateTimeZone.UTC);
            DateTime monDay = jodaTime.dayOfWeek().withMinimumValue();
            String monDayStr = formatter.print(monDay);
            Long time = new LocalDate(monDay).toDate().getTime();
            if (dueDateAvailables.containsKey(time)) {
                DefaultTicketGroupComponent groupComponent = dueDateAvailables.get(time);
                groupComponent.insertTicket(ticket);
            } else {
                DateTime maxValue = monDay.dayOfWeek().withMaximumValue();
                String sundayStr = formatter.print(maxValue);
                String titleValue = String.format("%s - %s", monDayStr, sundayStr);

                DefaultTicketGroupComponent groupComponent = new DefaultTicketGroupComponent(titleValue);
                dueDateAvailables.put(time, groupComponent);
                addComponent(groupComponent);
                groupComponent.insertTicket(ticket);
            }//  w w  w. j a  v  a 2s  .c  o  m
        } else {
            if (unspecifiedTasks == null) {
                unspecifiedTasks = new DefaultTicketGroupComponent(
                        UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED));
                addComponent(unspecifiedTasks);
            }
            unspecifiedTasks.insertTicket(ticket);
        }
    }
}

From source file:com.mycollab.module.project.view.ticket.StartDateOrderComponent.java

License:Open Source License

@Override
public void insertTickets(List<ProjectTicket> tickets) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern(MyCollabUI.getLongDateFormat())
            .withLocale(UserUIContext.getUserLocale());
    for (ProjectTicket task : tickets) {
        if (task.getStartDate() != null) {
            Date startDate = task.getStartDate();
            DateTime jodaTime = new DateTime(startDate, DateTimeZone.UTC);
            DateTime monDay = jodaTime.dayOfWeek().withMinimumValue();
            String monDayStr = formatter.print(monDay);
            Long time = new LocalDate(monDay).toDate().getTime();
            if (startDateAvailables.containsKey(time)) {
                DefaultTicketGroupComponent groupComponent = startDateAvailables.get(time);
                groupComponent.insertTicket(task);
            } else {
                DateTime maxValue = monDay.dayOfWeek().withMaximumValue();
                String sundayStr = formatter.print(maxValue);
                String titleValue = String.format("%s - %s", monDayStr, sundayStr);

                DefaultTicketGroupComponent groupComponent = new DefaultTicketGroupComponent(titleValue);
                startDateAvailables.put(time, groupComponent);
                addComponent(groupComponent);
                groupComponent.insertTicket(task);
            }/*from   www  .  j a v  a  2s.  c o m*/
        } else {
            if (unspecifiedTasks == null) {
                unspecifiedTasks = new DefaultTicketGroupComponent(
                        UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED));
                addComponent(unspecifiedTasks, 0);
            }
            unspecifiedTasks.insertTicket(task);
        }
    }
}

From source file:com.mycollab.vaadin.ui.field.DateFormatField.java

License:Open Source License

public DateFormatField(final String initialFormat) {
    this.dateFormat = initialFormat;
    dateInput = new TextField(null, initialFormat);
    dateInput.setImmediate(true);/*  ww  w .  j  a v  a 2 s .  c  om*/
    dateInput.setTextChangeEventMode(AbstractTextField.TextChangeEventMode.EAGER);
    now = new DateTime();
    dateExample = new Label();
    dateFormatInstance = DateTimeFormat.forPattern(dateFormat);
    dateExample.setValue("(" + dateFormatInstance.print(now) + ")");
    dateExample.setWidthUndefined();
    dateInput.addTextChangeListener(textChangeEvent -> {
        try {
            String newFormat = textChangeEvent.getText();
            dateFormatInstance = DateTimeFormat.forPattern(newFormat);
            dateExample.setValue("(" + dateFormatInstance.print(now) + ")");
        } catch (Exception e) {
            NotificationUtil.showErrorNotification(UserUIContext.getMessage(ErrorI18nEnum.INVALID_FORMAT));
            dateInput.setValue(initialFormat);
            dateFormatInstance = DateTimeFormat.forPattern(initialFormat);
            dateExample.setValue("(" + dateFormatInstance.print(now) + ")");
        }
    });
}

From source file:com.mycollab.vaadin.UserUIContext.java

License:Open Source License

/**
 * @param date is the UTC date value/* w  w w .  ja v  a2s.c  o  m*/
 * @return
 */
public static String formatDateTime(Date date) {
    if (date == null) {
        return "";
    } else {
        DateTime jodaDate = new DateTime(date)
                .toDateTime(DateTimeZone.forTimeZone(UserUIContext.getUserTimeZone()));
        if (jodaDate.getHourOfDay() > 0 || jodaDate.getMinuteOfHour() > 0) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(MyCollabUI.getDateTimeFormat())
                    .withLocale(UserUIContext.getUserLocale());
            return formatter.print(jodaDate);
        } else {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(MyCollabUI.getDateFormat())
                    .withLocale(UserUIContext.getUserLocale());
            return formatter.print(jodaDate);
        }
    }
}

From source file:com.mycompany.assignment1.Programme.java

public Programme(String name, String SD, String ED) {

    Name = name;/*from w w w  .j a  v  a 2  s  .co  m*/

    startdate = DateTime.parse(SD, DateTimeFormat.forPattern("dd/MM/yyyy"));
    enddate = DateTime.parse(ED, DateTimeFormat.forPattern("dd/MM/yyyy"));

}

From source file:com.mycompany.assignment1.Programme.java

public void printProgramme() {

    System.out.println(Name + ", " + startdate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")) + " - "
            + enddate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    for (int x = 0; x < modules.size(); x++) {
        System.out.println("-" + modules.get(x).getName());
        modules.get(x).studentlist();//from w w  w  . j  a va  2  s . c  o m
    }

}

From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java

License:Apache License

/**
 * finds the profiles that match user's interests given his web history
 * @param userID the user's id// w  w w.  j a va  2  s .com
 * @param history the user's web history
 * @param input a txt file that contains the necessary parameters
 */
public void perform(String userID, String[] history, File input) {

    System.out.println("total urls = " + history.length);
    //default parameters
    //number of random queries for each profile
    int numQueriesSuggestion = 5;
    //number of random webpages per query to suggest - total number of suggestions = 
    // numQueriesSuggestion*pagesPerQuerySuggestion
    int pagesPerQuerySuggestion = 1;
    //number of random queries to return as examples for alternatives profiles
    int numQueriesExample = 2;

    //we get the current date/time
    DateTime current = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
    String timestamp = fmt.print(current);

    //update user info - i'll store the results when i'll perform the last analysis
    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("profileAnalysis");
    DBCollection userinfo = db.getCollection("userinfo");
    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("$set", new BasicDBObject().append("timestamp", timestamp));
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("userID", userID);
    userinfo.update(searchQuery, newDocument, true, false);

    //read the neccessary parameters
    Utils utils = new Utils();
    utils.readInput(input);
    HashMap<String, ArrayList<String>> wordvectors = utils.wordvectors;
    HashMap<String, String> crawlerOutputPaths = utils.crawlerOutputPaths;

    //get the urls' content
    ArrayList<String> webpages = new ArrayList<>();
    ArrayList<String> urls = new ArrayList<>();
    for (int i = 0; i < history.length; i++) {
        WebParser pageParser = new WebParser(history[i]);
        pageParser.parse();
        String content = pageParser.getContent();
        if ("".equals(content) || content == null)
            continue;
        webpages.add(content);
        urls.add(history[i]);
    }

    //calculate the urls' scores
    HashMap<String, double[]> historyScores = new HashMap<>();
    String[] webpagesArr = new String[webpages.size()];
    webpagesArr = webpages.toArray(webpagesArr);
    String[] urlsArr = new String[urls.size()];
    urlsArr = urls.toArray(urlsArr);
    for (String profile : wordvectors.keySet()) {
        Scorer scorer = new Scorer(webpagesArr, urlsArr, wordvectors.get(profile));
        double[] semanticScores = scorer.getSemanticScores();
        double[] relevanceScores = scorer.getRelevanceScores();
        double[] confidenceScores = scorer.getConfidenceScores();
        double[] scores = scoreFormula(semanticScores, relevanceScores, confidenceScores);
        historyScores.put(profile, scores);
    }

    //find the maximum score of every url and get summation of the scores for each profile
    HashMap<String, Double> userProfilesScore = new HashMap<>();
    for (int i = 0; i < webpages.size(); i++) {
        double max = 0.0;
        String info = "undefined";
        for (String profile : historyScores.keySet()) {
            if (historyScores.get(profile)[i] > max) {
                max = historyScores.get(profile)[i];
                info = profile;
            }
        }
        if (!"undefined".equals(info)) {
            Double prevscore = userProfilesScore.get(info);
            userProfilesScore.put(info, (prevscore == null) ? max : prevscore + max);
        }
    }

    //find which profile level has maximum score e.g. if football/level=0 score is greater
    //than football/level=1 score then the user is better described as a football/level=0 user
    HashMap<String, Double> userProfileScores = new HashMap<>();
    HashMap<String, String> userProfileLevels = new HashMap<>();
    for (String s : userProfilesScore.keySet()) {
        String[] info = s.split("/");
        Double prevscore = userProfileScores.get(info[0] + "/" + info[1] + "/");
        if (prevscore == null) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        } else if (userProfilesScore.get(s) > prevscore) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        }
    }

    //put the final profiles together in this simple form: domain/profile/level of expertise and rank them
    Double totalScore = 0.0;
    for (String s : userProfileScores.keySet())
        totalScore += userProfileScores.get(s);

    Map<String, Double> userProfiles = new HashMap<>();
    for (String s : userProfileLevels.keySet())
        userProfiles.put(s + userProfileLevels.get(s), round(userProfileScores.get(s) * 100 / totalScore, 2));

    userProfiles = sortByValue(userProfiles);

    //find page suggestions for every profile
    HashMap<String, ArrayList<String>> pageSuggestions = new HashMap<>();
    for (String profile : userProfiles.keySet()) {
        String path = crawlerOutputPaths.get(profile);
        ArrayList<String> suggestions = getSuggestions(path, numQueriesSuggestion, pagesPerQuerySuggestion,
                history);
        pageSuggestions.put(profile, suggestions);
    }

    //find alternative profiles for every profile and representative queries
    HashMap<String, HashMap<String, ArrayList<String>>> alternativeProfiles = new HashMap<>();
    for (String userProfile : userProfiles.keySet()) {
        String[] userProfileInfo = userProfile.split("/");
        HashMap<String, ArrayList<String>> profileQueries = new HashMap<>();
        for (String profile : wordvectors.keySet()) {
            String[] profileInfo = profile.split("/");
            if (profileInfo[0].equals(userProfileInfo[0]) && profileInfo[1].equals(userProfileInfo[1])
                    && !profileInfo[2].equals(userProfileInfo[2])) {
                String path = crawlerOutputPaths.get(profile);
                ArrayList<String> queries = getQueries(path, numQueriesExample);
                for (int i = 0; i < queries.size(); i++) {
                    String query = queries.get(i);
                    queries.set(i, query.substring(query.lastIndexOf("\\") + 1).replace("-query", "")
                            .replace("+", " "));
                }
                profileQueries.put(profile, queries);
            }
        }
        alternativeProfiles.put(userProfile, profileQueries);
    }

    //prepare JSON response
    JSONObject response = new JSONObject();
    response.put("userID", userID);
    response.put("timestamp", timestamp);
    JSONArray list = new JSONArray();

    for (String profile : userProfiles.keySet()) {
        JSONObject profileInfo = new JSONObject();
        profileInfo.put("profile", profile);
        profileInfo.put("score", userProfiles.get(profile));

        JSONArray temp = new JSONArray();
        ArrayList<String> suggestions = pageSuggestions.get(profile);
        for (String s : suggestions)
            temp.add(s);
        profileInfo.put("suggestions", temp);

        JSONArray alternativesArray = new JSONArray();
        for (String s : alternativeProfiles.get(profile).keySet()) {
            JSONObject alternativeInfo = new JSONObject();
            alternativeInfo.put("alternative", s);
            ArrayList<String> queries = alternativeProfiles.get(profile).get(s);
            JSONArray queriesArray = new JSONArray();
            for (String str : queries) {
                queriesArray.add(str);
            }
            alternativeInfo.put("queries", queriesArray);
            alternativesArray.add(alternativeInfo);
        }

        profileInfo.put("alternatives", alternativesArray);
        list.add(profileInfo);
    }
    response.put("profiles", list);
    System.out.println("JSON response is ready: " + response);

    //delete previous analysis and store results
    DBCollection collection = db.getCollection("history");
    BasicDBObject previous = new BasicDBObject();
    previous.put("userID", userID);
    collection.remove(previous);
    DBObject dbObject = (DBObject) JSON.parse(response.toString());
    collection.insert(dbObject);
    System.out.println("I saved the analysis...");

}