List of usage examples for org.joda.time.format DateTimeFormatter print
public String print(ReadablePartial partial)
From source file:com.hmsinc.epicenter.velocity.DateTimeFormatTool.java
License:Open Source License
/** * Returns the specified date as a string formatted according to the * specified date and/or time styles.//from w w w .j a va2 s . co m * * @param dateStyle * the style pattern for the date * @param timeStyle * the style pattern for the time * @param obj * the date to be formatted * @return a formatted representation of the given date */ public String format(String dateStyle, String timeStyle, ReadableInstant date) { final String ret; if (date == null) { ret = null; } else { final DateTimeFormatter formatter = getDateTimeStyle(dateStyle, timeStyle, Locale.getDefault(), DateTimeZone.getDefault()); ret = formatter == null ? null : formatter.print(date); } return ret; }
From source file:com.hmsinc.epicenter.velocity.DateTimeFormatTool.java
License:Open Source License
/** * Returns the specified date as a string formatted according to the * specified {@link Locale} and date and/or time styles. * /*from w w w . j a va 2s . c o m*/ * @param dateStyle * the style pattern for the date * @param timeStyle * the style pattern for the time * @param obj * the date to be formatted * @param locale * the {@link Locale} to be used for formatting the date * @return a formatted representation of the given date */ public String format(String dateStyle, String timeStyle, ReadableInstant date, Locale locale) { final String ret; if (date == null) { ret = null; } else { final DateTimeFormatter formatter = getDateTimeStyle(dateStyle, timeStyle, locale, DateTimeZone.getDefault()); ret = formatter == null ? null : formatter.print(date); } return ret; }
From source file:com.hmsinc.epicenter.velocity.DateTimeFormatTool.java
License:Open Source License
/** * Returns the specified date as a string formatted according to the * specified {@link Locale} and date and/or time styles. * //from w w w .j a va 2 s. co m * @param dateStyle * the style pattern for the date * @param timeStyle * the style pattern for the time * @param obj * the date to be formatted * @param locale * the {@link Locale} to be used for formatting the date * @param timezone * the {@link TimeZone} the date should be formatted for * @return a formatted representation of the given date */ public String format(String dateStyle, String timeStyle, ReadableInstant date, Locale locale, DateTimeZone timezone) { final String ret; if (date == null) { ret = null; } else { final DateTimeFormatter formatter = getDateTimeStyle(dateStyle, timeStyle, locale, timezone); ret = formatter == null ? null : formatter.print(date); } return ret; }
From source file:com.hotwire.selenium.bex.BexAbstractPage.java
License:Open Source License
protected String convertToAmPm(DateTime time2Convert) { DateTimeFormatter fmt = DateTimeFormat.forPattern("h:mm aa"); return fmt.print(time2Convert); }
From source file:com.hula.lang.util.DateUtil.java
License:Apache License
/** * Convert a Date into a String/*from w w w . ja va 2 s. c o m*/ * * @param date The date to convert * @param format The format of the Date * @return A string containing the datre */ public static String toString(Date date, String format) { DateTimeFormatter fmt = DateTimeFormat.forPattern(format); return fmt.print(date.getTime()); }
From source file:com.hurence.logisland.processor.elasticsearch.ElasticsearchRecordConverter.java
License:Apache License
/** * Converts an Event into an Elasticsearch document * to be indexed later//from ww w . j ava 2 s. c o m * * @param record * @return */ public static String convertToString(Record record) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String document = ""; // convert event_time as ISO for ES if (record.hasField(FieldDictionary.RECORD_TIME)) { try { DateTimeFormatter dateParser = ISODateTimeFormat.dateTimeNoMillis(); document += "@timestamp : "; document += dateParser.print(record.getField(FieldDictionary.RECORD_TIME).asLong()) + ", "; } catch (Exception ex) { logger.error("unable to parse record_time iso date for {}", record); } } // add all other records for (Iterator<Field> i = record.getAllFieldsSorted().iterator(); i.hasNext();) { Field field = i.next(); String fieldName = field.getName().replaceAll("\\.", "_"); switch (field.getType()) { case STRING: document += fieldName + " : " + field.asString(); break; case INT: document += fieldName + " : " + field.asInteger().toString(); break; case LONG: document += fieldName + " : " + field.asLong().toString(); break; case FLOAT: document += fieldName + " : " + field.asFloat().toString(); break; case DOUBLE: document += fieldName + " : " + field.asDouble().toString(); break; case BOOLEAN: document += fieldName + " : " + field.asBoolean().toString(); break; default: document += fieldName + " : " + field.getRawValue().toString(); break; } } return document; } catch (Throwable ex) { logger.error("unable to convert record : {}, {}", record, ex.toString()); } return null; }
From source file:com.hurence.logisland.service.elasticsearch.ElasticsearchRecordConverter.java
License:Apache License
/** * Converts an Event into an Elasticsearch document * to be indexed later/*from w w w . j av a2 s . co m*/ *e * @param record to convert * @return the json converted record */ static String convertToString(Record record) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); XContentBuilder document = jsonBuilder().startObject(); final float[] geolocation = new float[2]; // convert event_time as ISO for ES if (record.hasField(FieldDictionary.RECORD_TIME)) { try { DateTimeFormatter dateParser = ISODateTimeFormat.dateTimeNoMillis(); document.field("@timestamp", dateParser.print(record.getField(FieldDictionary.RECORD_TIME).asLong())); } catch (Exception ex) { logger.error("unable to parse record_time iso date for {}", record); } } // add all other records record.getAllFieldsSorted().forEach(field -> { try { // cleanup invalid es fields characters like '.' String fieldName = field.getName().replaceAll("\\.", "_"); switch (field.getType()) { case STRING: document.field(fieldName, field.asString()); break; case INT: document.field(fieldName, field.asInteger().intValue()); break; case LONG: document.field(fieldName, field.asLong().longValue()); break; case FLOAT: document.field(fieldName, field.asFloat().floatValue()); if (fieldName.equals("lat") || fieldName.equals("latitude")) geolocation[0] = field.asFloat(); if (fieldName.equals("long") || fieldName.equals("longitude")) geolocation[1] = field.asFloat(); break; case DOUBLE: document.field(fieldName, field.asDouble().doubleValue()); if (fieldName.equals("lat") || fieldName.equals("latitude")) geolocation[0] = field.asFloat(); if (fieldName.equals("long") || fieldName.equals("longitude")) geolocation[1] = field.asFloat(); break; case BOOLEAN: document.field(fieldName, field.asBoolean().booleanValue()); break; default: document.field(fieldName, field.getRawValue()); break; } } catch (Throwable ex) { logger.error("unable to process a field in record : {}, {}", record, ex.toString()); } }); if ((geolocation[0] != 0) && (geolocation[1] != 0)) { GeoPoint point = new GeoPoint(geolocation[0], geolocation[1]); document.latlon("location", geolocation[0], geolocation[1]); } String result = document.endObject().string(); document.flush(); return result; } catch (Throwable ex) { logger.error("unable to convert record : {}, {}", record, ex.toString()); } return null; }
From source file:com.hurence.logisland.util.elasticsearch.ElasticsearchRecordConverter.java
License:Apache License
/** * Converts an Event into an Elasticsearch document * to be indexed later//from w w w. j a v a 2 s . co m * * @param record * @return */ public static String convert(Record record) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); XContentBuilder document = jsonBuilder().startObject(); // convert event_time as ISO for ES if (record.hasField(FieldDictionary.RECORD_TIME)) { try { DateTimeFormatter dateParser = ISODateTimeFormat.dateTimeNoMillis(); document.field("@timestamp", dateParser.print(record.getField(FieldDictionary.RECORD_TIME).asLong())); } catch (Exception ex) { logger.error("unable to parse record_time iso date for {}", record); } } // add all other records record.getAllFieldsSorted().forEach(field -> { try { // cleanup invalid es fields characters like '.' String fieldName = field.getName().replaceAll("\\.", "_"); switch (field.getType()) { case STRING: document.field(fieldName, field.asString()); break; case INT: document.field(fieldName, field.asInteger().intValue()); break; case LONG: document.field(fieldName, field.asLong().longValue()); break; case FLOAT: document.field(fieldName, field.asFloat().floatValue()); break; case DOUBLE: document.field(fieldName, field.asDouble().doubleValue()); break; case BOOLEAN: document.field(fieldName, field.asBoolean().booleanValue()); break; default: document.field(fieldName, field.getRawValue()); break; } } catch (Throwable ex) { logger.error("unable to process a field in record : {}, {}", record, ex.toString()); } }); String result = document.endObject().string(); document.flush(); return result; } catch (Throwable ex) { logger.error("unable to convert record : {}, {}", record, ex.toString()); } return null; }
From source file:com.inbravo.scribe.rest.service.crm.ms.auth.MSOffice365AuthManager.java
License:Open Source License
@Override public final String[] getCRMAuthToken(final ScribeCacheObject cacheObject) throws Exception { String stsEndpoint = null;/* w w w .jav a2 s .c om*/ String urnAddress = null; String userName = null; String password = null; String crmServiceURL = null; String crmServiceProtocal = null; logger.debug("----Inside getCRMAuthToken for agent: " + cacheObject.getScribeMetaObject().getCrmUserId()); /* Check if additonal info is present */ if (cacheObject.getAdditionalInfo() != null) { /* Parse the reponse */ stsEndpoint = cacheObject.getAdditionalInfo().get("STSEnpoint"); urnAddress = cacheObject.getAdditionalInfo().get("URNAddress"); } /* get CRM credentials */ userName = cacheObject.getScribeMetaObject().getCrmUserId(); password = cacheObject.getScribeMetaObject().getCrmPassword(); crmServiceURL = cacheObject.getScribeMetaObject().getCrmServiceURL(); crmServiceProtocal = cacheObject.getScribeMetaObject().getCrmServiceProtocol(); logger.debug("----Inside getCRMAuthToken userName: " + userName + " & password: " + password + " & stsEndpoint: " + stsEndpoint + " & urnAddress: " + urnAddress + " & crmServiceURL: " + crmServiceURL + " & crmServiceProtocal: " + crmServiceProtocal); final URL fileURL = CRMMessageFormatUtils.getFileURL(loginFileName); String msg = null; try { /* Get SAML from login */ if (samlForMSLogin == null) { logger.debug("----Inside getCRMAuthToken reading security template from file"); /* This logic is for reading the file once in lifetime only */ samlForMSLogin = MSCRMMessageFormatUtils.readStringFromFile(fileURL.getPath()); /* Convert for local usage */ msg = samlForMSLogin; } else { logger.debug("----Inside getCRMAuthToken reading security template from memory"); /* Convert for local usage */ msg = samlForMSLogin; } /* This is a trick to avoid error if password contains '$' */ userName = Matcher.quoteReplacement(userName); password = Matcher.quoteReplacement(password); logger.debug("----Inside getCRMAuthToken userName: " + userName + " & password: " + password + " & stsEndpoint: " + stsEndpoint); /* Get DB specific formatter */ final DateTimeFormatter isoDateFormat = DateTimeFormat.forPattern(msOffice365RequestDateFormat); /* Get current time */ final String currentDateTime = isoDateFormat .print(DateTime.now(DateTimeZone.forID((msOffice365RequestTimeZone)))); /* Add 5 minutes expiry time from now */ final String expireDateTime = isoDateFormat.print(DateTime .now(DateTimeZone.forID((msOffice365RequestTimeZone))).plusMinutes(loginExpirationInMinutes)); /* The final customer specific security header */ msg = String.format(msg, UUID.randomUUID().toString(), "ACQA", stsEndpoint, currentDateTime, expireDateTime, userName, password, urnAddress); logger.debug("----Inside getCRMAuthToken, login request: " + msg); /* Send SOAP message */ final String response = sOAPExecutor.getSOAPResponse(stsEndpoint, msg); logger.debug("----Inside getCRMAuthToken, login response: " + response); /* If a valid response */ if (response != null && !response.contains("internalerror")) { /* Extract all the values from response */ final String securityToken0 = MSCRMMessageFormatUtils.getValueFromXML(response, "//*[local-name()='CipherValue']/text()"); final String securityToken1 = MSCRMMessageFormatUtils.getValueFromXML(response, "//*[local-name()='CipherValue']/text()", 1); final String keyIdentifier = MSCRMMessageFormatUtils.getValueFromXML(response, "//*[local-name()='KeyIdentifier']/text()"); logger.debug("----Inside getCRMAuthToken securityToken0: " + securityToken0 + " & securityToken1: " + securityToken1 + " & keyIdentifier: " + keyIdentifier); return new String[] { securityToken0, securityToken1, keyIdentifier }; } else { /* Extract all the values from response */ final String error = MSCRMMessageFormatUtils.getValueFromXML(response, "//*[local-name()='Reason' and namespace-uri()='http://www.w3.org/2003/05/soap-envelope']/*[local-name()='Text' and namespace-uri()='http://www.w3.org/2003/05/soap-envelope']/text()"); throw new ScribeException(ScribeResponseCodes._1012 + " MS Login request failed : " + error); } } catch (final IOException e) { throw new ScribeException( ScribeResponseCodes._1015 + " Not able to connect to office 365 login server: " + stsEndpoint); } }
From source file:com.inbravo.scribe.rest.service.crm.ms.v5.MSCRMOffice365basedServiceManager.java
License:Open Source License
/** * //from w ww . j a v a 2 s . c o m * @param securityTokens * @return */ private final SOAPHeaderBlock[] createCRMOptionsHeaderBlock(final String organizationServiceURL, final String[] securityTokens, final String msCRMOperationType) { /* Get DB specific formatter */ final DateTimeFormatter isoDateFormat = DateTimeFormat.forPattern(msOffice365RequestDateFormat); /* Get current time */ final String currentDateTime = isoDateFormat .print(DateTime.now(DateTimeZone.forID((msOffice365RequestTimeZone)))); /* Add 5 minutes expiry time from now */ final String expireDateTime = isoDateFormat.print(DateTime .now(DateTimeZone.forID((msOffice365RequestTimeZone))).plusMinutes(loginExpirationInMinutes)); /* The final customer specific security header */ final String securityHeader = String.format(MSCRMSchemaConstants.securityHeaderTemplate, securityTokens[2], securityTokens[0], securityTokens[1]); try { /* Create new factory */ final OMFactory factory = OMAbstractFactory.getOMFactory(); /* Create security/addressing headers */ final OMNamespace addressingNS = factory.createOMNamespace(MSCRM_SAML_Constants._ADDRESSING, "a"); final OMNamespace securityNS = factory.createOMNamespace(MSCRM_SAML_Constants._WSSSecurity, "o"); final OMNamespace utitlityNS = factory.createOMNamespace(MSCRM_SAML_Constants._WSSSecurityUtility, "u"); final OMElement timeStamp = factory.createOMElement("Timestamp", utitlityNS); timeStamp.addAttribute("Id", "_0", utitlityNS); /* Add created timestamp information */ final OMElement created = factory.createOMElement("Created", utitlityNS); final OMText createdTime = factory.createOMText(currentDateTime + "Z"); created.addChild(createdTime); /* Add expires timestamp information */ final OMElement expires = factory.createOMElement("Expires", utitlityNS); final OMText expiresTime = factory.createOMText(expireDateTime + "Z"); expires.addChild(expiresTime); timeStamp.addChild(created); timeStamp.addChild(expires); /* Create security header block */ final SOAPHeaderBlock wsseHeader = OMAbstractFactory.getSOAP12Factory() .createSOAPHeaderBlock("Security", securityNS); wsseHeader.setMustUnderstand(true); /* Add time validity information */ wsseHeader.addChild(timeStamp); wsseHeader.addChild(AXIOMUtil.stringToOM(factory, securityHeader)); /* Create action header block for action */ final SOAPHeaderBlock actionHeader = OMAbstractFactory.getSOAP12Factory() .createSOAPHeaderBlock("Action", addressingNS); actionHeader.setMustUnderstand(true); final OMText actionText = factory .createOMText(MSCRM_2011_Schema_Constants._IORGANIZATIONSERVICE + msCRMOperationType); actionHeader.addChild(actionText); /* Create messageId header block for action */ final SOAPHeaderBlock messageIdHeader = OMAbstractFactory.getSOAP12Factory() .createSOAPHeaderBlock("MessageID", addressingNS); final OMText messageIdText = factory.createOMText(UUID.randomUUID().toString()); messageIdHeader.addChild(messageIdText); /* Create replyTo header block for action */ final SOAPHeaderBlock replyToHeader = OMAbstractFactory.getSOAP12Factory() .createSOAPHeaderBlock("ReplyTo", addressingNS); final OMElement address = factory.createOMElement("Address", addressingNS); final OMText addressText = factory.createOMText("http://www.w3.org/2005/08/addressing/anonymous"); address.addChild(addressText); replyToHeader.addChild(address); /* Create To header block for action */ final SOAPHeaderBlock toHeader = OMAbstractFactory.getSOAP12Factory().createSOAPHeaderBlock("To", addressingNS); toHeader.setMustUnderstand(true); final OMText toText = factory.createOMText(organizationServiceURL); toHeader.addChild(toText); return new SOAPHeaderBlock[] { actionHeader, messageIdHeader, replyToHeader, toHeader, wsseHeader }; } catch (final XMLStreamException e) { throw new ScribeException(ScribeResponseCodes._1015 + "Problem in adding security information to SOAP request to MS office 365 login server"); } }