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:com.digitalpebble.stormcrawler.bolt.FeedParserBolt.java

    private List<Outlink> parseFeed(String url, byte[] content, Metadata parentMetadata)
            throws MalformedURLException {
        List<Outlink> links = new ArrayList<>();
    
        SyndFeed feed = null;//from   w w  w  . ja v  a2  s .c  om
        try (ByteArrayInputStream is = new ByteArrayInputStream(content)) {
            SyndFeedInput input = new SyndFeedInput();
            feed = input.build(new InputSource(is));
        } catch (Exception e) {
            LOG.error("Exception parsing feed from DOM {}", url);
            return links;
        }
    
        URL sURL = new URL(url);
    
        List<SyndEntry> entries = feed.getEntries();
        for (SyndEntry entry : entries) {
            String targetURL = entry.getLink();
    
            // build an absolute URL
            try {
                targetURL = URLUtil.resolveURL(sURL, targetURL).toExternalForm();
            } catch (MalformedURLException e) {
                LOG.debug("MalformedURLException on {}", targetURL);
                continue;
            }
    
            targetURL = urlFilters.filter(sURL, parentMetadata, targetURL);
    
            if (StringUtils.isBlank(targetURL))
                continue;
    
            Outlink newLink = new Outlink(targetURL);
    
            Metadata targetMD = metadataTransfer.getMetaForOutlink(targetURL, url, parentMetadata);
            newLink.setMetadata(targetMD);
    
            String title = entry.getTitle();
            if (StringUtils.isNotBlank(title)) {
                targetMD.setValue("feed.title", title.trim());
            }
    
            Date publishedDate = entry.getPublishedDate();
            if (publishedDate != null) {
                // filter based on the published date
                if (filterHoursSincePub != -1) {
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.add(Calendar.HOUR, -filterHoursSincePub);
                    if (publishedDate.before(rightNow.getTime())) {
                        LOG.info("{} has a published date {} which is more than {} hours old", targetURL,
                                publishedDate.toString(), filterHoursSincePub);
                        continue;
                    }
                }
                targetMD.setValue("feed.publishedDate", publishedDate.toString());
            }
    
            SyndContent description = entry.getDescription();
            if (description != null && StringUtils.isNotBlank(description.getValue())) {
                targetMD.setValue("feed.description", description.getValue());
            }
    
            links.add(newLink);
        }
    
        return links;
    }
    

    From source file:com.mycompany.CRMFly.hibernateAccess.ContractsDAOImpl.java

    public List getStatisticsForCategoriesOnDates(Date after, Date before) {
        Calendar afterCalendar = prepareDate(after);
        Calendar beforeCalendar = prepareDate(before);
    
        Integer yearDif = beforeCalendar.get(Calendar.YEAR) - afterCalendar.get(Calendar.YEAR);
        Integer monthDif = beforeCalendar.get(Calendar.MONTH) - afterCalendar.get(Calendar.MONTH) + yearDif * 12;
        List<Statistics> stat = new ArrayList<Statistics>();
    
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        List<Object[]> res = new ArrayList<Object[]>();
    
        for (int i = 0; i < monthDif + 1; i++) {
            if (monthDif == 0) {
    
            } else {// w  w  w  .j a  v  a 2s . co m
                if (i == 0) {
                    afterCalendar.setTime(beforeCalendar.getTime());
                    afterCalendar.set(Calendar.DAY_OF_MONTH, 1);
                } else if (i == monthDif) {
                    beforeCalendar.setTime(afterCalendar.getTime());
                    afterCalendar.setTime(after);
                } else {
                    beforeCalendar.setTime(afterCalendar.getTime());
                    afterCalendar.add(Calendar.MONTH, -1);
                }
    
            }
            Date afterNew = afterCalendar.getTime();
            Date beforeNew = beforeCalendar.getTime();
            String afterString = afterNew.toString().substring(4, 7);
    
            Query query = sess.createQuery("select contr.type||'s - '||'" + afterString
                    + "', sum(contracts.totalSum), " + "avg(contracts.totalSum), count(contracts) "
                    + "from com.mycompany.CRMFly.entities.Contracts contracts "
                    + "inner join contracts.contragents " + "contr where "
                    + "contracts.begin_date between :date1 and :date2 " + "group by contr.type");
            query.setParameter("date1", afterNew);
            query.setParameter("date2", beforeNew);
            List list = query.list();
            if (list != null && list.size() != 0) {
                for (Iterator it = list.iterator(); it.hasNext();) {
                    Object[] row = (Object[]) it.next();
                    stat.add(new Statistics(row));
                }
            }
        }
        return stat;
    
    }
    

    From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

    public void updateUserStatus(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");
        String userStatus = request.getParameter("t");
        String statusId = request.getParameter("d");
    
        log.debug("userStatus: " + userStatus);
        log.debug("statusId: " + statusId);
    
        Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
        if (twitter == null) {
            // no connection
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;/*w  w  w.j av  a 2  s.c o  m*/
        }
    
        try {
            Status status = null;
    
            // update user status
            if (StringUtils.isNotBlank(statusId)) {
                status = twitter.updateStatus(userStatus, Long.parseLong(statusId));
            } else {
                status = twitter.updateStatus(userStatus);
            }
            if (status == null) {
                log.error("Status is null.");
                // general error
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
    
            JSONObject json = new JSONObject();
            JSONObject statusJSON = getStatusJSON(twitter, status);
    
            User currentUser = twitter.showUser(twitter.getId());
            Status lastUserStatus = currentUser.getStatus();
    
            // return as an array even though only it contains only one element, 
            // so we can reuse the same Trimpath template (Denny)
            JSONArray statusList = new JSONArray();
            statusList.add(statusJSON);
            json.put("statusList", statusList);
            lastRefreshed = Calendar.getInstance().getTime().toString();
    
            if (lastRefreshed == null) {
                json.element("lastRefreshed", "unable to retrieve last refreshed");
            } else {
                json.element("lastRefreshed", lastRefreshed.toString());
            }
    
            if (lastUserStatus == null) {
                json.element("lastStatusUpdate", "unable to retrieve last status");
            } else {
                Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                json.element("lastStatusUpdate", lastStatusUpdate.toString());
    
            }
    
            if (log.isDebugEnabled()) {
                log.debug(json.toString(2));
            }
    
            out.print(json.toString());
    
        } 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);
            }
        }
    }
    

    From source file:uk.ac.soton.itinnovation.sad.service.controllers.ProvController.java

    @RequestMapping(method = RequestMethod.POST, value = "/video")
    @ResponseBody/*from ww w .java 2  s  .  co  m*/
    public JsonResponse reportVideoAction(@RequestBody final String inputData) throws InterruptedException {
    
        logger.debug("Video action received: " + inputData);
    
        try {
            JSONObject inputDataAsJSON = (JSONObject) JSONSerializer.toJSON(inputData);
            JSONObject response = new JSONObject();
    
            logger.debug(inputDataAsJSON.toString(2));
    
            if (!inputDataAsJSON.containsKey("video_url")) {
                response.put("message", "Missing field \'video_url\' in request data");
                return new JsonResponse("error", response);
            }
    
            if (!inputDataAsJSON.containsKey("action")) {
                response.put("message", "Missing field \'action\' in request data");
                return new JsonResponse("error", response);
            }
    
            if (!inputDataAsJSON.containsKey("timestamp")) {
                response.put("message", "Missing field \'timestamp\' in request data");
                return new JsonResponse("error", response);
            }
    
            if (!inputDataAsJSON.containsKey("user_id")) {
                response.put("message", "Missing field \'user_id\' in request data");
                return new JsonResponse("error", response);
            }
    
            if (!inputDataAsJSON.containsKey("user_name")) {
                response.put("message", "Missing field \'user_name\' in request data");
                return new JsonResponse("error", response);
            }
    
            Long timeStamp_long = inputDataAsJSON.getLong("timestamp");
            Date timeStamp = new Date(timeStamp_long);
            String user_id = inputDataAsJSON.getString("user_id");
            String user_name = inputDataAsJSON.getString("user_name");
            String video_url = inputDataAsJSON.getString("video_url");
    
            if (inputDataAsJSON.getString("action").equals("play")) {
                ProvVideo video = new ProvVideo(video_url, "playVideo", user_id, user_name, "", timeStamp_long);
                provEMClient.reportActionByPerson(video);
                logger.debug("Video: " + video_url + ", action: PLAY, timestamp: " + timeStamp.toString()
                        + ", by USER ID [" + user_id + "]");
                provEMClient.pushActionTakenMeasurementToEcc("playVideo");
            } else {
    
                if (!inputDataAsJSON.containsKey("pause_time")) {
                    response.put("message", "Missing field \'pause_time\' in request data for 'pause' action");
                    return new JsonResponse("error", response);
                }
    
                String pause_time = inputDataAsJSON.getString("pause_time");
                ProvVideo video = new ProvVideo(video_url, "pauseVideo", user_id, user_name, pause_time,
                        timeStamp_long);
    
                provEMClient.reportActionByPerson(video);
                logger.debug("Video: " + video_url + ", action: PAUSE, timestamp: " + timeStamp.toString()
                        + ", PAUSED AT: " + pause_time + ", by USER ID [" + user_id + "]");
                provEMClient.pushActionTakenMeasurementToEcc("pauseVideo");
            }
    
            if (inputDataAsJSON.containsKey("res")) {
                String resolution = inputDataAsJSON.getString("res");
                logger.debug("Pushing resolution measurement to ECC: " + resolution);
                provEMClient.pushVideoQualityMeasurementToEcc(resolution);
            }
    
            return new JsonResponse("ok", response);
    
        } catch (Throwable ex) {
            return new JsonResponse("error",
                    Util.dealWithException("Failed to execute reportVideoAction method", ex, logger));
        }
    
    }
    

    From source file:fr.steren.climbtracker.MobileDataLayerListenerService.java

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        Log.d(TAG, "onDataChanged: " + dataEvents);
        final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
        dataEvents.close();//w  w  w  .  ja v  a  2s  . c o  m
    
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        String gradeSystemType = sharedPref.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);
    
        Location lastLocation = null;
    
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
    
        for (DataEvent event : events) {
            Log.d(TAG, "Event: " + event.getDataItem().toString());
            Uri uri = event.getDataItem().getUri();
            String path = uri.getPath();
    
            if (path.startsWith(Path.CLIMB)) {
                DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                String routeGradeLabel = dataMapItem.getDataMap().getString(Path.ROUTE_GRADE_LABEL_KEY);
                Date climbDate = new Date(dataMapItem.getDataMap().getLong(Path.CLIMB_DATE_KEY));
    
                // check that climb date and location date are not too far, do not save location if so.
                double latitude = 0;
                double longitude = 0;
                if (lastLocation != null
                        && Math.abs(lastLocation.getTime() - climbDate.getTime()) < MAX_TIME_FOR_LOCATION) {
                    latitude = lastLocation.getLatitude();
                    longitude = lastLocation.getLongitude();
                }
    
                if (routeGradeLabel != null) {
                    Log.d(TAG, "New Climb, grade : " + routeGradeLabel + " " + climbDate.toString());
    
                    AuthData authData = mFirebaseRef.getAuth();
                    if (authData != null) {
                        Climb newClimb = new Climb(climbDate, routeGradeLabel, gradeSystemType, latitude,
                                longitude);
                        mFirebaseRef.child("users").child(authData.getUid()).child("climbs").push()
                                .setValue(newClimb);
                    }
                }
            }
        }
    }
    

    From source file:org.apache.cassandra.tools.Shuffle.java

    /**
     * Print a list of pending token relocations for all nodes.
     *
     * @throws ShuffleError/*from  w  w  w . jav  a 2 s.  c  om*/
     */
    public void ls() throws ShuffleError {
        Map<String, List<CqlRow>> queuedRelocations = listRelocations();
        IPartitioner<?> partitioner = getPartitioner(thriftHost, thriftPort, thriftFramed);
        boolean justOnce = false;
    
        for (String host : queuedRelocations.keySet()) {
            for (CqlRow row : queuedRelocations.get(host)) {
                assert row.getColumns().size() == 2;
    
                if (!justOnce) {
                    writeln("%-42s %-15s %s", "Token", "Endpoint", "Requested at");
                    writeln("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    justOnce = true;
                }
    
                ByteBuffer tokenBytes = ByteBuffer.wrap(row.getColumns().get(0).getValue());
                ByteBuffer requestedAt = ByteBuffer.wrap(row.getColumns().get(1).getValue());
                Date time = TimestampSerializer.instance.deserialize(requestedAt);
                Token<?> token = partitioner.getTokenFactory().fromByteArray(tokenBytes);
    
                writeln("%-42s %-15s %s", token.toString(), host, time.toString());
            }
        }
    }
    

    From source file:com.example.GWTOAuthLoginDemo.client.GWTOAuthLoginDemo.java

    public void log(String msg) {
        if (appScreen == null) {
            return;//  w ww  . jav  a2  s  .c  o m
        }
        TextArea logTextArea = appScreen.getTextArea();
        Date d = new Date();
        String t = d.toString() + ": " + msg;
        int cW = logTextArea.getCharacterWidth();
        String currentText = logTextArea.getText();
        if (currentText.length() > 0) {
            logTextArea.setText(currentText + "\n" + t);
        } else {
            logTextArea.setText(t);
    
        }
        appScreen.getScrollPanel().scrollToBottom();
        Log.debug(msg);
    }
    

    From source file:com.mycompany.CRMFly.hibernateAccess.ContractsDAOImpl.java

    public List getStatisticsOnContractsForDates(Date after, Date before) {
        Calendar afterCalendar = prepareDate(after);
        Calendar beforeCalendar = prepareDate(before);
        //   after = afterCalendar.getTime();
        //   before = beforeCalendar.getTime();
        Integer yearDif = beforeCalendar.get(Calendar.YEAR) - afterCalendar.get(Calendar.YEAR);
        Integer monthDif = beforeCalendar.get(Calendar.MONTH) - afterCalendar.get(Calendar.MONTH) + yearDif * 12;
        List<Statistics> stat = new ArrayList<Statistics>();
    
        org.hibernate.Session sess = sessionFactory.getCurrentSession();
        sess.enableFetchProfile("contracts-with-clients");
        List<Object[]> res = new ArrayList<Object[]>();
        //   afterCalendar = prepareDate(before);
        //    afterCalendar.add(Calendar.MONTH, -1);
        for (int i = 0; i < monthDif + 1; i++) {
            if (monthDif == 0) {
    
            } else {//from ww  w .jav  a2 s .  c om
                if (i == 0) {
                    afterCalendar.setTime(beforeCalendar.getTime());
                    afterCalendar.set(Calendar.DAY_OF_MONTH, 1);
                } else if (i == monthDif) {
                    beforeCalendar.setTime(afterCalendar.getTime());
                    afterCalendar.setTime(after);
                } else {
                    beforeCalendar.setTime(afterCalendar.getTime());
                    afterCalendar.add(Calendar.MONTH, -1);
                }
    
            }
            //   beforeCalendar.add(Calendar.MONTH, -1);
            //    afterCalendar.add(Calendar.MONTH, -1);
            Date afterNew = afterCalendar.getTime();
            Date beforeNew = beforeCalendar.getTime();
            String afterString = afterNew.toString().substring(4, 7);
    
            /*  List results = sess.createCriteria(Contracts.class)
              .add( Restrictions.between("begin_date", after, before) )
             .setProjection( Projections.projectionList()
              .add( Projections.sum("totalSum") )
              .add( Projections.avg("totalSum") )
             .add( Projections.rowCount() )
             //.add( Projections.max("totalSum") )
                     
             ).list();*/
            Query query = sess.createQuery("select '" + afterString + "', sum(contracts.totalSum), "
                    + "avg(contracts.totalSum), count(contracts) "
                    + "from com.mycompany.CRMFly.entities.Contracts contracts "
                    + " where contracts.begin_date between :date1 and :date2");
            query.setParameter("date1", afterNew);
            query.setParameter("date2", beforeNew);
            List list = query.list();
            if (list != null && list.size() != 0) {
                for (Iterator it = list.iterator(); it.hasNext();) {
                    Object[] row = (Object[]) it.next();
                    stat.add(new Statistics(row));
                }
            }
        }
        return stat;
    
    }
    

    From source file:org.alfresco.module.org_alfresco_module_rm.script.TransferReportPost.java

    /**
     * Generates the JSON to represent the given record.
     *
     * @param writer Writer to write to/*from   ww w .j a v a 2s. c  o m*/
     * @param recordNode Record being transferred
     * @throws IOException
     */
    protected void generateTransferRecordHTML(Writer writer, NodeRef recordNode) throws IOException {
        writer.write("<div class=\"record\">\n");
        writer.write("  <span class=\"nodeName\">");
        writer.write(StringEscapeUtils
                .escapeHtml((String) this.nodeService.getProperty(recordNode, ContentModel.PROP_NAME)));
        writer.write("</span>&nbsp;(Unique Record Identifier:&nbsp;");
        writer.write(StringEscapeUtils.escapeHtml(
                (String) this.nodeService.getProperty(recordNode, RecordsManagementModel.PROP_IDENTIFIER)));
        writer.write(")");
    
        if (this.nodeService.hasAspect(recordNode, RecordsManagementModel.ASPECT_DECLARED_RECORD)) {
            Date declaredOn = (Date) this.nodeService.getProperty(recordNode,
                    RecordsManagementModel.PROP_DECLARED_AT);
            writer.write(" declared by ");
            writer.write(StringEscapeUtils.escapeHtml(
                    (String) this.nodeService.getProperty(recordNode, RecordsManagementModel.PROP_DECLARED_BY)));
            writer.write(" on ");
            writer.write(StringEscapeUtils.escapeHtml(declaredOn.toString()));
        }
    
        writer.write("\n</div>\n");
    }
    

    From source file:ch.agent.crnickl.demo.stox.Chart.java

    private TimeSeries convertToJFCTimeSeries(boolean interpolate, String name, TimeAddressable<Double> ts)
            throws KeyedException {
        Constructor<? extends RegularTimePeriod> constructor = getPeriodConstructor(ts.getTimeDomain());
        TimeSeries timeSeries = new TimeSeries(name);
        for (Observation<Double> obs : ts) {
            Double value = obs.getValue();
            if (ts.isMissing(value)) {
                if (interpolate)
                    continue;
            }/*from  ww w .  j  a  v a 2  s.  c  om*/
            Date date = JavaDateUtil.toJavaDate(obs.getTime());
            RegularTimePeriod period = null;
            try {
                period = constructor.newInstance(date);
            } catch (Exception e) {
                throw K.JFC_PERIOD_ERR.exception(e, date.toString());
            }
            timeSeries.add(period, value);
        }
        return timeSeries;
    }