Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:com.apm4all.tracy.RouteBuilder.java

License:Apache License

@Override
public void configure() throws Exception {
    Tracer tracer = new Tracer();
    tracer.setTraceOutExchanges(true);/*from   w w  w .java  2  s. c o  m*/
    tracer.setEnabled(false);

    // we configure the default trace formatter where we can
    // specify which fields we want in the output
    DefaultTraceFormatter formatter = new DefaultTraceFormatter();
    //      formatter.setShowOutBody(true);
    //      formatter.setShowOutBodyType(true);
    formatter.setShowBody(true);
    formatter.setShowBodyType(true);

    // set to use our formatter
    tracer.setFormatter(formatter);

    getContext().addInterceptStrategy(tracer);

    // configure we want to use servlet as the component for the rest DSL
    // and we enable json binding mode //netty4-http
    restConfiguration().component("servlet").bindingMode(RestBindingMode.json)
            // and output using pretty print
            .dataFormatProperty("prettyPrint", "true")
            // setup context path and port number that netty will use
            .contextPath("tws").port(8080)
            // add swagger api-doc out of the box
            .apiContextPath("/api-doc").apiProperty("api.title", "Tracy Web Services API")
            .apiProperty("api.version", "1.0.0")
            // and enable CORS
            .apiProperty("cors", "true");

    rest().description("Tracy Web Service").consumes("application/json").produces("application/json")
            .get("/applications/{application}/tasks/{task}/measurement")
            .description("Get measurement for a Task").outType(TaskMeasurement.class).param()
            .name("application").type(path).description("The application to measure").dataType("string")
            .endParam().param().name("task").type(path).description("The task to measure").dataType("string")
            .endParam().to("direct:taskMeasurement")

            .get("/applications/{application}/measurement").description("Get measurement for an Application")
            .outType(ApplicationMeasurement.class).param().name("application").type(path)
            .description("The application to measure").dataType("string").endParam()
            .to("bean:applicationMeasurementService?method=getApplicationMeasurement(${header.application})")

            .post("/applications/{application}/tasks/{task}/config").description("Set Task config")
            .type(TaskConfig.class).param().name("application").type(path).description("The application")
            .dataType("string").endParam().param().name("task").type(path).description("The task")
            .dataType("string").endParam().to("bean:esTaskConfig?method=setTaskConfig")

            .get("/applications/{application}/tasks/{task}/config").description("Get Task config")
            .outType(TaskConfig.class).param().name("application").type(path).description("The application")
            .dataType("string").endParam().param().name("task").type(path).description("The task")
            .dataType("string").endParam().to("bean:esTaskConfig?method=getTaskConfig")

            .options("/applications/{application}/tasks/{task}/config").to("direct:trash")

            .get("/registry").description("Get Tracy Registry containing supported environments")
            .to("direct:registry")

            .get("/capabilities")
            .description("Get Server capabilities (Applications/Tasks supported and associated views)")
            .to("direct:capabilities")

            .get("/applications/{application}/tasks/{task}/analysis").description("Get analysis for a Task")
            .outType(TaskAnalysisFake.class).param().name("application").type(path)
            .description("The application to analyse").dataType("string").endParam().param().name("task")
            .type(path).description("The task to analyse").dataType("string").endParam().param()
            .name("earliest").type(query).description("The earliest time (in epoch msec)").dataType("integer")
            .endParam().param().name("latest").type(query).description("The latest time (in epoch msec)")
            .dataType("integer").endParam().param().name("filter").type(query)
            .description("The expression to filter analysis").dataType("string").endParam().param().name("sort")
            .type(query).description("The fields to sort by").dataType("string").endParam().param()
            .name("limit").type(query).defaultValue("20")
            .description("The number of records to analyse, i.e. page size, default is 20").dataType("integer")
            .endParam().param().name("offset").type(query).description("The page number").defaultValue("1")
            .dataType("integer").endParam().to("direct:taskAnalysis")

            .delete("/tracy").description("Delete all Tracy events stored in backed")
            .to("direct:flushTracyRequest")

            .post("/tracySimulation").description("Produce Tracy for simulation purposes")
            .to("direct:toogleTracySimulation")

            .get("/demo").to("direct:getSimulation")

            .post("/demo").to("direct:setSimulation");

    from("direct:trash").stop();

    from("direct:getSimulation").routeId("getSimulation").setBody(simple("")).process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            Map<String, Boolean> state = new HashMap<String, Boolean>();
            state.put("demo", tracySimulationEnabled);
            exchange.getIn().setBody(state);
        }
    });

    from("direct:setSimulation").routeId("setSimulation")
            //               .log("${body}")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    Map<String, Boolean> state = (Map<String, Boolean>) exchange.getIn().getBody();
                    tracySimulationEnabled = state.get("demo");
                    state.put("demo", tracySimulationEnabled);
                    exchange.getIn().setBody(state);
                }
            });

    from("direct:toogleTracySimulation").routeId("toogleTracySimulation").setBody(simple(""))
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    String response;
                    tracySimulationEnabled = !tracySimulationEnabled;
                    if (tracySimulationEnabled) {
                        response = "Tracy simulation enabled";
                    } else {
                        response = "Tracy simulation disabled";
                    }
                    exchange.getIn().setBody(response);
                }
            });

    from("quartz://everySecond?cron=0/1+*+*+*+*+?").routeId("everySecondTimer").process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            Map<String, Object> headers = exchange.getIn().getHeaders();
            if (tracySimulationEnabled) {
                headers.put(TRACY_SIMULATION_ENABLED, new Boolean(true));
            } else {
                headers.put(TRACY_SIMULATION_ENABLED, new Boolean(false));
            }
        }
    }).to("seda:flushTracy").choice().when(simple("${in.header.TRACY_SIMULATION_ENABLED} == true"))
            //              .loop(100).to("seda:generateTracy")
            .to("seda:generateTracy") // To not loop
            .end();

    from("seda:generateTracy").routeId("generateTracy").setBody(simple("")).process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            //TODO: Extract Tracy generation to a separate thread
            final String COMPONENT = "hello-tracy";
            final String OUTER = "serviceEndpoint";
            final String INNER = "dodgyBackend";
            int status = 200;
            long random = new Double(Math.random() * 100).longValue() + 1;
            if (random <= 80) {
                status = 200;
            } //  80%  200: OK
            else if (random > 99) {
                status = 202;
            } //   1%  202: Accepted
            else if (random > 97) {
                status = 429;
            } //   1%  307: Temp redirect
            else if (random > 87) {
                status = 404;
            } //  10%  404: Not found
            else if (random > 84) {
                status = 401;
            } //   3%  401: Unauthorized
            else if (random > 82) {
                status = 400;
            } //   2%  404: Bad request
            else if (random > 81) {
                status = 307;
            } //   2%  429: Too many requests
            else if (random > 80) {
                status = 500;
            } //   1%  500: Internal server error
            Tracy.setContext(null, null, COMPONENT);
            Tracy.before(OUTER);
            Tracy.annotate("status", status);
            Tracy.before(INNER);
            //               long delayInMsec = new Double(Math.random() * 2).longValue() + 2;
            long delayInMsec = new Double(Math.random() * 200).longValue() + 100;
            Thread.sleep(delayInMsec);
            Tracy.after(INNER);
            //               delayInMsec = new Double(Math.random() * 2).longValue() + 2;
            delayInMsec = new Double(Math.random() * 10).longValue() + 10;
            Thread.sleep(delayInMsec);
            Tracy.after(OUTER);
            exchange.getIn().setBody(Tracy.getEventsAsJson());
            Tracy.clearContext();
        }
    }).to("seda:ingestTracy");

    from("direct:flushTracyRequest").routeId("flushTracyRequest").process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            flushTracy = true;
        }
    }).setBody(simple("Flushed all Tracy events")).log("Flush request accepted");

    from("seda:flushTracy").routeId("flushTracy")
            //            .log("Flush request processing started")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    Map<String, Object> headers = exchange.getIn().getHeaders();
                    if (flushTracy) {
                        headers.clear();
                        headers.put(FLUSH_TRACY, new Boolean(true));
                        flushTracy = false;
                    } else {
                        headers.clear();
                        headers.put(FLUSH_TRACY, new Boolean(false));
                    }
                    exchange.getIn().setBody("");
                }
            }).setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.DELETE))
            //            .log("Flush request ready to be sent")
            .choice().when(simple("${in.header.FLUSH_TRACY} == true"))
            //TODO: Hanle 404 status (nothing to delete) gracefully
            .to("http4://localhost:9200/tracy-*/tracy")
            //TODO: Investigate why Camel ES Delete is not working
            //               .setHeader(ElasticsearchConstants.PARAM_INDEX_NAME, simple("tracy-hello-tracy-*"))
            //                 .setHeader(ElasticsearchConstants.PARAM_INDEX_TYPE, simple("tracy"))
            //                .to("elasticsearch://local?operation=DELETE");
            .log("Flush request sent").end();

    from("seda:ingestTracy").routeId("ingestTracy")
            //TODO: If tracySegment instead of tracyFrame, split into Tracy frames (not required for MVC)
            .split(body())
            //          .setHeader(ElasticsearchConstants.PARAM_INDEX_NAME, "tracy-" + simple("${body[component]}")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    ObjectMapper m = new ObjectMapper();
                    JsonNode rootNode = m.readTree((String) exchange.getIn().getBody());
                    DateTime dt = new DateTime(rootNode.path("msecBefore").asLong(), DateTimeZone.UTC);
                    String esTimestamp = dt.toString("yyyy-MM-dd'T'HH:mm:ss.SSS");
                    ((ObjectNode) rootNode).put("@timestamp", esTimestamp);
                    StringBuilder index = new StringBuilder();
                    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy.MM.dd");
                    String dateString = fmt.print(dt);
                    index.append("tracy-").append(rootNode.path("component").textValue()).append("-")
                            .append(dateString);
                    exchange.getIn().setHeader(ElasticsearchConstants.PARAM_INDEX_NAME, index.toString());
                    exchange.getIn().setHeader(ElasticsearchConstants.PARAM_INDEX_TYPE, "tracy");
                    String indexId = rootNode.path("taskId").textValue() + "_"
                            + rootNode.path("optId").textValue();
                    exchange.getIn().setHeader(ElasticsearchConstants.PARAM_INDEX_ID, indexId);
                    exchange.getIn().setBody(m.writer().writeValueAsString(rootNode));
                }
            })
            //          .log("${body}")
            //          .log("${headers}")
            .to("elasticsearch://local?operation=INDEX");

    from("direct:registry").routeId("registry").process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            ObjectMapper m = new ObjectMapper();
            Map<String, Object> registry = m.readValue(
                    "{\"environments\":[{\"name\":\"Local1\",\"servers\":[{\"url\":\"http://localhost:8080/tws/v1\"}]},{\"name\":\"Local2\",\"servers\":[{\"url\":\"http://localhost:8080/tws/v1\"}]}]}",
                    Map.class);
            exchange.getIn().setBody(registry);
        }
    });

    from("direct:capabilities").routeId("capabilities").process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            ObjectMapper m = new ObjectMapper();
            Map<String, Object> capabilities = m.readValue(
                    "{\"capabilities\":{\"applications\":[{\"name\":\"appX\",\"views\":[{\"label\":\"Measurement\",\"name\":\"measurement\"}],\"tasks\":[{\"name\":\"taskX1\",\"views\":[{\"label\":\"Measurement\",\"name\":\"measurement\"}]}]}]}}",
                    Map.class);
            exchange.getIn().setBody(capabilities);
        }
    });

    from("direct:taskMeasurement").routeId("taskMeasurement").choice()
            .when(simple("${in.header.application} contains 'demo-live'"))
            .bean("esTaskMeasurement", "getTaskMeasurement")
            .when(simple("${in.header.application} contains 'demo-static'"))
            .to("bean:taskMeasurementService?method=getTaskMeasurement(${header.application}, ${header.task})")
            .end();

    from("direct:taskAnalysis").routeId("taskAnalysis")
            //                .log("${headers}")
            .choice().when(simple("${in.header.application} contains 'demo-live'"))
            .bean("esTaskAnalysis", "getTaskAnalysis")
            .when(simple("${in.header.application} contains 'demo-static'"))
            .to("bean:taskAnalysisService?method=getTaskAnalysis"
                    + "(${header.application}, ${header.task}, ${header.earliest}, ${header.latest}, ${header.filter}, ${header.sort}, ${header.limit}, ${header.offset})")
            .end();
}

