List of usage examples for java.util Calendar AM_PM
int AM_PM
To view the source code for java.util Calendar AM_PM.
Click Source Link
get
and set
indicating whether the HOUR
is before or after noon. From source file:edu.pdx.its.portal.routelandia.DatePickUp.java
/** * Display the current time* /*from ww w . jav a 2 s . co m*/ */ public void setCurrentTimeOnView() { thisTimePicker = (TimePicker) findViewById(R.id.timePicker); weekDaySpinner = (Spinner) findViewById(R.id.spinner); final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); am_pm = c.get(Calendar.AM_PM); dayofweek = getDayOfWeekInStr(c.get(Calendar.DAY_OF_WEEK)); departureTime = (new StringBuilder().append(hour).append(":").append(minute)).toString(); thisTimePicker.setCurrentHour(hour); thisTimePicker.setCurrentMinute(minute); // We have to do the -1 because DAY_OF_WEEK is 1-7, instead of 0-6. weekDaySpinner.setSelection(c.get(Calendar.DAY_OF_WEEK) - 1); }
From source file:MailDateFormatter.java
/** * A method that returns a string rapresenting a date. * * @param date the date// w ww .jav a2 s . c o m * * @param format the format as one of * FORMAT_MONTH_DAY, * FORMAT_MONTH_DAY_YEAR, * FORMAT_HOURS_MINUTES, * FORMAT_HOURS_MINUTES_SECONDS * FORMAT_DAY_MONTH * FORMAT_DAY_MONTH_YEAR * constants * * @param separator the separator to be used */ public static String getFormattedStringFromDate(Date date, int format, String separator) { Calendar cal = Calendar.getInstance(); cal.setTime(date); StringBuffer ret = new StringBuffer(); switch (format) { case FORMAT_HOURS_MINUTES: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM) == Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator).append(printTwoDigits(cal.get(Calendar.MINUTE))).append(getAMPM(cal)); break; case FORMAT_HOURS_MINUTES_SECONDS: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM) == Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator).append(printTwoDigits(cal.get(Calendar.MINUTE))).append(separator) .append(cal.get(Calendar.SECOND)).append(getAMPM(cal)); break; case FORMAT_MONTH_DAY: ret.append(cal.get(Calendar.MONTH) + 1).append(separator).append(cal.get(Calendar.DAY_OF_MONTH)); break; case FORMAT_DAY_MONTH: ret.append(cal.get(Calendar.DAY_OF_MONTH)).append(separator).append(cal.get(Calendar.MONTH) + 1); break; case FORMAT_MONTH_DAY_YEAR: ret.append(cal.get(Calendar.MONTH) + 1).append(separator).append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator).append(cal.get(Calendar.YEAR)); break; case FORMAT_DAY_MONTH_YEAR: ret.append(cal.get(Calendar.DAY_OF_MONTH)).append(separator).append(cal.get(Calendar.MONTH) + 1) .append(separator).append(cal.get(Calendar.YEAR)); break; default: // Log.error("getFormattedStringFromDate: invalid format ("+ // format+")"); } return ret.toString(); }
From source file:amhamogus.com.daysoff.fragments.AddEventFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_add_event, container, false); ButterKnife.bind(this, rootView); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); addEventHeader.setText(calendarId);/*from w w w .j a v a 2s . co m*/ // Set default date and time values // based on the current time final Calendar currentDate = Calendar.getInstance(); hour = currentDate.get(Calendar.HOUR); minute = currentDate.get(Calendar.MINUTE); amOrPm = currentDate.get(Calendar.AM_PM); if (amOrPm == Calendar.AM) { noonOrNight = "AM"; } else { noonOrNight = "PM"; } // By default, events are set to 30 minutes. Based on the // current minute value round to the next 30 minute set if (minute <= 29) { // Minute value is between 0 and 29. // Set the start time to half past. minute = 30; // Set end time to the the next hour. futureMinute = 0; // Set future hour to the next hour. if (hour > 12) { // The app tries to mange hours in 12 hour format // So hour values should not exceed 12. If hour does // exceed 12, we convert to 12 hour format. hour = hour - 12; futureHour = hour + 1; } else if (hour == 0) { // In 12 hour format. Convert 0 to 12. // Noon or midnight is set to '0' which is not // helpful for users, thus we change 0 to 12 hour = 12; futureHour = 1; } else { // futureHour = hour + 1; } } else { // Current minute is between 30 and 60. // Round to the nearest hour. minute = 0; futureMinute = 30; if (hour > 12) { // The app tries to mange hours in 12 hour format // So hour values should not exceed 12. If hour does // exceed 12, we convert to 12 hour format. hour = hour - 12; futureHour = hour; } else if (hour == 0 || hour == 12) { // In 12 hour format. Convert 0 to 12. // Noon or midnight is set to '0' which is not // helpful for users, thus we change 0 to 12 hour = 1; futureHour = 1; } else { hour = hour + 1; futureHour = hour; } } // Update form with default start and end time // for a new event. startTimeLabel.setText("" + hour + ":" + String.format("%02d", minute) + " " + noonOrNight); startTimeLabel.setOnClickListener(this); endTimeLabel.setText("" + futureHour + ":" + String.format("%02d", futureMinute) + " " + noonOrNight); endTimeLabel.setOnClickListener(this); // Add click listener to checkboxes food.setOnClickListener(this); movie.setOnClickListener(this); outdoors.setOnClickListener(this); return rootView; }
From source file:org.sakaiproject.user.impl.PrecachingDbUserService.java
/** UVa SAK-1382: replace Aaron's init() code to schedule one task to run at the same time each day * add a 2nd task "onetimeTask" to run immediately." *//*from w w w . j a va2 s. c om*/ public void init() { super.init(); if (log.isDebugEnabled()) { log.debug( "init(): (grand-super) BaseUserDirectoryService includes this general cache just created in its code, m_callCache==" + m_callCache); log.debug( "init(): (super) DbUserService includes this eid/id map, wired in user-components.xml, cache==" + cache); } // LOAD the various sakai config options Boolean runOnStartup = serverConfigurationService().getBoolean("precache.users.run.startup", false); Boolean runDaily = serverConfigurationService().getBoolean("precache.users.run.daily", false); String cacheTimeString = serverConfigurationService().getString("precache.users.refresh.time", "04:00"); this.siteUserIdsQuery = serverConfigurationService().getString("precache.users.userlist.query", this.siteUserIdsQuery); this.logUsersRemoved = serverConfigurationService().getBoolean("precache.users.log.usersRemoved", this.logUsersRemoved); this.logUsersNotRemoved = serverConfigurationService().getBoolean("precache.users.log.usersNotRemoved", this.logUsersNotRemoved); this.logUsersAccessed = serverConfigurationService().getBoolean("precache.users.log.usersAccessed", this.logUsersAccessed); this.logUsersNotAccessed = serverConfigurationService().getBoolean("precache.users.log.usersNotAccessed", this.logUsersNotAccessed); Calendar cal = Calendar.getInstance(); if (runOnStartup) { log.info("init() scheduling user precache for startup run"); // set up onetime task to run after short delay cal.setTime(new Date()); cal.add(Calendar.MINUTE, 5); Date onetimeTaskStart = cal.getTime(); onetimeTask = new UserCacheTimerTask(); bootTimer.schedule(onetimeTask, onetimeTaskStart); log.info("User precache refresh onetime task scheduled to run in 5 minutes without repetition."); } else { log.info("User precache not scheduled for startup run"); } if (runDaily) { // set up recurring task cal.setTime(new Date()); cal.add(Calendar.DATE, 1); // start tomorrow long recurringTaskPeriod = 24l * 60l * 60l * 1000l; log.info("User precache will schedule recurring task every 24 hours, beginning tomorrow"); try { String[] parts = cacheTimeString.trim().split(":"); Integer hour = new Integer(parts[0]); if (hour < 12) { cal.set(Calendar.AM_PM, Calendar.AM); } else { cal.set(Calendar.AM_PM, Calendar.PM); } cal.set(Calendar.HOUR, hour); cal.set(Calendar.MINUTE, new Integer(parts[1])); Date recurringTaskStart = cal.getTime(); scheduledTask = new UserCacheTimerTask(); dailyTimer.scheduleAtFixedRate(scheduledTask, recurringTaskStart, recurringTaskPeriod); log.info("User precache scheduled for daily run at " + cacheTimeString); } catch (RuntimeException e) { log.error( "User precache: Didn't schedule user cache refresh: Bad config?, it should be like: 'precache.users.refresh.time = 04:00' : " + e.getMessage(), e); } } else { log.info("User precache not scheduled for daily run"); } }
From source file:com.enadein.carlogbook.ui.TypeReportFragment.java
private long convertDateToLong(int year, int month, int day, boolean trunk) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year);//from ww w . ja v a 2 s . co m c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, day); if (trunk) { CommonUtils.trunkDay(c); } else { c.set(Calendar.AM_PM, 1); c.set(Calendar.HOUR, 11); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); } return c.getTime().getTime(); }
From source file:org.kuali.rice.kew.rule.web.RoutingReportAction.java
public ActionForward calculateRoute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { RoutingReportForm routingForm = (RoutingReportForm) form; // this is never actually used?? List<RemotableAttributeError> errors = new ArrayList<RemotableAttributeError>(); if (getDocumentTypeService().findByName(routingForm.getDocumentType()) == null) { GlobalVariables.getMessageMap().putError("Document type is required.", "doctype.documenttypeservice.doctypename.required"); }/*from w w w .j a v a 2 s. co m*/ Timestamp date = null; if (!org.apache.commons.lang.StringUtils.isEmpty(routingForm.getDateRef())) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); try { Calendar calendar = Calendar.getInstance(); calendar.setTime(sdf.parse(routingForm.getDateRef())); calendar.set(Calendar.HOUR, Integer.parseInt(routingForm.getEffectiveHour())); calendar.set(Calendar.MINUTE, Integer.parseInt(routingForm.getEffectiveMinute())); calendar.set(Calendar.AM_PM, Integer.parseInt(routingForm.getAmPm())); date = new Timestamp(calendar.getTimeInMillis()); } catch (Exception e) { LOG.error("error parsing date", e); GlobalVariables.getMessageMap().putError("Invalid date.", "routereport.effectiveDate.invalid"); } } if (!GlobalVariables.getMessageMap().hasNoErrors()) { throw new ValidationException("Errors populating rule attributes."); } DocumentTypeService documentTypeService = (DocumentTypeService) KEWServiceLocator .getService(KEWServiceLocator.DOCUMENT_TYPE_SERVICE); DocumentType docType = documentTypeService.findByName(routingForm.getDocumentType()); DocumentRouteHeaderValue routeHeader = new DocumentRouteHeaderValue(); routeHeader.setDocumentId(""); routeHeader.setDocumentTypeId(docType.getDocumentTypeId()); routeHeader.setDocRouteLevel(new Integer(0)); routeHeader.setDocVersion(new Integer(KewApiConstants.DocumentContentVersions.CURRENT)); List<RouteReportRuleTemplateContainer> ruleTemplateContainers = new ArrayList<RouteReportRuleTemplateContainer>(); if (routingForm.getReportType().equals(DOC_TYPE_REPORTING)) { List routeNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(docType, true); for (Iterator iter = routeNodes.iterator(); iter.hasNext();) { RouteNode routeNode = (RouteNode) iter.next(); if (routeNode.isFlexRM()) { RuleTemplateBo ruleTemplate = getRuleTemplateService() .findByRuleTemplateName(routeNode.getRouteMethodName()); if (ruleTemplate != null) { ruleTemplateContainers.add(new RouteReportRuleTemplateContainer(ruleTemplate, routeNode)); if (ruleTemplate.getDelegationTemplate() != null) { ruleTemplateContainers.add(new RouteReportRuleTemplateContainer( ruleTemplate.getDelegationTemplate(), routeNode)); } } } } } else { RuleTemplateBo ruleTemplate = getRuleTemplateService() .findByRuleTemplateId(routingForm.getRuleTemplateId()); RouteNode routeNode = new RouteNode(); routeNode.setRouteNodeName(ruleTemplate.getName()); ruleTemplateContainers.add(new RouteReportRuleTemplateContainer(ruleTemplate, routeNode)); if (ruleTemplate.getDelegationTemplate() != null) { ruleTemplateContainers .add(new RouteReportRuleTemplateContainer(ruleTemplate.getDelegationTemplate(), routeNode)); } } String xmlDocumentContent = routingForm.getDocumentContent(); if (routingForm.getReportType().equals(TEMPLATE_REPORTING)) { List<WorkflowRuleAttribute> attributes = new ArrayList<WorkflowRuleAttribute>(); for (RouteReportRuleTemplateContainer ruleTemplateContainer : ruleTemplateContainers) { RuleTemplateBo ruleTemplate = ruleTemplateContainer.ruleTemplate; for (RuleTemplateAttributeBo ruleTemplateAttribute : ruleTemplate .getActiveRuleTemplateAttributes()) { if (!ruleTemplateAttribute.isWorkflowAttribute()) { continue; } WorkflowRuleAttribute workflowAttribute = ruleTemplateAttribute.getWorkflowAttribute(); RuleAttribute ruleAttribute = ruleTemplateAttribute.getRuleAttribute(); if (ruleAttribute.getType().equals(KewApiConstants.RULE_XML_ATTRIBUTE_TYPE)) { ((GenericXMLRuleAttribute) workflowAttribute) .setExtensionDefinition(RuleAttribute.to(ruleAttribute)); } List<RemotableAttributeError> attValidationErrors = workflowAttribute .validateRoutingData(routingForm.getFields()); if (attValidationErrors != null && !attValidationErrors.isEmpty()) { errors.addAll(attValidationErrors); } attributes.add(workflowAttribute); } } if (!GlobalVariables.getMessageMap().hasNoErrors()) { throw new ValidationException("errors in search criteria"); } DocumentContent docContent = new AttributeDocumentContent(attributes); xmlDocumentContent = docContent.getDocContent(); } routeHeader.setDocContent(xmlDocumentContent); routeHeader.setInitiatorWorkflowId(getUserSession(request).getPrincipalId()); routeHeader.setDocRouteStatus(KewApiConstants.ROUTE_HEADER_INITIATED_CD); routeHeader.setDocTitle("Routing Report"); routeHeader.setRoutingReport(true); long magicCounter = 0; FlexRM flexRM = new FlexRM(date); int numberOfRules = 0; int numberOfActionRequests = 0; Set<String> alreadyProcessedRuleTemplateNames = new HashSet<String>(); for (Object element : ruleTemplateContainers) { // initialize the RouteContext RouteContext context = RouteContext.createNewRouteContext(); context.setActivationContext(new ActivationContext(ActivationContext.CONTEXT_IS_SIMULATION)); try { RouteReportRuleTemplateContainer ruleTemplateContainer = (RouteReportRuleTemplateContainer) element; RuleTemplateBo ruleTemplate = ruleTemplateContainer.ruleTemplate; RouteNode routeLevel = ruleTemplateContainer.routeNode; if (!alreadyProcessedRuleTemplateNames.contains(ruleTemplate.getName())) { alreadyProcessedRuleTemplateNames.add(ruleTemplate.getName()); List<ActionRequestValue> actionRequests = flexRM.getActionRequests(routeHeader, routeLevel, null, ruleTemplate.getName()); numberOfActionRequests += actionRequests.size(); numberOfRules += flexRM.getNumberOfMatchingRules(); magicCounter = populateActionRequestsWithRouteLevelInformationAndIterateMagicCounter(routeLevel, actionRequests, magicCounter); //routeHeader.getActionRequests().addAll(actionRequests); routeHeader.getSimulatedActionRequests().addAll(actionRequests); } } finally { RouteContext.clearCurrentRouteContext(); } } if (numberOfActionRequests == 0) { if (numberOfRules == 0) { GlobalVariables.getMessageMap().putError("*", "routereport.noRules"); } else { GlobalVariables.getMessageMap().putError("*", "routereport.noMatchingRules"); } if (GlobalVariables.getMessageMap().hasErrors()) { throw new ValidationException("errors in search criteria"); } } // PROBLEM HERE!!!! RouteLogForm routeLogForm = new RouteLogForm(); routeLogForm.setShowFuture(true); if (StringUtils.isNotBlank(routingForm.getBackUrl())) { routeLogForm.setReturnUrlLocation(routingForm.getBackUrl()); } LOG.debug("Value of getDisplayCloseButton " + routingForm.getShowCloseButton()); LOG.debug("Value of isDisplayCloseButton " + routingForm.isDisplayCloseButton()); routeLogForm.setShowCloseButton(routingForm.isDisplayCloseButton()); request.setAttribute("routeHeader", routeHeader); new RouteLogAction().populateRouteLogFormActionRequests(routeLogForm, routeHeader); request.setAttribute("KualiForm", routeLogForm); //END PROBLEM AREA //return mapping.findForward("basic"); return mapping.findForward("routeLog"); }
From source file:CalendarUtils.java
private static void modify(Calendar val, int field, boolean round) { boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == CalendarUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); }// w ww . j av a2 s. c om } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case CalendarUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field val.add(fields[i][0], -offset); } throw new RuntimeException("We do not support that field."); }
From source file:Main.java
/** * <p>Internal calculation method.</p> * /* w w w.j a v a 2 s. co m*/ * @param val the calendar * @param field the field constant * @param round true to round, false to truncate * @throws ArithmeticException if the year is over 280 million */ private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
From source file:rml.controller.ShopController.java
@RequestMapping(value = "/Shop", method = RequestMethod.GET) @ResponseBody/* ww w .j a v a 2 s.com*/ public Object shopLogin(Shop shop) { ReturnJson returnJson = new ReturnJson(); returnJson.setErrorCode(1000); returnJson.setReturnMessage("?"); returnJson.setServerStatus(0); if (StringUtils.isEmpty(shop.getMobile()) || StringUtils.isEmpty(shop.getPassword())) { returnJson.setErrorCode(1001); returnJson.setReturnMessage("?" + shop.toString()); returnJson.setServerStatus(1); return returnJson; } String result1 = MD5.GetMD5Code(shop.getRandomKey() + "at^&*ta"); if (!result1.equals(shop.getSecretKey())) { returnJson.setErrorCode(99999); returnJson.setReturnMessage("" + shop.toString()); returnJson.setServerStatus(1); return returnJson; } try { shop.setPassword(MD5.GetMD5Code(shop.getPassword())); Shop shop1 = shopService.getShop(shop); if (shop1 == null) { returnJson.setErrorCode(1002); returnJson.setReturnMessage("??"); returnJson.setServerStatus(1); return returnJson; } if (shop1.getStatus() == 1) { returnJson.setErrorCode(1003); returnJson.setReturnMessage(","); returnJson.setServerStatus(1); return returnJson; } if (shop1.getStatus() == 3) { returnJson.setErrorCode(1004); returnJson.setReturnMessage(""); returnJson.setServerStatus(1); return returnJson; } Date today = new Date(); Order order = new Order(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateString = formatter.format(new Date()); dateString = dateString + " 00:00:00"; order.setStartDate(dateString); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); dateString = formatter1.format(new Date()); order.setEndDate(dateString); order.setShopId(shop1.getUuid()); int orderDaily = 0; try { orderDaily = orderService.getShopReport(order); } catch (Exception e) { } Calendar calendar = Calendar.getInstance(Locale.CHINA); int YEAR = calendar.getMinimum(Calendar.YEAR);// ???() int day = calendar.getMinimum(Calendar.DAY_OF_WEEK);// ???() calendar.set(Calendar.YEAR, YEAR); calendar.set(Calendar.DAY_OF_WEEK, day); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.AM_PM, 0); calendar.set(Calendar.MINUTE, 0); Date date = calendar.getTime(); int orderTotal = 0; order.setStartDate(date.toLocaleString()); try { orderTotal = orderService.getShopReport(order); } catch (Exception e) { } shop1.setMoneyDaily(orderDaily); shop1.setMoneyTotal(orderTotal); returnJson.setReturnObject(shop1); } catch (Exception ex) { ex.printStackTrace(); returnJson.setErrorCode(1005); returnJson.setReturnMessage("?"); returnJson.setServerStatus(2); return returnJson; } return returnJson; }
From source file:com.concursive.connect.web.modules.calendar.utils.DimDimUtils.java
/** * Calls Dimdim server methods based on the action set on MeetingInviteesBean * * @param meetingInviteesBean - meeting parameters to be called are to be set to the class * @param attendeeUser - host or participant based on the meeting action * @return - Url to dimdim server or the message returned *///w ww . ja v a2 s . c o m public static HashMap<String, String> processDimdimMeeting(MeetingInviteesBean meetingInviteesBean, User attendeeUser) { //return result HashMap<String, String> resultMap = new HashMap<String, String>(); try { //get meeting Meeting meeting = meetingInviteesBean.getMeeting(); //get meeting host User hostUser = UserUtils.loadUser(meeting.getOwner()); //comma separate the attendee mailids for dimdim String attendeeMailIds = ""; if (meetingInviteesBean.getMembersFoundList() != null && meetingInviteesBean.getMembersFoundList().size() > 0) { Set<User> userSet = meetingInviteesBean.getMembersFoundList().keySet(); for (User user : userSet) { attendeeMailIds += user.getEmail() + ", "; } } if (meetingInviteesBean.getMeetingChangeUsers() != null && meetingInviteesBean.getMeetingChangeUsers().size() > 0) { for (User user : meetingInviteesBean.getMeetingChangeUsers()) { attendeeMailIds += user.getEmail() + ", "; } } attendeeMailIds = trimComma(attendeeMailIds); //Modify meeting if (meetingInviteesBean.getAction() == ACTION_MEETING_DIMDIM_EDIT || meetingInviteesBean.getAction() == ACTION_MEETING_APPROVE_JOIN) { //check for meetingId if not present then call schedule meeting if (!StringUtils.hasText(meeting.getDimdimMeetingId())) { meetingInviteesBean.setAction(ACTION_MEETING_DIMDIM_SCHEDULE); resultMap = processDimdimMeeting(meetingInviteesBean, attendeeUser); meetingInviteesBean.setAction(ACTION_MEETING_DIMDIM_EDIT); return resultMap; } //set the query string values as params Map<String, String> params = new HashMap<String, String>(); params.put("name", meeting.getDimdimUsername()); params.put("password", meeting.getDimdimPassword()); params.put("meetingID", meeting.getDimdimMeetingId()); SimpleDateFormat dtFormater = new SimpleDateFormat("MMMM dd, yyyy"); TimeZone timeZone = Calendar.getInstance().getTimeZone(); if (hostUser.getTimeZone() != null) { timeZone = TimeZone.getTimeZone(hostUser.getTimeZone()); } Calendar calendar = Calendar.getInstance(timeZone); calendar.setTime(meeting.getStartDate()); params.put("startDate", dtFormater.format(meeting.getStartDate())); params.put("endDate", dtFormater.format(meeting.getEndDate())); params.put("startHour", calendar.get(Calendar.HOUR) + ""); params.put("startMinute", calendar.get(Calendar.MINUTE) + ""); params.put("timeAMPM", calendar.get(Calendar.AM_PM) == 0 ? "AM" : "PM"); params.put("confname", meeting.getTitle()); params.put("timezone", timeZone.getID()); params.put("feedback", hostUser.getEmail()); if (StringUtils.hasText(attendeeMailIds)) { params.put("attendees", attendeeMailIds); } params.put("agenda", meeting.getDescription()); if (meeting.getByInvitationOnly()) { params.put("attendeePwd", meeting.getDimdimMeetingKey()); params.put("waitingarea", "false"); } else { params.put("attendeePwd", ""); params.put("waitingarea", "false"); } params.put("response", "json"); //post to dimdim server and process response LOG.debug("JSON POST"); String urlPrefix = meeting.getDimdimUrl() + URL_DIMDIM_EDIT; JSONObject dimdimResp = JSONObject.fromObject(HTTPUtils.post(urlPrefix, params)); String resSuccess = dimdimResp.getString("code"); String resText = dimdimResp.getJSONObject("data").getString("text"); //get meetingid if successful if (DIMDIM_CODE_SUCCESS.equals(resSuccess)) { resultMap.put(resSuccess, meeting.getDimdimMeetingId()); return resultMap; } resultMap.put(resSuccess, resText); return resultMap; } //create a new meeting if (meetingInviteesBean.getAction() == ACTION_MEETING_DIMDIM_SCHEDULE) { //set the query string values as params Map<String, String> params = new HashMap<String, String>(); params.put("name", meeting.getDimdimUsername()); params.put("password", meeting.getDimdimPassword()); SimpleDateFormat dtFormater = new SimpleDateFormat("MMMM dd, yyyy"); TimeZone timeZone = Calendar.getInstance().getTimeZone(); if (hostUser.getTimeZone() != null) { timeZone = TimeZone.getTimeZone(hostUser.getTimeZone()); } Calendar calendar = Calendar.getInstance(timeZone); calendar.setTime(meeting.getStartDate()); params.put("startDate", dtFormater.format(meeting.getStartDate())); params.put("endDate", dtFormater.format(meeting.getEndDate())); params.put("startHour", calendar.get(Calendar.HOUR) + ""); params.put("startMinute", calendar.get(Calendar.MINUTE) + ""); params.put("timeAMPM", calendar.get(Calendar.AM_PM) == 0 ? "AM" : "PM"); params.put("confname", meeting.getTitle()); params.put("timezone", timeZone.getID()); params.put("feedback", hostUser.getEmail()); if (StringUtils.hasText(attendeeMailIds)) { params.put("attendees", attendeeMailIds); } params.put("agenda", meeting.getDescription()); if (StringUtils.hasText(meeting.getDimdimMeetingKey())) { params.put("attendeePwd", meeting.getDimdimMeetingKey()); params.put("waitingarea", "false"); } params.put("response", "json"); //post to dimdim server and process response LOG.debug("JSON POST"); String urlPrefix = meeting.getDimdimUrl() + URL_DIMDIM_SCHEDULE; JSONObject dimdimResp = JSONObject.fromObject(HTTPUtils.post(urlPrefix, params)); String resSuccess = dimdimResp.getString("code"); String resText = dimdimResp.getJSONObject("data").getString("text"); //get meetingid if successful if (DIMDIM_CODE_SUCCESS.equals(resSuccess)) { resText = resText.substring(resText.lastIndexOf("is ") + 3); resultMap.put(resSuccess, resText); return resultMap; } resultMap.put(resSuccess, resText); return resultMap; } //join an existing meeting if (meetingInviteesBean.getAction() == ACTION_MEETING_DIMDIM_JOIN) { //set the query string values as params Map<String, String> params = new HashMap<String, String>(); params.put("meetingRoomName", meeting.getDimdimUsername()); params.put("displayname", attendeeUser.getNameFirstLast()); if (StringUtils.hasText(meeting.getDimdimMeetingKey())) { params.put("attendeePwd", meeting.getDimdimMeetingKey()); } params.put("response", "json"); //post to dimdim server and process response LOG.debug("JSON POST"); String urlPrefix = meeting.getDimdimUrl() + URL_DIMDIM_JOIN; JSONObject dimdimResp = JSONObject.fromObject(HTTPUtils.post(urlPrefix, params)); String resSuccess = dimdimResp.getString("code"); String resText = dimdimResp.getJSONObject("data").getString("text"); //if successful return dimdim url if (DIMDIM_CODE_SUCCESS.equals(resSuccess)) { resultMap.put(resSuccess, urlPrefix + buildDimdimUrl(params)); return resultMap; } resultMap.put(resSuccess, resText); return resultMap; } //start a meeting if (meetingInviteesBean.getAction() == ACTION_MEETING_DIMDIM_START) { //set the query string values as params Map<String, String> params = new HashMap<String, String>(); params.put("name", meeting.getDimdimUsername()); params.put("password", meeting.getDimdimPassword()); params.put("meetingID", meeting.getDimdimMeetingId()); params.put("response", "json"); //post to dimdim server and process response LOG.debug("JSON POST"); String urlPrefix = meeting.getDimdimUrl() + URL_DIMDIM_START; JSONObject dimdimResp = JSONObject.fromObject(HTTPUtils.post(urlPrefix, params)); String resSuccess = dimdimResp.getString("code"); String resText = dimdimResp.getJSONObject("data").getString("text"); if (DIMDIM_CODE_SUCCESS.equals(resSuccess)) { resultMap.put(resSuccess, urlPrefix + buildDimdimUrl(params)); return resultMap; } resultMap.put(resSuccess, resText); return resultMap; } //delete a meeting if (meetingInviteesBean.getAction() == ACTION_MEETING_DIMDIM_CANCEL) { //set the query string values as params Map<String, String> params = new HashMap<String, String>(); params.put("name", meeting.getDimdimUsername()); params.put("password", meeting.getDimdimPassword()); params.put("meetingID", meeting.getDimdimMeetingId()); params.put("response", "json"); //post to dimdim server and process response LOG.debug("JSON POST"); String urlPrefix = meeting.getDimdimUrl() + URL_DIMDIM_DELETE; JSONObject dimdimResp = JSONObject.fromObject(HTTPUtils.post(urlPrefix, params)); String resSuccess = dimdimResp.getString("code"); String resText = dimdimResp.getJSONObject("data").getString("text"); if (DIMDIM_CODE_SUCCESS.equals(resSuccess)) { resultMap.put(resSuccess, urlPrefix + buildDimdimUrl(params)); return resultMap; } resultMap.put(resSuccess, resText); return resultMap; } LOG.error("Unknown Dimdim meeting senario or action."); resultMap.put("0", "Error occured while accessing Dimdim server."); return resultMap; } catch (Exception e) { LOG.error(e.toString()); resultMap.put("0", "Error occured while accessing Dimdim server."); return resultMap; } }