Skip to content

Commit

Permalink
Change to use jaxb4 (javax -> jakarta), uplift xsd to 4.1.0
Browse files Browse the repository at this point in the history
Change Date to Instant
Add module-info
Change module name
  • Loading branch information
at055612 committed Jun 19, 2024
1 parent f6168e9 commit ad7f27d
Show file tree
Hide file tree
Showing 36 changed files with 588 additions and 96 deletions.
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ buildscript {
plugins {
//plugin for downloading content from the 'net
id "de.undercouch.download" version "3.4.3"
id "io.github.gradle-nexus.publish-plugin" version "1.0.0"
id "io.github.gradle-nexus.publish-plugin" version "1.2.0"
//plugin for producing a tree of task dependencies, run task 'taskTree'
id "com.dorongold.task-tree" version "1.5"
id "signing"
Expand Down Expand Up @@ -67,7 +67,7 @@ ext.getMajorVersion = { versionStr ->

// Set this to the desired release version of the event-logging XML schema on github
// *****************************************************************************
def eventLoggingSchemaVer = "v4.0.0"
def eventLoggingSchemaVer = "v4.1.0"
// *****************************************************************************

// Set this to the last release of this repo on this branch, or earlier branches
Expand Down Expand Up @@ -246,7 +246,7 @@ subprojects {

// This means the reports from our integration tests won't over-write the reports from our unit tests.
tasks.withType(Test) {
reports.html.destination = file("${reporting.baseDir}/${name}")
reports.html.outputLocation = file("${reporting.baseDir}/${name}")

//Use full logging for test exceptions so we can see where the failure occurred
testLogging {
Expand Down
11 changes: 7 additions & 4 deletions event-logging-api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ apply plugin: 'maven-publish'
apply plugin: 'signing'
apply plugin: 'io.swagger.core.v3.swagger-gradle-plugin'

ext.moduleName = 'event.logging.api'
ext.moduleName = 'uk.gov.gchq.eventlogging'

def schemaDir = project.file('schema')

// We want a jar like event-logging-5.0-beta.16_schema-v4.0-beta.3.jar,
// not event-logging-api-5.0-beta.16_schema-v4.0-beta.3.jar
archivesBaseName = "event-logging"
base.archivesName = "event-logging"

dependencies {
implementation libs.jaxb_api
Expand Down Expand Up @@ -61,6 +61,8 @@ jar {
)
}
version versions.eventLogging
// We want a jar like event-logging-5.0-beta.16_schema-v4.0-beta.3.jar,
// not event-logging-api-5.0-beta.16_schema-v4.0-beta.3.jar
}

javadoc {
Expand Down Expand Up @@ -188,12 +190,13 @@ tasks.build.dependsOn diffAgainstLatest
task runExampleAppBuild(type: GradleBuild) {
dependsOn publishToMavenLocal

buildFile = '../example-logged-application/build.gradle'
// Defaults to build.gradle
dir = '../example-logged-application'
tasks = ['clean', 'build']
startParameter.projectProperties = [mavenVersion: projectVersionForMaven]

doFirst {
println "Running separate example application build [$buildFile]"
println "Running separate example application build [$dir]"
}
}

Expand Down
14 changes: 14 additions & 0 deletions event-logging-api/src/main/java/module-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module uk.gov.gchq.eventlogging {

exports event.logging;
exports event.logging.impl;
exports event.logging.jaxb;
exports event.logging.jaxb.fluent;
exports event.logging.util;

requires transitive jakarta.xml.bind;
requires java.xml;
requires org.slf4j;

opens event.logging to jakarta.xml.bind;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import event.logging.EventTime;
import event.logging.Purpose;

import java.util.Date;
import java.time.Instant;
import java.util.function.Supplier;

/**
Expand All @@ -34,7 +34,7 @@ public interface EventLoggingService {
* implementation being used. If this method is not implemented it will return an empty event by default.
*
* Using {@link EventLoggingService#createEvent(String, String, EventAction)} should be preferred.
*
*
* @return An event that is ready to have additional properties set.
*/

Expand Down Expand Up @@ -77,7 +77,7 @@ default Event createEvent(final String typeId,
final EventAction eventAction) {
return Event.builder()
.withEventTime(EventTime.builder()
.withTimeCreated(new Date())
.withTimeCreated(Instant.now())
.build())
.withEventDetail(EventDetail.builder()
.withTypeId(typeId)
Expand All @@ -90,7 +90,7 @@ default Event createEvent(final String typeId,

/**
* Logs an event.
*
*
* @param event The event to log.
*/
void log(Event event);
Expand Down Expand Up @@ -139,17 +139,17 @@ default void log(final String typeId,
* Set to true if the event logging service should validate the output XML against the schema. This option helps
* identify areas of code that are producing invalid data. For performance reasons it is recommended that
* validation is not performed in production.
*
*
* If validate is set to null then the system property shall be used to determine if validation is performed.
*
*
* @param validate
* The validation flag.
*/
void setValidate(Boolean validate);

/**
* Use to determine if the event logging service is set to validate output data against the XML schema.
*
*
* @return True if the validate flag is set.
*/
boolean isValidate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public DefaultEventLoggingService(ErrorHandler schemaValidationErrorHandler,
public void log(final Event event) {
final String data = eventSerializer.serialize(event);
final String trimmed = data.trim();
if (trimmed.length() > 0) {
if (!trimmed.isEmpty()) {
// Validate data here if the configuration option is set.
if (checkValidating()) {
xmlValidator.validate(trimmed);
Expand All @@ -109,7 +109,7 @@ private boolean checkValidating() {

// If we aren't setting validate on .
final String val = System.getProperty(VALIDATE);
return Boolean.valueOf(val);
return Boolean.parseBoolean(val);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
import event.logging.Event;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;

public class DefaultEventSerializer implements EventSerializer {
private static JAXBContext context;
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultEventSerializer.class);

@Override
public String serialize(final Event event) {
Expand Down Expand Up @@ -54,15 +56,26 @@ private static Marshaller getMarshaller() {
}
}

private synchronized static JAXBContext getContext() {
try {
if (context == null) {
context = JAXBContext.newInstance(Event.class);
}
private static JAXBContext getContext() {
// Initialize-on-Demand, Holder Class Idiom
return Holder.JAXB_CONTEXT;
}

return context;
private static JAXBContext createContext() {
try {
LOGGER.info("Creating JAXB context");
return JAXBContext.newInstance(Event.class);
} catch (final Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}


// --------------------------------------------------------------------------------


// Initialize-on-Demand, Holder Class Idiom
private static class Holder {
private static final JAXBContext JAXB_CONTEXT = createContext();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,15 @@ String getDescription() {
return description;
}

@SuppressWarnings("unchecked")
@Override
public <T extends EventAction> EventLoggerBuilder.WorkStep<T> withDefaultEventAction(
final T defaultEventAction) {

// At this point we are moving from the builder having unknown type to it having a known
// EventAction so type casts are unavoidable.

//noinspection unchecked
this.eventAction = (T_EVENT_ACTION) defaultEventAction;
//noinspection unchecked
return (EventLoggerBuilder.WorkStep<T>) this;
}

Expand Down Expand Up @@ -374,7 +373,7 @@ public void runActionAndLog() {
basicBuilder.description,
basicBuilder.purpose,
basicBuilder.eventAction,
loggedAction::apply,
loggedAction,
basicBuilder.exceptionHandler,
basicBuilder.isLogEventRequired);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,32 @@
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.Date;
import java.time.Instant;

public class DateAdaptor {
private static final Logger LOGGER = LoggerFactory.getLogger(DateAdaptor.class);
public class InstantAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantAdapter.class);

public static Date parseDate(final String string) {
public static Instant parseDate(final String string) {
try {
return new Date(DateUtil.parseDateTimeString(string));
final Long millis = DateUtil.parseDateTimeString(string);
return millis == null
? null
: Instant.ofEpochMilli(millis);
} catch (final ParseException e) {
LOGGER.error(e.getMessage(), e);
}

return null;
}

public static String printDate(final Date date) {
/**
* @param date
* @return The instant in the form "yyyy-MM-dd HH:mm:ss.SSS zzz"
*/
public static String printDate(final Instant date) {
if (date == null) {
return null;
}

return DateUtil.createNormalDateTimeString(date.getTime());
return DateUtil.createNormalDateTimeString(date.toEpochMilli());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private DateUtil() {

/**
* Create a 'file' format date string.
*
*
* @param ms
* The date to create the string for.
* @return string The date as a 'file' format date string.
Expand All @@ -67,7 +67,7 @@ public static String createFileDateTimeString(final Long ms) {

/**
* Create a 'normal' format date string.
*
*
* @param ms
* The date to create the string for.
* @return string The date as a 'normal' format date string.
Expand All @@ -85,7 +85,7 @@ public static String createNormalDateTimeString(final Long ms) {

/**
* Creates a string from a date given the appropriate time format and millisecond separator.
*
*
* @param ms
* The date to use.
* @param timeFormat
Expand Down Expand Up @@ -122,7 +122,7 @@ private static String createDateTimeString(final long ms, final DateFormat timeF
* @return A Date object set to the supplied date.
*/
public static Long parseDateTimeString(final String date) throws ParseException {
if (NULL.equals(date) || date == null || date.length() == 0) {
if (NULL.equals(date) || date == null || date.isEmpty()) {
return null;
}

Expand All @@ -143,7 +143,7 @@ public static Long parseDateTimeString(final String date) throws ParseException
* Utility method for padding a string to a certain number of characters. Characters are appended to the left hand
* side of the string to make it the specified length. IF the string is already longer than the specified length is
* is just returned and not truncated.
*
*
* @param str
* The string to pad.
* @param size
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import event.logging.User;

import java.lang.reflect.InvocationTargetException;
import java.time.Instant;
import java.util.Date;

public final class EventLoggingUtil {
Expand All @@ -33,12 +34,32 @@ private EventLoggingUtil() {
// Utility class.
}

/**
* Use {@link EventLoggingUtil#createEventTime(Instant)} instead.
*/
@Deprecated(forRemoval = true)
public static EventTime createEventTime(final Date date) {
final Instant instant = date != null
? date.toInstant()
: null;
return createEventTime(instant);
}

public static EventTime createEventTime(final Instant date) {
return EventTime.builder()
.withTimeCreated(date)
.build();
}

/**
* @return An EventTime for the current time, i.e. {@link Instant#now()}
*/
public static EventTime createCurrentEventTime() {
return EventTime.builder()
.withTimeCreated(Instant.now())
.build();
}

public static User createUser(final String userId) {
return User.builder()
.withId(userId)
Expand Down
Loading

0 comments on commit ad7f27d

Please sign in to comment.