From source file:com.app.intuit.util.WebUtils.java

License:Open Source License

public static String formatTimestamp(Timestamp timestamp) {
    String str = null;//from w  ww  . ja v a2 s.c o  m
    if (timestamp != null) {
        DateTime dt = new DateTime(timestamp);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("d MMMM, yyyy");
        str = dt.toString(fmt);
    }
    return str;
}

From source file:com.app.intuit.util.WebUtils.java

License:Open Source License

public static String formatTimestampWithTime(Timestamp timestamp) {
    String str = null;/*  w w  w.ja v a2  s  .c  om*/
    if (timestamp != null) {
        DateTime dt = new DateTime(timestamp);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("d MMMM, yyyy k:m");
        str = dt.toString(fmt);
    }
    return str;
}

From source file:com.app.intuit.util.WebUtils.java

License:Open Source License

public static String formatTimestampOnlyTime(Timestamp timestamp) {
    String str = null;/*from   w ww  . j av  a 2s. com*/
    if (timestamp != null) {
        DateTime dt = new DateTime(timestamp);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("k:m");
        str = dt.toString(fmt);
    }
    return str;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

License:Apache License

private Map<String, String> createValueMap(Azure azure, String namespaceName, String resourceType,
        Set<String> queueStats) {
    Map<String, String> valueMap = new HashMap<String, String>();
    valueMap.put("SubscriptionId", azure.getSubscriptionId());
    valueMap.put("NameSpace", namespaceName);
    valueMap.put("ResourceType", resourceType);

    String stats = Joiner.on(",").skipNulls().join(queueStats);
    valueMap.put("Stats", stats);

    DateTime dateTime = new DateTime(DateTimeZone.UTC).minusMinutes(15);
    String endTime = dateTime.toString(DateTimeFormat.forPattern(DATE_FORMAT));
    String startTime = dateTime.minusMinutes(1).toString(DateTimeFormat.forPattern(DATE_FORMAT));
    valueMap.put("StartTime", startTime);
    valueMap.put("EndTime", endTime);
    return valueMap;
}

From source file:com.arcusys.liferay.vaadinplugin.util.DownloadInfo.java

License:Apache License

public DownloadInfo(Version version, VaadinReleaseType releaseType, String downloadUrl, DateTime releaseDate) {
    this.downloadUrl = downloadUrl;
    this.version = version;
    this.releaseType = releaseType;
    this.releaseDate = releaseDate;

    this.name = version + " (" + releaseDate.toString("dd-MM-yyyy hh:mm") + ")";
}

From source file:com.avid.central.obsplugin.inewslibrary.ExportStories.java

public ExportStoryData ProcessRundown(List<Story> stories, ExportConfiguration config) {
    ExportStoryData exportData = new ExportStoryData(config);

    // create a new OBS_Export
    ExportRundown _export = new ExportRundown();

    // Represents the starting time of an item, can be calculated from previous item start time or set explicitly by the user
    int currentStartTime = 0;

    // Flags the fact that the previous Story parsed was a break with a defined time
    boolean lastStoryWasBreak = false;

    // Flags the fact that we have now validated the header
    boolean headerValid = false;

    // identifiers used in exporting cue sheets
    String CueSheetLocation = "<p family=\"0\" font=\"\" pitch=\"0\">" + config.cuesheet_id + "</p>";
    String BodyStart = "<body";
    String BodyEnd = "</body>";

    // do everything inside a try {} block
    // if we encounter any of the conditions listed above which preclude exporting the rundown
    // then we throw an exception which includes the reason why
    try {//from www .  ja v  a 2 s. c  o m
        // go through stories and decide what to do with each
        for (Story story : stories) {
            List<mos> vizGrapics = new ArrayList<mos>();

            // is this a break story?
            if (story.Story.getHead().getMeta().isBreak()) {
                // yes it is
                // need to get the content of the info Field
                String info = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.info_field);
                if (null == info) {
                    RaiseError(String.format("field \"%s\" was not found", config.info_field));
                }

                String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.subject_field);
                if (null == subject) {
                    RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                }

                // is it one of our "special" fields
                if (info.equalsIgnoreCase(config.obs_channel_id)) {
                    if (subject.length() == 0) {
                        // the channelID is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.obs_channel_id));
                    }

                    // this is the Story that contains the channel ID
                    _export.Rundown.ChannelID = subject;

                    // determine the mode, first test for MDS
                    if (subject.toUpperCase().startsWith(config.mds_prefix.toUpperCase())) {
                        exportData.setMdsMode(true);
                    } else if (!subject.toUpperCase().startsWith(config.onc_prefix.toUpperCase())
                            && config.onc_prefix.length() > 0) {
                        RaiseError(String.format("the %s was not identified as an ONC or MDS rundown",
                                config.obs_channel_id));
                    }

                } else if (info.equalsIgnoreCase(config.title_id)) {
                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        // the rundown name is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.title_id));
                    }

                    // this is the Story that contains the rundown name
                    _export.Rundown.Title = subject;
                } else if (info.equalsIgnoreCase(config.day_id)) {
                    // this is the Story that contains the rundown day
                    if (subject.length() > 0) {
                        _export.Rundown.Day = subject;
                    }

                } else if (info.equalsIgnoreCase(config.date_id)) {
                    // this is the Story that contains the rundown date
                    if (subject.length() > 0) {
                        _export.Rundown.Date = subject;
                    }
                }

                String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.start_time_field);
                if (null == startTime && exportData.getValidateFields()) {
                    RaiseError(String.format("field \"%s\" was not found", config.start_time_field));
                }

                // check for start and end time data
                if (subject.equalsIgnoreCase(config.start_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute start time
                        currentStartTime = Integer.parseInt(startTime.substring(1));
                        _export.Rundown.RundownStartTime = currentStartTime;
                    } else {
                        // start time is relative to start of show
                        currentStartTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                        _export.Rundown.RundownStartTime = currentStartTime;
                    }
                } else if (subject.equalsIgnoreCase(config.end_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute end time
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1));
                    } else {
                        // start time is relative to start of show
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                    }

                    lastStoryWasBreak = true;
                }
            } else {
                if (!story.Story.getHead().getMeta().isFloat()) {
                    // this is not a floated Story so we must have passed the "header"
                    // if we haven't validated the "header" at this point then now is the time to do so!
                    if (!headerValid) {
                        if (-1 == _export.Rundown.RundownStartTime && exportData.getValidateFields()) {
                            // the start time has not been set so abort the export
                            RaiseError("the rundown start time is missing");
                        }

                        headerValid = true;
                    }

                    // every time we encounter a non-break, non-floated Story reset the rundown end time to unspecified
                    // it should get set to the correct value by the final break Story
                    _export.Rundown.RundownEndTime = -1;

                    // get the subject
                    String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.subject_field);
                    if (null == subject) {
                        RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                    }

                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        RaiseError("at least one story is missing its Subject details");
                    }

                    // check for an update and retrieve modification time
                    String updatedTimestamp = null;
                    int update = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.update_field);
                    DateTime modificationTime = GetFieldDateValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.modified_field);
                    if (null != modificationTime) {
                        DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinuteSecond();
                        updatedTimestamp = modificationTime.toString(fmt);
                    }

                    // get the start time
                    String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.start_time_field);

                    // do we have start time data?
                    if (startTime != null && !startTime.isEmpty()) {
                        // update the running start time
                        if (startTime.charAt(0) == '@') {
                            // we have an absolute start time
                            currentStartTime = Integer.parseInt(startTime.substring(1));
                        } else {
                            // start time is relative to start of show
                            currentStartTime = Integer.parseInt(startTime.substring(1))
                                    + _export.Rundown.RundownStartTime;
                        }
                    } else {
                        // no start time specified so we need to get it from the previous item
                        // if there are not yet any stories in the list then just use the start time we are carrying forward
                        if (_export.Stories.size() > 0 && !lastStoryWasBreak) {
                            // there is at least one Story
                            currentStartTime += _export.Stories.get(_export.Stories.size() - 1).StoryDuration;
                        }
                    }

                    // get the VideoID
                    String videoID = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.video_id_field);
                    if (exportData.getMdsMode()) {
                        if (null == videoID) {
                            RaiseError(String.format("field \"%s\" was not found", config.video_id_field));
                        }
                        if (videoID.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its VideoID details");
                        }
                    } else if (null == videoID || videoID.isEmpty()) {
                        videoID = "";
                    }

                    // get the Type
                    String type = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.type_field);
                    if (exportData.getMdsMode()) {
                        if (null == type) {
                            RaiseError(String.format("field \"%s\" was not found", config.type_field));
                        }
                        if (type.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its type details");
                        }
                    }

                    // get the Upmix
                    String upMix = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.upmix_field);
                    if (exportData.getMdsMode()) {
                        if (null == upMix) {
                            RaiseError(String.format("field \"%s\" was not found", config.upmix_field));
                        }
                        if (upMix.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its upmix details");
                        }
                    }

                    // get the Music
                    String music = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.music_field);
                    if (exportData.getMdsMode()) {
                        if (null == music || music.length() == 0) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its music element");
                        }
                    }

                    if (!exportData.getMdsMode() && exportData.getValidateFields()) {
                        // get the Endorsement details
                        String endorseBy = GetFieldStringValue(
                                story.Story.getFields().getStringOrBooleanOrDate(), config.endorse_field);
                        if (null == endorseBy) {
                            RaiseError(String.format("field \"%s\" was not found", config.endorse_field));
                        }
                        if (endorseBy.length() == 0) {
                            exportData.getResponse().setMessage("At least one story has not been approved");
                            //                                RaiseError("at least one story has not been approved");
                        }

                        // get the Export Approval flags
                        int approved = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                                config.export_field);
                        if (approved == 0) {
                            RaiseError("at least one story is not ready for export");
                        }
                    }

                    // get VIZ production cue
                    // are there any anchored elements?
                    if (exportData.getCheckGrahics()) {
                        if (null != story.Story.getAeset() && story.Story.getAeset().getAe().size() > 0) {
                            // is there one for VIZ?
                            for (Ae ae : story.Story.getAeset().getAe()) {

                                for (Object ap : ae.getMcOrAp()) {
                                    if (ap.getClass() != Nsml.Aeset.Ae.Mc.class) {
                                        continue;
                                    }

                                    Nsml.Aeset.Ae.Mc mc = (Nsml.Aeset.Ae.Mc) ap;
                                    for (Object content : mc.getAp()) {
                                        if (content.getClass() != ApContent.class) {
                                            continue;
                                        }

                                        ApContent apContent = (ApContent) content;
                                        for (Object data : apContent.getContent()) {
                                            if (data.getClass() == String.class) {
                                                String graphic = (String) data;
                                                if (!graphic.contains(config.viz_id)) {
                                                    continue;
                                                }

                                                for (AttachmentType at : story.Story.getAesetAtts()
                                                        .getAttachment()) {
                                                    if (mc.getIdref().equals(at.getId())) {
                                                        // found it!
                                                        String graphicData = at.getValue();
                                                        if (graphicData != null) {
                                                            try {
                                                                AttachmentContent ac = AttachmentContent
                                                                        .Parse(graphicData);
                                                                if (ac != null) {
                                                                    vizGrapics.add(ac.mos);
                                                                }
                                                            } catch (Exception ex) {
                                                            }

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (0 == vizGrapics.size()) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its graphic element");
                        }
                    }

                    // Story looks OK so add it to the export
                    OBSStory obsStory = new OBSStory();

                    obsStory.Subject = subject;
                    obsStory.Type = type;
                    obsStory.StoryStartTime = currentStartTime;
                    obsStory.StoryDuration = GetFieldIntegerValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.duration_field);
                    obsStory.VideoID = videoID;

                    if (exportData.getMdsMode()) {
                        obsStory.Upmix = upMix.equals("1") || upMix.equals("true");
                        obsStory.Music = music;
                        obsStory.Graphics = vizGrapics;
                    } else {
                        if (null != updatedTimestamp) {
                            obsStory.Modified = updatedTimestamp;
                            obsStory.Update = update == 1;
                        }
                    }

                    // the story body as NSML
                    String formattedBody;

                    // unformatted version of the story body
                    String unformattedBody;

                    // the contents of the script info tag
                    String scriptInfo = null;

                    // the contents of the cue sheet tag
                    String cueSheet = null;

                    int cueSheetLocation = -1;

                    // get the story body free of all formatting
                    unformattedBody = GetStoryBody(story.Story);

                    // look for escape characters in the value and encode them
                    unformattedBody = unformattedBody.replace("&", "&amp;");
                    unformattedBody = unformattedBody.replace("\"", "&quot;");
                    unformattedBody = unformattedBody.replace("<", "&lt;");
                    unformattedBody = unformattedBody.replace(">", "&gt;");
                    unformattedBody = unformattedBody.replace("'", "&apos;");

                    // now look for a cue sheet
                    cueSheetLocation = unformattedBody.indexOf(config.cuesheet_id);

                    if (cueSheetLocation >= 0) {
                        // there is a cue sheet so extract it from the unformatted body if MDS mode
                        if (exportData.getMdsMode() && unformattedBody
                                .length() > (cueSheetLocation + config.cuesheet_id.length())) {
                            cueSheet = unformattedBody
                                    .substring(cueSheetLocation + config.cuesheet_id.length());
                        }

                        // crop the cue sheet from the unformatted body
                        unformattedBody = unformattedBody.substring(0, cueSheetLocation);
                    }

                    // we now have the unformatted body free of cue sheet data together with the cue sheet if it exists

                    // are we exporting the story in its formatted version?
                    if (exportData.getRetainFormatting()) {
                        formattedBody = "";

                        // get the formatted story body
                        // first get offsets to body tags
                        int storyStart = story.StoryAsNSML.indexOf(BodyStart);
                        int storyEnd = story.StoryAsNSML.indexOf(BodyEnd);

                        // check for non-empty body
                        if (-1 != storyEnd) {
                            // make sure we extract the end tag
                            storyEnd += BodyEnd.length();
                            formattedBody = story.StoryAsNSML.substring(storyStart, storyEnd);
                            // now we have the formatted story body

                            // if the story is not empty and has a cue sheet section we need to remove it
                            cueSheetLocation = formattedBody.indexOf(CueSheetLocation);

                            if (cueSheetLocation >= 0 && unformattedBody.length() > 0) {
                                // there is a cue sheet and the story isn't empty so we need to remove the cue sheet from the formatted body
                                String script = formattedBody.substring(0, cueSheetLocation);
                                // add back the body end tag
                                script += BodyEnd;
                                scriptInfo = "<![CDATA[\n" + script + "]]>";

                            } else if (unformattedBody.length() > 0) {
                                scriptInfo = "<![CDATA[\n" + formattedBody + "]]>";
                            }

                        }

                    } else {
                        // simply export the unformatted body
                        scriptInfo = unformattedBody;
                    }

                    obsStory.ScriptInfo = scriptInfo;
                    if (exportData.getMdsMode() && null != cueSheet) {
                        obsStory.CueSheet = cueSheet;
                    }

                    _export.Stories.add(obsStory);

                    lastStoryWasBreak = false;
                }
            }
        }

        // check that we have an end time
        if (-1 == _export.Rundown.RundownEndTime) {
            if (exportData.getValidateFields()) {
                // nope, reject this one
                RaiseError("the rundown end time is missing");
            } else {
                _export.Rundown.RundownEndTime = _export.Rundown.RundownStartTime;
            }
        }

        // check for Channel ID
        if (_export.Rundown.ChannelID.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.obs_channel_id));
        }

        // check for Channel Name
        if (_export.Rundown.Title.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.title_id));
        }

        // check for Date
        if (_export.Rundown.Date.length() == 0) {
            // log a warning here (no date specified)
            // set date to today's date
            DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-mm-dd");
            _export.Rundown.Date = DateTime.now().toString(dtf);
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The date information was missing from the rundown");
            }
        }
        exportData.getResponse().setDate(_export.Rundown.Date);

        // check for Day
        if (_export.Rundown.Day.length() == 0) {
            // log a warning here (no day specified)
            // set date to today's date
            _export.Rundown.Day = String.format("%02d", DateTime.now().dayOfMonth().get());
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The day information was missing from the rundown");
            }
        }
        exportData.getResponse().setDay(_export.Rundown.Day);

        exportData.setRundownAsXml(_export.GenerateXML(exportData.getMdsMode()));

        exportData.getResponse().setChannelID(_export.Rundown.ChannelID);
        exportData.getResponse().setStartTime(_export.Rundown.GetStartTime());
        exportData.getResponse().setEndTime(_export.Rundown.GetEndTime());
        exportData.getResponse().setTitle(_export.Rundown.Title);

        exportData.getResponse().setFileName(_export.GenerateFileName());
        exportData.getResponse().setResult(1);
    } catch (Exception ex) {
        exportData.getResponse().setMessage(ex.getMessage());
    }

    return exportData;
}

