List of usage examples for java.util Date toString
public String toString()
where:dow mon dd hh:mm:ss zzz yyyy
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
public void getTweets(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;/*from ww w . j a v a2 s .co m*/ } String cacheKey = userToken; Element element = null; // force refresh boolean force = Boolean.parseBoolean(request.getParameter("force")); if (force) { log.debug("force refresh for " + userToken); // remove tweets cache tweetsCache.remove(cacheKey); } else { element = tweetsCache.get(cacheKey); } if (element == null) { synchronized (tweetsCache) { // if it is still null after acquiring lock element = tweetsCache.get(cacheKey); if (element == null) { log.debug("cache miss: getting tweets for " + userToken); System.out.println("Last refreshed: " + Calendar.getInstance().getTime()); try { ResponseList<Status> friendStatus = twitter.getFriendsTimeline(); long maxId = Long.MIN_VALUE; JSONObject json = new JSONObject(); lastRefreshed = Calendar.getInstance().getTime().toString(); if (lastRefreshed == null) { json.element("lastRefreshed", "unable to retrieve last refreshed"); } else { json.element("lastRefreshed", lastRefreshed.toString()); } User currentUser = twitter.showUser(twitter.getId()); Status lastUserStatus = currentUser.getStatus(); if (lastUserStatus == null) { json.element("lastStatusUpdate", "unable to retrieve last status"); } else { Date lastStatusUpdate = lastUserStatus.getCreatedAt(); json.element("lastStatusUpdate", lastStatusUpdate.toString()); } for (Status status : friendStatus) { maxId = Math.max(maxId, status.getId()); json.accumulate("statusList", getStatusJSON(twitter, status)); } if (log.isDebugEnabled()) { log.debug(json.toString(2)); } out.print(json.toString()); element = new Element(cacheKey, new TweetsCacheElement(System.currentTimeMillis(), maxId, json)); tweetsCache.put(element); return; } catch (TwitterException e) { log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); if (e.getStatusCode() == 401) { // invalid credentials response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if (e.getStatusCode() == -1) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return; } } } } // tweets available in cache log.debug("cache hit: getting tweets for " + userToken); TweetsCacheElement tweets = (TweetsCacheElement) element.getObjectValue(); // if just refreshed too quickly, don't request update, just use // whatever in cache long period = System.currentTimeMillis() - tweets.getLastRefresh(); System.out.println("Already refreshed: " + (period / 1000) + " second(s) ago"); if (period < 2 * 60 * 1000) { log.debug("refreshed too quickly: " + (period / 1000) + " seconds"); JSONObject json = tweets.getResult(); lastRefreshed = Calendar.getInstance().getTime().toString(); json.element("lastRefreshed", lastRefreshed.toString()); out.print(json.toString()); return; } // get new updates since the last id long maxId = tweets.lastId; try { JSONObject json = tweets.getResult(); ResponseList<Status> friendStatus = twitter.getFriendsTimeline(new Paging(maxId)); tweets.setLastRefresh(System.currentTimeMillis()); log.debug(String.format("Got %d new tweets", friendStatus.size())); if (friendStatus.size() > 0) { JSONArray newTweets = new JSONArray(); lastRefreshed = Calendar.getInstance().getTime().toString(); json.element("lastRefreshed", lastRefreshed.toString()); for (Status status : friendStatus) { maxId = Math.max(maxId, status.getId()); newTweets.add(getStatusJSON(twitter, status)); } if (log.isDebugEnabled()) { log.debug("new tweets:\n" + newTweets.toString(2)); } json.getJSONArray("statusList").addAll(0, newTweets); tweets.setLastId(maxId); User currentUser = twitter.showUser(twitter.getId()); Status lastUserStatus = currentUser.getStatus(); if (lastUserStatus == null) { json.element("lastStatusUpdate", "unable to retrieve last status"); } else { Date lastStatusUpdate = lastUserStatus.getCreatedAt(); json.element("lastStatusUpdate", lastStatusUpdate.toString()); } } out.print(json.toString()); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { log.error(e); } }
From source file:com.bemis.portal.migration.customer.service.impl.CustomerMigrationLocalServiceImpl.java
@Override public void migrateCustomers(Date lastModifiedDate, long companyId) throws BemisCustomerSiteTemplateNotFoundException { // Check that the required Bemis Customer Site is available long setPrototypeId = _bemisPortalService.getBemisCustomerSiteTemplateId(); if (setPrototypeId == NOTFOUND_LAYOUTSET_PROTO_ID) { throw new BemisCustomerSiteTemplateNotFoundException(); }/* w w w .j a v a 2 s . c om*/ if (_log.isInfoEnabled()) { _log.info(">>> Migrating as of " + lastModifiedDate.toString()); } migrateCustomerOrgs(lastModifiedDate, setPrototypeId); migrateCustomerUsersAsOfDate(lastModifiedDate, companyId); }
From source file:com.att.arocollector.AROCollectorActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate(...)"); // Setup handler for uncaught exceptions. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override/*www .j a va 2 s .co m*/ public void uncaughtException(Thread thread, Throwable e) { handleUncaughtException(thread, e); } }); super.onCreate(savedInstanceState); setContentView(R.layout.splash); final TextView splashText = (TextView) findViewById(R.id.splash_message); splashText.setText(String.format(getString(R.string.splashmessageopensource), getString(R.string.app_brand_name), getString(R.string.app_url_name))); AttenuatorManager.getInstance().init(); Intent intent = getIntent(); //delay int delayDl = intent.getIntExtra(BundleKeyUtil.DL_DELAY, 0); int delayUl = intent.getIntExtra(BundleKeyUtil.UL_DELAY, 0); if (delayDl >= 0) { AttenuatorManager.getInstance().setDelayDl(delayDl); } else { Log.i(TAG, "Invalid attenuation delay value" + delayDl + "ms"); } if (delayUl >= 0) { AttenuatorManager.getInstance().setDelayUl(delayUl); } else { Log.i(TAG, "Invalid attenuation delay value" + delayUl + "ms"); } //throttle int throttleDl = intent.getIntExtra(BundleKeyUtil.DL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED); int throttleUl = intent.getIntExtra(BundleKeyUtil.UL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED); AttenuatorManager.getInstance().setThrottleDL(throttleDl); Log.d(TAG, "Download speed throttle value: " + throttleDl + " kbps"); AttenuatorManager.getInstance().setThrottleUL(throttleUl); Log.d(TAG, "Upload speed throttle value: " + throttleUl + " kbps"); printLog = intent.getBooleanExtra(BundleKeyUtil.PRINT_LOG, false); setVideoOption(intent); bitRate = intent.getIntExtra(BundleKeyUtil.BIT_RATE, 0); String screenSizeTmp = intent.getStringExtra(BundleKeyUtil.SCREEN_SIZE); screenSize = screenSizeTmp == null ? screenSize : screenSizeTmp; setVideoOrient(intent); Log.i(TAG, "get from intent delayTime: " + AttenuatorManager.getInstance().getDelayDl() + "get from intent delayTimeUL: " + AttenuatorManager.getInstance().getDelayUl() + "get from intent throttleDL: " + AttenuatorManager.getInstance().getThrottleDL() + "get from intnetn throttleUL: " + AttenuatorManager.getInstance().getThrottleUL() + " video: " + videoOption + " bitRate: " + bitRate + " screenSize: " + screenSize + " orientation: " + videoOrient); context = getApplicationContext(); launchAROCpuTraceService(); launchAROCpuTempService(); if (networkAndAirplaneModeCheck()) { // register to listen for close down message registerAnalyzerCloseCmdReceiver(); Log.d(TAG, "register the attenuator delay signal"); startVPN(); } { // test code PackageInfo packageInfo = null; try { packageInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } boolean valu = (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // build datetime Date buildDate = new Date(BuildConfig.TIMESTAMP); String appBuildDate = ""; if (buildDate != null) { appBuildDate = buildDate.toString(); } String display = "App Build Date: " + appBuildDate + "\n" // +" DownStream Delay Time: " + AttenuatorManager.getInstance().getDelayDl() + " ms\n" // +" UpStream Delay Time: " + AttenuatorManager.getInstance().getDelayUl() + " ms\n" // +" DownStream Throttle: " + AttenuatorManager.getInstance().getThrottleDL() + " kbps\n" // +" Upstream Throttle: " + AttenuatorManager.getInstance().getThrottleUL() + " kbps\n" + AttenuatorUtil.getInstance().notificationMessage() + "\n" + " Version: " + packageInfo.versionName + " (" + (valu ? "Debug" : "Production") + ")"; ((TextView) findViewById(R.id.version)).setText(display); } }
From source file:com.fanniemae.ezpie.LogManager.java
public void addFileDetails(String filename, String logGroup) { if (_logLevel == LogLevel.ERROR_ONLY) { return;/* w w w. j a v a 2s. com*/ } if (!FileUtilities.isValidFile(_logFilename)) { return; } File fi = new File(filename); long lastModified = fi.lastModified(); Date dtModified = new Date(lastModified); try (RandomAccessFile raf = new RandomAccessFile(_logFilename, "rw")) { raf.seek(raf.length() - _footerLength); raf.write(String.format(_basicLine, logGroup, "File Name", fi.getName(), elapsedTime()).getBytes()); // Turning off the full path on log, could be security concern. // raf.write(String.format(_basicLine, "", "Full Path", filename, elapsedTime()).getBytes()) raf.write(String .format(_basicLine, groupString(""), "Last Modified Date", dtModified.toString(), elapsedTime()) .getBytes()); raf.write(String.format(_basicLine, groupString(""), "Size", String.format("%,d bytes", fi.length()), elapsedTime()).getBytes()); raf.write(_footerByteArray); raf.close(); } catch (IOException e) { throw new PieException("Error trying to add message to debug page.", e); } }
From source file:org.dataone.proto.trove.mn.service.v1.impl.MNReadImpl.java
/** * MNRead.listObjects(session[, fromDate][, toDate][, formatId][, replicaStatus][, start=0][, count=1000]) * ObjectList// w w w. ja v a 2 s .c o m * * Retrieve the list of objects present on the MN that match the calling parameters. This method is required to * support the process of Member Node synchronization. At a minimum, this method MUST be able to return a list of * objects that match: * * fromDate < SystemMetadata.dateSysMetadataModified * * but is expected to also support date range (by also specifying toDate), and should also support slicing of the * matching set of records by indicating the starting index of the response (where 0 is the index of the first item) * and the count of elements to be returned. * * Note that date time precision is limited to one millisecond. If no timezone information is provided, the UTC will * be assumed. * * Access control for this method MUST be configured to allow calling by Coordinating Nodes and MAY be configured to * allow more general access. Use Cases: * * UC06, UC16 Rest URL: * * GET /object[?fromDate={fromDate}&toDate={toDate} &formatId={formatId}&replicaStatus={replicaStatus} * &start={start}&count={count}] Parameters: * * session (Types.Session) Session information that contains the identity of the calling user as retrieved from * the X.509 certificate which must be traceable to the CILogon service. The subject of the session defaults to the * public user if the certificate was not provided with the request. Transmitted as part of the SSL handshake * process. fromDate (Types.DateTime) Entries with SystemMetadata.dateSysMetadataModified greater than or equal to * (>=) fromDate must be returned. Transmitted as a URL query parameter, and so must be escaped accordingly. toDate * (Types.DateTime) Entries with SystemMetadata.dateSysMetadataModified less than (<) toDate must be returned. * Transmitted as a URL query parameter, and so must be escaped accordingly. formatId (Types.ObjectFormatIdentifier) * Restrict results to the specified object format identifier. Transmitted as a URL query parameter, and so must * be escaped accordingly. replicaStatus (boolean) Indicates if replicated objects should be returned in the list * (i.e. any entries present in the SystemMetadata.replica, objects that have been replicated to this member node). * If false, then no objects that have been replicated should be returned. If true, then any objects can be * returned, regardless of replication status. If not present, then the replicaStatus filter should be ignored. * Transmitted as a URL query parameter, and so must be escaped accordingly. start=0 (integer) The zero-based * index of the first value, relative to the first record of the resultset that matches the parameters. Transmitted * as a URL query parameter, and so must be escaped accordingly. count=1000 (integer) The maximum number of * entries that should be returned in the response. The Member Node may return fewer and the caller should check the * total in the response to determine if further pages may be retrieved. Transmitted as a URL query parameter, and * so must be escaped accordingly. * * Returns: * * The list of PIDs that match the query criteria. If none match, an empty list is returned. * * * @param startTime * @param endTime * @param objectFormatId * @param replicaStatus * @param start * @param count * @return ObjectList * @throws InvalidRequest * @throws InvalidToken * @throws NotAuthorized * @throws NotImplemented * @throws ServiceFailure */ @Override public ObjectList listObjects(Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start, Integer count) throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure { int total = 0; // Send a properties file? as a string, until we come up with a query syntax to support by default. Properties searchProperties = new Properties(); if (startTime != null) { searchProperties.setProperty("startTime", startTime.toString()); } if (endTime != null) { searchProperties.setProperty("endTime", endTime.toString()); } if (objectFormatId != null) { searchProperties.setProperty("objectFormatId", objectFormatId.getValue()); } if (replicaStatus != null) { searchProperties.setProperty("replicaStatus", Boolean.toString(replicaStatus.booleanValue())); } if (start != null) { searchProperties.setProperty("start", Integer.toString(start)); } else { searchProperties.setProperty("start", "0"); } if (count != null) { searchProperties.setProperty("count", Integer.toString(count)); } else { searchProperties.setProperty("count", "1000"); } ObjectList objectList; try { objectList = (ObjectList) dataoneDataObjectDirectory.search(searchProperties); } catch (Exception ex) { ex.printStackTrace(); throw new ServiceFailure("2312", "SolrIndex failed-" + ex.getMessage()); } return objectList; /* File[] fileList = null; File dir = new File(dataoneCacheDirectory + File.separator + "object"); if (startTime == null && endTime == null) { fileList = dir.listFiles(); } else { DateTime startDate = new DateTime(startTime); DateTime endDate = new DateTime(endTime); FileFilterByDateTime fileFilter = new FileFilterByDateTime(startDate, endDate); fileList = dir.listFiles(fileFilter); } total = fileList.length; ObjectList objectList = new ObjectList(); objectList.setTotal(total); int i = 0; for (i = 0; i < count && ((i + start) < fileList.length); i++) { String fileName = fileList[i + start].getName(); String filePath = dataoneCacheDirectory + File.separator + "meta" + File.separator + fileName; logger.info(filePath); ObjectInfo objectInfo = new ObjectInfo(); try { SystemMetadata systemMetadata = TypeMarshaller.unmarshalTypeFromFile(SystemMetadata.class, filePath); if (objectFormatId != null && !(systemMetadata.getFormatId().getValue().contentEquals(objectFormatId.getValue()))) { continue; } objectInfo.setIdentifier(systemMetadata.getIdentifier()); objectInfo.setChecksum(systemMetadata.getChecksum()); objectInfo.setSize(systemMetadata.getSize()); objectInfo.setDateSysMetadataModified(systemMetadata.getDateSysMetadataModified()); objectInfo.setFormatId(systemMetadata.getFormatId()); objectList.addObjectInfo(objectInfo); } catch (Exception ex) { logger.error(ex.getMessage()); InvalidRequest exception = new InvalidRequest("002", ex.getMessage()); throw exception; } } objectList.setCount(i); objectList.setStart(start); */ }
From source file:org.codice.ddf.catalog.ui.query.FeedbackApplication.java
private static FeedbackRequest parseFeedbackRequest(String json) { FeedbackRequest feedbackRequest = new FeedbackRequest(); String name = UNKNOWN; String email = UNKNOWN; String searchStr = UNKNOWN; String workspaceId = UNKNOWN; String workspaceName = UNKNOWN; Date searchInitiated = null; List<Object> searchStatus = null; List<Object> searchResults = null; Map<String, Object> rootObject = GSON.fromJson(json, GsonTypeAdapters.MAP_STRING_TO_OBJECT_TYPE); Object userObj = rootObject.get("user"); if (userObj instanceof Map) { Map<String, Object> userObject = (Map<String, Object>) userObj; name = (String) userObject.get("name"); email = (String) userObject.get("email"); }//from w w w. java 2 s. c om Object searchObj = rootObject.get("search"); if (searchObj instanceof Map) { Map<String, Object> searchObject = (Map<String, Object>) searchObj; searchStr = (String) searchObject.get("cql"); searchInitiated = (Date) searchObject.get("initiated"); searchStatus = (List) searchObject.get("status"); Object resultsObj = searchObject.get("results"); if (resultsObj instanceof List) { searchResults = (List) resultsObj; } } Object workspaceObj = rootObject.get("workspace"); if (workspaceObj instanceof Map) { Map<String, Object> workspaceObject = (Map<String, Object>) workspaceObj; workspaceId = (String) workspaceObject.get("id"); workspaceName = (String) workspaceObject.get("name"); } String comments = (String) rootObject.get("comments"); feedbackRequest.setUsername(name); feedbackRequest.setEmail(email); feedbackRequest.setQuery(searchStr); if (searchInitiated != null) { feedbackRequest.setQueryInitiated(searchInitiated.toString()); } if (searchResults != null) { String prettyPrintedJson = GSON.toJson(searchResults); feedbackRequest.setQueryResults(prettyPrintedJson); } if (searchStatus != null) { feedbackRequest .setQueryStatus(searchStatus.stream().map(Object::toString).collect(Collectors.joining(", "))); } feedbackRequest.setWorkspaceId(workspaceId); feedbackRequest.setWorkspaceName(workspaceName); feedbackRequest.setComments(comments); return feedbackRequest; }
From source file:gov.utah.dts.sdc.actions.ThirdPartyStudentAction.java
public String generateRoadTest() throws Exception { log.debug("generateRoadTest"); int start = decodeTime(getRoadTestStartTime()); Date startDate = new Date(getRoadTestCompletionDate().getTime() + start); log.debug("startDate " + startDate.toString()); int end = decodeTime(getRoadTestEndTime()); Date endDate = new Date(getRoadTestCompletionDate().getTime() + end); log.debug("endDate " + endDate.toString()); if (endDate.before(startDate)) { addActionError("Start Time Must Be Before End Time"); return INPUT; }//from w ww.j a va2 s.co m String retVal = createStudent(); if (retVal.equals(SUCCESS)) { log.debug("return the jasper report"); insertRoadAuditDate(getRoadMap(startDate, endDate)); getSession().put(Constants.Report_WrittenCompletionStudent, getStudent()); return GENERATE_REPORT; } else if (retVal.equals(Constants.EDITSTUDENT)) { log.debug("Existing Student Jasper report"); getSession().put(Constants.Report_WrittenCompletionStudent, getStudent()); return GENERATE_REPORT; } return INPUT; }
From source file:com.digitalpebble.stormcrawler.bolt.SiteMapParserBolt.java
private List<Outlink> parseSiteMap(String url, byte[] content, String contentType, Metadata parentMetadata) throws UnknownFormatException, IOException { crawlercommons.sitemaps.SiteMapParser parser = new crawlercommons.sitemaps.SiteMapParser(strictMode); URL sURL = new URL(url); AbstractSiteMap siteMap;//from ww w. j av a 2s .co m // let the parser guess what the mimetype is if (StringUtils.isBlank(contentType) || contentType.contains("octet-stream")) { siteMap = parser.parseSiteMap(content, sURL); } else { siteMap = parser.parseSiteMap(contentType, content, sURL); } List<Outlink> links = new ArrayList<>(); if (siteMap.isIndex()) { SiteMapIndex smi = (SiteMapIndex) siteMap; Collection<AbstractSiteMap> subsitemaps = smi.getSitemaps(); // keep the subsitemaps as outlinks // they will be fetched and parsed in the following steps Iterator<AbstractSiteMap> iter = subsitemaps.iterator(); while (iter.hasNext()) { AbstractSiteMap asm = iter.next(); String target = asm.getUrl().toExternalForm(); // build an absolute URL try { target = URLUtil.resolveURL(sURL, target).toExternalForm(); } catch (MalformedURLException e) { LOG.debug("MalformedURLException on {}", target); continue; } Date lastModified = asm.getLastModified(); if (lastModified != null) { // filter based on the published date if (filterHoursSinceModified != -1) { Calendar rightNow = Calendar.getInstance(); rightNow.add(Calendar.HOUR, -filterHoursSinceModified); if (lastModified.before(rightNow.getTime())) { LOG.info("{} has a modified date {} which is more than {} hours old", target, lastModified.toString(), filterHoursSinceModified); continue; } } } // apply filtering to outlinks target = urlFilters.filter(sURL, parentMetadata, target); if (StringUtils.isBlank(target)) continue; // configure which metadata gets inherited from parent Metadata metadata = metadataTransfer.getMetaForOutlink(target, url, parentMetadata); metadata.setValue(isSitemapKey, "true"); Outlink ol = new Outlink(target); ol.setMetadata(metadata); links.add(ol); LOG.debug("{} : [sitemap] {}", url, target); } } // sitemap files else { SiteMap sm = (SiteMap) siteMap; // TODO see what we can do with the LastModified info Collection<SiteMapURL> sitemapURLs = sm.getSiteMapUrls(); Iterator<SiteMapURL> iter = sitemapURLs.iterator(); while (iter.hasNext()) { SiteMapURL smurl = iter.next(); double priority = smurl.getPriority(); // TODO handle priority in metadata ChangeFrequency freq = smurl.getChangeFrequency(); // TODO convert the frequency into a numerical value and handle // it in metadata String target = smurl.getUrl().toExternalForm(); // build an absolute URL try { target = URLUtil.resolveURL(sURL, target).toExternalForm(); } catch (MalformedURLException e) { LOG.debug("MalformedURLException on {}", target); continue; } Date lastModified = smurl.getLastModified(); if (lastModified != null) { // filter based on the published date if (filterHoursSinceModified != -1) { Calendar rightNow = Calendar.getInstance(); rightNow.add(Calendar.HOUR, -filterHoursSinceModified); if (lastModified.before(rightNow.getTime())) { LOG.info("{} has a modified date {} which is more than {} hours old", target, lastModified.toString(), filterHoursSinceModified); continue; } } } // apply filtering to outlinks target = urlFilters.filter(sURL, parentMetadata, target); if (StringUtils.isBlank(target)) continue; // configure which metadata gets inherited from parent Metadata metadata = metadataTransfer.getMetaForOutlink(target, url, parentMetadata); metadata.setValue(isSitemapKey, "false"); Outlink ol = new Outlink(target); ol.setMetadata(metadata); links.add(ol); LOG.debug("{} : [sitemap] {}", url, target); } } return links; }
From source file:com.dell.asm.asmcore.asmmanager.app.AsmManagerApp.java
public static void createScheduledDeploymentStatusSyncJob(int delay) { _logger.info("Create Scheduled deployment status sync job."); IJobManager jobMgr = JobManager.getInstance(); try {//w w w .j av a2 s . com Set<JobKey> jobKeySet = jobMgr.getScheduler().getJobKeys( GroupMatcher.jobGroupEquals(ScheduledDeploymentSyncStatusJob.class.getSimpleName())); if ((jobKeySet != null) && !jobKeySet.isEmpty()) { for (JobKey jobKey : jobKeySet) { _logger.info("Found Job Key " + jobKey.getName() + ", deleting"); jobMgr.deleteJob(jobKey); } } Date scheduleDate = new Date(); scheduleDate = DateUtils.addSeconds(scheduleDate, delay); SimpleTriggerImpl trigger = new SimpleTriggerImpl(); trigger.setRepeatCount(0); trigger.setName(UUID.randomUUID().toString()); trigger.setGroup(ScheduledDeploymentSyncStatusJob.class.getSimpleName()); trigger.setStartTime(scheduleDate); JobDetail jobDetail = jobMgr.createNamedJob(ScheduledDeploymentSyncStatusJob.class); Date nextRun = jobMgr.scheduleJob(jobDetail, trigger); _logger.info("next run for ScheduledDeploymentSyncStatusJob scheduled at: " + nextRun.toString()); if (!jobMgr.getScheduler().isStarted()) { jobMgr.getScheduler().start(); _logger.info("scheduler started"); } } catch (Exception e) { String msg = "Failed to schedule recurring ScheduledDeploymentSyncStatusJob: " + e.getMessage(); _logger.error(msg, e); } }
From source file:com.dattasmoon.pebble.plugin.NotificationService.java
@Override public void onAccessibilityEvent(AccessibilityEvent event) { // handle the prefs changing, because of how accessibility services // work, sharedprefsonchange listeners don't work if (watchFile.lastModified() > lastChange) { loadPrefs();/* w ww .ja v a2s. c o m*/ } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal())); } // if we are off, don't do anything. if (mode == Mode.OFF) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications"); } return; } //handle quiet hours if (quiet_hours) { Calendar c = Calendar.getInstance(); Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)); if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs " + quiet_hours_before.toString() + " and " + quiet_hours_after.toString()); } if (quiet_hours_before.after(quiet_hours_after)) { if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning."); } return; } } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning."); } return; } } // handle if they only want notifications if (notifications_only) { if (event != null) { Parcelable parcelable = event.getParcelableData(); if (!(parcelable instanceof Notification)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is not a notification and notifications only is enabled. Returning."); } return; } } } if (no_ongoing_notifs) { Parcelable parcelable = event.getParcelableData(); if (parcelable instanceof Notification) { Notification notif = (Notification) parcelable; if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning."); } return; } } else { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is not a notification."); } } } // Handle the do not disturb screen on settings PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (Constants.IS_LOGGABLE) { Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn + " screen=" + powMan.isScreenOn()); } if (!notifScreenOn && powMan.isScreenOn()) { return; } if (event == null) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event is null. Returning."); } return; } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Event: " + event.toString()); } // main logic PackageManager pm = getPackageManager(); String eventPackageName; if (event.getPackageName() != null) { eventPackageName = event.getPackageName().toString(); } else { eventPackageName = ""; } if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Service package list is: "); for (String strPackage : packages) { Log.i(Constants.LOG_TAG, strPackage); } Log.i(Constants.LOG_TAG, "End Service package list"); } switch (mode) { case EXCLUDE: // exclude functionality if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Mode is set to exclude"); } for (String packageName : packages) { if (packageName.equalsIgnoreCase(eventPackageName)) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName + " which is on the exclude list. Returning."); } return; } } break; case INCLUDE: // include only functionality if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Mode is set to include only"); } boolean found = false; for (String packageName : packages) { if (packageName.equalsIgnoreCase(eventPackageName)) { found = true; break; } } if (!found) { Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning."); return; } break; } // get the title String title = ""; try { boolean renamed = false; for (int i = 0; i < pkg_renames.length(); i++) { if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) { renamed = true; title = pkg_renames.getJSONObject(i).getString("to"); } } if (!renamed) { title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString(); } } catch (NameNotFoundException e) { title = eventPackageName; } catch (JSONException e) { title = eventPackageName; } // get the notification text String notificationText = event.getText().toString(); // strip the first and last characters which are [ and ] notificationText = notificationText.substring(1, notificationText.length() - 1); if (notification_extras) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Fetching extras from notification"); } Parcelable parcelable = event.getParcelableData(); if (parcelable instanceof Notification) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim()); } else { notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim()); } } } // Check ignore lists for (int i = 0; i < ignores.length(); i++) { try { JSONObject ignore = ignores.getJSONObject(i); String app = ignore.getString("app"); boolean exclude = ignore.optBoolean("exclude", true); boolean case_insensitive = ignore.optBoolean("insensitive", true); if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) { //this rule doesn't apply to all apps and this isn't the app we're looking for. continue; } String regex = ""; if (case_insensitive) { regex += "(?i)"; } if (!ignore.getBoolean("raw")) { regex += Pattern.quote(ignore.getString("match")); } else { regex += ignore.getString("match"); } Pattern p = Pattern.compile(regex); Matcher m = p.matcher(notificationText); if (m.find()) { if (exclude) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '" + regex + "' and exclude is on. Returning"); } return; } } else { if (!exclude) { if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' does not match: '" + regex + "' and include is on. Returning"); } return; } } } catch (JSONException e) { continue; } } // Send the alert to Pebble sendToPebble(title, notificationText); if (Constants.IS_LOGGABLE) { Log.i(Constants.LOG_TAG, event.toString()); Log.i(Constants.LOG_TAG, event.getPackageName().toString()); } }