List of usage examples for java.text DateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java
/** * Create a date format for the specified pattern. * * @param pattern The date pattern//from ww w .ja va 2 s . c om * @return The DateFormat */ private DateFormat getFormat(String pattern) { DateFormat format = new SimpleDateFormat(pattern); if (timeZone != null) { format.setTimeZone(timeZone); } return format; }
From source file:org.sakaiproject.news.tool.NewsAction.java
/** * build the context for the Main (Layout) panel * /*from w w w. java2s . co m*/ * @return (optional) template name for this panel */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { context.put("tlang", rb); String mode = (String) state.getAttribute(STATE_MODE); if (MODE_OPTIONS.equals(mode)) { return buildOptionsPanelContext(portlet, context, rundata, state); } context.put(GRAPHIC_VERSION_TEXT, state.getAttribute(GRAPHIC_VERSION_TEXT)); context.put(FULL_STORY_TEXT, state.getAttribute(FULL_STORY_TEXT)); // build the menu Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION)); // add options if allowed addOptionsMenu(bar, (JetspeedRunData) rundata); if (!bar.getItems().isEmpty()) { context.put(Menu.CONTEXT_MENU, bar); } context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION)); context.put(GRAPHIC_VERSION_TEXT, state.getAttribute(GRAPHIC_VERSION_TEXT)); context.put(FULL_STORY_TEXT, state.getAttribute(FULL_STORY_TEXT)); String url = (String) state.getAttribute(STATE_CHANNEL_URL); NewsChannel channel = null; List items = new Vector(); try { channel = NewsService.getChannel(url); items = NewsService.getNewsitems(url); } catch (NewsConnectionException e) { // display message addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() })); if (log.isDebugEnabled()) { log.debug(e); } } catch (NewsFormatException e) { // display message addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() })); if (log.isDebugEnabled()) { log.debug(e); } } catch (Exception e) { // display message addAlert(state, rb.getFormattedMessage("unavailable", new Object[] { e.getLocalizedMessage() })); if (log.isDebugEnabled()) { log.debug(e); } } context.put("channel", channel); context.put("news_items", items); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, new ResourceLoader().getLocale()); df.setTimeZone(TimeService.getLocalTimeZone()); context.put("dateFormat", df); try { // tracking event if (state.getAttribute(FEED_ACCESS) == null) { if (state.getAttribute(STATE_DETECT_REGISTERED_EVENT) == null) { // is News tool EventTrackingService.post(EventTrackingService.newEvent(FEED_ACCESS, "/news/site/" + SiteService.getSite(ToolManager.getCurrentPlacement().getContext()).getId() + "/placement/" + SessionManager.getCurrentToolSession().getPlacementId(), false)); } } else { // extends News tool EventTrackingService.post(EventTrackingService.newEvent((String) state.getAttribute(FEED_ACCESS), "/news/site/" + SiteService.getSite(ToolManager.getCurrentPlacement().getContext()).getId() + "/placement/" + SessionManager.getCurrentToolSession().getPlacementId(), false)); } } catch (IdUnusedException e) { //should NEVER actually happen if (Log.getLogger("chef").isDebugEnabled()) { Log.debug("chef", "failed to log news access event due to invalid siteId"); } } return (String) getContext(rundata).get("template") + "-Layout"; }
From source file:org.wso2.carbon.connector.integration.test.amazonsns.AmazonSNSAuthConnector.java
/** * Connect method which is generating authentication of the connector for each request. * * @throws UnsupportedEncodingException/*from w ww .ja v a 2 s . c o m*/ * @throws IllegalStateException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws JSONException */ public final Map<String, String> getRequestPayload(final JSONObject signatureRequestObject) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, UnsupportedEncodingException, JSONException { final StringBuilder canonicalRequest = new StringBuilder(); final StringBuilder stringToSign = new StringBuilder(); final StringBuilder payloadBuilder = new StringBuilder(); final StringBuilder payloadStrBuilder = new StringBuilder(); final StringBuilder authHeader = new StringBuilder(); init(signatureRequestObject); // Generate time-stamp which will be sent to API and to be used in Signature final Date date = new Date(); final TimeZone timeZone = TimeZone.getTimeZone(AmazonSNSConstants.GMT); final DateFormat dateFormat = new SimpleDateFormat(AmazonSNSConstants.ISO8601_BASIC_DATE_FORMAT); dateFormat.setTimeZone(timeZone); final String amzDate = dateFormat.format(date); final DateFormat shortDateFormat = new SimpleDateFormat(AmazonSNSConstants.SHORT_DATE_FORMAT); shortDateFormat.setTimeZone(timeZone); final String shortDate = shortDateFormat.format(date); signatureRequestObject.put(AmazonSNSConstants.AMZ_DATE, amzDate); final Map<String, String> parameterNamesMap = getParameterNamesMap(); final Map<String, String> parametersMap = getSortedParametersMap(signatureRequestObject, parameterNamesMap); canonicalRequest.append(signatureRequestObject.get(AmazonSNSConstants.HTTP_METHOD)); canonicalRequest.append(AmazonSNSConstants.NEW_LINE); canonicalRequest.append(AmazonSNSConstants.FORWARD_SLASH); canonicalRequest.append(AmazonSNSConstants.NEW_LINE); final String charSet = Charset.defaultCharset().toString(); final Set<String> keySet = parametersMap.keySet(); for (String key : keySet) { payloadBuilder.append(URLEncoder.encode(key, charSet)); payloadBuilder.append(AmazonSNSConstants.EQUAL); payloadBuilder.append(URLEncoder.encode(parametersMap.get(key), charSet)); payloadBuilder.append(AmazonSNSConstants.AMPERSAND); payloadStrBuilder.append(AmazonSNSConstants.QUOTE); payloadStrBuilder.append(key); payloadStrBuilder.append(AmazonSNSConstants.QUOTE); payloadStrBuilder.append(AmazonSNSConstants.COLON); payloadStrBuilder.append(AmazonSNSConstants.QUOTE); payloadStrBuilder.append(parametersMap.get(key)); payloadStrBuilder.append(AmazonSNSConstants.QUOTE); payloadStrBuilder.append(AmazonSNSConstants.COMMA); } // Adds authorization header to message context, removes additionally appended comma at the end if (payloadStrBuilder.length() > 0) { signatureRequestObject.put(AmazonSNSConstants.REQUEST_PAYLOAD, payloadStrBuilder.substring(0, payloadStrBuilder.length() - 1)); } // Appends empty string since no URL parameters are used in POST API requests canonicalRequest.append(""); canonicalRequest.append(AmazonSNSConstants.NEW_LINE); final Map<String, String> headersMap = getSortedHeadersMap(signatureRequestObject, parameterNamesMap); final StringBuilder canonicalHeaders = new StringBuilder(); final StringBuilder signedHeader = new StringBuilder(); for (Entry<String, String> entry : headersMap.entrySet()) { canonicalHeaders.append(entry.getKey()); canonicalHeaders.append(AmazonSNSConstants.COLON); canonicalHeaders.append(entry.getValue()); canonicalHeaders.append(AmazonSNSConstants.NEW_LINE); signedHeader.append(entry.getKey()); signedHeader.append(AmazonSNSConstants.SEMI_COLON); } canonicalRequest.append(canonicalHeaders.toString()); canonicalRequest.append(AmazonSNSConstants.NEW_LINE); // Remove unwanted semi-colon at the end of the signedHeader string String signedHeaders = ""; if (signedHeader.length() > 0) { signedHeaders = signedHeader.substring(0, signedHeader.length() - 1); } canonicalRequest.append(signedHeaders); canonicalRequest.append(AmazonSNSConstants.NEW_LINE); // HashedPayload = HexEncode(Hash(requestPayload)) String requestPayload = ""; if (payloadBuilder.length() > 0) { /* * First removes the additional ampersand appended to the end of the payloadBuilder, then o further * modifications to preserve unreserved characters as per the API guide * (http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html) */ requestPayload = payloadBuilder.substring(0, payloadBuilder.length() - 1) .replace(AmazonSNSConstants.PLUS, AmazonSNSConstants.URL_ENCODED_PLUS) .replace(AmazonSNSConstants.URL_ENCODED_TILT, AmazonSNSConstants.TILT) .replace(AmazonSNSConstants.ASTERISK, AmazonSNSConstants.URL_ENCODED_ASTERISK); } canonicalRequest.append(bytesToHex(hash(requestPayload)).toLowerCase()); stringToSign.append(AmazonSNSConstants.AWS4_HMAC_SHA_256); stringToSign.append(AmazonSNSConstants.NEW_LINE); stringToSign.append(amzDate); stringToSign.append(AmazonSNSConstants.NEW_LINE); stringToSign.append(shortDate); stringToSign.append(AmazonSNSConstants.FORWARD_SLASH); stringToSign.append(signatureRequestObject.get(AmazonSNSConstants.REGION)); stringToSign.append(AmazonSNSConstants.FORWARD_SLASH); stringToSign.append(signatureRequestObject.get(AmazonSNSConstants.SERVICE)); stringToSign.append(AmazonSNSConstants.FORWARD_SLASH); stringToSign.append(signatureRequestObject.get(AmazonSNSConstants.TERMINATION_STRING)); stringToSign.append(AmazonSNSConstants.NEW_LINE); stringToSign.append(bytesToHex(hash(canonicalRequest.toString())).toLowerCase()); final byte[] signingKey = getSignatureKey(signatureRequestObject, signatureRequestObject.get(AmazonSNSConstants.SECRET_ACCESS_KEY).toString(), shortDate, signatureRequestObject.get(AmazonSNSConstants.REGION).toString(), signatureRequestObject.get(AmazonSNSConstants.SERVICE).toString()); // Construction of authorization header value to be in cluded in API request authHeader.append(AmazonSNSConstants.AWS4_HMAC_SHA_256); authHeader.append(AmazonSNSConstants.COMMA); authHeader.append(AmazonSNSConstants.CREDENTIAL); authHeader.append(AmazonSNSConstants.EQUAL); authHeader.append(signatureRequestObject.get(AmazonSNSConstants.ACCESS_KEY_ID)); authHeader.append(AmazonSNSConstants.FORWARD_SLASH); authHeader.append(shortDate); authHeader.append(AmazonSNSConstants.FORWARD_SLASH); authHeader.append(signatureRequestObject.get(AmazonSNSConstants.REGION)); authHeader.append(AmazonSNSConstants.FORWARD_SLASH); authHeader.append(signatureRequestObject.get(AmazonSNSConstants.SERVICE)); authHeader.append(AmazonSNSConstants.FORWARD_SLASH); authHeader.append(signatureRequestObject.get(AmazonSNSConstants.TERMINATION_STRING)); authHeader.append(AmazonSNSConstants.COMMA); authHeader.append(AmazonSNSConstants.SIGNED_HEADERS); authHeader.append(AmazonSNSConstants.EQUAL); authHeader.append(signedHeaders); authHeader.append(AmazonSNSConstants.COMMA); authHeader.append(AmazonSNSConstants.API_SIGNATURE); authHeader.append(AmazonSNSConstants.EQUAL); authHeader.append(bytesToHex(hmacSHA256(signingKey, stringToSign.toString())).toLowerCase()); // Adds authorization header to message context signatureRequestObject.put(AmazonSNSConstants.AUTHORIZATION_HEADER, authHeader.toString()); Map<String, String> responseMap = new HashMap<String, String>(); responseMap.put(AmazonSNSConstants.AUTHORIZATION_HEADER, authHeader.toString()); responseMap.put(AmazonSNSConstants.AMZ_DATE, amzDate); responseMap.put(AmazonSNSConstants.REQUEST_PAYLOAD, requestPayload); return responseMap; }
From source file:at.alladin.rmbt.controlServer.HistoryResource.java
@Post("json") public String request(final String entity) { long startTime = System.currentTimeMillis(); addAllowOrigin();// w ww . j av a2 s . c o m JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY"), clientIpRaw)); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } else lang = settings.getString("RMBT_DEFAULT_LANGUAGE"); // System.out.println(request.toString(4)); if (conn != null) { final Client client = new Client(conn); if (request.optString("uuid").length() > 0 && client.getClientByUuid(UUID.fromString(request.getString("uuid"))) > 0) { final Locale locale = new Locale(lang); final Format format = new SignificantFormat(2, locale); String limitRequest = ""; if (request.optInt("result_limit", 0) != 0) { final int limit = request.getInt("result_limit"); //get offset string if there is one String offsetString = ""; if ((request.optInt("result_offset", 0) != 0) && (request.getInt("result_offset") >= 0)) { offsetString = " OFFSET " + request.getInt("result_offset"); } limitRequest = " LIMIT " + limit + offsetString; } final ArrayList<String> deviceValues = new ArrayList<>(); String deviceRequest = ""; if (request.optJSONArray("devices") != null) { final JSONArray devices = request.getJSONArray("devices"); boolean checkUnknown = false; final StringBuffer sb = new StringBuffer(); for (int i = 0; i < devices.length(); i++) { final String device = devices.getString(i); if (device.equals("Unknown Device")) checkUnknown = true; else { if (sb.length() > 0) sb.append(','); deviceValues.add(device); sb.append('?'); } } if (sb.length() > 0) deviceRequest = " AND (COALESCE(adm.fullname, t.model) IN (" + sb.toString() + ")" + (checkUnknown ? " OR model IS NULL OR model = ''" : "") + ")"; // System.out.println(deviceRequest); } final ArrayList<String> filterValues = new ArrayList<>(); String networksRequest = ""; if (request.optJSONArray("networks") != null) { final JSONArray tmpArray = request.getJSONArray("networks"); final StringBuilder tmpString = new StringBuilder(); if (tmpArray.length() >= 1) { tmpString.append("AND nt.group_name IN ("); boolean first = true; for (int i = 0; i < tmpArray.length(); i++) { if (first) first = false; else tmpString.append(','); tmpString.append('?'); filterValues.add(tmpArray.getString(i)); } tmpString.append(')'); } networksRequest = tmpString.toString(); } final JSONArray historyList = new JSONArray(); final PreparedStatement st; try { if (client.getSync_group_id() == 0) { //use faster request ignoring sync-group as user is not synced (id=0) st = conn.prepareStatement(String.format( "SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND client_id = ?" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } else { //use slower request including sync-group if client is synced st = conn.prepareStatement(String.format("SELECT DISTINCT" + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name," + " COALESCE(adm.fullname, t.model) model" + " FROM test t" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN network_type nt ON t.network_type=nt.uid" + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'" + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))" + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest, limitRequest)); } int i = 1; st.setLong(i++, client.getUid()); if (client.getSync_group_id() != 0) st.setInt(i++, client.getSync_group_id()); for (final String value : deviceValues) st.setString(i++, value); for (final String filterValue : filterValues) st.setString(i++, filterValue); //System.out.println(st.toString()); final ResultSet rs = st.executeQuery(); while (rs.next()) { final JSONObject jsonItem = new JSONObject(); jsonItem.put("test_uuid", rs.getString("uuid")); final Date date = rs.getTimestamp("time"); final long time = date.getTime(); final String tzString = rs.getString("timezone"); final TimeZone tz = TimeZone.getTimeZone(tzString); jsonItem.put("time", time); jsonItem.put("timezone", tzString); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); dateFormat.setTimeZone(tz); jsonItem.put("time_string", dateFormat.format(date)); jsonItem.put("speed_upload", format.format(rs.getInt("speed_upload") / 1000d)); jsonItem.put("speed_download", format.format(rs.getInt("speed_download") / 1000d)); final long ping = rs.getLong("ping_median"); jsonItem.put("ping", format.format(ping / 1000000d)); // backwards compatibility for old clients jsonItem.put("ping_shortest", format.format(ping / 1000000d)); jsonItem.put("model", rs.getString("model")); jsonItem.put("network_type", rs.getString("network_type_group_name")); //for appscape-iPhone-Version: also add classification to the response jsonItem.put("speed_upload_classification", Classification .classify(classification.THRESHOLD_UPLOAD, rs.getInt("speed_upload"))); jsonItem.put("speed_download_classification", Classification .classify(classification.THRESHOLD_DOWNLOAD, rs.getInt("speed_download"))); jsonItem.put("ping_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); // backwards compatibility for old clients jsonItem.put("ping_shortest_classification", Classification .classify(classification.THRESHOLD_PING, rs.getLong("ping_median"))); historyList.put(jsonItem); } if (historyList.length() == 0) errorList.addError("ERROR_DB_GET_HISTORY"); // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); rs.close(); st.close(); } catch (final SQLException e) { e.printStackTrace(); errorList.addError("ERROR_DB_GET_HISTORY_SQL"); // errorList.addError("ERROR_DB_GET_CLIENT_SQL"); } answer.put("history", historyList); } else errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } catch (final IllegalArgumentException e) { errorList.addError("ERROR_REQUEST_NO_UUID"); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY_SUCCESS"), clientIpRaw, Long.toString(elapsedTime))); return answerString; }
From source file:com.squid.kraken.v4.api.core.ServiceUtils.java
/** * Convert Date to ISO 8601 String.//from w w w. j a v a 2 s . c o m * * @param date * @return */ @Deprecated public String toISO8601(Date date) { DateFormat df = new SimpleDateFormat(ISO8601); df.setTimeZone(TimeZone.getTimeZone("UTC")); String formatted = df.format(date); return formatted; }
From source file:org.sakaiproject.poll.tool.producers.PollToolProducer.java
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { voteBean.setPoll(null);// w w w . j av a 2 s. c om voteBean.voteCollection = null; String locale = localegetter.get().toString(); Map<String, String> langMap = new HashMap<String, String>(); langMap.put("lang", locale); langMap.put("xml:lang", locale); UIOutput.make(tofill, "polls-html", null).decorate(new UIFreeAttributeDecorator(langMap)); UIOutput.make(tofill, "poll-list-title", messageLocator.getMessage("poll_list_title")); boolean renderDelete = false; //populate the action links if (this.isAllowedPollAdd() || this.isSiteOwner()) { UIBranchContainer actions = UIBranchContainer.make(tofill, "actions:", Integer.toString(0)); LOG.debug("this user has some admin functions"); if (this.isAllowedPollAdd()) { LOG.debug("User can add polls"); //UIOutput.make(tofill, "poll-add", messageLocator // .getMessage("action_add_poll")); UIInternalLink.make(actions, NAVIGATE_ADD, UIMessage.make("action_add_poll"), new PollViewParameters(AddPollProducer.VIEW_ID, "New 0")); } if (this.isSiteOwner()) { UIInternalLink.make(actions, NAVIGATE_PERMISSIONS, UIMessage.make("action_set_permissions"), new SimpleViewParameters(PermissionsProducer.VIEW_ID)); } } List<Poll> polls = new ArrayList<Poll>(); String siteId = externalLogic.getCurrentLocationId(); if (siteId != null) { polls = pollListManager.findAllPolls(siteId); } else { LOG.warn("Unable to get siteid!"); } if (polls.isEmpty()) { UIOutput.make(tofill, "no-polls", messageLocator.getMessage("poll_list_empty")); UIOutput.make(tofill, "add-poll-icon"); if (this.isAllowedPollAdd()) { UIInternalLink.make(tofill, "add-poll", UIMessage.make("new_poll_title"), new PollViewParameters(AddPollProducer.VIEW_ID, "New 0")); } } else { // fix for broken en_ZA locale in JRE http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488119 Locale M_locale = null; String langLoc[] = localegetter.get().toString().split("_"); if (langLoc.length >= 2) { if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) M_locale = new Locale("en", "GB"); else M_locale = new Locale(langLoc[0], langLoc[1]); } else { M_locale = new Locale(langLoc[0]); } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale); TimeZone tz = externalLogic.getLocalTimeZone(); df.setTimeZone(tz); //m_log.debug("got timezone: " + tz.getDisplayName()); UIOutput.make(tofill, "poll_list_remove_confirm", messageLocator.getMessage("poll_list_remove_confirm")); UIOutput.make(tofill, "poll_list_reset_confirm", messageLocator.getMessage("poll_list_reset_confirm")); UIForm deleteForm = UIForm.make(tofill, "delete-poll-form"); // Create a multiple selection control for the tasks to be deleted. // We will fill in the options at the loop end once we have collected them. UISelect deleteselect = UISelect.makeMultiple(deleteForm, "delete-poll", null, "#{pollToolBean.deleteids}", new String[] {}); //get the headers for the table /*UIMessage.make(deleteForm, "poll-question-title","poll_question_title"); UIMessage.make(deleteForm, "poll-open-title", "poll_open_title"); UIMessage.make(deleteForm, "poll-close-title", "poll_close_title");*/ UIMessage.make(deleteForm, "poll-result-title", "poll_result_title"); UIMessage.make(deleteForm, "poll-remove-title", "poll_remove_title"); UILink question = UILink.make(tofill, "poll-question-title", messageLocator.getMessage("poll_question_title"), "#"); question.decorators = new DecoratorList( new UITooltipDecorator(messageLocator.getMessage("poll_question_title_tooltip"))); UILink open = UILink.make(tofill, "poll-open-title", messageLocator.getMessage("poll_open_title"), "#"); open.decorators = new DecoratorList( new UITooltipDecorator(messageLocator.getMessage("poll_open_title_tooltip"))); UILink close = UILink.make(tofill, "poll-close-title", messageLocator.getMessage("poll_close_title"), "#"); close.decorators = new DecoratorList( new UITooltipDecorator(messageLocator.getMessage("poll_close_title_tooltip"))); StringList deletable = new StringList(); for (int i = 0; i < polls.size(); i++) { Poll poll = (Poll) polls.get(i); boolean canVote = pollVoteManager.pollIsVotable(poll); UIBranchContainer pollrow = UIBranchContainer.make(deleteForm, canVote ? "poll-row:votable" : "poll-row:nonvotable", poll.getPollId().toString()); LOG.debug("adding poll row for " + poll.getText()); if (canVote) { UIInternalLink voteLink = UIInternalLink.make(pollrow, NAVIGATE_VOTE, poll.getText(), new PollViewParameters(PollVoteProducer.VIEW_ID, poll.getPollId().toString())); //we need to add a decorator for the alt text voteLink.decorators = new DecoratorList(new UITooltipDecorator( messageLocator.getMessage("poll_vote_title") + ":" + poll.getText())); } else { //the poll is lazily loaded so get the options poll.setOptions(pollListManager.getOptionsForPoll(poll.getPollId())); //is this not votable because of no options? if (poll.getPollOptions().size() == 0) UIOutput.make(pollrow, "poll-text", poll.getText() + " (" + messageLocator.getMessage("poll_no_options") + ")"); else UIOutput.make(pollrow, "poll-text", poll.getText()); } if (pollListManager.isAllowedViewResults(poll, externalLogic.getCurrentUserId())) { UIInternalLink resultsLink = UIInternalLink.make(pollrow, "poll-results", messageLocator.getMessage("action_view_results"), new PollViewParameters(ResultsProducer.VIEW_ID, poll.getPollId().toString())); resultsLink.decorators = new DecoratorList(new UITooltipDecorator( messageLocator.getMessage("action_view_results") + ":" + poll.getText())); } if (poll.getVoteOpen() != null) UIOutput.make(pollrow, "poll-open-date", df.format(poll.getVoteOpen())).decorators = new DecoratorList( new UIFreeAttributeDecorator("name", "realDate:" + poll.getVoteOpen().toString())); else UIVerbatim.make(pollrow, "poll-open-date", " "); if (poll.getVoteClose() != null) UIOutput.make(pollrow, "poll-close-date", df.format(poll.getVoteClose())).decorators = new DecoratorList( new UIFreeAttributeDecorator("name", "realDate:" + poll.getVoteClose().toString())); else UIVerbatim.make(pollrow, "poll-close-date", " "); if (pollCanEdit(poll)) { UIInternalLink editLink = UIInternalLink.make(pollrow, "poll-revise", messageLocator.getMessage("action_revise_poll"), new PollViewParameters(AddPollProducer.VIEW_ID, poll.getPollId().toString())); editLink.decorators = new DecoratorList(new UITooltipDecorator( messageLocator.getMessage("action_revise_poll") + ":" + poll.getText())); } if (pollCanDelete(poll)) { deletable.add(poll.getPollId().toString()); UISelectChoice delete = UISelectChoice.make(pollrow, "poll-select", deleteselect.getFullID(), (deletable.size() - 1)); delete.decorators = new DecoratorList(new UITooltipDecorator( UIMessage.make("delete_poll_tooltip", new String[] { poll.getText() }))); UIMessage message = UIMessage.make(pollrow, "delete-label", "delete_poll_tooltip", new String[] { poll.getText() }); UILabelTargetDecorator.targetLabel(message, delete); LOG.debug("this poll can be deleted"); renderDelete = true; } } deleteselect.optionlist.setValue(deletable.toStringArray()); deleteForm.parameters.add(new UIELBinding("#{pollToolBean.siteID}", siteId)); if (renderDelete) UICommand.make(deleteForm, "delete-polls", UIMessage.make("poll_list_delete"), "#{pollToolBean.processActionDelete}").decorators = new DecoratorList( new UITooltipDecorator(messageLocator.getMessage("poll_list_delete_tooltip"))); UICommand.make(deleteForm, "reset-polls-votes", UIMessage.make("poll_list_reset"), "#{pollToolBean.processActionResetVotes}").decorators = new DecoratorList( new UITooltipDecorator(messageLocator.getMessage("poll_list_reset_tooltip"))); } }
From source file:org.apereo.openlrs.storage.elasticsearch.XApiOnlyElasticsearchTierTwoStorage.java
@Override public Page<OpenLRSEntity> findWithFilters(Map<String, String> filters, Pageable pageable) { String actor = filters.get(StatementUtils.ACTOR_FILTER); String activity = filters.get(StatementUtils.ACTIVITY_FILTER); String since = filters.get(StatementUtils.SINCE_FILTER); String until = filters.get(StatementUtils.UNTIL_FILTER); int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER)); ;/*from ww w. ja v a 2 s . c om*/ XApiActor xApiActor = null; if (StringUtils.isNotBlank(actor)) { ObjectMapper objectMapper = new ObjectMapper(); try { xApiActor = objectMapper.readValue(actor.getBytes(), XApiActor.class); } catch (Exception e) { log.error(e.getMessage(), e); } } SearchQuery searchQuery = null; if (StringUtils.isNotBlank(activity) && xApiActor != null) { QueryBuilder actorQuery = buildActorQuery(xApiActor); QueryBuilder activityQuery = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); BoolQueryBuilder boolQuery = boolQuery().must(actorQuery).must(activityQuery); searchQuery = startQuery(limit, boolQuery).build(); } else if (xApiActor != null) { QueryBuilder query = buildActorQuery(xApiActor); if (query != null) { searchQuery = startQuery(limit, query).build(); } } else if (StringUtils.isNotBlank(activity)) { QueryBuilder query = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); searchQuery = startQuery(limit, query).build(); } else if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) { QueryBuilder query = null; if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) { query = new RangeQueryBuilder("stored").from(since).to(until); } else { if (StringUtils.isNotBlank(since)) { query = new RangeQueryBuilder("stored").from(since).to("now"); } if (StringUtils.isNotBlank(until)) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone tz = TimeZone.getTimeZone("UTC"); formatter.setTimeZone(tz); Date date = (Date) formatter.parse(until); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, -1); query = new RangeQueryBuilder("stored").from(formatter.format(calendar.getTime())) .to(until); } catch (ParseException e) { log.error(e.getMessage(), e); return null; } } } NativeSearchQueryBuilder searchQueryBuilder = startQuery(limit, query); searchQuery = searchQueryBuilder.withSort(new FieldSortBuilder("stored").order(SortOrder.DESC)).build(); } else if (limit > 0) { searchQuery = startQuery(limit, null).build(); } if (searchQuery != null) { if (log.isDebugEnabled()) { if (searchQuery.getQuery() != null) { log.debug(String.format("Elasticsearch query %s", searchQuery.getQuery().toString())); } } Iterable<Statement> iterableStatements = esSpringDataRepository.search(searchQuery); if (iterableStatements != null) { return new PageImpl<OpenLRSEntity>(IteratorUtils.toList(iterableStatements.iterator())); } } return null; }
From source file:com.intuit.wasabi.tests.service.IntegrationPages.java
/** * Returns date n days later in UTC timezone as string * * @return string// w w w .j a v a 2 s.c o m */ private String getDatePlusDays(int days) { DateTime dt = new DateTime(); dt = dt.plusDays(days); final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(dt.toDate()); }
From source file:com.squid.kraken.v4.api.core.ServiceUtils.java
/** * Convert ISO 8601 (javascript) string to Date. */// w w w .j a v a2 s . c o m public Date toDate(String iso8601string) throws ParseException { if (iso8601string == null) { return null; } DateFormat df = new SimpleDateFormat(ISO8601); df.setTimeZone(TimeZone.getTimeZone("UTC")); // fix for javascript toISOString int z = iso8601string.indexOf('Z'); if (z > 0) { iso8601string = iso8601string.substring(0, z) + "+0000"; } try { Date date = df.parse(iso8601string); return date; } catch (ParseException e) { // try the short version DateFormat dfshort = new SimpleDateFormat(ISO8601short); dfshort.setTimeZone(TimeZone.getTimeZone("UTC")); try { return dfshort.parse(iso8601string); } catch (ParseException ee) { DateFormat lastChance = new SimpleDateFormat(JavaDateToStringFormat); lastChance.setTimeZone(TimeZone.getTimeZone("UTC")); return lastChance.parse(iso8601string); } } }
From source file:com.ebay.pulsar.analytics.resources.PulsarQueryResource.java
@POST @Path("yesterday") @Consumes(MediaType.APPLICATION_JSON)//from w w w . ja va2 s. c o m @Produces(MediaType.APPLICATION_JSON) public Response yesterday(@Context HttpServletRequest request, CoreRequest req) { if (logger.isDebugEnabled()) { logger.debug("Yesterday API called from IP: " + request.getRemoteAddr()); } req.setNamespace(RequestNameSpace.yesterday); req.setGranularity("fifteen_minute"); Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getTimeZone("MST")); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); Date end = new Date(c.getTimeInMillis()); c.add(Calendar.DATE, -1); Date start = new Date(c.getTimeInMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("MST")); req.setStartTime(dateFormat.format(start)); req.setEndTime(dateFormat.format(end)); boolean trace = request.getParameter("debug") == null ? false : true; return processRequest(req, trace); }