COM-interface API-vejledning: Java Spring Boot + JACOB-bibliotek

I denne artikel vil jeg vise dig, hvordan du integrerer JACOB-biblioteket i din Spring Boot-applikation. Dette hjælper dig med at ringe til et COM-interface API via DLL-biblioteket i din webapplikation.

Af illustrative grunde vil jeg også give en beskrivelse af en COM API, så du kan bygge din applikation oven på den. Du kan finde alle kodestykkerne i denne GitHub-repo.

Men først en hurtig note: på C the Signs implementerede vi denne løsning, der gjorde det muligt for os at integrere med EMIS Health. Det er et elektronisk patientjournalsystem, der anvendes i den primære pleje i Storbritannien. Til integration brugte vi deres medfølgende DLL-bibliotek.

Den tilgang, som jeg vil vise dig her (desinficeret for at undgå at lække følsomme oplysninger), rullede ud til produktion for mere end to år siden og har siden bevist sin holdbarhed.

Da vi for nylig har brugt en helt ny tilgang til integration med EMIS, lukkes det gamle system om en måned eller to. Så denne tutorial er dens svanesang. Sov, min lille prins.

Hvad er DLL API?

Lad os først starte med en klar beskrivelse af DLL-biblioteket. For at gøre dette forberedte jeg en kort mock-up af den originale tekniske dokumentation.

Lad os se igennem det for at se, hvad de tre metoder til en COM-grænseflade er.

InitialiseWithID-metode

Denne metode er en sikkerhedsfunktion, der kræves på stedet, der lader os få en forbindelse til en API-server, som vi vil integrere med biblioteket.

Det kræver AccountID(GUID) for den aktuelle API-bruger (for at få adgang til serveren) og nogle andre initialiseringsargumenter, der er angivet nedenfor.

Denne funktion understøtter også en automatisk login-funktion. Hvis en klient har en logget version af det kørende system (biblioteket er en del af dette system) og kalder metoden på den samme vært, udfylder API'et automatisk login under brugerens konto. Derefter returnerer den SessionIDtil efterfølgende API-opkald.

Ellers skal klienten fortsætte med Logonfunktionen (se næste del) ved hjælp af den returnerede LoginID.

For at ringe til funktionen skal du bruge navnet InitialiseWithIDmed følgende argumenter:

Navn Ind ud Type Beskrivelse
adresse I Snor forudsat integrationsserver IP
Konto-id I Snor forudsat unik GUID-streng
LoginID Ud Snor GUID-streng brugt til Logon API-opkald
Fejl Ud Snor Fejlbeskrivelse
Resultat Ud Heltal -1 = Se fejl

1 = Vellykket initialisering afventer logon

2 = Kan ikke oprette forbindelse til server på grund af manglende server eller forkerte detaljer

3 = Uovertruffen konto-id

4 = Autologon vellykket

Sessions ID Ud Snor GUID bruges til efterfølgende interaktioner (hvis automatisk log ind er vellykket)

Logonmetode

Denne metode bestemmer brugerens autoritet. Brugernavnet her er det id, der bruges til at logge ind på systemet. Adgangskoden er API-adgangskoden, der er indstillet til dette brugernavn.

I succes scenariet returnerer opkaldet en SessionIDstreng (GUID), der skal sendes til andre efterfølgende opkald for at godkende dem.

For at ringe til funktionen skal du bruge navnet Logonmed følgende argumenter:

Navn Ind ud Type Beskrivelse
LoginID I Snor Login-id'et returneres ved initialiseringsmetoden Initialiser med ID
brugernavn I Snor angivet API-brugernavn
adgangskode I Snor angivet API-adgangskode
Sessions ID Ud Snor GUID bruges til efterfølgende interaktioner (hvis logon lykkes)
Fejl Ud Snor Fejlbeskrivelse
Resultat Ud Heltal -1 = Teknisk fejl

1 = vellykket

2 = Udløbet

3 = mislykkedes

4 = Ugyldigt login-ID eller login-ID har ikke adgang til dette produkt

getMatchedUsers Method

Dette opkald giver dig mulighed for at finde brugerdataposter, der matcher specifikke kriterier. Søgeudtrykket kan kun henvise til et felt ad gangen, såsom efternavn, fornavn eller fødselsdato.

Et vellykket opkald returnerer en XML-streng med dataene i den.

For at ringe til funktionen skal du bruge navnet getMatchedUsersmed følgende argumenter:

