List of usage examples for org.joda.time.format DateTimeFormat forPattern
public static DateTimeFormatter forPattern(String pattern)
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 {// w ww.j a v a2s .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.esofthead.mycollab.shell.view.SetupNewInstanceView.java
License:Open Source License
private boolean isValidDayPattern(String dateFormat) { try {// w w w. ja va2 s . c o m DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat); formatter.print(new DateTime()); return true; } catch (Exception e) { return false; } }
From source file:com.esofthead.mycollab.vaadin.AppContext.java
License:Open Source License
/** * @param date is the UTC date value/*from w ww . jav a2 s .c o m*/ * @return */ public static String formatDateTime(Date date) { // return date == null ? "" : DateTimeUtils.formatDate(date, AppContext.getDateTimeFormat(), AppContext.getUserTimeZone()); if (date == null) { return ""; } else { DateTime jodaDate = new DateTime(date) .toDateTime(DateTimeZone.forTimeZone(AppContext.getUserTimeZone())); if (jodaDate.getHourOfDay() > 0 || jodaDate.getMinuteOfHour() > 0) { DateTimeFormatter formatter = DateTimeFormat.forPattern(AppContext.getDateTimeFormat()); return formatter.print(jodaDate); } else { DateTimeFormatter formatter = DateTimeFormat.forPattern(AppContext.getDateFormat()); return formatter.print(jodaDate); } } }
From source file:com.esofthead.mycollab.vaadin.web.ui.field.DateFormatField.java
License:Open Source License
public DateFormatField(final String initialFormat) { this.dateFormat = initialFormat; dateInput = new TextField(null, initialFormat); dateInput.setImmediate(true);/*from ww w.j a v a 2s. c o m*/ dateInput.setTextChangeEventMode(AbstractTextField.TextChangeEventMode.EAGER); now = new DateTime(); dateExample = new Label(); dateFormatInstance = DateTimeFormat.forPattern(dateFormat); dateExample.setValue("(" + dateFormatInstance.print(now) + ")"); dateExample.setWidthUndefined(); dateInput.addTextChangeListener(new FieldEvents.TextChangeListener() { @Override public void textChange(FieldEvents.TextChangeEvent event) { try { String newFormat = event.getText(); dateFormatInstance = DateTimeFormat.forPattern(newFormat); dateExample.setValue("(" + dateFormatInstance.print(now) + ")"); } catch (Exception e) { NotificationUtil.showErrorNotification("Invalid format"); dateInput.setValue(initialFormat); dateFormatInstance = DateTimeFormat.forPattern(initialFormat); dateExample.setValue("(" + dateFormatInstance.print(now) + ")"); } } }); }
From source file:com.esri.geoevent.clusterSimulator.simulator.DateTimeParser.java
License:Apache License
public static long parseTime(String timeString) { if (timeString == null) return 0; try {//from www. j a va 2 s . c om DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser().withZoneUTC(); return formatter.parseMillis(timeString); } catch (IllegalArgumentException e) { } try { return DateFormat.getDateInstance().parse(timeString).getTime(); } catch (ParseException | NumberFormatException e) { } try { DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yy hh:mm:ss aa"); return formatter.parseMillis(timeString); } catch (IllegalArgumentException e) { } try { DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yy HH:mm:ss"); return formatter.parseMillis(timeString); } catch (IllegalArgumentException e) { } return 0; }
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); }//from w w w . jav a 2 s .c o m 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.example.ashwin.popularmovies.FetchMovieTask.java
License:Apache License
protected Void doInBackground(String... params) { if (params.length == 0) { return null; }//ww w.j av a 2s . c o m // needs to be outside try catch to use in finally HttpURLConnection urlConnection = null; BufferedReader reader = null; // will contain the raw JSON response as a string String movieJsonStr = null; try { // http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=**REMOVED** Uri.Builder builder = new Uri.Builder(); builder.scheme("http").authority("api.themoviedb.org").appendPath("3").appendPath("discover") .appendPath("movie"); if (params[0].equals(mContext.getString(R.string.pref_sort_label_upcoming))) { // so here we need to get today's date and 3 weeks from now DateTime todayDt = new DateTime(); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); String todayDateString = fmt.print(todayDt); builder.appendQueryParameter("primary_release_date.gte", todayDateString); // 3 weeks from now DateTime dtPlusTwoWeeks = todayDt.plusWeeks(3); String twoWeeksLaterDate = fmt.print(dtPlusTwoWeeks); builder.appendQueryParameter("primary_release_date.lte", twoWeeksLaterDate); } else { builder.appendQueryParameter("sort_by", params[0]); // here we need to get a minimum vote count, value is set to 200 minimum votes if (params[0].equals(mContext.getString(R.string.pref_sort_user_rating))) builder.appendQueryParameter("vote_count.gte", "200"); } builder.appendQueryParameter("api_key", mContext.getString(R.string.tmdb_api_key)); String website = builder.build().toString(); URL url = new URL(website); // Create the request to themoviedb and open connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // nothing to do return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // doesn't affect JSON but it's a lot easier for a human to read buffer.append(line + "\n"); } if (buffer.length() == 0) { // empty stream return null; } movieJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { getMovieDataFromJsonDb(movieJsonStr); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.example.Database.java
public String getDate(int daysago) { DateTime date = new DateTime(); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); date = date.minusDays(daysago);// w ww .j a v a 2 s.c om return fmt.print(date); }
From source file:com.example.getstarted.util.CloudStorageHelper.java
License:Apache License
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. *///from ww w. j av a 2 s. c om public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create(BlobInfo.newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(), fileStream.openStream()); logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[] { fileStream.getName(), fileName }); // return the public download link return blobInfo.getMediaLink(); }
From source file:com.example.managedvms.gettingstartedjava.util.CloudStorageHelper.java
License:Open Source License
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. *//*w w w . j av a 2 s .c o m*/ public String uploadFile(Part filePart, final String bucketName) throws IOException { DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = filePart.getSubmittedFileName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create(BlobInfo.builder(bucketName, fileName) // Modify access list to allow all users with link to read file .acl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(), filePart.getInputStream()); logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[] { filePart.getSubmittedFileName(), fileName }); // return the public download link return blobInfo.mediaLink(); }