Skip to content

Commit

Permalink
#188571765 Additional Jersey Example using code and annotations to se…
Browse files Browse the repository at this point in the history
…t up and configure (#137)

* Moving jersey example to an xml specific folder and creating a Jersey 2.3.0 example using annotations

* Explicitly annotate a ServletContainer to configure the application path

* Cleanup
  • Loading branch information
bakennedy authored Nov 15, 2024
1 parent 0907675 commit 66b0584
Show file tree
Hide file tree
Showing 22 changed files with 666 additions and 3 deletions.
File renamed without changes.
132 changes: 132 additions & 0 deletions jersey-servlet-example-annotations/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.moesif.servlet.jersey</groupId>
<artifactId>jersey-servlet-example-annotations</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>jersey-servlet-example-annotations</name>

<properties>
<jersey.version>2.30</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>

<build>
<finalName>jersey-servlet-example-annotations</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<inherited>true</inherited>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.heroku</groupId>
<artifactId>webapp-runner-main</artifactId>
<version>8.5.68.1</version>
<destFileName>webapp-runner.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>

</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>

<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>

<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->
<dependency>
<groupId>com.moesif.servlet</groupId>
<artifactId>moesif-servlet</artifactId>
<version>1.8.1</version>
</dependency>

<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>compile</scope>
</dependency>

</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.moesif.servlet.jersey.example;

import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import org.glassfish.jersey.servlet.ServletContainer;

@WebServlet(
urlPatterns = {"/api/*"},
initParams = {
@WebInitParam(
name = "javax.ws.rs.Application",
value = "com.moesif.servlet.jersey.example.MoesifJerseyApplication"
)
},
loadOnStartup = 1
)
public class JerseyServlet extends ServletContainer {
// No additional code needed here
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.moesif.servlet.jersey.example;

import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;

import java.util.logging.Logger;


public class MoesifJerseyApplication extends ResourceConfig {
Logger log = Logger.getLogger(MoesifJerseyApplication.class.getName());

public MoesifJerseyApplication() {
log.info("Registering MoesifJerseyApplication");
packages("com.moesif.servlet.jersey.example");
register(MultiPartFeature.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.moesif.servlet.jersey.example;

import com.moesif.servlet.MoesifConfiguration;
import com.moesif.servlet.MoesifFilter;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

@WebFilter(
urlPatterns ="/*",
initParams = {
@WebInitParam(name = "application-id",
value = "Your Moesif Application Id"),
@WebInitParam(name = "logBody", value = "true")
}
)
public class MoesifServletFilter extends MoesifFilter {
Logger log = Logger.getLogger(MoesifServletFilter.class.getName());

@Override
public void init(FilterConfig filterConfig) throws ServletException {
setDebug(true);

// Use custom logic to determine User ID and other event metadata from requests
MoesifConfiguration config = new MoesifConfiguration() {
@Override
public String identifyUser(HttpServletRequest request, HttpServletResponse response) {
return "demo-user";
}

@Override
public String identifyCompany(HttpServletRequest request, HttpServletResponse response) {
return "demo-company";
}

@Override
public String getSessionToken(HttpServletRequest request, HttpServletResponse response) {
return "demo-session";
}

@Override
public String getApiVersion(HttpServletRequest request, HttpServletResponse response) {
return "1.0.0";
}
};
setConfigure(config);
super.init(filterConfig);
log.info("MoesifFilter initialized with " + this.getAPI());
}
}
68 changes: 68 additions & 0 deletions jersey-servlet-example-xml/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
### Jersey Servlet

There are multiple ways to run Jersey, as a Java Servlet or embedded with a Java NIO framework like Grizzly. This subsection focuses on running Jersey as a Servlet.

Edit the web.xml file to add your application id that you obtained from your Moesif Account.

```xml
<filter>
<filter-name>MoesifFilter</filter-name>
<filter-class>com.moesif.servlet.MoesifFilter</filter-class>
<init-param>
<param-name>application-id</param-name>
<param-value>Your Moesif application id</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MoesifFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

```

#### Running the Jersey Servlet example

In order to run this example you will need to have Java 7+ and Maven installed.

Before starting, check that your maven version is 3.0.x or above:

```sh
mvn -v
```

1. Clone the repository

```sh
git clone https://github.com/Moesif/moesif-servlet
cd moesif-servlet
```

2. Update web.xml to use your own Moesif ApplicationId
(Register for an account on [moesif.com](https://www.moesif.com))

```sh
vim jersey-servlet-example/src/main/webapp/WEB-INF/web.xml
```

3. Compile the example

```sh
cd jersey-servlet-example
mvn clean install
```

4. Run jersey-servlet-example

```sh
java -jar target/dependency/webapp-runner.jar target/*.war
```

5. Go to `http://localhost:8080/api/demo` or the port that Tomcat is running on.

In your Moesif Account, you should see API calls logged under API Analytics -> Live Event Stream.

Shut it down manually with Ctrl-C.
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
<modelVersion>4.0.0</modelVersion>

<groupId>com.moesif.servlet.jersey</groupId>
<artifactId>jersey-servlet-example</artifactId>
<artifactId>jersey-servlet-example-xml</artifactId>
<packaging>war</packaging>
<version>1.3.2</version>
<name>jersey-servlet-example</name>
<name>jersey-servlet-example-xml</name>

<build>
<finalName>jersey-servlet-example</finalName>
<finalName>jersey-servlet-example-xml</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.moesif.servlet.jersey.example;

import javax.annotation.PostConstruct;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.moesif.api.MoesifAPIClient;
import com.moesif.api.APIHelper;
import com.moesif.api.controllers.APIController;
import com.moesif.api.models.CompanyModel;
import com.moesif.api.models.CompanyBuilder;
import com.moesif.api.models.CampaignModel;
import com.moesif.api.models.CampaignBuilder;

/**
* Root resource (exposed at "companies" path)
*/
@Path("companies/{id}")
public class CompaniesServlet {

private APIController apiClient;

@Context
private Configuration config;

@PostConstruct
public void init() {
String applicationId = (String) config.getProperty("application-id");
apiClient = new MoesifAPIClient(applicationId).getAPI();
}

/**
* Method handling HTTP POST requests. The returned object will be sent
* to the client as "application/json" media type.
*
* @return Response that will be returned as an application/json.
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response updateCompany(@PathParam("id") String id) throws Throwable {

// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
CampaignModel campaign = new CampaignBuilder()
.utmSource("google")
.utmCampaign("cpc")
.utmMedium("adwords")
.utmTerm("api+tooling")
.utmContent("landing")
.build();

// Only companyId is required
// metadata can be any custom object
CompanyModel company = new CompanyBuilder()
.companyId("67890")
.companyDomain("acmeinc.com") // If set, Moesif will enrich your profiles with publicly available info
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"org_name\": \"Acme, Inc\"," +
"\"plan_name\": \"Free\"," +
"\"deal_stage\": \"Lead\"," +
"\"mrr\": 24000," +
"\"demographics\": {" +
"\"alexa_ranking\": 500000," +
"\"employee_count\": 47" +
"}" +
"}"))
.build();

apiClient.updateCompany(company);

return Response.status(Status.CREATED).entity("{"
+ "\"updated_company\": true"
+ "}").build();

}
}
Loading

0 comments on commit 66b0584

Please sign in to comment.