From source file:com.brandboat.loader.PhoenixDB.java

public static String toTimeStamp(DateTime dt) {
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
    return dt.toString(dtf);
}

From source file:com.brewtab.irclog.SQLFromIrssiLog.java

License:Open Source License

private String timestampFormat(DateTime t) {
    return t.toString("yyyy-MM-dd HH:mm:ss");
}

From source file:com.chiorichan.dvr.registry.VideoInput.java

License:Mozilla Public License

@Override
public void run() {
    currentThread = Thread.currentThread();

    Loader.getLogger().info("Starting Video Input Thread - " + currentThread.getName());

    do {/*from   w w w . java 2  s . c  o  m*/
        try {
            if (device.isOpen()) {
                img = device.getImage();

                if (img != null)
                    if (busy == false) {
                        busy = true;

                        long start = System.currentTimeMillis();
                        currentFPS = Math.round(1000 / ((float) (System.currentTimeMillis() - lastTimeStamp)));

                        lastTimeStamp = System.currentTimeMillis();

                        // Determine the current time for the timestamp and frame position
                        DateTime dt = new DateTime();

                        Graphics2D gd = img.createGraphics();
                        VideoUtils.adjustGraphics(gd);
                        Font font = new Font("Sans", Font.PLAIN, 18);
                        String text = dt.toString("YYYY/MM/dd hh:mm:ss.SSS aa");
                        TextLayout textLayout = new TextLayout(text, font, gd.getFontRenderContext());
                        gd.setPaint(Color.WHITE);
                        gd.setFont(font);
                        FontMetrics fm = gd.getFontMetrics();
                        //int x = (img.getWidth() / 2) - (fm.stringWidth( text ) / 2);
                        int x = img.getWidth() - fm.stringWidth(text) - 20;
                        int y = img.getHeight() - 20;
                        textLayout.draw(gd, x, y);
                        gd.dispose();
                        /*
                         * float ninth = 1.0f / 9.0f;
                         * float[] kernel = new float[9];
                         * for ( int z = 0; z < 9; z++ )
                         * {
                         * kernel[z] = ninth;
                         * }
                         * ConvolveOp op = new ConvolveOp( new Kernel( 3, 3, kernel ), ConvolveOp.EDGE_NO_OP, null );
                         * BufferedImage image2 = op.filter( bi, null );
                         * Graphics2D g2 = image2.createGraphics();
                         * //VideoUtils.adjustGraphics( g2 );
                         * g2.setPaint( Color.BLACK );
                         * textLayout.draw( g2, x, y );
                         */

                        Loader.getLogger()
                                .info(ChatColor.BLUE + "Frame Saved: Current FPS: " + currentFPS + ", Device: "
                                        + this.getChannelName() + ", Time Taken: "
                                        + (System.currentTimeMillis() - start) + ", Thread: "
                                        + currentThread.getName());
                        writer.addFrame(dt, img);

                        busy = false;
                    } else
                        Loader.getLogger().warning(
                                "Received a new Frame from Video Input Device but the processing subroutine was busy, Thread: "
                                        + currentThread.getName() + ", Device: " + this.getChannelName());
            }

            // This should get us about 25 FPS if possible.
            Thread.sleep(100L);
        } catch (Exception ex) {
            Loader.getLogger().severe("Exception Encountered in the Video Input Thread, Thread: "
                    + currentThread.getName() + ", Device: " + this.getChannelName(), ex);
        }
    } while (DVRLoader.isRunning);

    Loader.getLogger().info("Stopping Video Input Thread - " + currentThread.getName());
}