Navn Ind ud Type Beskrivelse
Sessions ID I Snor Sessions-id'et returneres efter logonmetoden
MatchTerm I Snor Søgeterm
MatchedList Ud Snor XML i overensstemmelse med den medfølgende tilsvarende XSD-ordning
Sessions ID Ud Snor GUID bruges til efterfølgende interaktioner (hvis logon lykkes)
Fejl Ud Snor Fejlbeskrivelse
Resultat Ud Heltal -1 = Teknisk fejl

1 = brugere fundet

2 = Adgang nægtet

3 = Ingen brugere

DLL Library Application Flow

To make it easier to grasp what we want to implement, I decided to create a simple flow diagram.

It describes a step-by-step scenario of how a web client can interact with our server-based application using its API. It encapsulates interaction with the DLL Library and allows us to get hypothetical users with the provided match term (search criteria):

Registering COM

Now let's learn how we can access the DLL library. To be able to interact with a 3rd party COM interface, it needs to be added to the registry.

Here's what the docs say:

Registret er en systemdatabase, der indeholder oplysninger om konfigurationen af ​​systemhardware og software samt om brugere af systemet. Ethvert Windows-baseret program kan tilføje oplysninger til registreringsdatabasen og læse oplysninger tilbage fra registreringsdatabasen. Kunder søger i registreringsdatabasen efter interessante komponenter, der skal bruges.

Registret vedligeholder oplysninger om alle de COM-objekter, der er installeret i systemet. Hver gang et program opretter en forekomst af en COM-komponent, høres registreringsdatabasen for at løse enten CLSID eller ProgID for komponenten i stienavnet på server-DLL eller EXE, der indeholder den.

Efter at have bestemt komponentens server, indlæser Windows serveren enten i procesområdet for klientapplikationen (komponenter i processen) eller starter serveren i sit eget procesrum (lokale og eksterne servere).

Serveren opretter en forekomst af komponenten og returnerer til klienten en henvisning til en af ​​komponentens grænseflader.

For at lære at gøre det siger den officielle Microsoft-dokumentation:

Du kan køre et kommandolinjeværktøj kaldet Assembly Registration Tool (Regasm.exe) for at registrere eller afregistrere en samling til brug med COM.

Regasm.exe tilføjer oplysninger om klassen til systemregistret, så COM-klienter kan bruge .NET Framework-klassen gennemsigtigt.

Klassen RegistrationServices giver den tilsvarende funktionalitet. En administreret komponent skal registreres i Windows-registreringsdatabasen, før den kan aktiveres fra en COM-klient

Sørg for, at din værtsmaskine har installeret de nødvendige .NET Frameworkkomponenter. Derefter kan du udføre følgende CLI-kommando:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe {PATH_TO_YOUR_DLL_FILE} /codebase

A message will display indicating whether the file was successfully registered. Now we're ready for the next step.

Defining the Backbone of the Application

DllApiService

First of all, let's define the interface that describes our DLL library as it is:

public interface DllApiService { /** * @param accountId identifier for which we trigger initialisation * @return Tuple3 from values of Outcome, SessionID/LoginID, error * where by the first argument you can understand what is the result of the API call */ Mono
    
      initialiseWithID(String accountId); /** * @param loginId is retrieved before using {@link DllApiService#initialiseWithID(String)} call * @param username * @param password * @return Tuple3 from values of Outcome, SessionID, Error * where by the first argument you can understand what is the result of the API call */ Mono
     
       logon(String loginId, String username, String password); /** * @param sessionId is retrieved before using either * {@link DllApiService#initialiseWithID(String)} or * {@link DllApiService#logon(String, String, String)} calls * @param matchTerm * @return Tuple3 from values of Outcome, MatchedList, Error * where by the first argument you can understand what is the result of the API call */ Mono
      
        getMatchedUsers(String sessionId, String matchTerm); enum COM_API_Method { InitialiseWithID, Logon, getMatchedUsers } }
      
     
    

As you might have noticed, all the methods map with the definition of the COM Interface described above, except for the initialiseWithID function.

I decided to omit the address variable in the signature (the IP of the integration server) and inject it as an environment variable which we will be implementing.

SessionIDService Explained

To be able to retrieve any data using the library, first we need to get the SessionID.

According to the flow diagram above, this involves calling the initialiseWithID method first. After that, depending on the result, we will get either the SessionID or LoginID to use in subsequent Logon calls.

So basically this is a two-step process behind the scenes. Now, let's create the interface, and after that, the implementation:

public interface SessionIDService { /** * @param accountId identifier for which we retrieve SessionID * @param username * @param password * @return Tuple3 containing the following values: * result ( Boolean), sessionId (String) and status (HTTP Status depending on the result) */ Mono
    
      getSessionId(String accountId, String username, String password); }
    
