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.hihframework.core.utils.DateUtils.java

    /**
     * ??2004-07-28 ?//from  w ww .  java2 s  .c o m
     *
     * @param date 
     * @return ?
     */
    public static String getDayWeek(java.sql.Date date) {
    
        String days[] = { "", "", "", "", "", "",
                "" };
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.setFirstDayOfWeek(Calendar.SUNDAY);
    
        return date.toString() + " " + days[cale.get(Calendar.DAY_OF_WEEK) - 1];
    }
    

    From source file:HttpEventCollector_Log4j2Test.java

    /**
     * sending a message via httplogging using log4j2 to splunk
     *//*  w  w w  .  j  av a2 s  .c om*/
    @Test
    public void canSendEventUsingLog4j2() throws Exception, IOException, InterruptedException {
        TestUtil.enableHttpEventCollector();
        String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName);
        String loggerName = "splunkLogger4j2";
        HashMap<String, String> userInputs = new HashMap<String, String>();
        userInputs.put("user_logger_name", loggerName);
        userInputs.put("user_httpEventCollector_token", token);
        org.apache.logging.log4j.core.LoggerContext context = TestUtil
                .resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs);
        //use httplogger
        List<String> msgs = new ArrayList<String>();
    
        Date date = new Date();
        String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}",
                date.toString());
    
        Logger logger = context.getLogger(loggerName);
        logger.info(jsonMsg);
        msgs.add(jsonMsg);
    
        jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date.toString());
        logger.error(jsonMsg);
        msgs.add(jsonMsg);
    
        TestUtil.verifyEventsSentToSplunk(msgs);
    
        TestUtil.deleteHttpEventCollectorToken(httpEventCollectorName);
        System.out.println("====================== Test pass=========================");
    }
    

    From source file:HttpEventCollector_Log4j2Test.java

    /**
     * sending a message via httplogging using log4j2 to splunk and set index, source and sourcetype
     *//*from w  w  w  . j  av a 2 s.c  o  m*/
    @Test
    public void canSendEventUsingLog4j2WithOptions() throws Exception, IOException, InterruptedException {
    
        String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName);
        String loggerName = "splunkLogger4j2WithOptions";
        HashMap<String, String> userInputs = new HashMap<String, String>();
        userInputs.put("user_logger_name", loggerName);
        userInputs.put("user_httpEventCollector_token", token);
        userInputs.put("user_index", "main");
        userInputs.put("user_host", "host.example.com");
        userInputs.put("user_source", "splunktest");
        userInputs.put("user_sourcetype", "battlecat");
    
        org.apache.logging.log4j.core.LoggerContext context = TestUtil
                .resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs);
        //use httplogger
        List<String> msgs = new ArrayList<String>();
    
        Date date = new Date();
        String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}",
                date.toString());
    
        Logger logger = context.getLogger(loggerName);
        logger.info(jsonMsg);
        msgs.add(jsonMsg);
    
        jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date.toString());
        logger.error(jsonMsg);
        msgs.add(jsonMsg);
    
        TestUtil.verifyEventsSentToSplunk(msgs);
    
        TestUtil.deleteHttpEventCollectorToken(httpEventCollectorName);
        System.out.println("====================== Test pass=========================");
    }
    

    From source file:eu.cloud4soa.frontend.commons.server.services.soa.MonitoringServiceImpl.java

    private Map<MonitoringMetricType, List<IMonitoringMetric>> getMonitoringStatisticsWhithinRangeLimited(
            String applicationUriId, String paasOfferingId, Date start, Date end, int maxResults,
            int monitoringMaxNumDisplayableValues) {
        logger.debug("Getting monitoring statistics for application " + applicationUriId + " between dates "
                + start.toString() + " and " + end.toString() + " with maxResults " + maxResults);
    
        Map<MonitoringMetricType, List<IMonitoringMetric>> tempResult = new HashMap<MonitoringMetricType, List<IMonitoringMetric>>();
    
        try {// w  w w .j a  v  a  2 s  .c o m
            //Getting statistics 
            //Obtaining supported metrics
            List<ServiceQualityInstance> sms = monitoringModule.getSupportedMetrics(paasOfferingId);
            List<MonitoringMetricType> supportedMetrics = translateServiceQualityInstance(sms);
    
            for (MonitoringMetricType supportedMetric : supportedMetrics) {
                List<IMonitoringMetric> metrics = getMonitoringMetricsWhithinRangeLimited(applicationUriId,
                        supportedMetric, start, end, maxResults, monitoringMaxNumDisplayableValues);
                tempResult.put(supportedMetric, metrics);
            }
    
        } catch (SOAException e) {
            String msg = "Error in getMonitoringStatisticsWhithinRangeLimited for application " + applicationUriId;
            logger.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    
        //Processing metrics 
        Map<MonitoringMetricType, List<IMonitoringMetric>> result = new HashMap<MonitoringMetricType, List<IMonitoringMetric>>();
        for (MonitoringMetricType type : tempResult.keySet()) {
            List<IMonitoringMetric> metrics = tempResult.get(type);
    
            // Invert (time scale).
            metrics = invertTimeScale(metrics);
    
            // Filtering not valid statistics
            metrics = filterNotValidMetrics(metrics);
    
            // Resampling statistics
            metrics = resamplingStatistics(metrics, monitoringMaxNumDisplayableValues);
    
            result.put(type, metrics);
        }
    
        return result;
    }
    

    From source file:eu.cloud4soa.frontend.commons.server.services.soa.MonitoringServiceImpl.java

    public List<IMonitoringMetric> getMonitoringMetricsWhithinRangeLimited(String applicationUriId,
            MonitoringMetricType metricKey, Date start, Date end, int maxResults,
            int monitoringMaxNumDisplayableValues) {
        logger.debug("Getting monitoring metrics for application " + applicationUriId + " and metric " + metricKey
                + " between dates " + start.toString() + " and " + end.toString() + " with maxResults "
                + maxResults);/*w ww .ja va 2  s .  c o  m*/
    
        List<eu.cloud4soa.api.governance.monitoring.IMonitoringMetric> monitoringMetrics;
        try {
            monitoringMetrics = monitoringModule.getMonitoringMetricsWhithinRangeLimited(applicationUriId,
                    getMetricKey(metricKey), start, end, maxResults);
    
            return translateMonitoringMetrics(metricKey, monitoringMetrics);
        } catch (SOAException e) {
            String msg = "Error in getMonitoringStatisticsWhithinRangeLimited for application " + applicationUriId;
            logger.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }
    

    From source file:cc.arduino.mvd.services.XivelyService.java

    private JSONObject createPayload(String code, String pin, String value) throws JSONException {
        JSONObject root = new JSONObject();
    
        Date d = Calendar.getInstance(Locale.getDefault()).getTime();
    
        JSONObject datapoint = new JSONObject();
        datapoint.put("at", d.toString());
        datapoint.put("value", value);
    
        JSONArray datapoints = new JSONArray();
        datapoints.put(datapoint);/*  w w  w  .j  av  a2 s  .  c  o  m*/
    
        JSONObject datastream = new JSONObject();
        datastream.put("id", code + "+" + pin);
        datastream.put("datapoints", datapoints);
    
        JSONArray datastreams = new JSONArray();
        datastreams.put(datastream);
    
        root.put("version", "1.0.0");
        root.put("datastreams", datastreams);
    
        return root;
    }
    

    From source file:org.codice.ddf.registry.transformer.RegistryTransformerTest.java

    @Test
    public void testFullRegistryPackage() throws Exception {
        MetacardImpl metacard = convert("/csw-full-registry-package.xml");
    
        Date date = Date.from(ZonedDateTime.parse("2015-11-01T06:15:30-07:00").toInstant());
        assertThat(RegistryUtility.getStringAttribute(metacard, Core.CREATED, null), is(date.toString()));
    
        date = Date.from(ZonedDateTime.parse("2015-11-01T13:15:30Z").toInstant());
        assertThat(RegistryUtility.getStringAttribute(metacard, DateTime.START, null), is(date.toString()));
    
        date = Date.from(ZonedDateTime.parse("2015-12-01T23:01:40Z").toInstant());
        assertThat(RegistryUtility.getStringAttribute(metacard, DateTime.END, null), is(date.toString()));
    
        date = Date.from(ZonedDateTime.parse("2016-01-26T17:16:34.996Z").toInstant());
        assertThat(RegistryUtility.getStringAttribute(metacard, Core.MODIFIED, null), is(date.toString()));
    
        assertThat(RegistryUtility.getStringAttribute(metacard, RegistryObjectMetacardType.LINKS, null),
                is("https://some/link/to/my/repo"));
    
        assertThat(RegistryUtility.getStringAttribute(metacard, Core.LOCATION, null),
                is("POINT (112.267472 33.467944)"));
        assertThat(RegistryUtility.getStringAttribute(metacard, RegistryObjectMetacardType.REGION, null),
                is("USA"));
    
        List<String> attributeValuesList = RegistryUtility.getListOfStringAttribute(metacard,
                RegistryObjectMetacardType.DATA_SOURCES);
        assertThat(attributeValuesList.size(), is(2));
        assertThat(attributeValuesList, hasItem("youtube"));
        assertThat(attributeValuesList, hasItem("myCamera"));
    
        attributeValuesList = RegistryUtility.getListOfStringAttribute(metacard, Topic.KEYWORD);
        assertThat(attributeValuesList.size(), is(2));
        assertThat(attributeValuesList, hasItem("video"));
        assertThat(attributeValuesList, hasItem("sensor"));
    
        assertThat(RegistryUtility.getStringAttribute(metacard, RegistryObjectMetacardType.SECURITY_LEVEL, null),
                is("role=guest"));
        assertThat(RegistryUtility.getStringAttribute(metacard, Metacard.TITLE, null), is("Node Name"));
        assertThat(RegistryUtility.getStringAttribute(metacard, Metacard.DESCRIPTION, null),
                is("A little something describing this node in less than 1024 characters"));
        assertThat(RegistryUtility.getStringAttribute(metacard, Metacard.CONTENT_TYPE_VERSION, null), is("2.9.x"));
    
        attributeValuesList = RegistryUtility.getListOfStringAttribute(metacard,
                RegistryObjectMetacardType.SERVICE_BINDING_TYPES);
        assertThat(attributeValuesList.size(), is(2));
        assertThat(attributeValuesList, hasItem("Csw_Federated_Source"));
        assertThat(attributeValuesList, hasItem("soap13"));
    
        attributeValuesList = RegistryUtility.getListOfStringAttribute(metacard,
                RegistryObjectMetacardType.SERVICE_BINDINGS);
        assertThat(attributeValuesList.size(), is(2));
        assertThat(attributeValuesList, hasItem("REST"));
        assertThat(attributeValuesList, hasItem("SOAP"));
    
        assertThat(RegistryUtility.getStringAttribute(metacard, Contact.POINT_OF_CONTACT_NAME, null), is("Codice"));
        assertThat(RegistryUtility.getListOfStringAttribute(metacard, Contact.POINT_OF_CONTACT_ADDRESS),
                hasItem("1234 Some Street, Phoenix, AZ 85037, USA"));
        assertThat(RegistryUtility.getListOfStringAttribute(metacard, Contact.POINT_OF_CONTACT_PHONE),
                hasItem("(555) 555-5555 ext 1234"));
        assertThat(RegistryUtility.getListOfStringAttribute(metacard, Contact.POINT_OF_CONTACT_EMAIL),
                hasItem("emailaddress@something.com"));
        assertThat(RegistryUtility.getStringAttribute(metacard, Metacard.POINT_OF_CONTACT, null),
                is("john doe, (111) 111-1111 ext 1234, emailaddress@something.com"));
    }
    

    From source file:org.mitre.openid.connect.web.AuthenticationTimeStamper.java

    /**
     * Set the timestamp on the session to mark when the authentication happened,
     * useful for calculating authentication age. This gets stored in the sesion
     * and can get pulled out by other components.
     *//*w ww  . j  a  va 2 s.c o m*/
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
    
        Date authTimestamp = new Date();
    
        HttpSession session = request.getSession();
    
        session.setAttribute(AUTH_TIMESTAMP, authTimestamp);
    
        if (session.getAttribute(AuthorizationRequestFilter.PROMPT_REQUESTED) != null) {
            session.setAttribute(AuthorizationRequestFilter.PROMPTED, Boolean.TRUE);
            session.removeAttribute(AuthorizationRequestFilter.PROMPT_REQUESTED);
        }
    
        logger.info("Successful Authentication of " + authentication.getName() + " at " + authTimestamp.toString());
    
        super.onAuthenticationSuccess(request, response, authentication);
    
    }
    

    From source file:edu.lternet.pasta.portal.HarvestReport.java

    private String reportIdFormatter(String reportId) {
    
        String newId;//from  ww  w.  ja  v  a  2  s  .c  om
    
        if (reportId != null) {
            String tokens[] = reportId.split("-");
            Integer length = tokens.length;
    
            Long epoch = Long.valueOf(tokens[length - 1]);
    
            Time time = new Time(epoch);
            Date date = new Date(epoch);
    
            newId = date.toString();
    
            return newId + " (" + tokens[1] + ")";
        } else {
            return "";
        }
    }
    

    From source file:loadTest.LoadTestIT.java

    @DirtiesContext
    @Test(dataProvider = "loadTestDataProvider")
    public void loadTest(LoadTestConfigModel ltModel) throws Exception {
    
        //validate context
        PieShareAppService appService = this.applicationContext.getBean(PieShareAppService.class);
        Assert.assertNotNull(appService);//ww  w  .ja v a 2s .com
    
        String userName = "testUser";
        PieUser user = this.applicationContext.getBean("pieUser", PieUser.class);
        ClusterManagementService service = this.applicationContext.getBean(ClusterManagementService.class);
    
        PlainTextChannel loadTestChannel = this.applicationContext.getBean(PlainTextChannel.class);
        loadTestChannel.setChannelId("loadTest");
        service.registerChannel("loadTest", loadTestChannel);
    
        counter = this.applicationContext.getBean(ITTasksCounter.class);
    
        if (LUtil.IsMaster()) {
            comparer = this.applicationContext.getBean(LFileComparer.class);
    
            if (LUtil.UseDocker()) {
                INetworkService networkService = this.applicationContext.getBean(NetworkService.class);
                networkService.setNicDisplayName("docker0");
                //start slave nodes
                for (int i = 1; i < ltModel.getNodeCount(); i++) {
                    if (!lUtil.startDockerSlave(ltModel)) {
                        i--;
                    }
                }
            }
        }
    
        PieShareConfiguration config = user.getPieShareConfiguration();
        config.setPwdFile(new File("./loadTest/pwdFile"));
        config.setTmpDir(new File("./loadTest/tmpDir"));
        config.setWorkingDir(new File("./loadTest/workingDir"));
    
        LoginTask task = this.applicationContext.getBean(LoginTask.class);
    
        LoginCommand command = new LoginCommand();
        PlainTextPassword pwd = new PlainTextPassword();
        pwd.password = "test".getBytes();
        command.setPlainTextPassword(pwd);
        command.setUserName(userName);
    
        IPieExecutorTaskFactory executorFactory = this.applicationContext.getBean("pieExecutorTaskFactory",
                PieExecutorTaskFactory.class);
    
        if (LUtil.IsMaster()) {
            executorFactory.registerTaskProvider(AllFilesCompleteMessage.class,
                    new Provider<AllFilesCompleteTask>() {
    
                        @Override
                        public AllFilesCompleteTask get() {
                            return new AllFilesCompleteTask();
                        }
                    });
            executorFactory.registerTaskProvider(ClientIsUpMessage.class, new Provider<ClientIsUpTask>() {
    
                @Override
                public ClientIsUpTask get() {
                    return new ClientIsUpTask();
                }
            });
        } else {
            executorFactory.registerTaskProvider(AllClientsDoneMessage.class, new Provider<AllClientsDoneTask>() {
    
                @Override
                public AllClientsDoneTask get() {
                    return new AllClientsDoneTask();
                }
            });
            executorFactory.registerTaskProvider(MasterIsReadyMessage.class, new Provider<MasterIsReadyTask>() {
    
                @Override
                public MasterIsReadyTask get() {
                    return new MasterIsReadyTask();
                }
            });
        }
    
        command.setCallback(new ILoginFinished() {
    
            @Override
            public void error(Exception ex) {
                Assert.fail(ex.getMessage());
            }
    
            @Override
            public void wrongPassword(WrongPasswordException ex) {
                Assert.fail(ex.getMessage());
            }
    
            @Override
            public void OK() {
            }
        });
    
        if (LUtil.IsMaster()) {
            user.getPieShareConfiguration().getWorkingDir().mkdirs();
            System.out.println("Creating files!");
            for (int i = 0; i < ltModel.getFileCount(); i++) {
                String fileName = String.format("testFile_%s", i);
                File file = new File(user.getPieShareConfiguration().getWorkingDir(), fileName);
                TestFileUtils.createFile(file, ltModel.getFileSize());
            }
    
            System.out.println("Files successfully created!");
            PieLogger.info(this.getClass(), "Files successfully created!");
        }
    
        //this block syncs master and client nodes so test starts when all ready
        if (LUtil.IsMaster()) {
            while (counter.getCount(ClientIsUpTask.class) < ltModel.getNodeCount() - 1) {
                Thread.sleep(2000);
                PieLogger.debug(this.getClass(), String.format("Waiting for nodes to start up! Missing nodes: %s",
                        ltModel.getNodeCount() - 1 - counter.getCount(ClientIsUpTask.class)));
            }
    
            MasterIsReadyMessage masterReadyMsg = this.applicationContext.getBean(MasterIsReadyMessage.class);
            masterReadyMsg.getAddress().setClusterName("loadTest");
            masterReadyMsg.getAddress().setChannelId("loadTest");
            service.sendMessage(masterReadyMsg);
    
        } else {
            ClientIsUpMessage message = this.applicationContext.getBean(ClientIsUpMessage.class);
            message.getAddress().setClusterName("loadTest");
            message.getAddress().setChannelId("loadTest");
            service.sendMessage(message);
    
            while (counter.getCount(MasterIsReadyMessage.class) < 1) {
                Thread.sleep(2000);
            }
        }
    
        task.setEvent(command);
        task.run();
    
        System.out.println("Waiting for completion!");
        if (LUtil.IsMaster()) {
            PieLogger.info(this.getClass(), "Master");
    
            Date start = new Date();
    
            while (counter.getCount(AllFilesCompleteTask.class) < (ltModel.getNodeCount() - 1)) {
                Thread.sleep(1000);
            }
    
            Date stop = new Date();
    
            long resultTime = stop.getTime() - start.getTime();
    
            Assert.assertTrue(comparer.getResult());
    
            LUtil.writeCSVResult(ltModel, resultTime);
    
            AllClientsDoneMessage doneMsg = this.applicationContext.getBean(AllClientsDoneMessage.class);
            doneMsg.getAddress().setClusterName("loadTest");
            doneMsg.getAddress().setChannelId("loadTest");
            service.sendMessage(doneMsg);
    
        } else {
            PieLogger.info(this.getClass(), "Slave");
            BitTorrentService torrentService = this.applicationContext.getBean(BitTorrentService.class);
    
            while (user.getPieShareConfiguration().getWorkingDir().listFiles().length < ltModel.getFileCount()
                    || torrentService.activeTorrents()) {
                Thread.sleep(1000);
            }
    
            PieLogger.info(this.getClass(), "WorkingDirFileCount: "
                    + String.valueOf(user.getPieShareConfiguration().getWorkingDir().listFiles().length));
            PieLogger.info(this.getClass(), "TestModelCount: " + String.valueOf(ltModel.getFileCount()));
    
            AllFilesCompleteMessage message = this.applicationContext.getBean(AllFilesCompleteMessage.class);
    
            LocalFileService fileService = this.applicationContext.getBean(LocalFileService.class);
            FileUtilitiesService fileUtilitiesService = this.applicationContext.getBean(FileUtilitiesService.class);
    
            File parent = user.getPieShareConfiguration().getWorkingDir();
            List<PieFile> files = new ArrayList<>();
            fileUtilitiesService.walkFilderTree(parent, new IFilderIterationCallback() {
                @Override
                public void handleFile(PieFile file) {
                    files.add(file);
                }
    
                @Override
                public void handleFolder(PieFolder folder) {
                    //ignore for now
                }
            });
    
            message.setFiles(files);
    
            message.getAddress().setClusterName("loadTest");
            message.getAddress().setChannelId("loadTest");
            service.sendMessage(message);
    
            PieLogger.info(this.getClass(), "Before waiting for AllClientsDone!");
            while (counter.getCount(AllClientsDoneMessage.class) < 1) {
                Thread.sleep(1000);
            }
            PieLogger.info(this.getClass(), "After waiting for AllClientsDone!");
    
            //this sleep alows the master to be first up in order to receive all client up notifications
            Thread.sleep(5000);
        }
    
        Date now = new Date();
        System.out.println(now.toString() + ": Finished!");
    }