I'm trying to create a Jersey Resource that allows me to reuse an ElasticSearch TransportClient. So I would like to use a single instance of TransportClient over all Resources that require it. So far I've got this:
Resource:
#Path("/request")
public class ConfigurationResource {
private final TransportClient transportClient;
#Inject
public ConfigurationResource(TransportClient transportClient)
{
this.transportClient = transportClient;
}
#GET
#Produces(MediaType.TEXT_PLAIN)
public String AlarmStatus(){
if(transportClient != null)
return "Not NULL! ID: ";
else
return "NULL :(";
}
}
Binding:
public class WebMainBinder extends AbstractBinder {
#Override
protected void configure() {
TransportClient transportClient = null;
try {
transportClient = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
return;
}
bind(transportClient).to(TransportClient.class);
}
}
Main Application:
#ApplicationPath("service")
public class WebMain extends ResourceConfig {
public WebMain(){
register(new WebMainBinder());
packages(true, "com.eniacdevelopment.EniacHome.Resources");
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>com.eniacdevelopment.EniacHome.Application.WebMain</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>com.eniacdevelopment.EniacHome.Application.WebMain</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
</web-app>
I've also tried using a factory like so:
public class TransportClientFactory implements Factory<TransportClient> {
private TransportClient transportClient;
#Override
public TransportClient provide() {
if(this.transportClient == null){
try {
transportClient = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
return transportClient;
}
#Override
public void dispose(TransportClient transportClient) {
}
}
And then binding it this way:
bindFactory(TransportClientFactory.class)
.to(TransportClient.class).in(Singleton.class);
But no success. I keep on getting Unsatisfied dependencies for type TransportClient with qualifiers #Default.
Help would be much appreciated!
I've found Jersey's DI container functionality pretty unpleasant. I prefer to use Guice for managing my DI, so if you're open to using Guice, you can see how to wire up Jersey and Guice to collaborate in this demo project: https://bitbucket.org/marshallpierce/guice-jaxrs-examples. The common subproject has the shared logic, and there are other subprojects for the jersey and resteasy specific parts.
Alright got it to work:
When I at first tried to deploy the app to glassfish it complained about some guava dependency. I swapped the Guava jar in glassfish/modules with the one maven had installed and got it to deploy. It may have something to do with that. No guarentees here.
I decided to drop the whole glassfish stuff and start from scratch. On the jersey introduction page there's this maven archetype that can be isntalled like so:
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-service
-Dpackage=com.example
-DarchetypeVersion=2.24
Starting from there helped me out.
Related
Tis is my first time deploying with weblogic, I have a spring boot application and when i add in weblogic than I can't find the path for my rest call, in my main application I even added this log to see where is running but i get no output:
private static final Logger LOGGER = LoggerFactory.getLogger(KpiApplication.class);
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(KpiApplication.class);
Environment env = app.run(args).getEnvironment();
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
System.out.println("LEXA"+ env.getProperty("server.port")+InetAddress.getLocalHost().getHostAddress());
try {
LOGGER.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}\n\t" +
"External: \t{}://{}:{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
env.getProperty("server.port"),
protocol,
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getActiveProfiles());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SpringApplication.run(KpiApplication.class);
}
}
In my weblogic i see this path in this section but i just says page not found:
The rest I'm trying to execute is this but everytime is a page not found:
#RestController
public class AccountController extends KpiAbstractController {
#Autowired
private AccountService accountService;
#GetMapping("/v1/accounts")
public ResponseEntity<AccountDTO> getAccounts(#RequestParam #ApiParam("Point of sale owner ID") String ownerPosId,
#RequestParam #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startPeriod,
#RequestParam #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endPeriod,
HttpServletRequest request)
All the application is already setted up and my manager just told me try it, but he doesn't know the link too, any idea where I can find it please
Have you done what's written in Spring Boot docs "traditional deployment" part? https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.traditional-deployment
Looks like, you didn't.
You get no output from your logs, because public static void main will not be called on WebLogic - you will need to extend SpringBootServletInitializer instead.
Also for weblogic you would usually create src/main/webapp/weblogic.xml file where you would set context-root, e.g.
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.5/weblogic-web-app.xsd">
<context-root>myapp</context-root>
</weblogic-web-app>
Which make you application accessible at http://server:port/myapp URL.
Another thing you didn't mention is if you have a sole AdminServer or AdminServer+ManagedServer? If the letter, then you should deploy your application via AdminServer to ManagedServer and access it at ManagedServer host:port.
Module Class
public class MorphiaModule extends AbstractModule {
#Override
protected void configure() {
bind(PlayMorphia.class).asEagerSingleton();
}
}
PlayMorphia
#Singleton
public class PlayMorphia {
MongoClient mongo = null;
Datastore datastore = null;
Morphia morphia = null;
#Inject
public PlayMorphia(ApplicationLifecycle lifecycle, Environment env, Configuration config) {
try {
configure(config, env.classLoader(), env.isTest()); // Method calling to get the config
} catch (Exception e) {
e.printStackTrace();
}
lifecycle.addStopHook(()->{
if (env.isTest()) {
mongo().close();
}
return CompletableFuture.completedFuture(null);
});
}
}
In My application.conf, I mentioned the correct package/path name for Module class i.e.
play.modules.enabled += "configuration.MorphiaModule"
I followed the Play framework official doc on Eager Binding: https://www.playframework.com/documentation/2.6.x/JavaDependencyInjection#Eager-bindings
At compile time, I am getting this:
CreationException: Unable to create injector, see the following errors:
1) No implementation for play.inject.ApplicationLifecycle was bound.
while locating play.inject.ApplicationLifecycle
for the 1st parameter of configuration.PlayMorphia. .
(PlayMorphia.java:28)
at configuration.MorphiaModule.configure(MorphiaModule.java:24) (via
modules: com.google.inject.util.Modules$OverrideModule ->
configuration.MorphiaModule)
What am I doing wrong here? Any help would be appreciable.
I want to deploy a Java Netbeans Webapp with an embedded Jetty Server; the server itself works, but I always get the following error:
I searched through mounds of examples on the web, configured & reconfigured my web.xml; although my configuration seems fine, I can't get it to work.
I should point out, that when I run the app from whithin Netbeans using the built-in Glassfish server, it works fine, which tells me that web.xml is probably configured well.
Can anyone help with this?
My code follows.
P.S. I know that it's been asked on SO, but those examples did not work for me either.
Project structure:
WebContext setup:
import org.eclipse.jetty.webapp.WebAppContext;
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
JettyServer.java:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
public class JettyServer {
private Server server;
public JettyServer() {
this(8585);
}
public JettyServer(Integer runningPort) {
server = new Server(runningPort);
}
public void setHandler(ContextHandlerCollection contexts) {
server.setHandler(contexts);
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
server.join();
}
public boolean isStarted() {
return server.isStarted();
}
public boolean isStopped() {
return server.isStopped();
}
}
Deploy.java (main method):
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
/**
*
* #author Motty Waldner <motty#timeworksny.com>
*/
public class Deploy {
private final static Logger log = Logger.getLogger(Deploy.class);
static JettyServer jettyServer = new JettyServer();
public static void main(String[] args) throws Exception {
// add hook to stop server upon service termination
// (service calls System.exit(0) upon termination,
// so it should work under normal circumstances)
addShutdownHook();
ContextHandlerCollection contexts = new ContextHandlerCollection();
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext().getHandler()};
contexts.setHandlers(handlers);
jettyServer = new JettyServer();
try {
jettyServer.start();
} catch (Exception e) {
log.error("Error Starting Jetty Server", e);
}
}
private static void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
jettyServer.stop();
log.info("Shutdown Hook is running: Jetty Server instance being stopped.");
} catch (Exception e) {
log.error("error", e);
}
log.info("Application Terminating ...");
}
});
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Test App</display-name>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name> struts2 </filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<servlet-mapping>
<servlet-name>StrutsController</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Thanks in advance for the help!
Is there any stack trace logs available?
Without more logs, I can only imagine based on experience that it may be caused by directory resolving, it worked fine in your IDE since it can find the proper files without any further context configuration staff ,which may be not the case when you carry out a real deployment.
Maybe the url-pattern is wrong, try to change to something like:
<servlet-mapping>
<servlet-name>StrutsController</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
change from
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
to
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase(webAppContext);
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
try this one let me know
Change
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext().getHandler()};
to
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext()};
I have created RPC service in my existing application using the RPC tutorial mentioned on the page
http://www.gwtproject.org/doc/latest/tutorial/RPC.html#services. I am still getting the 404 no service found exception. Here is what I have done.
Created the service interface on client side.
#RemoteServiceRelativePath("searchportoutorder")
public interface SearchPortOutOrderService extends RemoteService {
List<SearchPortOutOrderModel> fetchMoreRecords();
}
Created the asynce interface on client.
public interface SearchPortOutOrderServiceAsync {
void fetchMoreRecords(AsyncCallback<List<SearchPortOutOrderModel>> async);
}
Create the service impl under package server.
public class SearchPortOutOrderServiceImpl extends RemoteServiceServlet implements SearchPortOutOrderService {
List<SearchPortOutOrderModel> models = new ArrayList<SearchPortOutOrderModel>();
private void initializeModel() {
for(int i=0;i<10000;i++){
SearchPortOutOrderModel model = new SearchPortOutOrderModel();
model.setOrderId("1234-132131-12312-12312");
model.setCustomer("ashish testing");
model.setOrderDate("2014-12-25");
model.setLastUpdated("2014-02-15");
model.setStatus("Completed");
models.add(model);
}
}
#Override public List<SearchPortOutOrderModel> fetchMoreRecords() {
initializeModel();
return models;
}
Update the web.xml file to involve the servlet.
<servlet>
<servlet-name>searchPortOutOrderService</servlet-name>
<servlet-class>com.inetwork.gwt.client.searchportoutorder.server.SearchPortOutOrderServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>searchPortOutOrderService</servlet-name>
<url-pattern>/report/searchportoutorder</url-pattern>
</servlet-mapping>
I am still getting 404 exception saying that the service is not found.Do I need to modified anything else in my code like .gwt.xml file.
if your gwt module name is not report
modify *.gwt.xml like this.
<module rename-to='report'>
or replace url-pattern in web.xml to your gwt-module-name.
I'm trying to rewrite a legacy app in JSF and the other apps thave have been rewritten have the maven version posted in the footer.
I'm trying to figure out how their doing it and so far, here's what i have figured out that they are doing:
footer.xhtml
<h:outputText id="fullBuildString" value="#{ApplicationInfo.fullBuildString}" />
ApplicationInfoBacking.java
public class ApplicationInfoBacking {
private String buildTime;
private String iteration;
private String version;
private String inception;
private String fullBuildString;
#PostConstruct
public void init() {
fullBuildString = generateFullBuildString();
}
public String getBuildTime() {
return buildTime;
}
public void setBuildTime(final String buildTime) {
this.buildTime = buildTime;
}
public String getIteration() {
return iteration;
}
public void setIteration(final String iteration) {
this.iteration = iteration;
}
public String getVersion() {
return version;
}
public void setVersion(final String version) {
this.version = version;
}
public String getInception() {
return inception;
}
public void setInception(final String inception) {
this.inception = inception;
}
/**
* #return ApplicationName vVersion (Iteration) BuildTime
*/
public String getFullBuildString() {
return fullBuildString;
}
public String generateFullBuildString() {
if ((version == null) || "".equals(version.trim())) {
version = "Unknown version";
}
if ((iteration == null) || "".equals(iteration.trim())) {
iteration = "Unknown iteration";
}
if ((buildTime == null) || "".equals(buildTime.trim())) {
buildTime = "Unknown build time";
}
final StringBuilder build = new StringBuilder();
build.append("v. ").append(version);
if (!Phase.PRODUCTION.equals(PlatformUtil.getPhase()) && !Phase.BETA.equals(PlatformUtil.getPhase())) {
build.append(" (").append(iteration).append(")");
build.append(" ").append(buildTime);
}
return build.toString();
}
}
faces-config.xml
<managed-bean>
<managed-bean-name>ApplicationInfo</managed-bean-name>
<managed-bean-class>path.to.class.ApplicationInfoBacking</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<property-name>buildTime</property-name>
<value>#{initParam.buildTime}</value>
</managed-property>
<managed-property>
<property-name>iteration</property-name>
<value>#{initParam.iteration}</value>
</managed-property>
<managed-property>
<property-name>version</property-name>
<value>#{initParam.version}</value>
</managed-property>
<managed-property>
<property-name>inception</property-name>
<value>#{initParam.inception}</value>
</managed-property>
</managed-bean>
web.xml
<context-param>
<param-name>buildTime</param-name>
<param-value>${buildNumber}</param-value>
</context-param>
<context-param>
<param-name>iteration</param-name>
<param-value>${iteration}</param-value>
</context-param>
<context-param>
<param-name>version</param-name>
<param-value>${pom.version}</param-value>
</context-param>
This is what is actually displayed when i load the app:
v. ${pom.version}
For some reason the ${pom.version} is not getting interpreted.
Does anyone know why?
It looks like they are using the buildnumber plugin: http://mojo.codehaus.org/buildnumber-maven-plugin/
You need to add that to your web-module, then enable filtering for the web.xml through the resources section in pom.xml - I think the faces-config does not need to be changed. I was not aware you can use initParam.
If you cant you could still filter the faces-config directly in case your IDE does not like filtering the web.xml
the "pom.version" may not work as it is deprecated? Try using project.version
have the maven pom keys coming from different properties file
read the properties file on app startup and put it in application scoped bean
pom.version is not interpreted because at runtime there is no such thing as a pom. The pom.xml is in memory as a Java object tree of the project setup at build time only when Maven reads the pom and creates the model. At runtime Maven is not running so pom.version has no value. Also pom.* is deprecated.. it should be project.*
In order to do what you want use the solution proposed in the other answer..