@Service @RequiredArgsConstructor public class SessionIDServiceImpl implements SessionIDService { private final DllApiService dll; @Override public Mono
    
      getSessionId(String accountId, String username, String password) { return dll.initialiseWithID(accountId) .flatMap(t4 -> { switch (t4.getT1()) { case -1: return just(of(false, t4.getT3(), SERVICE_UNAVAILABLE)); case 1: { return dll.logon(t4.getT2(), username, password) .map(t3 -> { switch (t3.getT1()) { case -1: return of(false, t3.getT3(), SERVICE_UNAVAILABLE); case 1: return of(true, t3.getT2(), OK); case 2: case 4: return of(false, t3.getT3(), FORBIDDEN); default: return of(false, t3.getT3(), BAD_REQUEST); } }); } case 4: return just(of(true, t4.getT2(), OK)); default: return just(of(false, t4.getT3(), BAD_REQUEST)); } }); } }
    

API Facade

The next step is to design our web application API. It should represent and encapsulate our interaction with the COM Interface API:

@Configuration public class DllApiRouter { @Bean public RouterFunction dllApiRoute(DllApiRouterHandler handler) { return RouterFunctions.route(GET("/api/sessions/{accountId}"), handler::sessionId) .andRoute(GET("/api/users/{matchTerm}"), handler::matchedUsers); } }

Besides the Router class, let's define an implementation of its handler with logic for retrieving the SessionID and the user records data.

For the second scenario, to be able to make a DLL getMatchedUsers API call according to the design, let's use the mandatory header X-SESSION-ID:

@Slf4j @Component @RequiredArgsConstructor public class DllApiRouterHandler { private static final String SESSION_ID_HDR = "X-SESSION-ID"; private final DllApiService service; private final AccountRepo accountRepo; private final SessionIDService sessionService; public Mono sessionId(ServerRequest request) { final String accountId = request.pathVariable("accountId"); return accountRepo.findById(accountId) .flatMap(acc -> sessionService.getSessionId(accountId, acc.getApiUsername(), acc.getApiPassword())) .doOnEach(logNext(t3 -> { if (t3.getT1()) { log.info(format("SessionId to return %s", t3.getT2())); } else { log.warn(format("Session Id could not be retrieved. Cause: %s", t3.getT2())); } })) .flatMap(t3 -> status(t3.getT3()).contentType(APPLICATION_JSON) .bodyValue(t3.getT1() ? t3.getT2() : Response.error(t3.getT2()))) .switchIfEmpty(Mono.just("Account could not be found with provided ID " + accountId) .doOnEach(logNext(log::info)) .flatMap(msg -> badRequest().bodyValue(Response.error(msg)))); } public Mono matchedUsers(ServerRequest request) { return sessionIdHeader(request).map(sId -> Tuples.of(sId, request.queryParam("matchTerm") .orElseThrow(() -> new IllegalArgumentException( "matchTerm query param should be specified")))) .flatMap(t2 -> service.getMatchedUsers(t2.getT1(), t2.getT2())) .flatMap(this::handleT3) .onErrorResume(IllegalArgumentException.class, this::handleIllegalArgumentException); } private Mono sessionIdHeader(ServerRequest request) { return Mono.justOrEmpty(request.headers() .header(SESSION_ID_HDR) .stream() .findFirst() .orElseThrow(() -> new IllegalArgumentException(SESSION_ID_HDR + " header is mandatory"))); } private Mono handleT3(Tuple3 t3) { switch (t3.getT1()) { case 1: return ok().contentType(APPLICATION_JSON) .bodyValue(t3.getT2()); case 2: return status(FORBIDDEN).contentType(APPLICATION_JSON) .bodyValue(Response.error(t3.getT3())); default: return badRequest().contentType(APPLICATION_JSON) .bodyValue(Response.error(t3.getT3())); } } private Mono handleIllegalArgumentException(IllegalArgumentException e) { return Mono.just(Response.error(e.getMessage())) .doOnEach(logNext(res -> log.info(String.join(",", res.getErrors())))) .flatMap(res -> badRequest().contentType(MediaType.APPLICATION_JSON) .bodyValue(res)); } @Getter @Setter @NoArgsConstructor public static class Response implements Serializable { private String message; private Set errors; private Response(Set errors) { this.errors = errors; } public static Response error(String error) { return new Response(singleton(error)); } } }

Account Entity

As you might have noticed, we've imported AccountRepo in the router's handler to find the entity in a database by the provided accountId. This lets us get the corresponding API user credentials and use all three in the DLL Logon API call.

To get a clearer picture, let's define the managed Account entity as well:

