List of usage examples for java.text DateFormat parse
public Date parse(String source) throws ParseException
From source file:acromusashi.kafka.log.producer.util.StrftimeFormatMapper.java
/** * ??STRFTime??STRFTime??????// www .j av a 2s . c o m * * @param timeStr STRFTime?? * @param strfFormatStr STRFTime * @param outputFormatStr * @return ?? * @throws ParseException */ public static String convertStftToDateStr(String timeStr, String strfFormatStr, String outputFormatStr) throws ParseException { DateFormat strfFormat; // STRFTime????????Apache?? if (StringUtils.isEmpty(strfFormatStr) == true) { strfFormat = new SimpleDateFormat(DEFAULT_STRFTIME, Locale.ENGLISH); } else { // STRFTime?DateFormat??? strfFormat = StrftimeFormatMapper.convertStftToDateFormat(strfFormatStr); } // STRFTime???DateFormat??Date??? Date logDate = strfFormat.parse(timeStr); // ????? DateFormat outputDateFormat = new SimpleDateFormat(outputFormatStr); String returnDate = outputDateFormat.format(logDate); return returnDate; }
From source file:controllers.core.TimesheetController.java
/** * Get the timesheet report of an actor for a given string date. * //w w w. j a v a 2 s .co m * if the string date is empty: the start date corresponds to the first day * (monday) of the current week<br/> * else: the start date corresponds to the first day (monday) of the week * including the given date * * Note: if the report doesn't exist, the system creates it. * * @param stringDate * a date in the format yyyy-MM-dd: the system gets the weekly * report including this date, if empty it uses the current date. * @param actor * the actor of the timesheet */ public static TimesheetReport getTimesheetReport(String stringDate, Actor actor) { // get the date: either given as a parameter or the current Date date = null; if (!stringDate.equals("")) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); date = formatter.parse(stringDate); } catch (ParseException e) { log.error(e.getMessage()); return null; } } else { date = new Date(); } // get the first day of the week including the date // we consider the first day as Monday Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.clear(Calendar.MINUTE); cal.clear(Calendar.SECOND); cal.clear(Calendar.MILLISECOND); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date startDate = cal.getTime(); TimesheetReport report = TimesheetDao.getTimesheetReportByActorAndStartDate(actor.id, startDate); if (report == null) { report = new TimesheetReport(); report.actor = actor; report.orgUnit = actor.orgUnit; report.type = TimesheetReport.Type.WEEKLY; report.startDate = startDate; report.status = TimesheetReport.Status.OPEN; report.save(); } return report; }
From source file:com.webbfontaine.valuewebb.model.util.Utils.java
public static Date localeStringToDate(String date) throws ParseException { if (StringUtils.trimToEmpty(date).isEmpty()) { return null; }// www . ja v a2 s.c o m DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, LocaleSelector.instance().getLocale()); return dateFormat.parse(date); }
From source file:io.seldon.importer.articles.FileItemAttributesImporter.java
public static Map<String, String> getAttributes(String url, String existingCategory) { ItemProcessResult itemProcessResult = new ItemProcessResult(); itemProcessResult.client_item_id = url; itemProcessResult.extraction_status = "EXTRACTION_FAILED"; logger.info("Trying to get attributes for " + url); Map<String, String> attributes = null; String title = ""; String category = ""; String subCategory = ""; String img_url = ""; String description = ""; String tags = ""; String leadtext = ""; String link = ""; String publishDate = ""; String domain = ""; try {/* w ww . j a v a2 s .c o m*/ long now = System.currentTimeMillis(); long timeSinceLastRequest = now - lastUrlFetchTime; if (timeSinceLastRequest < minFetchGapMsecs) { long timeToSleep = minFetchGapMsecs - timeSinceLastRequest; logger.info( "Sleeping " + timeToSleep + "msecs as time since last fetch is " + timeSinceLastRequest); Thread.sleep(timeToSleep); } Document articleDoc = Jsoup.connect(url).userAgent("SeldonBot/1.0").timeout(httpGetTimeout).get(); lastUrlFetchTime = System.currentTimeMillis(); //get IMAGE URL if (StringUtils.isNotBlank(imageCssSelector)) { Element imageElement = articleDoc.select(imageCssSelector).first(); if (imageElement != null) { if (imageElement.attr("content") != null) { img_url = imageElement.attr("content"); } if (StringUtils.isBlank(img_url) && imageElement.attr("src") != null) { img_url = imageElement.attr("src"); } if (StringUtils.isBlank(img_url) && imageElement.attr("href") != null) { img_url = imageElement.attr("href"); } } } if (StringUtils.isBlank(img_url) && StringUtils.isNotBlank(defImageUrl)) { logger.info("Setting image to default: " + defImageUrl); img_url = defImageUrl; } img_url = StringUtils.strip(img_url); //get TITLE if (StringUtils.isNotBlank(titleCssSelector)) { Element titleElement = articleDoc.select(titleCssSelector).first(); if (titleElement != null && titleElement.attr("content") != null) { title = titleElement.attr("content"); } } //get Lead Text if (StringUtils.isNotBlank(leadTextCssSelector)) { Element leadElement = articleDoc.select(leadTextCssSelector).first(); if (leadElement != null && leadElement.attr("content") != null) { leadtext = leadElement.attr("content"); } } //get publish date if (StringUtils.isNotBlank(publishDateCssSelector)) { //2013-01-21T10:40:55Z Element pubElement = articleDoc.select(publishDateCssSelector).first(); if (pubElement != null && pubElement.attr("content") != null) { String pubtext = pubElement.attr("content"); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date result = null; try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date withUTC format " + pubtext); } //try a simpler format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date " + pubtext); } if (result != null) publishDate = dateFormatter.format(result); else logger.error("Failed to parse date " + pubtext); } } //get Link if (StringUtils.isNotBlank(linkCssSelector)) { Element linkElement = articleDoc.select(linkCssSelector).first(); if (linkElement != null && linkElement.attr("content") != null) { link = linkElement.attr("content"); } } //get CONTENT if (StringUtils.isNotBlank(textCssSelector)) { Element descriptionElement = articleDoc.select(textCssSelector).first(); if (descriptionElement != null) description = Jsoup.parse(descriptionElement.html()).text(); } //get TAGS Set<String> tagSet = AttributesImporterUtils.getTags(articleDoc, tagsCssSelector, title); if (tagSet.size() > 0) tags = CollectionTools.join(tagSet, ","); //get CATEGORY - client specific if (StringUtils.isNotBlank(categoryCssSelector)) { Element categoryElement = articleDoc.select(categoryCssSelector).first(); if (categoryElement != null && categoryElement.attr("content") != null) { category = categoryElement.attr("content"); if (StringUtils.isNotBlank(category)) category = category.toUpperCase(); } } else if (StringUtils.isNotBlank(categoryClassPrefix)) { String className = "io.seldon.importer.articles.category." + categoryClassPrefix + "CategoryExtractor"; Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(); CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance(); category = extractor.getCategory(url, articleDoc); } //get Sub CATEGORY - client specific if (StringUtils.isNotBlank(subCategoryCssSelector)) { Element subCategoryElement = articleDoc.select(subCategoryCssSelector).first(); if (subCategoryElement != null && subCategoryElement.attr("content") != null) { subCategory = subCategoryElement.attr("content"); if (StringUtils.isNotBlank(subCategory)) subCategory = category.toUpperCase(); } } else if (StringUtils.isNotBlank(subCategoryClassPrefix)) { String className = "io.seldon.importer.articles.category." + subCategoryClassPrefix + "SubCategoryExtractor"; Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(); CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance(); subCategory = extractor.getCategory(url, articleDoc); } // Get domain if (domainIsNeeded) { domain = getDomain(url); } if (StringUtils.isNotBlank(title) && (imageNotNeeded || StringUtils.isNotBlank(img_url)) && (categoryNotNeeded || StringUtils.isNotBlank(category)) && (!domainIsNeeded || StringUtils.isNotBlank(domain))) { attributes = new HashMap<String, String>(); attributes.put(TITLE, title); if (StringUtils.isNotBlank(category)) attributes.put(CATEGORY, category); if (StringUtils.isNotBlank(subCategory)) attributes.put(SUBCATEGORY, subCategory); if (StringUtils.isNotBlank(link)) attributes.put(LINK, link); if (StringUtils.isNotBlank(leadtext)) attributes.put(LEAD_TEXT, leadtext); if (StringUtils.isNotBlank(img_url)) attributes.put(IMG_URL, img_url); if (StringUtils.isNotBlank(tags)) attributes.put(TAGS, tags); attributes.put(CONTENT_TYPE, VERIFIED_CONTENT_TYPE); if (StringUtils.isNotBlank(description)) attributes.put(DESCRIPTION, description); if (StringUtils.isNotBlank(publishDate)) attributes.put(PUBLISH_DATE, publishDate); if (StringUtils.isNotBlank(domain)) attributes.put(DOMAIN, domain); System.out.println("Item: " + url + "; Category: " + category); itemProcessResult.extraction_status = "EXTRACTION_SUCCEEDED"; } else { logger.warn("Failed to get title for article " + url); logger.warn("[title=" + title + ", img_url=" + img_url + ", category=" + category + ", domain=" + domain + "]"); } { // check for failures for the log result if (StringUtils.isBlank(title)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "title"; } if (!imageNotNeeded && StringUtils.isBlank(img_url)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "img_url"; } if (!categoryNotNeeded && StringUtils.isBlank(category)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "category"; } } } catch (Exception e) { logger.warn("Article: " + url + ". Attributes import FAILED", e); itemProcessResult.error = e.toString(); } AttributesImporterUtils.logResult(logger, itemProcessResult); return attributes; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;//from w w w . ja va 2s . c o m NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getUser(String cn) { LDAPUser user = null;/* www . jav a 2 s. c o m*/ NamingEnumeration results = null; DirContext ctx = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:com.att.aro.core.util.Util.java
/** * Parses HTTP date formats. Synchronized because DateFormat objects are not * thread-safe. If defaultForExpired is true and value is an invalid * dateFormat (such as -1 or 0 meaning already expired), the returned Date * will be "beginning of time" Jan 1 1970. * * @param value// w w w .ja va 2s.c o m * @param defaultForExpired * boolean - true/false provide default "beginning of time" Jan 1 * 1970 GMT Date * @return formated Date value else null. */ public static Date readHttpDate(String value, boolean defaultForExpired) { if (value != null) { for (DateFormat dateFormat : dateFormats) { try { return dateFormat.parse(value.trim()); } catch (ParseException e) { // logger.error(e.getMessage()); } } } if (defaultForExpired) { return BEGINNING_OF_TIME; } // logger.warn("Unable to parse HTTP date: " + value); return null; }
From source file:com.hcc.cms.util.PageUtils.java
public static String getFormattedDate(String dateReceivedFromUser) { DateFormat userDateFormat = new SimpleDateFormat("MM/dd/yy"); DateFormat dateFormatNeeded = new SimpleDateFormat("MMMM dd, yyyy"); Date date;//from ww w . j a v a 2s. c o m try { date = userDateFormat.parse(dateReceivedFromUser); String convertedDate = dateFormatNeeded.format(date); return convertedDate; } catch (ParseException e) { log.error("Error while parsing date", e); } return dateReceivedFromUser; }
From source file:controller.InputSanitizer.java
/** * Ueberprueft ob ein Datum day.month.year ein gueltiges datum ergibt * @param day//from w ww . ja v a 2s .c om * @param month * @param year * @return Date.getTime () if valid * else error message */ public static String checkDate(String day, String month, String year) { String result = null; DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy"); Calendar cal = new GregorianCalendar(); Date projectStartDate = null; String projectStart = day + "." + month + "." + year; int monthInt = Integer.parseInt(month) - 1; int dayInt = Integer.parseInt(day); cal.set(Calendar.MONTH, monthInt); int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (dayInt <= maxDay) { try { formatter.setLenient(false); projectStartDate = formatter.parse(projectStart); result = Long.toString(projectStartDate.getTime()); } catch (ParseException e) { result = "Ihre Eingabe ist kein gültiges Datum."; } } else { result = "Ihre Eingabe ist kein gültiges Datum."; } return result; }
From source file:net.sf.webissues.core.WebIssuesTaskDataHandler.java
private static Calendar parseDateAttribute(TaskRepository repository, Issue issue, String attributeName) { Folder folder = issue.getFolder();// w ww.j a va2 s . c o m IssueType type = folder.getType(); Attribute attr = type.getByName(attributeName); if (attr != null && attr.getType().equals(Attribute.AttributeType.DATETIME)) { DateFormat fmt = new SimpleDateFormat( attr.isDateOnly() ? Client.DATEONLY_FORMAT : Client.DATETIME_FORMAT); Date d; try { String val = issue.getAttributeValueByName(attributeName); d = fmt.parse(val); } catch (ParseException e) { return null; } Calendar c = Calendar.getInstance(); c.setTime(d); return c; } return null; }