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:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

    /**
     * Generate an "archive" of the data package by parsing and retrieving
     * components of the data package resource map
     * /* w  w  w . j  a v a 2 s  .  c  o  m*/
     * @param scope
     *          The scope value of the data package
     * @param identifier
     *          The identifier value of the data package
     * @param revision
     *          The revision value of the data package
     * @param map
     *          The resource map of the data package
     * @param authToken
     *          The authentication token of the user requesting the archive
     * @param transaction
     *          The transaction id of the request
     * @return The file name of the data package archive
     * @throws Exception
     */
    public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
            AuthToken authToken, String transaction) throws Exception {
    
        String zipName = transaction + ".zip";
        String zipPath = tmpDir + "/";
    
        EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);
    
        StringBuffer manifest = new StringBuffer();
    
        Date now = new Date();
        manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");
    
        DataPackageManager dpm = null;
    
        /*
         * It is necessary to create a temporary file while building the ZIP archive
         * to prevent the client from accessing an incomplete product.
         */
        String tmpName = DigestUtils.md5Hex(transaction);
        File zFile = new File(zipPath + tmpName);
    
        if (zFile.exists()) {
            String gripe = "The resource " + zipName + "already exists!";
            throw new ResourceExistsException(gripe);
        }
    
        try {
            dpm = new DataPackageManager();
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }
    
        FileOutputStream fOut = null;
    
        try {
            fOut = new FileOutputStream(zFile);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    
        if (dpm != null && fOut != null) {
    
            String map = null;
    
            try {
                map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                throw e;
            }
    
            Scanner mapScanner = new Scanner(map);
    
            ZipOutputStream zOut = new ZipOutputStream(fOut);
    
            while (mapScanner.hasNextLine()) {
    
                FileInputStream fIn = null;
                String objectName = null;
                File file = null;
    
                String line = mapScanner.nextLine();
    
                if (line.contains(URI_MIDDLE_METADATA)) {
    
                    try {
                        file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                        objectName = emlPackageId.toString() + ".xml";
                    } catch (ClassNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (SQLException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
    
                    if (file != null) {
                        try {
                            fIn = new FileInputStream(file);
                            Long size = FileUtils.sizeOf(file);
                            manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                        } catch (FileNotFoundException e) {
                            logger.error(e.getMessage());
                            e.printStackTrace();
                        }
                    }
    
                } else if (line.contains(URI_MIDDLE_REPORT)) {
    
                    try {
                        file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                                authToken, userId);
                        objectName = emlPackageId.toString() + ".report.xml";
                    } catch (ClassNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (SQLException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
    
                    if (file != null) {
                        try {
                            fIn = new FileInputStream(file);
                            Long size = FileUtils.sizeOf(file);
                            manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                        } catch (FileNotFoundException e) {
                            logger.error(e.getMessage());
                            e.printStackTrace();
                        }
                    }
    
                } else if (line.contains(URI_MIDDLE_DATA)) {
    
                    String[] lineParts = line.split("/");
                    String entityId = lineParts[lineParts.length - 1];
                    String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                            scope, identifier, revision, null);
                    String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                            identifier, revision, entityId);
    
                    String entityName = null;
                    String xml = null;
    
                    try {
                        entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                        xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                        objectName = dpm.findObjectName(xml, entityName);
                        file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                                userId);
                    } catch (UnauthorizedException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                        manifest.append(objectName + " (access denied)\n");
                    } catch (ResourceNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (SQLException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
    
                    if (file != null) {
                        try {
                            fIn = new FileInputStream(file);
                            Long size = FileUtils.sizeOf(file);
                            manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                        } catch (FileNotFoundException e) {
                            logger.error(e.getMessage());
                            e.printStackTrace();
                        }
                    }
    
                }
    
                if (objectName != null && fIn != null) {
    
                    ZipEntry zipEntry = new ZipEntry(objectName);
    
                    try {
                        zOut.putNextEntry(zipEntry);
    
                        int length;
                        byte[] buffer = new byte[1024];
    
                        while ((length = fIn.read(buffer)) > 0) {
                            zOut.write(buffer, 0, length);
                        }
    
                        zOut.closeEntry();
                        fIn.close();
    
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
    
                }
    
            }
    
            // Create ZIP archive manifest
            File mFile = new File(zipPath + transaction + ".txt");
            FileUtils.writeStringToFile(mFile, manifest.toString());
            ZipEntry zipEntry = new ZipEntry("manifest.txt");
    
            try {
    
                FileInputStream fIn = new FileInputStream(mFile);
                zOut.putNextEntry(zipEntry);
    
                int length;
                byte[] buffer = new byte[1024];
    
                while ((length = fIn.read(buffer)) > 0) {
                    zOut.write(buffer, 0, length);
                }
    
                zOut.closeEntry();
                fIn.close();
    
            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
    
            // Close ZIP archive
            zOut.close();
    
            FileUtils.forceDelete(mFile);
    
        }
    
        File tmpFile = new File(zipPath + tmpName);
        File zipFile = new File(zipPath + zipName);
    
        // Copy hidden ZIP archive to visible ZIP archive, thus making available
        if (!tmpFile.renameTo(zipFile)) {
            String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
            throw new IOException();
        }
    
        return zipName;
    
    }
    

    From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java

    public HashMap<String, Object> processRenewal(CertEnrollmentRequest data, HttpServletRequest request,
            AuthCredentials credentials) throws EBaseException {
        try {// w  ww . ja va 2 s .  c  o m
            if (CMS.debugOn()) {
                HashMap<String, String> params = data.toParams();
                printParameterValues(params);
            }
    
            CMS.debug("RenewalProcessor: processRenewal()");
    
            startTiming("enrollment");
            request.setAttribute("reqType", "renewal");
    
            // in case of renew, "profile" is the orig profile
            // while "renewProfile" is the current profile used for renewal
            String renewProfileId = (this.profileID == null) ? data.getProfileId() : this.profileID;
            CMS.debug("RenewalProcessor: profile: " + renewProfileId);
    
            IProfile renewProfile = ps.getProfile(renewProfileId);
            if (renewProfile == null) {
                CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                        CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
                throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                        CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
            }
            if (!ps.isProfileEnable(renewProfileId)) {
                CMS.debug("RenewalProcessor: Profile " + renewProfileId + " not enabled");
                throw new BadRequestDataException("Profile " + renewProfileId + " not enabled");
            }
    
            BigInteger certSerial = null;
    
            // get serial number from <SerialNumber> element (no auth required)
            CertId serial = data.getSerialNum();
            if (serial != null) {
                CMS.debug("RenewalProcessor: serial number: " + serial);
                certSerial = serial.toBigInteger();
            }
    
            // if not found, get serial number from profile input (no auth required)
            if (certSerial == null) {
    
                IPluginRegistry registry = (IPluginRegistry) CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);
    
                // find SerialNumRenewInput
                for (ProfileInput input : data.getInputs()) {
    
                    String inputId = input.getId();
                    if (inputId == null) {
                        throw new BadRequestException("Missing input ID");
                    }
    
                    String classId = input.getClassId();
                    if (classId == null) {
                        throw new BadRequestException("Missing class ID in input " + inputId);
                    }
    
                    IPluginInfo pluginInfo = registry.getPluginInfo("profileInput", classId);
                    if (pluginInfo == null) {
                        throw new BadRequestException("Unregistered class ID " + classId + " in input " + inputId);
                    }
    
                    String className = pluginInfo.getClassName();
                    if (!SerialNumRenewInput.class.getName().equals(className)) {
                        // check the next input
                        continue;
                    }
    
                    CMS.debug("RenewalProcessor: found SerialNumRenewInput");
                    ProfileAttribute attribute = input.getAttribute(SerialNumRenewInput.SERIAL_NUM);
    
                    if (attribute == null) {
                        throw new BadRequestException(
                                "Missing attribute " + SerialNumRenewInput.SERIAL_NUM + " in input " + inputId);
                    }
    
                    String value = attribute.getValue();
                    CMS.debug("RenewalProcessor: profile input " + SerialNumRenewInput.SERIAL_NUM + " value: "
                            + value);
    
                    if (!StringUtils.isEmpty(value)) {
                        serial = new CertId(value);
                        certSerial = serial.toBigInteger();
                        break;
                    }
                }
            }
    
            // if still not found, get serial number from client certificate (if provided)
            if (certSerial == null) {
    
                if (!request.isSecure()) {
                    throw new BadRequestException("Missing serial number");
                }
    
                // ssl client auth is to be used
                // this is not authentication. Just use the cert to search
                // for orig request and find the right profile
                CMS.debug("RenewalProcessor: get serial number from client certificate");
                certSerial = getSerialNumberFromCert(request);
            }
    
            CMS.debug("processRenewal: serial number of cert to renew:" + certSerial.toString());
            ICertRecord rec = certdb.readCertificateRecord(certSerial);
            if (rec == null) {
                CMS.debug("processRenewal: cert record not found for serial number " + certSerial.toString());
                throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
            }
    
            // check to see if the cert is revoked or revoked_expired
            if ((rec.getStatus().equals(ICertRecord.STATUS_REVOKED))
                    || (rec.getStatus().equals(ICertRecord.STATUS_REVOKED_EXPIRED))) {
                CMS.debug("processRenewal: cert found to be revoked. Serial number = " + certSerial.toString());
                throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_CA_CANNOT_RENEW_REVOKED_CERT"));
            }
    
            X509CertImpl origCert = rec.getCertificate();
            if (origCert == null) {
                CMS.debug("processRenewal: original cert not found in cert record for serial number "
                        + certSerial.toString());
                throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
            }
    
            Date origNotAfter = origCert.getNotAfter();
            CMS.debug("processRenewal: origNotAfter =" + origNotAfter.toString());
    
            String origSubjectDN = origCert.getSubjectDN().getName();
            CMS.debug("processRenewal: orig subj dn =" + origSubjectDN);
    
            IRequest origReq = getOriginalRequest(certSerial, rec);
            if (origReq == null) {
                CMS.debug("processRenewal: original request not found");
                throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
            }
    
            String profileId = origReq.getExtDataInString(IRequest.PROFILE_ID);
            CMS.debug("RenewalSubmitter: renewal original profileId=" + profileId);
    
            String aidString = origReq.getExtDataInString(IRequest.AUTHORITY_ID);
    
            Integer origSeqNum = origReq.getExtDataInInteger(IEnrollProfile.REQUEST_SEQ_NUM);
            IProfile profile = ps.getProfile(profileId);
            if (profile == null) {
                CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                        CMSTemplate.escapeJavaScriptStringHTML(profileId)));
                throw new EBaseException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                        CMSTemplate.escapeJavaScriptStringHTML(profileId)));
            }
            if (!ps.isProfileEnable(profileId)) {
                CMS.debug("RenewalSubmitter: Profile " + profileId + " not enabled");
                throw new BadRequestDataException("Profile " + profileId + " not enabled");
            }
    
            IProfileContext ctx = profile.createContext();
    
            if (aidString != null)
                ctx.set(IEnrollProfile.REQUEST_AUTHORITY_ID, aidString);
    
            IProfileAuthenticator authenticator = renewProfile.getAuthenticator();
            IProfileAuthenticator origAuthenticator = profile.getAuthenticator();
    
            if (authenticator != null) {
                CMS.debug("RenewalSubmitter: authenticator " + authenticator.getName() + " found");
                setCredentialsIntoContext(request, credentials, authenticator, ctx);
            }
    
            // for renewal, this will override or add auth info to the profile context
            if (origAuthenticator != null) {
                CMS.debug("RenewalSubmitter: for renewal, original authenticator " + origAuthenticator.getName()
                        + " found");
                setCredentialsIntoContext(request, credentials, origAuthenticator, ctx);
            }
    
            // for renewal, input needs to be retrieved from the orig req record
            CMS.debug("processRenewal: set original Inputs into profile Context");
            setInputsIntoContext(origReq, profile, ctx, locale);
            ctx.set(IEnrollProfile.CTX_RENEWAL, "true");
            ctx.set("renewProfileId", renewProfileId);
            ctx.set(IEnrollProfile.CTX_RENEWAL_SEQ_NUM, origSeqNum.toString());
    
            // for ssl authentication; pass in servlet for retrieving
            // ssl client certificates
            SessionContext context = SessionContext.getContext();
            context.put("profileContext", ctx);
            context.put("sslClientCertProvider", new SSLClientCertProvider(request));
            CMS.debug("RenewalSubmitter: set sslClientCertProvider");
            if (origSubjectDN != null)
                context.put("origSubjectDN", origSubjectDN);
    
            // before creating the request, authenticate the request
            IAuthToken authToken = null;
            Principal principal = request.getUserPrincipal();
            if (principal instanceof PKIPrincipal)
                authToken = ((PKIPrincipal) principal).getAuthToken();
            if (authToken == null)
                authToken = authenticate(request, origReq, authenticator, context, true, credentials);
    
            // authentication success, now authorize
            authorize(profileId, renewProfile, authToken);
    
            ///////////////////////////////////////////////
            // create and populate requests
            ///////////////////////////////////////////////
            startTiming("request_population");
            IRequest[] reqs = profile.createRequests(ctx, locale);
            populateRequests(data, true, locale, origNotAfter, origSubjectDN, origReq, profileId, profile, ctx,
                    authenticator, authToken, reqs);
            endTiming("request_population");
    
            ///////////////////////////////////////////////
            // submit request
            ///////////////////////////////////////////////
            String errorCode = submitRequests(locale, profile, authToken, reqs);
            String errorReason = null;
    
            List<String> errors = new ArrayList<String>();
            if (errorCode != null) {
                for (IRequest req : reqs) {
                    String error = req.getError(locale);
                    if (error != null) {
                        String code = req.getErrorCode(locale);
                        errors.add(codeToReason(locale, code, error, req.getRequestId()));
                    }
                }
                errorReason = StringUtils.join(errors, '\n');
            }
    
            HashMap<String, Object> ret = new HashMap<String, Object>();
            ret.put(ARG_REQUESTS, reqs);
            ret.put(ARG_ERROR_CODE, errorCode);
            ret.put(ARG_ERROR_REASON, errorReason);
            ret.put(ARG_PROFILE, profile);
    
            CMS.debug("RenewalSubmitter: done serving");
            endTiming("enrollment");
    
            return ret;
        } finally {
            SessionContext.releaseContext();
            endAllEvents();
        }
    }
    

    From source file:com.google.plus.wigwamnow.social.FacebookProvider.java

    /** 
     * Send the <code>access_token</code> to the server for authorization.
     *///  ww  w  . jav  a 2  s . c o  m
    @Override
    public void hybridAuth(Activity activity) {
        String host = activity.getResources().getString(R.string.external_host);
        final String endpoint = host + "/auth/facebook/hybrid.json";
        // Send the Facebook access_token, which is portable, to the server alone with the Date
        // when it expires.
        String fbAccessToken = Session.getActiveSession().getAccessToken();
        Date fbAccessTokenExpires = Session.getActiveSession().getExpirationDate();
        JSONObject params = new JSONObject();
        try {
            params.put("access_token", fbAccessToken);
            params.put("expires_at", fbAccessTokenExpires.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSON Exception", e);
        }
    
        JsonObjectRequest jor = new JsonObjectRequest(com.android.volley.Request.Method.POST, endpoint, params,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject json) {
                        Log.i(TAG, json.toString());
                    }
                }, new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError e) {
                        Log.e(TAG, "FB Auth Error", e);
                    }
                });
        WigwamNow.getQueue().add(jor);
    }
    

    From source file:com.shinymetal.gradereport.AbstractActivity.java

    protected void setRecurringAlarm(Context context, boolean force) {
    
        boolean alarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class),
                PendingIntent.FLAG_NO_CREATE) != null);
    
        if (alarmUp && !force)
            return;/*from w w  w. j av  a  2s.c  o m*/
    
        Intent downloader = new Intent(context, AlarmReceiver.class);
        downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,
                PendingIntent.FLAG_UPDATE_CURRENT);
    
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
        Date firstRun = new Date();
        long mSyncInterval = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this)
                .getString(getString(R.string.pref_sync_key), "15")) * 60000;
    
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstRun.getTime() + 10, mSyncInterval, pendingIntent);
    
        if (BuildConfig.DEBUG)
            Log.d(this.toString(), TS.get() + this.toString() + " Set alarmManager.setRepeating to: "
                    + firstRun.toString() + " interval: " + mSyncInterval);
    }
    

    From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java

    private void verifyTimeWindow(final Map<String, Object> claims) {
    
        Date iatDate = getIatDate(claims);
        Date expDate = getExpDate(claims);
    
        Date currentDate = new Date();
        if (iatDate != null && iatDate.after(currentDate)) {
            throw new InvalidTokenException(String.format(
                    "Token validity window is in the future. Token is issued at [%s]. Current date is [%s]",
                    iatDate.toString(), currentDate.toString()));
        }//  w  w w  . j a  va2s.c  om
    
        if (expDate != null && expDate.before(currentDate)) {
            throw new InvalidTokenException(
                    String.format("Token is expired. Expiration date is [%s]. Current date is [%s]",
                            expDate.toString(), currentDate.toString()));
        }
    }
    

    From source file:edu.hawaii.soest.pacioos.text.FileTextSource.java

    protected boolean execute() {
        log.debug("FileTextSource.execute() called.");
        boolean failed = false; // indicates overall success of execute()
    
        // do not execute the stream if there is no connection
        if (!isConnected())
            return false;
    
        try {/* w  ww.j av a  2s . c  o m*/
    
            // open the data file for monitoring
            FileReader reader = new FileReader(new File(getDataFilePath()));
            this.fileReader = new BufferedReader(reader);
    
            // add channels of data that will be pushed to the server.    
            // Each sample will be sent to the Data Turbine as an rbnb frame.    
            int channelIndex = 0;
    
            long lastSampleTimeAsSecondsSinceEpoch = getLastSampleTime();
    
            // poll the data file for new lines of data and insert them into the RBNB
            while (true) {
                String line = fileReader.readLine();
    
                if (line == null) {
                    Thread.currentThread().sleep(this.pollInterval);
    
                } else {
    
                    // test the line for the expected data pattern
                    boolean valid = this.validateSample(line);
    
                    // if the line matches the data pattern, insert it into the DataTurbine
                    if (valid) {
                        log.debug("This line matches the data line pattern: " + line);
    
                        Date sampleDate = getSampleDate(line);
    
                        if (this.dateFormats == null || this.dateFields == null) {
                            log.warn("Using the default datetime format and field for sample data. "
                                    + "Use the -f and -d options to explicitly set date time fields.");
                        }
                        log.debug("Sample date is: " + sampleDate.toString());
    
                        // convert the sample date to seconds since the epoch
                        long sampleTimeAsSecondsSinceEpoch = (sampleDate.getTime() / 1000L);
    
                        // only insert samples newer than the last sample seen at startup 
                        // and that are not in the future (> 1 hour since the CTD clock
                        // may have drifted)
                        Calendar currentCal = Calendar.getInstance();
                        this.tz = TimeZone.getTimeZone(this.timezone);
                        currentCal.setTimeZone(this.tz);
                        currentCal.add(Calendar.HOUR, 1);
                        Date currentDate = currentCal.getTime();
    
                        if (lastSampleTimeAsSecondsSinceEpoch < sampleTimeAsSecondsSinceEpoch
                                && sampleTimeAsSecondsSinceEpoch < currentDate.getTime() / 1000L) {
    
                            int numberOfChannelsFlushed = 0;
                            try {
                                //insert into the DataTurbine
                                numberOfChannelsFlushed = this.sendSample(line);
    
                            } catch (SAPIException sapie) {
                                // reconnect if an exception is thrown on Flush()
                                log.error("Error while flushing the source: " + sapie.getMessage());
                                failed = true;
    
                            }
    
                            // reset the last sample time to the sample just inserted
                            lastSampleTimeAsSecondsSinceEpoch = sampleTimeAsSecondsSinceEpoch;
                            log.debug("Last sample time is now: "
                                    + (new Date(lastSampleTimeAsSecondsSinceEpoch * 1000L).toString()));
                            log.info(getRBNBClientName() + " Sample sent to the DataTurbine: " + line.trim());
    
                        } else {
                            log.info("The current line is earlier than the last entry "
                                    + "in the Data Turbine or is a date in the future. "
                                    + "Skipping it. The line was: " + line);
    
                        }
    
                    } else {
                        log.info("The current line doesn't match an expected "
                                + "data line pattern. Skipping it.    The line was: " + line);
    
                    }
                } // end if()
            } // end while
    
        } catch (ParseException pe) {
            log.info("There was a problem parsing the sample date string. The message was: " + pe.getMessage());
            failed = true;
            return !failed;
    
        } catch (SAPIException sapie) {
            log.info("There was a problem communicating with the DataTurbine. The message was: "
                    + sapie.getMessage());
            failed = true;
            return !failed;
    
        } catch (InterruptedException ie) {
            log.info("There was a problem while polling the data file. The message was: " + ie.getMessage());
            failed = true;
            return !failed;
    
        } catch (IOException ioe) {
            log.info("There was a problem opening the data file. The message was: " + ioe.getMessage());
            failed = true;
            return !failed;
    
        } finally {
            try {
                this.fileReader.close();
    
            } catch (IOException ioe2) {
                log.error("There was a problem closing the data file. The message was: " + ioe2.getMessage());
    
            }
    
        }
    
    }
    

    From source file:org.cesecore.certificates.util.ValidityDateTest.java

    /** Test the Date the feature was designed for (http://en.wikipedia.org/wiki/Year_2038_problem) */
    @Test/*from w w  w. ja v a  2 s. c o  m*/
    public void testParseCaLatestValidDateTime() {
        LOG.trace(">testParseCaLatestValidDateTime");
        final String bug2038Hex = "80000000";
        LOG.info("bug2038Hex: " + bug2038Hex);
        final String bug2038Iso = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ssZZ", TimeZone.getTimeZone("UTC"))
                .format(Long.parseLong("80000000", 16) * 1000);
        LOG.info("bug2038Iso: " + bug2038Iso);
        final Date bug2038HexDate = ValidityDate.parseCaLatestValidDateTime(bug2038Hex);
        LOG.info("bug2038HexDate: " + bug2038HexDate);
        final Date bug2038IsoDate = ValidityDate.parseCaLatestValidDateTime(bug2038Iso);
        LOG.info("bug2038IsoDate: " + bug2038IsoDate);
        Assert.assertEquals("The two date formats should yield the same Date!", bug2038HexDate, bug2038IsoDate);
        // Test now also
        final Date now = new Date();
        LOG.info("now:        " + now);
        final String nowIso = FastDateFormat
                .getInstance(ValidityDate.ISO8601_DATE_FORMAT, TimeZone.getTimeZone("UTC")).format(now);
        LOG.info("nowIso:     " + nowIso);
        final Date nowIsoDate = ValidityDate.parseCaLatestValidDateTime(nowIso);
        LOG.info("nowIsoDate: " + nowIsoDate);
        // Compare as strings since we will loose milliseconds in the conversion to ISO8601 format
        Assert.assertEquals("Unable to parse current time correctly!", now.toString(), nowIsoDate.toString());
        // Test unhappy path (return of default value)
        final Date defaultIsoDate = ValidityDate.parseCaLatestValidDateTime("COFFEE");
        Assert.assertEquals("Default value not returned when invalid date-time specified!",
                new Date(Long.MAX_VALUE).toString(), defaultIsoDate.toString());
        LOG.trace("<testParseCaLatestValidDateTime");
    }
    

    From source file:sce.RESTAppMetricJob.java

    public void sendEmail(JobExecutionContext context, String email) throws JobExecutionException {
        try {/*from   w  ww  .  j  a v a 2  s .  c  o  m*/
            Date d = new Date();
            String message = "Job was executed at: " + d.toString() + "\n";
            SchedulerMetaData schedulerMetadata = context.getScheduler().getMetaData();
            //Get the scheduler instance id
            message += "Scheduler Instance Id: " + schedulerMetadata.getSchedulerInstanceId() + "\n";
            //Get the scheduler name
            message += "Scheduler Name: " + schedulerMetadata.getSchedulerName() + "\n";
            try {
                //Get the scheduler ip
                Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
                message += "Scheduler IP: ";
                for (; n.hasMoreElements();) {
                    NetworkInterface e = n.nextElement();
                    //System.out.println("Interface: " + e.getName());
                    Enumeration<InetAddress> a = e.getInetAddresses();
                    for (; a.hasMoreElements();) {
                        InetAddress addr = a.nextElement();
                        message += !addr.getHostAddress().equals("127.0.0.1") ? addr.getHostAddress() + " " : "";
                    }
                }
                message += "\n";
            } catch (SocketException e) {
                throw new JobExecutionException(e);
            }
            //Returns the result (if any) that the Job set before its execution completed (the type of object set as the result is entirely up to the particular job).
            //The result itself is meaningless to Quartz, but may be informative to JobListeners or TriggerListeners that are watching the job's execution. 
            message += "Result: " + (context.getResult() != null ? context.getResult() : "") + "\n";
            //Get the unique Id that identifies this particular firing instance of the trigger that triggered this job execution. It is unique to this JobExecutionContext instance as well. 
            message += "Fire Instance Id: "
                    + (context.getFireInstanceId() != null ? context.getFireInstanceId() : "") + "\n";
            //Get a handle to the Calendar referenced by the Trigger instance that fired the Job. 
            message += "Calendar: " + (context.getCalendar() != null ? context.getCalendar().getDescription() : "")
                    + "\n";
            //The actual time the trigger fired. For instance the scheduled time may have been 10:00:00 but the actual fire time may have been 10:00:03 if the scheduler was too busy. 
            message += "Fire Time: " + (context.getFireTime() != null ? context.getFireTime() : "") + "\n";
            //the job name
            message += "Job Name: "
                    + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getName() : "")
                    + "\n";
            //the job group
            message += "Job Group: "
                    + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getGroup() : "")
                    + "\n";
            //The amount of time the job ran for (in milliseconds). The returned value will be -1 until the job has actually completed (or thrown an exception), and is therefore generally only useful to JobListeners and TriggerListeners.
            //message += "RunTime: " + context.getJobRunTime() + "\n";
            //the next fire time
            message += "Next Fire Time: "
                    + (context.getNextFireTime() != null && context.getNextFireTime().toString() != null
                            ? context.getNextFireTime().toString()
                            : "")
                    + "\n";
            //the previous fire time
            message += "Previous Fire Time: "
                    + (context.getPreviousFireTime() != null && context.getPreviousFireTime().toString() != null
                            ? context.getPreviousFireTime().toString()
                            : "")
                    + "\n";
            //refire count
            message += "Refire Count: " + context.getRefireCount() + "\n";
    
            //job data map
            message += "\nJob data map: \n";
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) {
                message += entry.getKey() + " = " + entry.getValue() + "\n";
            }
            Mail.sendMail("SCE notification", message, email, null, null);
        } catch (SchedulerException e) {
            throw new JobExecutionException(e);
        }
    }
    

    From source file:org.akaza.openclinica.bean.extract.odm.ClinicalDataReportBean.java

    protected void addOneDN(DiscrepancyNoteBean dn, String currentIndent) {
        StringBuffer xml = this.getXmlOutput();
        String indent = this.getIndent();
        String nls = System.getProperty("line.separator");
        //Boolean p = s.length()>0||i.length()>0||d.toString().length()>0||n>0 ? true : false;
        xml.append(currentIndent + "<OpenClinica:DiscrepancyNote ");
        if (dn.getOid() != null) {
            String i = dn.getOid();//  w w w .j  a  va  2s  . com
            if (i.length() > 0) {
                xml.append("ID=\"" + StringEscapeUtils.escapeXml(i) + "\" ");
            }
        }
        if (dn.getStatus() != null) {
            String s = dn.getStatus();
            if (s.length() > 0) {
                xml.append("Status=\"" + s + "\" ");
            }
        }
        if (dn.getNoteType() != null) {
            String s = dn.getNoteType();
            if (s.length() > 0) {
                xml.append("NoteType=\"" + s + "\" ");
            }
        }
        if (dn.getDateUpdated() != null) {
            Date d = dn.getDateUpdated();
            if (d.toString().length() > 0) {
                xml.append("DateUpdated=\"" + new SimpleDateFormat("yyyy-MM-dd").format(d) + "\" ");
            }
        }
        if (dn.getEntityName() != null) {
            String s = dn.getEntityName();
            if (s.length() > 0) {
                xml.append("EntityName=\"" + s + "\" ");
            }
        }
        int n = dn.getNumberOfChildNotes();
        if (n > 0) {
            xml.append("NumberOfChildNotes=\"" + dn.getNumberOfChildNotes() + "\"");
        }
        xml.append(">");
        xml.append(nls);
        if (dn.getChildNotes() != null && dn.getChildNotes().size() > 0) {
            for (ChildNoteBean cn : dn.getChildNotes()) {
                xml.append(currentIndent + indent + "<OpenClinica:ChildNote ");
    
                if (cn.getOid() != null) {
                    String s = cn.getOid();
                    if (s.length() > 0) {
                        xml.append("ID=\"" + s + "\" ");
                    }
                }
                if (cn.getStatus() != null) {
                    String s = cn.getStatus();
                    if (s.length() > 0) {
                        xml.append("Status=\"" + s + "\" ");
                    }
                }
                if (cn.getDateCreated() != null) {
                    Date d = cn.getDateCreated();
                    if (d.toString().length() > 0) {
                        xml.append("DateCreated=\"" + new SimpleDateFormat("yyyy-MM-dd").format(d) + "\" ");
                    }
                }
                if (cn.getOwnerUserName() != "") {
                    String ownerUserName = cn.getOwnerUserName();
                    if (ownerUserName.length() > 0) {
                        xml.append("UserName=\"" + ownerUserName + "\" ");
                    }
    
                }
                if (cn.getOwnerFirstName() != "" || cn.getOwnerLastName() != "") {
                    String ownerLastName = cn.getOwnerLastName();
                    String ownerFirstName = cn.getOwnerFirstName();
                    if (ownerLastName.length() > 0 || ownerFirstName.length() > 0) {
                        xml.append("Name=\"" + ownerFirstName + " " + ownerLastName + "\"");
                    }
    
                }
                xml.append(">");
                xml.append(nls);
                if (cn.getDescription() != null) {
                    String dc = cn.getDescription();
                    if (dc.length() > 0) {
                        xml.append(currentIndent + indent + indent + "<OpenClinica:Description>"
                                + StringEscapeUtils.escapeXml(dc) + "</OpenClinica:Description>");
                        xml.append(nls);
                    }
                }
                if (cn.getDetailedNote() != null) {
                    String nt = cn.getDetailedNote();
                    if (nt.length() > 0) {
                        xml.append(currentIndent + indent + indent + "<OpenClinica:DetailedNote>"
                                + StringEscapeUtils.escapeXml(nt) + "</OpenClinica:DetailedNote>");
                        xml.append(nls);
                    }
                }
    
                if (cn.getUserRef() != null) {
                    String uid = cn.getUserRef().getElementDefOID();
                    String userName = cn.getUserRef().getUserName();
                    String fullName = cn.getUserRef().getFullName();
                    String temp = "";
                    if (userName.length() > 0) {
                        temp += " OpenClinica:UserName=\"" + StringEscapeUtils.escapeXml(userName) + "\"";
                    }
                    if (fullName.length() > 0) {
                        temp += " OpenClinica:FullName=\"" + StringEscapeUtils.escapeXml(fullName) + "\"";
                    }
                    if (uid.length() > 0) {
                        xml.append(currentIndent + indent + indent + "<UserRef UserOID=\""
                                + StringEscapeUtils.escapeXml(uid) + " \"" + temp + "/>");
                        xml.append(nls);
                    }
                }
                xml.append(currentIndent + indent + "</OpenClinica:ChildNote>");
                xml.append(nls);
            }
        }
        xml.append(currentIndent + "</OpenClinica:DiscrepancyNote>");
        xml.append(nls);
    }
    

    From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

    /**
     * Process bounces.// www  .j  ava2s.co  m
     *
     * @param protocol the protocol
     * @param host the host
     * @param port the port
     * @param userName the user name
     * @param password the password
     */
    public void processBounces(String protocol, String host, String port, String userName, String password) {
        Properties properties = getServerProperties(protocol, host, port);
        Session session = Session.getDefaultInstance(properties);
    
        List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();
    
        try {
            // connects to the message store
            Store store = session.getStore(protocol);
            System.out.println(userName);
            System.out.println(password);
            System.out.println(userName.length());
            System.out.println(password.length());
            //store.connect(userName, password);
            //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
            store.connect("bojan.dimic@aquest-solutions.com", "bg181076");
    
            // opens the inbox folder
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);
    
            // fetches new messages from server
            Message[] messages = folderInbox.getMessages();
    
            for (int i = 0; i < messages.length; i++) {
                BouncedEmail bouncedEmail = new BouncedEmail();
                Message msg = messages[i];
                Address[] fromAddress = msg.getFrom();
                String from = fromAddress[0].toString();
                String failedAddress = "";
                Enumeration<?> headers = messages[i].getAllHeaders();
                while (headers.hasMoreElements()) {
                    Header h = (Header) headers.nextElement();
                    //System.out.println(h.getName() + ":" + h.getValue());
                    //System.out.println("");                
                    String mID = h.getName();
                    if (mID.contains("X-Failed-Recipients")) {
                        failedAddress = h.getValue();
                    }
                }
                String subject = msg.getSubject();
                String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                String sentDate = msg.getSentDate().toString();
    
                String contentType = msg.getContentType();
                String messageContent = "";
    
                if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                }
    
                String bounceReason = "Unknown reason";
    
                for (BounceCode bounceCode : bounceCodes) {
                    if (messageContent.contains(bounceCode.getCode())) {
                        bounceReason = bounceCode.getExplanation();
                    }
                }
    
                //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
                //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
                //                
                //                // enhanced bounce codes
                //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
                //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
                //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
                //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
                //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
                //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
                //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
                //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
                //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}
    
                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t To: " + toList);
                System.out.println("\t CC: " + ccList);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t X-Failed-Recipients:" + failedAddress);
                System.out.println("\t Content Type:" + contentType);
                System.out.println("\t Bounce reason:" + bounceReason);
                //System.out.println("\t Message: " + messageContent);
    
                bouncedEmail.setEmail_address(failedAddress);
                bouncedEmail.setBounce_reason(bounceReason);
    
                //Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
                //String strDate = date.toString();
                System.out.println(sentDate);
                Date dt = null;
                //Date nd = null;
                try {
                    dt = formatter.parse(sentDate);
                    //nd = sqlFormat.parse(dt.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                System.out.println("Date " + dt.toString());
                //System.out.println("Date " + nd.toString());
                System.out.println(new Timestamp(new Date().getTime()));
                bouncedEmail.setSend_date(dt);
                bouncedEmailDao.saveOrUpdate(bouncedEmail);
            }
    
            // disconnect
            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for protocol: " + protocol);
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        }
    }