@TypeAlias("Account") @Document(collection = "accounts") public class Account { @Version private Long version; /** * unique account ID for API, provided by supplier * defines restriction for data domain visibility * i.e. data from one account is not visible for another */ @Id private String accountId; /** * COM API username, provided by supplier */ private String apiUsername; /** * COM API password, provided by supplier */ private String apiPassword; @CreatedDate private Date createdAt; @LastModifiedDate private Date updatedOn; }

The JACOB Library Setup

All parts of our application are ready now except the core – the configuration and use of the JACOB library. Let's start with setting up the library.

The library is distributed via sourceforge.net. I did not find it available anywhere on either the Central Maven Repo or any other repositories online. So I decided to import it manually into our project as a local package.

To do that, I downloaded it and put it in the root folder under /libs/jacob-1.19.

After that, put the following maven-install-plugin configuration into pom.xml. This will add the library to the local repository during Maven's install build phase:

 org.apache.maven.plugins maven-install-plugin   install-jacob validate  ${basedir}/libs/jacob-1.19/jacob.jar default net.sf.jacob-project jacob 1.19 jar true   install-file    

That will let you easily add the dependency as usual:

 net.sf.jacob-project jacob 1.19 

The library import is finished. Now let's get it ready to use it.

To interact with the COM component, JACOB provides a wrapper called an ActiveXComponent class (as I mentioned before).

It has a method called invoke(String function, Variant... args) that lets us make exactly what we want.

Generally speaking, our library is set up to create the ActiveXComponent bean so we can use it anywhere we want in the app (and we want it in the implementation of DllApiService).

So let's define a separate Spring @Configuration with all the essential preparations:

@Slf4j @Configuration public class JacobCOMConfiguration { private static final String COM_INTERFACE_NAME = "NAME_OF_COM_INTERFACE_AS_IN_REGISTRY"; private static final String JACOB_LIB_PATH = System.getProperty("user.dir") + "\\libs\\jacob-1.19"; private static final String LIB_FILE = System.getProperty("os.arch") .equals("amd64") ? "\\jacob-1.19-x64.dll" : "\\jacob-1.19-x86.dll"; private File temporaryDll; static { log.info("JACOB lib path: {}", JACOB_LIB_PATH); log.info("JACOB file lib path: {}", JACOB_LIB_PATH + LIB_FILE); System.setProperty("java.library.path", JACOB_LIB_PATH); System.setProperty("com.jacob.debug", "true"); } @PostConstruct public void init() throws IOException { InputStream inputStream = new FileInputStream(JACOB_LIB_PATH + LIB_FILE); temporaryDll = File.createTempFile("jacob", ".dll"); FileOutputStream outputStream = new FileOutputStream(temporaryDll); byte[] array = new byte[8192]; for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) { outputStream.write(array, 0, i); } outputStream.close(); System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath()); LibraryLoader.loadJacobLibrary(); log.info("JACOB library is loaded and ready to use"); } @Bean public ActiveXComponent dllAPI() { ActiveXComponent activeXComponent = new ActiveXComponent(COM_INTERFACE_NAME); log.info("API COM interface {} wrapped into ActiveXComponent is created and ready to use", COM_INTERFACE_NAME); return activeXComponent; } @PreDestroy public void clean() { temporaryDll.deleteOnExit(); log.info("Temporary DLL API library is cleaned on exit"); } }

It's worth mentioning that, besides defining the bean, we initialize the library components based on the host machine's ISA (instruction set architecture).

Also, we follow some common recommendations to make a copy of the corresponding library's file. This avoids any potential corruption of the original file during runtime. We also need to cleanup all allocated resources when the applications terminates.

Now the library is set up and ready to use. Finally, we can implement our last main component that helps us interact with the DLL API:  DllApiServiceImpl.

How to Implement a DLL Library API Service

As all COM API calls are going to be cooked using a common approach, let's implement InitialiseWithID first. After that, all other methods can be implemented easily in a similar way.

Som jeg nævnte før, for at interagere med COM-grænsefladen, giver JACOB os den ActiveXComponentklasse, der har invoke(String function, Variant... args)metoden.

Hvis du vil vide mere om Variantklassen, siger JACOB-dokumentationen følgende (du kan finde den i arkivet eller under /libs/jacob-1.19i projektet):

Multi-format datatypen bruges til alle tilbagekald og mest kommunikation mellem Java og COM. Det giver en enkelt klasse, der kan håndtere alle datatyper.

Dette betyder, at alle argumenter, der er defineret i InitialiseWithIDsignaturen, skal pakkes ind new Variant(java.lang.Object in)og sendes til invokemetoden. Brug den samme rækkefølge som specificeret i interface-beskrivelsen i begyndelsen af ​​denne artikel.

