List of usage examples for java.text DateFormat format
public final String format(Date date)
From source file:com.wso2telco.gsma.authenticators.attributeshare.AbstractAttributeShare.java
public static void persistConsentedScopeDetails(AuthenticationContext context) throws DBUtilException, NamingException { AttributeConfigDao attributeConfigDao = new AttributeConfigDaoImpl(); String msisdn = context.getProperty(Constants.MSISDN).toString(); String operator = context.getProperty(Constants.OPERATOR).toString(); String clientId = context.getProperty(Constants.CLIENT_ID).toString(); List<SpConsent> spConsentDetailsList = attributeConfigDao.getScopeExpireTime(operator, clientId, context.getProperty(Constants.LONGLIVEDSCOPES).toString()); List<UserConsentHistory> userConsentHistoryList = new ArrayList(); for (SpConsent spConsent : spConsentDetailsList) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today);// w ww . j a va2 s . co m calendar.add(Calendar.DATE, spConsent.getExpPeriod()); UserConsentHistory userConsentHistory = new UserConsentHistory(); userConsentHistory.setMsisdn(msisdn); userConsentHistory.setConsentId(spConsent.getConsentId()); userConsentHistory.setConsentExpireTime(dateFormat.format(calendar.getTime())); userConsentHistory.setConsentStatus(Constants.TRUE); userConsentHistory.setClientId(clientId); userConsentHistory.setOperatorName(operator); userConsentHistoryList.add(userConsentHistory); } attributeConfigDao.saveUserConsentedAttributes(userConsentHistoryList); }
From source file:nl.tue.gale.ae.GaleContext.java
public static void addCookie(Resource resource, String name, String value, int age) { checkNotNull(name);//from ww w . j a v a 2 s . com if (value == null) value = "Null"; String host = ""; String path = sc(resource).getContextPath(); /* * if * (req(resource).getHeader("User-Agent").contains("compatible; MSIE") * && age == 0) { host = * URIs.of(req(resource).getRequestURL().toString()) .getHost(); path = * "/"; } */ String expires = null; if (age >= 0) { if (age == 0) age = -86400; DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US); c.add(Calendar.SECOND, age); df.setCalendar(c); expires = df.format(c.getTime()); } else expires = ""; StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : ImmutableMap .of(name, encodeURL(value), "Expires", expires, "Path", path, "Domain", host).entrySet()) if (!"".equals(entry.getValue())) { sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); sb.append("; "); } sb.delete(sb.length() - 2, sb.length()); resp(resource).setContentType("text/html"); resp(resource).addHeader("Set-Cookie", sb.toString()); }
From source file:com.eurotong.orderhelperandroid.Common.java
@TargetApi(9) public static void downloadFile(String fileName) { try {/*from w w w.ja v a 2s.co m*/ //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); Date date = new Date(); String datetime = dateFormat.format(date); // Create a URL for the desired page URL url = new URL( Common.GetBaseUrl() + Customer.Current().CustomerID + "/" + fileName + "?d=" + datetime); // Read all the text returned by the server BufferedInputStream in = new BufferedInputStream(url.openStream()); //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE); /* DataOutputStream out = new DataOutputStream(fos); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) Log.i(Define.APP_CATALOG, str); out.writeUTF(str); } */ BufferedOutputStream out = new BufferedOutputStream(fos, 4096); byte[] data = new byte[4096]; int bytesRead = 0, totalRead = 0; while ((bytesRead = in.read(data, 0, data.length)) >= 0) { out.write(data, 0, bytesRead); // update progress bar totalRead += bytesRead; /* int totalReadInKB = totalRead / 1024; msg = Message.obtain(parentActivity.activityHandler, AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0); parentActivity.activityHandler.sendMessage(msg); */ } in.close(); //fos.close(); out.close(); Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_file_finished), Toast.LENGTH_LONG).show(); try { if (fileName.equals(Define.MENU_FILE_NAME)) { Product.ParseMenuList(Common.GetFileInputStreamFromStorage(fileName)); Log.i(Define.APP_CATALOG, "menus size:" + ""); Product.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.BUSINESS_INFO_FILE_NAME)) { BusinessInfo bi = BusinessInfo .Parse(Common.GetFileInputStreamFromStorage(Define.BUSINESS_INFO_FILE_NAME)); Log.i(Define.APP_CATALOG, "setting: businessname:" + bi.getBusinessName()); BusinessInfo.Reload(); } else if (fileName.equals(Define.SETTING_FILE_NAME)) { Setting setting = Setting.Parse(Common.GetFileInputStreamFromStorage(Define.SETTING_FILE_NAME)); Log.i(Define.APP_CATALOG, "setting: printer port" + setting.getPrinterPort()); setting.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_BAR_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_BAR_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_BAR_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.PRINT_LAYOUT_KITCHEN_NAME)) { PrintLayout bi = PrintLayout .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_KITCHEN_NAME)); Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_KITCHEN_NAME); PrintLayout.Reload(); } else if (fileName.equals(Define.DEVICE_FILE)) { Device bi = Device.Parse(Common.GetFileInputStreamFromStorage(Define.DEVICE_FILE)); Log.i(Define.APP_CATALOG, Define.DEVICE_FILE); Device.Reload(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { Log.e(Define.APP_CATALOG, e.toString()); } catch (IOException e) { Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_error), Toast.LENGTH_LONG).show(); Log.e(Define.APP_CATALOG, e.toString()); e.printStackTrace(); } catch (Exception e) { Toast.makeText(MyApplication.getAppContext(), fileName + MyApplication.getAppContext().getString(R.string.msg_download_error), Toast.LENGTH_LONG).show(); Log.e(Define.APP_CATALOG, e.toString()); } }
From source file:com.cubusmail.mail.util.MessageUtils.java
/** * Format the date./*from www . j a v a2s.c o m*/ * * @param date * @return */ public static String formatMailDate(Date date) { if (date != null) { DateFormat format = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.SHORT, Locale.GERMAN); return format.format(date); } else { return ""; } }
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP POST request and obtains authentication token. * // ww w .ja v a2 s . c o m * @param credentials Authentication credentials * * @return {@link ConnectionTraits} with valid token OR with an error message if exception is caught or token retrieval failed or * token is <code>null</code> or an empty string. Does NOT return <code>null</code>. */ private static ConnectionTraits obtainToken(Credentials credentials) { ConnectionTraits connection = new ConnectionTraits(); try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("https://login.microsoftonline.com/extSTS.srf"); request.addHeader("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); request.addHeader("Content-Type", "application/soap+xml; charset=utf-8"); Date now = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ"); String nowAsString = df.format(now); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.SECOND, 10 * 60); Date expires = calendar.getTime(); String expirationAsString = df.format(expires); String message = requestTemplate; message = message.replace("#{user}", credentials.getUsername()); message = message.replace("#{pass}", credentials.getPassword()); message = message.replace("#{created}", nowAsString); message = message.replace("#{expires}", expirationAsString); message = message.replace("#{resource}", "appgportal.cloudapp.net"); StringEntity requestBody = new StringEntity(message, HTTP.UTF_8); requestBody.setContentType("text/xml"); request.setEntity(requestBody); BasicHttpResponse response = null; response = (BasicHttpResponse) client.execute(request); HttpEntity entity = response.getEntity(); InputStream inputStream = null; String token = null; inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = reader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } token = actualResponse.toString(); String start = "<wst:RequestedSecurityToken>"; int index = token.indexOf(start); if (-1 == index) { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); InputStream errorInputStream = new ByteArrayInputStream(token.getBytes()); Document currentDoc = documentBuilder.parse(errorInputStream); if (currentDoc == null) { return null; } String errorReason = null; String errorExplained = null; Node rootNode = null; if ((rootNode = currentDoc.getFirstChild()) != null && /* <S:Envelope> */ (rootNode = XmlUtility.getChildNode(rootNode, "S:Body")) != null && (rootNode = XmlUtility.getChildNode(rootNode, "S:Fault")) != null) { Node node = null; if ((node = XmlUtility.getChildNode(rootNode, "S:Reason")) != null) { errorReason = XmlUtility.getChildNodeValue(node, "S:Text"); } if ((node = XmlUtility.getChildNode(rootNode, "S:Detail")) != null && (node = XmlUtility.getChildNode(node, "psf:error")) != null && (node = XmlUtility.getChildNode(node, "psf:internalerror")) != null) { errorExplained = XmlUtility.getChildNodeValue(node, "psf:text"); } } if (!TextUtils.isEmpty(errorReason) && !TextUtils.isEmpty(errorExplained)) { logError(null, Router.class.getSimpleName() + ".obtainToken(): " + errorReason + " - " + errorExplained); connection.setError(String.format(ERROR_TOKEN, errorReason + ": " + errorExplained)); return connection; } } else { token = token.substring(index); String end = "</wst:RequestedSecurityToken>"; index = token.indexOf(end) + end.length(); token = token.substring(0, index); if (!TextUtils.isEmpty(token)) { connection.setToken(token); return connection; } } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainToken() Failed"); return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed with exception.")); } return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed.")); }
From source file:Debug.java
public static void debug(String message, Calendar value) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); debug(message, (value == null) ? "null" : df.format(value.getTime())); }
From source file:Debug.java
public static void debug(String message, Date value) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); debug(message, (value == null) ? "null" : df.format(value)); }
From source file:codesample.AuthenticationSample.java
/***************************************************************************************************************** * * Creates a string containing the elapsed time since the program started. The execution time will be reset to * 00:00.000 if the execution time exceeds an hour. * * @return Returns the elapsed time from start of program. * ***************************************************************************************************************** *//* w w w . java2s . c om*/ public static String logTime() { DateFormat dateFormat = new SimpleDateFormat("mm:ss.SSS"); long timeDifference = System.nanoTime() - startTime; long dateTime = (timeDifference / NANOSECONDS_IN_A_MILLISECOND); String time = dateFormat.format(dateTime); return time; }
From source file:com.evolveum.midpoint.web.component.prism.ContainerWrapper.java
private static String formatTime(XMLGregorianCalendar time) { DateFormat formatter = DateFormat.getDateInstance(); return formatter.format(time.toGregorianCalendar().getTime()); }
From source file:Debug.java
public static String getDebug(String message, Date value) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); return getDebug(message, (value == null) ? "null" : df.format(value)); }