Example usage for java.util Date toString

List of usage examples for java.util Date toString

Introduction

In this page you can find the example usage for java.util Date toString.

Prototype

public String toString() 

Source Link

Document

Converts this Date object to a String of the form:
 dow mon dd hh:mm:ss zzz yyyy
where:
  • dow is the day of the week ( Sun, Mon, Tue, Wed, Thu, Fri, Sat ).

    Usage

    From source file:org.alfresco.repo.node.index.FullIndexRecoveryComponent.java

    private void performPartialRecovery() {
        // Log the AUTO recovery
        IndexTransactionTrackerListener trackerListener = new IndexTransactionTrackerListener() {
            long lastLogged = 0L;
    
            public void indexedTransactions(long fromTimeInclusive, long toTimeExclusive) {
                long now = System.currentTimeMillis();
                if (now - lastLogged < 10000L) {
                    // Don't log more than once a minute
                    return;
                }/*  w  w  w. j  a va2s  . c  om*/
                lastLogged = now;
                // Log it
                Date toTimeDate = new Date(toTimeExclusive);
                String msgAutoProgress = I18NUtil.getMessage(MSG_TRACKING_PROGRESS, toTimeDate.toString());
                logger.info(msgAutoProgress);
            }
        };
        try {
            // Register the listener
            indexTracker.setListener(trackerListener);
            // Trigger the tracker, which will top up the indexes
            logger.info(I18NUtil.getMessage(MSG_TRACKING_STARTING));
            indexTracker.reindex();
            logger.info(I18NUtil.getMessage(MSG_TRACKING_COMPLETE));
        } finally {
            // Remove the listener
            indexTracker.setListener(null);
        }
    }
    

    From source file:org.jpos.gl.rule.CanPost.java

    public void check(GLSession session, GLTransaction txn, String param, Account account, int[] entryOffsets,
            short[] layers) throws GLException {
        Journal journal = txn.getJournal();/*from  w ww . j  av  a 2  s.c o  m*/
        Date postDate = txn.getPostDate();
        Date end = journal.getEnd();
        Date start = journal.getStart();
        Date lockDate = journal.getLockDate();
    
        session.checkPermission(GLPermission.POST, journal);
    
        if (journal.isClosed()) {
            throw new GLException("Journal '" + journal.getName() + "' is closed");
        }
        if (postDate == null)
            throw new GLException("Invalid transaction. Posting date is null");
    
        if (start != null && postDate.compareTo(start) < 0) {
            throw new GLException("Journal '" + journal.getName()
                    + "' cannot accept transactions with a posting date less than " + start.toString());
        }
        if (end != null && postDate.compareTo(end) > 0) {
            throw new GLException("Journal '" + journal.getName()
                    + "' cannot accept transactions with a post date greater than " + end.toString());
        }
        if (lockDate != null && postDate.compareTo(lockDate) <= 0) {
            throw new GLException(
                    "Journal '" + journal.getName() + "' has a temporary lockDate at " + lockDate.toString());
        }
        checkEntries(txn, postDate);
    }
    

    From source file:org.alfresco.module.org_alfresco_module_rm.job.PublishUpdatesJobExecuter.java

    /**
     * @see org.alfresco.module.org_alfresco_module_rm.job.RecordsManagementJobExecuter#executeImpl()
     *//*from   ww w.j  ava2 s  . c o  m*/
    public void executeImpl() {
        if (logger.isDebugEnabled()) {
            logger.debug("Job Starting");
        }
    
        AuthenticationUtil.runAs(new RunAsWork<Object>() {
            public Object doWork() {
                if (rmLoaded()) {
                    // Get a list of the nodes that have updates that need to be published
                    List<NodeRef> nodeRefs = getUpdatedNodes();
    
                    // Deal with each updated disposition action in turn
                    for (NodeRef nodeRef : nodeRefs) {
                        if (nodeService.exists(nodeRef)) {
                            boolean publishing = ((Boolean) nodeService.getProperty(nodeRef,
                                    PROP_PUBLISH_IN_PROGRESS)).booleanValue();
                            if (!publishing) {
                                // Mark the update node as publishing in progress
                                markPublishInProgress(nodeRef);
                                try {
                                    Date start = new Date();
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("Starting publish of updates ...");
                                        logger.debug("   - for " + nodeRef.toString());
                                        logger.debug("   - at " + start.toString());
                                    }
    
                                    // Publish updates
                                    publishUpdates(nodeRef);
    
                                    if (logger.isDebugEnabled()) {
                                        Date end = new Date();
                                        long duration = end.getTime() - start.getTime();
                                        logger.debug("Completed publish of updates ...");
                                        logger.debug("   - for " + nodeRef.toString());
                                        logger.debug("   - at " + end.toString());
                                        logger.debug("   - duration " + Long.toString(duration));
                                    }
                                } finally {
                                    // Ensure the update node has either completed the publish or is marked as no longer in progress
                                    unmarkPublishInProgress(nodeRef);
                                }
                            }
                        }
                    }
                }
                return null;
            };
        }, AuthenticationUtil.getSystemUserName());
    
        if (logger.isDebugEnabled()) {
            logger.debug("Job Finished");
        }
    }
    

    From source file:com.saarang.samples.apps.iosched.gcm.command.NotificationCommand.java

    private void processCommand(Context context, NotificationCommandModel command) {
        // Check format
        if (!"1.0.00".equals(command.format)) {
            LogUtils.LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
            return;//from   w  w w  .  j a va  2s . c o m
        }
    
        // Check app version
        if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) {
            LogUtils.LOGD(TAG, "Command has version range.");
            int minVersion = 0;
            int maxVersion = Integer.MAX_VALUE;
            try {
                if (!TextUtils.isEmpty(command.minVersion)) {
                    minVersion = Integer.parseInt(command.minVersion);
                }
                if (!TextUtils.isEmpty(command.maxVersion)) {
                    maxVersion = Integer.parseInt(command.maxVersion);
                }
                LogUtils.LOGD(TAG, "Version range: " + minVersion + " - " + maxVersion);
                PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                LogUtils.LOGD(TAG, "My version code: " + pinfo.versionCode);
                if (pinfo.versionCode < minVersion) {
                    LogUtils.LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode
                            + " < " + minVersion);
                    return;
                }
                if (pinfo.versionCode > maxVersion) {
                    LogUtils.LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode
                            + " > " + maxVersion);
                    return;
                }
            } catch (NumberFormatException ex) {
                LogUtils.LOGE(TAG,
                        "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion);
                return;
            } catch (Exception ex) {
                LogUtils.LOGE(TAG, "Unexpected problem doing version check.", ex);
                return;
            }
        }
    
        // Check if we are the right audience
        LogUtils.LOGD(TAG, "Checking audience: " + command.audience);
        if ("remote".equals(command.audience)) {
            if (PrefUtils.isAttendeeAtVenue(context)) {
                LogUtils.LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
                return;
            } else {
                LogUtils.LOGD(TAG, "Relevant (attendee is remote).");
            }
        } else if ("local".equals(command.audience)) {
            if (!PrefUtils.isAttendeeAtVenue(context)) {
                LogUtils.LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
                return;
            } else {
                LogUtils.LOGD(TAG, "Relevant (attendee is local).");
            }
        } else if ("all".equals(command.audience)) {
            LogUtils.LOGD(TAG, "Relevant (audience is 'all').");
        } else {
            LogUtils.LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience);
            return;
        }
    
        // Check if it expired
        Date expiry = command.expiry == null ? null : TimeUtils.parseTimestamp(command.expiry);
        if (expiry == null) {
            LogUtils.LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
            return;
        } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
            LogUtils.LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
            return;
        } else {
            LogUtils.LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")");
        }
    
        // decide the intent that will be fired when the user clicks the notification
        Intent intent;
        if (TextUtils.isEmpty(command.dialogText)) {
            // notification leads directly to the URL, no dialog
            if (TextUtils.isEmpty(command.url)) {
                intent = new Intent(context, MyScheduleActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            } else {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(command.url));
            }
        } else {
            // use a dialog
            intent = new Intent(context, MyScheduleActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
                            | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE,
                    command.dialogTitle == null ? "" : command.dialogTitle);
            intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE,
                    command.dialogText == null ? "" : command.dialogText);
            intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES,
                    command.dialogYes == null ? "OK" : command.dialogYes);
            intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, command.dialogNo == null ? "" : command.dialogNo);
            intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, command.url == null ? "" : command.url);
        }
    
        final String title = TextUtils.isEmpty(command.title)
                ? context.getString(com.saarang.samples.apps.iosched.R.string.app_name)
                : command.title;
        final String message = TextUtils.isEmpty(command.message) ? "" : command.message;
    
        // fire the notification
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
                new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
                        .setSmallIcon(com.saarang.samples.apps.iosched.R.drawable.ic_stat_notification)
                        .setTicker(command.message).setContentTitle(title).setContentText(message)
                        //.setColor(context.getResources().getColor(R.color.theme_primary))
                        // Note: setColor() is available in the support lib v21+.
                        // We commented it out because we want the source to compile 
                        // against support lib v20. If you are using support lib
                        // v21 or above on Android L, uncomment this line.
                        .setContentIntent(
                                PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
                        .setAutoCancel(true).build());
    }
    

    From source file:ingestor.SingleFileProcessor.java

    public Boolean WriteObjectToHCP(URL encodedPathURL, File inSourceFile) throws Exception {
        if (inSourceFile.toString().endsWith(".inuse"))
            throw new IOException();
        ScreenLog.begin("Write Object to HCP");
        HCPClient client = new HCPClient(CometProperties.getInstance());
        client.setRootpath(CometProperties.getInstance().getDestinationRootPath(pathPrefix));
        FileInputStream fis = null;//  www  . j a va  2s.c o  m
        Boolean fileLock = false;
        //FileLocker fis=null;
        File fileLockFile = new File(inSourceFile.getAbsolutePath() + ".inuse");
        if (CometProperties.getInstance().getUseFileLocking()) {
            if (fileLockFile.exists()) {
                ScreenLog.warning("\tLock file already exists, bail:" + inSourceFile.getAbsolutePath() + ".inuse");
                return true; //acceptable outcome
            } else {
                ScreenLog.out("\tLock file does not exist, create it:" + inSourceFile.getAbsolutePath() + ".inuse");
                StringHelper.touch(fileLockFile);
                fileLock = true;
            }
        } else {
            ScreenLog.fine("\tNot using file locking");
        }
    
        fis = new FileInputStream(inSourceFile);
        String captured = client.HttpPutHCPContent(new InputStreamEntity(fis, -1), encodedPathURL);
    
        fis.close();
        if (fileLock) {
            ScreenLog.fine("deleting file lock");
            fileLockFile.delete();
        }
        ScreenLog.out("output from PUT operation: " + captured);
        ScreenLog.out("filename(" + inSourceFile.toString() + ") status code = " + client.getStatusCode() + "\n");
    
        if (409 == client.getStatusCode()) {
            logger.fine(" Object already exists on HCP, ignore the error for transaction \""
                    + inSourceFile.getAbsolutePath() + "\" to \"" + encodedPathURL);
        }
        // If the return code is anything BUT 200 range indicating success, we have to throw an exception.
        else {
            if (2 != client.getStatusCode() / 100)
                eObjectStatus = WriteStatus.WRITE_FAILURE;
            else {
                eObjectStatus = WriteStatus.WRITE_SUCCESS;
            }
            Date d = new Date();
            logger.force("[" + d.toString() + "] PUT \"" + inSourceFile.getAbsolutePath() + "\" to \""
                    + encodedPathURL + "\" " + client.getStatusCode());
        }
        ScreenLog.end("Write Object to HCP");
        return eObjectStatus == WriteStatus.WRITE_SUCCESS;
    }
    

    From source file:edu.ku.brc.specify.tools.datamodelgenerator.DataDict.java

    /**
     * @return//from  ww w .j  a v  a2s  .  co m
     */
    public boolean writeTables(final String outFileName, final Vector<TableDef> tbls) {
    
        try {
            if (tables == null) {
                System.err.println("Datamodel information is null - datamodel file will not be written!!");
                return false;
            }
            System.err.println("writing data model tree to file: " + outFileName);
    
            //Element root = XMLHelper.readFileToDOM4J(new FileInputStream(XMLHelper.getConfigDirPath(datamodelOutputFileName)));
            File file = new File(outFileName);
            FileWriter fw = new FileWriter(file);
            fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            fw.write("<!-- \n");
            fw.write("    Do Not Edit this file!\n");
            fw.write("    Run DatamodelGenerator \n");
            Date date = new Date();
            fw.write("    Generated: " + date.toString() + "\n");
            fw.write("-->\n");
    
            //using betwixt for writing out datamodel file.  associated .betwixt files allow you to map and define 
            //output format of attributes in xml file.
            BeanWriter beanWriter = new BeanWriter(fw);
            XMLIntrospector introspector = beanWriter.getXMLIntrospector();
    
            introspector.getConfiguration().setWrapCollectionsInElement(false);
    
            beanWriter.getBindingConfiguration().setMapIDs(false);
            beanWriter.setWriteEmptyElements(false);
            beanWriter.enablePrettyPrint();
            beanWriter.write("database", tbls);
    
            fw.close();
    
            return true;
    
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataDict.class, ex);
            ex.printStackTrace();
            return false;
        }
    }
    

    From source file:org.kuali.kra.committee.service.CommitteeScheduleServiceImplTest.java

    /**
     * This method test's advance submission days for added event.
     * @throws Exception// w w w  .  j  a va 2  s . c o m
     */
    @Test
    public void testAddScheduleAdvancedSubmissionDays() throws Exception {
        prerequisite();
    
        scheduleData.setRecurrenceType(StyleKey.NEVER.toString());
        scheduleData.setTime(new Time12HrFmt(TIME12HR_11_59, MERIDIEM.PM));
    
        context.checking(new Expectations() {
            {
                Date dt = scheduleData.getScheduleStartDate();
                List<Date> dates = new LinkedList<Date>();
                dates.add(new Date());
                Time24HrFmt time = new Time24HrFmt(TIME24HR_23_59);
                one(scheduleService).getScheduledDates(dt, dt, time, null);
                will(returnValue(dates));
            }
        });
    
        test(1);
        java.sql.Date testDate = committee.getCommitteeSchedules().get(0).getProtocolSubDeadline();
        java.sql.Date expectedDate = new java.sql.Date(
                DateUtils.addDays(new Date(), -committee.getAdvancedSubmissionDaysRequired()).getTime());
        assertEquals(expectedDate.toString(), testDate.toString());
    }
    

    From source file:samples.json.KinesisMessageModel.java

    /**
     * //from  ww w  . ja v a 2s .  co  m
     * @param userid
     *        Sample int data field
     * @param username
     *        Sample String data field
     * @param firstname
     *        Sample String data field
     * @param lastname
     *        Sample String data field
     * @param city
     *        Sample String data field
     * @param state
     *        Sample String data field (2 characters)
     * @param email
     *        Sample String data field
     * @param phone
     *        Sample String data field
     * @param likesports
     *        Sample boolean data field
     * @param liketheatre
     *        Sample boolean data field
     * @param likeconcerts
     *        Sample boolean data field
     * @param likejazz
     *        Sample boolean data field
     * @param likeclassical
     *        Sample boolean data field
     * @param likeopera
     *        Sample boolean data field
     * @param likerock
     *        Sample boolean data field
     * @param likevegas
     *        Sample boolean data field
     * @param likebroadway
     *        Sample boolean data field
     * @param likemusicals
     *        Sample boolean data field
     */
    public KinesisMessageModel(String timenow, int userid, String username, String firstname, String lastname,
            String city, String state, String email, String phone, boolean likesports, boolean liketheatre,
            boolean likeconcerts, boolean likejazz, boolean likeclassical, boolean likeopera, boolean likerock,
            boolean likevegas, boolean likebroadway, boolean likemusicals) {
        Date currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
        this.timenow = currentTimestamp.toString();
        this.userid = userid;
        this.username = username;
        this.firstname = firstname;
        this.lastname = lastname;
        this.city = city;
        this.state = state;
        this.email = email;
        this.phone = phone;
        this.likesports = likesports;
        this.liketheatre = liketheatre;
        this.likeconcerts = likeconcerts;
        this.likejazz = likejazz;
        this.likeclassical = likeclassical;
        this.likeopera = likeopera;
        this.likerock = likerock;
        this.likevegas = likevegas;
        this.likebroadway = likebroadway;
        this.likemusicals = likemusicals;
    }
    

    From source file:com.baasbox.service.push.providers.APNServer.java

    @Override
    public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
        PushLogger pushLogger = PushLogger.getInstance();
        pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
        ApnsService service = null;/*w w w.  ja v  a  2s  .  c  o m*/
        try {
            if (BaasBoxLogger.isDebugEnabled())
                BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
            if (!isInit) {
                pushLogger.addMessage("............ APNS is not initialized!");
                return true;
            }
    
            String payload = null;
            try {
                service = getService();
            } catch (com.notnoop.exceptions.InvalidSSLConfig e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending push notification");
                throw new PushNotInitializedException(
                        "Error decrypting certificate.Verify your password for given certificate");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }
    
            JsonNode contentAvailableNode = bodyJson.findValue("content-available");
            Integer contentAvailable = null;
            if (!(contentAvailableNode == null)) {
                if (!(contentAvailableNode.isInt()))
                    throw new PushContentAvailableFormatException(
                            "Content-available MUST be an Integer (1 for silent notification)");
                contentAvailable = contentAvailableNode.asInt();
            }
    
            JsonNode categoryNode = bodyJson.findValue("category");
            String category = null;
            if (!(categoryNode == null)) {
                if (!(categoryNode.isTextual()))
                    throw new PushCategoryFormatException("Category MUST be a String");
                category = categoryNode.asText();
            }
    
            JsonNode soundNode = bodyJson.findValue("sound");
            String sound = null;
            if (!(soundNode == null)) {
                if (!(soundNode.isTextual()))
                    throw new PushSoundKeyFormatException("Sound value MUST be a String");
                sound = soundNode.asText();
            }
    
            JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
            String actionLocKey = null;
    
            if (!(actionLocKeyNode == null)) {
                if (!(actionLocKeyNode.isTextual()))
                    throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
                actionLocKey = actionLocKeyNode.asText();
            }
    
            JsonNode locKeyNode = bodyJson.findValue("localizedKey");
            String locKey = null;
    
            if (!(locKeyNode == null)) {
                if (!(locKeyNode.isTextual()))
                    throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
                locKey = locKeyNode.asText();
            }
    
            JsonNode locArgsNode = bodyJson.get("localizedArguments");
    
            List<String> locArgs = new ArrayList<String>();
            if (!(locArgsNode == null)) {
                if (!(locArgsNode.isArray()))
                    throw new PushLocalizedArgumentsFormatException(
                            "LocalizedArguments MUST be an Array of String");
                for (JsonNode locArgNode : locArgsNode) {
                    if (locArgNode.isNumber())
                        throw new PushLocalizedArgumentsFormatException(
                                "LocalizedArguments MUST be an Array of String");
                    locArgs.add(locArgNode.toString());
                }
            }
    
            JsonNode customDataNodes = bodyJson.get("custom");
    
            Map<String, JsonNode> customData = new HashMap<String, JsonNode>();
    
            if (!(customDataNodes == null)) {
                customData.put("custom", customDataNodes);
            }
    
            JsonNode badgeNode = bodyJson.findValue("badge");
            int badge = 0;
            if (!(badgeNode == null)) {
                if (!(badgeNode.isNumber()))
                    throw new PushBadgeFormatException("Badge value MUST be a number");
                else
                    badge = badgeNode.asInt();
            }
    
            if (BaasBoxLogger.isDebugEnabled())
                BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                        + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                        + " with Localized-Key: " + locKey);
            if (BaasBoxLogger.isDebugEnabled())
                BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
            if (BaasBoxLogger.isDebugEnabled())
                BaasBoxLogger.debug("Custom Data: " + customData.toString());
    
            pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                    + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                    + " with Localized-Key: " + locKey);
            pushLogger.addMessage("Localized arguments: " + locArgs.toString());
            pushLogger.addMessage("Custom Data: " + customData.toString());
            pushLogger.addMessage("Timeout: " + timeout);
    
            PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound)
                    .actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge)
                    .customFields(customData).category(category);
            if (contentAvailable != null && contentAvailable.intValue() == 1) {
                payloadBuilder.instantDeliveryOrSilentNotification();
            }
            payload = payloadBuilder.build();
    
            Collection<? extends ApnsNotification> result = null;
            if (timeout <= 0) {
                try {
                    result = service.push(deviceid, payload);
                } catch (NetworkIOException e) {
                    pushLogger.addMessage("Error sending push notification ...");
                    pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                    BaasBoxLogger.error("Error sending push notification");
                    BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                    throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                    //icallbackPush.onError(ExceptionUtils.getMessage(e));
                }
            } else {
                try {
                    Date expiry = new Date(Long.MAX_VALUE);
                    pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout,
                            expiry.toString());
                    result = service.push(deviceid, payload, expiry);
                } catch (NetworkIOException e) {
                    pushLogger.addMessage("Error sending push notification ...");
                    pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                    BaasBoxLogger.error("Error sending enhanced push notification");
                    BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                    throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                    //icallbackPush.onError(ExceptionUtils.getMessage(e));
                }
    
            }
            if (result != null) {
                Iterator<? extends ApnsNotification> it = result.iterator();
                while (it.hasNext()) {
                    ApnsNotification item = it.next();
                    //item.
                }
    
            }
            //icallbackPush.onSuccess();
            return false;
        } catch (Exception e) {
            pushLogger.addMessage("Error sending push notification (APNS)...");
            pushLogger.addMessage(ExceptionUtils.getMessage(e));
            throw e;
        } finally {
            if (service != null)
                service.stop();
        }
    }
    

    From source file:me.skydeveloper.tikona.SessionTab.java

    /**
     * Updates Session Details returned from TikonaSession
     *///from w  w  w. ja v a2  s .  c  o m
    protected void updateSessionDetails() {
        if (tikonaSession != null) {
            for (TikonaSession session : tikonaSession) {
                if (session.isLoggedIn()) {
                    sessionStart.setText(session.getSessionStart());
                    sessionDuration.setText(session.getSessionDuration());
                    sessionUsage.setText(session.getSessionUsage());
    
                    long sessionStartMilli = 0;
                    try {
                        //TODO => Manage session when session is null error 100 - Logged in but button is not visible
                        if (session.getSessionStart() != null) {
                            Date sessionDateTime = new SimpleDateFormat("MM/dd/yyy HH:mm:ss", Locale.ENGLISH)
                                    .parse(session.getSessionStart());
                            sessionStartMilli = sessionDateTime.getTime();
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
    
                    long currentTime = selfcarePreferences.getLong("lastCheckedAt", 0);
    
                    /*SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d h:mm:ss", Locale.ENGLISH);
                            
                    String dateTime = null;
                    try {
                    Date date2 = dateFormat.parse(date.toString());
                    dateTime = dateFormat.format(date);
                    } catch (ParseException e) {
                    e.printStackTrace();
                    }*/
    
                    Date date = new Date(System.currentTimeMillis());
    
                    lastCheckedAt.setText(date.toString());
    
                    Log.d("timeTest", sessionStartMilli + "");
                    Log.d("timeTest", currentTime + "");
                    //Log.d("timeTest",currentTime + "");
    
                    if (sessionStartMilli > currentTime) {
                        if (!selfcarePreferences.getString("username", "").equals("")
                                && !selfcarePreferences.getString("password", "").equals("")) {
                            remainingUsage.setText("Fetching details ...");
                            HttpRequest data = new HttpRequest();
                            data.setMethod("POST");
                            data.setUri("https://selfcare.tikona.in/EncryptData.do");
                            String username = selfcarePreferences.getString("username", "");
                            String password = selfcarePreferences.getString("password", "");
                            data.setParam("data", username + "~" + password);
                            Selfcare selfcareData = new Selfcare();
                            selfcareData.execute(data);
                        } else {//
    
                            TextView remainingUsage = (TextView) getView().findViewById(R.id.remainigUsageValue);
                            remainingUsage.setText(R.string.ltvd);
                            //TODO => Uncomment this once selfcare login is fixed
                            /*remainingUsage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), SelfcareLogin.class);
                                startActivity(intent);
                            }
                            });*/
                        }
                    } else {//If we already have selfcare data
                        String balance = selfcarePreferences.getString("balance", "");//Already processed
                        String current = sessionUsage.getText().toString().replace("MB", "").replace("GB", "")
                                .replace("KB", "").replace("B", "").trim();
    
                        int remainingData = 0;
                        if (current.length() >= 1 && !balance.equals("You are now on secondary policy")) {
                            remainingData = Integer.parseInt(balance) - Integer.parseInt(current);
                            if (remainingData > 0) {
                                remainingUsage.setText(remainingData + " MB");
                            } else {
                                remainingUsage.setText(R.string.secondaryPolicy);
                            }
                        } else {
                            remainingUsage.setText(R.string.secondaryPolicy);
                        }
    
                        //FOR SCREENSHOT PURPOSES
                        /*TextView test = (TextView) getActivity().findViewById(R.id.userid);
                        test.setText("11XXXXXX");
                        TextView test2 = (TextView) getActivity().findViewById(R.id.name);
                        test2.setText("Guest User");*/
    
                    }
    
                    sessionEditor = sessionPreferences.edit();
                    sessionEditor.putString("sessionStart", session.getSessionStart());
                    sessionEditor.putString("sessionDuration", session.getSessionDuration());
                    sessionEditor.putString("sessionUsage", session.getSessionUsage());
                    sessionEditor.apply();
    
                    Snackbar.make(getView(), "Session details updated", Snackbar.LENGTH_LONG).show();
                } else if (!session.isLogoutButtonVisibility()) {
                    Toast.makeText(getActivity(),
                            "Empty Response. This happens when logout button is not visible on login page. There is nothing can be done. :( ",
                            Toast.LENGTH_LONG).show();
    
                } else if (session.isCacheError()) {
                    Toast.makeText(getActivity(),
                            "Empty response. Happens randomly not my fault :) Try after some time",
                            Toast.LENGTH_LONG).show();
                    //TODO => Extract method for updating selfcare easily
    
                } else {
                    Toast.makeText(getActivity(), "You are not logged in. Redirecting to login page",
                            Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(REQUEST_DATA));
                    if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                        startActivity(intent);
                    } else {
                        Toast.makeText(getActivity(), "No Browser found", Toast.LENGTH_SHORT).show();
                    }
    
                }
                Log.d("Session Start => ", "" + session.getSessionStart());
                Log.d("Session Duration => ", "" + session.getSessionDuration());
                Log.d("Session Usage => ", "" + session.getSessionUsage());
                Log.d("IsLoggedIn => ", "" + session.isLoggedIn());
                Log.d("LogoutButtonStatus => ", "" + session.isLogoutButtonVisibility());
    
                break;//TODO => Temporary solution to prevent multiple loops
            }
        }
    }