The only other important thing we haven't touched on yet is how to distinguish in and out type arguments.

For that purpose, Variant provides a constructor that accepts the data object and information about whether this is by reference or not. This means that after invoke is called, all variants that were initialized as references can be accessed after the call. So we can extract the results from out arguments.

To do that, just pass an extra boolean variable to the constructor as the second parameter: new Variant(java.lang.Object pValueObject, boolean fByRef).

Initializing the Variant object as reference puts an additional requirement on the client to decide when to release the value (so it can be scrapped by the garbage collector).

For that purpose, you have the safeRelease() method that is supposed to be called when the value is taken from the corresponding Variant object.

Putting all the pieces together gives us the following service's implementation:

@RequiredArgsConstructor public class DllApiServiceImpl implements DllApiService { @Value("${DLL_API_ADDRESS}") private String address; private final ActiveXComponent dll; @Override public Mono
    
      initialiseWithID(final String accountId) { return Mono.just(format("Calling %s(%s, %s, %s, %s, %s, %s)",// InitialiseWithID, address, accountId, "loginId/out", "error/out", "outcome/out", "sessionId/out")) .doOnEach(logNext(log::info)) //invoke COM interface method and extract the result mapping it onto corresponding *Out inner class .map(msg -> invoke(InitialiseWithID, vars -> InitialiseWithIDOut.builder() .loginId(vars[3].toString()) .error(vars[4].toString()) .outcome(valueOf(vars[5].toString())) .sessionId(vars[6].toString()) .build(), // new Variant(address), new Variant(accountId), initRef(), initRef(), initRef(), initRef())) //Handle the response according to the documentation .map(out -> { final String errorVal; switch (out.outcome) { case 2: errorVal = "InitialiseWithID method call failed. DLL API request outcome (response code from server via DLL) = 2 " +// "(Unable to connect to server due to absent server, or incorrect details)"; break; case 3: errorVal = "InitialiseWithID method call failed. DLL API request outcome (response code from server via DLLe) = 3 (Unmatched AccountID)"; break; default: errorVal = handleOutcome(out.outcome, out.error, InitialiseWithID); } return of(out, errorVal); }) .doOnEach(logNext(t2 -> { InitialiseWithIDOut out = t2.getT1(); log.info("{} API call result:\noutcome: {}\nsessionId: {}\nerror: {}\nloginId: {}",// InitialiseWithID, out.outcome, out.sessionId, t2.getT2(), out.loginId); })) .map(t2 -> { InitialiseWithIDOut out = t2.getT1(); //out.outcome == 4 auto-login successful, SessionID is retrieved return of(out.outcome, out.outcome == 4 ? out.sessionId : out.loginId, t2.getT2()); }); } private static Variant initRef() { return new Variant("", true); } private static String handleOutcome(Integer outcome, String error, COM_API_Method method) { switch (outcome) { case 1: return "no error"; case 2: return format("%s method call failed. DLL API request outcome (response code from server via DLL) = 2 (Access denied)", method); default: return format("%s method call failed. DLL API request outcome (response code from server via DLL) = %s (server technical error). " + // "DLL API is temporary unavailable (server behind is down), %s", method, outcome, error); } } /** * @param method to be called in COM interface * @param returnFunc maps Variants (references) array onto result object that is to be returned by the method * @param vars arguments required for calling COM interface method * @param type of the result object that is to be returned by the method * @return result of the COM API method invocation in defined format */ private T invoke(COM_API_Method method, Function returnFunc, Variant... vars) { dll.invoke(method.name(), vars); T res = returnFunc.apply(vars); asList(vars).forEach(Variant::safeRelease); return res; } @SuperBuilder private static abstract class Out { final Integer outcome; final String error; } @SuperBuilder private static class InitialiseWithIDOut extends Out { final String loginId; final String sessionId; }
    

Two other methods, Logon and getMatchedUsers, are implemented accordingly. You can refer to my GitHub repo for a complete version of the service if you want to check it out.

Congratulations – You've Learned a Few Things

We've gone through a step by step scenario that showed us how a hypothetical COM API could be distributed and called in Java.

We also learned how the JACOB library can be configured and effectively used to interact with a DDL library within your Spring Boot 2 application.

En lille forbedring ville være at cache det hentede SessionID, der kunne forbedre det generelle flow. Men det er lidt uden for denne artikels anvendelsesområde.

Hvis du vil undersøge nærmere, kan du finde det på GitHub, hvor det implementeres ved hjælp af Spring's cachemekanisme.

Håber du nød at gå igennem alt sammen med mig og fandt denne tutorial nyttig!