read manifest.mf while initializing JAX-RS - java

I am trying to read information from MANIFEST.MF while initializing JAX-RS. I use Glassfish app server.
My first idea was to use the following piece of code:
Properties prop = new Properties();
prop.load(getClasses().getClass().getResourceAsStream("/META-INF/MANIFEST.MF"));
String version = prop.getProperty("Implementation-Version");
But this code reads info from another MANIFEST.MF, not from my WAR so I need to use ServletContext:
package com.remal.forum.service.configuration.rest;
import java.io.InputStream;
import java.util.jar.Manifest;
import javax.servlet.ServletContext;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
#ApplicationPath("api")
public class Configurator extends Application {
#Context
protected ServletContext servletContext;
public Configurator() {
...
InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(inputStream);
manifest.getAttributes("Implementation-Version");
...
}
}
But the injected servletContext is always null. What is wrong here?

Related

How to use extensions in OpenTelemetry java

I am trying to extend OpenTelemetry java agent and I don't see any indication it is trying to load my jar.
I am running the following cmd:
java -javaagent:../src/main/resources/opentelemetry-javaagent.jar -Dotel.javaagent.configuration-file=../src/main/resources/agent-prp.properties -jar simple-service-1.0-SNAPSHOT-jar-with-dependencies.jar
my config file is (the attributes are working):
otel.javaagent.extensions=/Users/foo/source/simple-service/src/main/resources/span-processor-1.0-SNAPSHOT.jar
otel.resource.attributes=service.name=foooBarr
my extension is:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SpanProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class FooSpanProcessor implements SpanProcessor {
private static final ObjectMapper objMapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(FooSpanProcessor.class);
#Override
public void onStart(Context parentContext, ReadWriteSpan span) {
log.error("fffffffffff");
span.setAttribute("fooToken", FooProperties.INSTANCE.fooToken);
span.setAttribute("service.name", FooProperties.INSTANCE.serviceName);
span.setAttribute("runtime", FooProperties.INSTANCE.javaVersion);
span.setAttribute("tracerVersion", "0.0.1");
span.setAttribute("framework", FooProperties.INSTANCE.frameWork);
span.setAttribute("envs", FooProperties.INSTANCE.environment);
span.setAttribute("metaData", FooProperties.INSTANCE.metadata);
}
#Override
public boolean isStartRequired() {
return true;
}
#Override
public void onEnd(ReadableSpan span) {
}
....
I don't see any indication that my extension is loaded, I don't see any of my parameters on the produced spans. can any body help me?
"otel.javaagent.extensions" is not supported in the config file. add it with -D.
add the span processor to a config call implementing sdkTracerProviderConfigurer

AttributeNotFoundException through JMX in Startup bean on Wildfly

Hello everyone!
I'm trying to load wildfly server's system properties through JMX in Startup bean's #PostConstruct method. It works fine on the already started server instance when deployment starts, but fails while starting with server instance bootstrapping.
Wildfly 11.0.0.CR1
Startup bean code:
package ru.wildfly.test.ejb.wildflyconsulregistrar.startup;
import ru.wildfly.test.ejb.wildflyconsulregistrar.api.ConsulRegistrar;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
#Startup
#Singleton
public class WildflyConsulRegistrarStartupBean {
#Inject
private ConsulRegistrar consulRegistrar;
#PostConstruct
public void initialize() {
registerServices();
}
private void registerServices() {
consulRegistrar.registerService("WildflyTestCluster");
}
.............
}
ConsulRegistrar code:
package ru.wildfly.test.ejb.wildflyconsulregistrar.impl;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import ru.test.ejb.wildflyconsulregistrar.api.ConsulRegistrar;
import ru.wildfly.test.ejb.wildflyconsulregistrar.serversettings.api.CurrentServerNodeSettings;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
#Dependent
public class ConsulRegistrarImpl implements ConsulRegistrar {
...............
#Inject
private CurrentServerNodeSettings currentServerNodeSettings;
.............
#Override
public void registerService(String serviceName) {
String currentNodeName = currentServerNodeSettings.getCurrentNodeName();
........................
}
.......................
}
CurrentServerNodeSettings code:
package ru.wildfly.test.ejb.wildflyconsulregistrar.serversettings.impl;
import ru.wildfly.test.ejb.wildflyconsulregistrar.serversettings.api.CurrentServerNodeSettings;
import javax.enterprise.context.Dependent;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
#Dependent
public class CurrentServerNodeSettingsWildflyImpl implements CurrentServerNodeSettings {
....................
#Override
public String getCurrentNodeName() {
String currentNodeName = getPlatformMBeanServerAttributeValue(String.class, "jboss.as:system-property=server.name", "value");
return currentNodeName;
}
private <T> T getPlatformMBeanServerAttributeValue(Class<T> valueType, String objectName, String attributeName) {
T attributeValue = null;
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
Object attributeObject = mBeanServer.getAttribute(new ObjectName(objectName), attributeName);
attributeValue = attributeObject != null ? (valueType.cast(attributeObject)) : null;
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
return attributeValue;
}
}
Error message:
Caused by: java.lang.IllegalStateException:
javax.management.AttributeNotFoundException:
"WFLYCTL0216: Management resource '[(\"system-property\" => \"server.name\")]' not found"
at ru.wildfly.test.ejb.wildflyconsulregistrar.serversettings.impl.CurrentServerNodeSettingsWildflyImpl
.getPlatformMBeanServerAttributeValue(CurrentServerNodeSettingsWildflyImpl.java:41)
I have found the same issue on jboss forum https://developer.jboss.org/message/971717#971717 , but it was unanswered.
Any suggestions?
This is a dependency problem during startup, i.e. the server name is set after your #PostConstruct method gets executed. Try to load the server name lazy when it is accessed from the application for the first time.
In Wildfly there is no generic way to enforce the sequence of deployments from the application despite the definition of module dependencies. But this won't help in your case.

Vertx Webroot In Fat Jar

I am building a fat jar for a Vertx-Web application. I would like to serve some static files. I packaged the jar file, with webroot folder. See below screenshot for my jar structure:
I was able to load the webroot/static/test.html file by doing:
routingContext.response().sendFile("webroot/static/test.html");
However, I am not able to get the static handler to work. Below is my full code:
package com.jdescript;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
public class WebVerticle extends AbstractVerticle {
private HttpServer httpServer;
#Override
public void start() throws IOException {
httpServer = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route("/static/*").handler(StaticHandler.create());
router.route("/test").handler(routingContext -> {
routingContext.response().sendFile("webroot/static/test.html");
});
httpServer.requestHandler(router::accept).listen(9999);
}
}
In the above example, http://localhost:9999/static/test.html will say "Not Found", while http://localhost:9999/test will render test.html.
Any help will be appreciated.
Was answered by the Vert.x group at https://groups.google.com/forum/?fromgroups#!topic/vertx/yKInZuYcqDE. My webroot should look like "webroot/test.html", instead of "webroot/static/test.html".

Lookup datasource with custom variable in runtime

I have context.xml defined in META-INF as follow:
<Context path="/7Restaurant">
<Resource name="datasource"
type="javax.sql.DataSource"
auth="Container"
maxActive="10"
maxIdle="3"
maxWait="10000"
username="work"
password=""
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/7restaurant"/>
</Context>
I am about to deploy my web app (Servlet, in Tomcat 7). The only problem is that, how can I change the url, username, etc. to match that with the environment the WAR package is deployed.
So, in essence, how could such a file is modified; or any other technique so that user can finely connect to the database in the environment it will be deployed on.
I am so new in web-app eclipse, tomcat, postgresql stack; so I expect my question to be wrong, if that's the case; please let me know any other way to solve this.
My context initializer in Java:
package com.restaurant.web;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import javax.naming.*;
import javax.servlet.*;
import javax.sql.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import com.restaurant.dao.dbpostgres.DBDAO;
import com.restaurant.setup.GeneralConfigurerSetup;
import com.restaurant.web.Logger;
import sun.java2d.loops.DrawGlyphListAA.General;
public class Database implements ServletContextListener {
private void contextInitialized2(ServletContext servletContext) throws Exception
{
/*
//prepare META-INF/context.xml
DocumentBuilder docbldr = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docbldr.newDocument();
Element context = doc.createElement("Context");
context.setAttribute("path", "/7Restaurant");
Element resource = doc.createElement("Resource");
resource.setAttribute("name", "datasource");
resource.setAttribute("type", "javax.sql.DataSource");
resource.setAttribute("auth", "Container");
resource.setAttribute("maxActive", "10");
resource.setAttribute("maxIdle", "3");
resource.setAttribute("maxWait", "10000");
resource.setAttribute("username", Configurer.get(GeneralConfigurerSetup.DB_USERNAME));
resource.setAttribute("password", Configurer.get(GeneralConfigurerSetup.DB_PASSWORD));
resource.setAttribute("driverClassName", Configurer.get(GeneralConfigurerSetup.DB_CLASS));
resource.setAttribute("url", Configurer.get(GeneralConfigurerSetup.DB_JDBCURL));
context.appendChild(resource);
doc.appendChild(context);
System.out.println(System.getProperty("java.class.path"));
File fOut = new File("META-INF/context.xml");
System.out.println(fOut.getAbsolutePath());
if (fOut.exists()) fOut.delete();
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
Source input = new DOMSource(doc);
Result output = new StreamResult(fOut);
tf.transform(input, output);
*/
//META-INF/context
InitialContext enc = new InitialContext();
Context compContext = (Context) enc.lookup("java:comp/env");
DataSource dataSource = (DataSource) compContext.lookup("datasource");
DBDAO.setDataSource(dataSource);
}
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
try {
contextInitialized2(servletContext);
} catch(Exception e) {
Logger.error("Initializing failed: " + e.getMessage());
System.exit(-1);
}
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
Remove context.xml from your build (just to be safe), and put it in your tomcat folder under conf/Catalina/localhost. Rename it so it's whatever you want your app context name to be (like myapp.xml).
As you can see, that allows each environment to have different myapp.xml files, and when you deploy the war, it will pick that up instead of using an internal one.

How to read a configuration file in eclipse dynamic web project?

I know that there is a configuration file called web.xml
What I want to achieve is have another configuration file that has application specific configuration and it has to be read when the web server is started. I also want a Class to be able to read this configuration. Is there a way I can configure this is web.xml file itself or is there another way
You can use the Apache Commons Configuration. Have a look at the user guide. Since you want it to be done on startup here is a sample ServletContextListener:
package test;
import java.io.File;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
public class ConfigurationListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
File configFile;
try {
configFile = new File(context.getResource("/WEB-INF/configuration.xml").getPath());
Configuration config = new XMLConfiguration(configFile);
context.setAttribute("configuration", config);
} catch (ConfigurationException | MalformedURLException ex) {
Logger.getLogger(ConfigurationListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {}
}
Now get your configuration anywhere in your web application like this:
Configuration config = (Configuration) request.getServletContext().getAttribute("configuration");
I would create a class to hold the configuration though rather than adding it as an attribute to the ServletContext. The class would simply provide access to the configuration through a static method.

Categories

Resources