How to use jolokia to retrieve mbean for a class - java

I have a mbean for a class say foo.bar.Log4j
and I want to use jolokia to list all loggers?
I have tried reading on https://jolokia.org/reference/pdf/jolokia-reference.pdf but that tells me how to get values of predefined java.memory etc
Please suggest on how to get jolokia to retrieve loggers for a user-defined class

You have to keep in mind that even if your mbean is a singleton in your servlet, your servlet could be running on multiple endpoints - that's why the namespace alone is not sufficient to identify your mbean instance.
If you want to get all instances of foo.bar.Log4j, you can use the read endpoint like this:
http://yourserver/jolokia/read/foo.bar.Log4j:*
In general, you can get a list of all your available mbeans like this:
http://yourserver/jolokia/list
You should end up with a large json document that contains everything you might want to fetch. You will see things like
"foo.bar.Log4j": {
"name=foo,type=MyLogger": {
"desc": ...
"attr": {
...
}}}
You can now get the attributes using something like this:
http://yourserver/jolokia/read/foo.bar.Log4j:type=name=foo,type=MyLogger
In addition to type and name, you may see other fields as well, for example context or id. This a:b key is the Java ObjectName for your mbean.

Related

How can I handle a giant static configuration class used in multiple applications?

A related group of applications I've been assigned share a database table for configuration values that has a table with columns 'application', 'config_name', 'config_type' (IE String, Integer), and 'config_value'. There's also a stored procedure that takes in a string (applicationName) and returns all config names, types, and values where applicationName == application.
In each application, a wrapper class is instantiated which contains a static ThreadLocal (hereafter 'static config)', and that static config pulls all values from the config table for the application.
When loading configuration values, the stored procedure returns a massive list of properties that are iterated over, going through a massive list of if-else statements testing whether the 'config_name' column matches a string literal, and if so, loads the value into a differently named variable.
EX:
if (result.isBeforeFirst()) {
while(result.next()) {
if (result.getString("config_name").equals("myConfig1") {
myConfigurationValue1 = result.getString(config_value); }
else if (result.getString("config_name").equals("myConfig2") {
myConfigurationValue2 = result.getString(config_value); }
}}
These cover between 60-100ish configs per app, and each application has an identical Configuration class save for the names of the properties they're trying to read.
So my questions are:
Having one gigantic configuration class is poor design, right? I'm not entirely sure how to break them down and I can't share them here, but I'm assuming best practice would be to have multiple configuration classes that have all the components needed to perform a particular operation, IE 'LocalDatabaseConfig' or '(ExternalSystemName)DatabaseConfig'?
Once broken down, what's the best way to get config valuee where needed without static access? If I have each class instantiate the configuration it needs I'll be doing a lot of redundant db operations, but if I just pass them from the application entry point then many classes have to 'hold on' to data they don't need to feed it to later classes... Is this a time when static config classes are the best option??
Is there an elegant way to load properties from the DB (in core java - company is very particular with third party libraries) without using this massive if-else chain I keep thinking that ideally we'd just dynamically load each property as it's referenced, but the only way I can think to do that is to use another stored procedure that takes in a unique identifier for a property and load it that way, but that would involve a lot more string literals...m
(Might be invalidated by 3) Is there a better way for the comparison in the pseudo-code above to test for a property rather than using a string literal? Could this be resolved if we just agreed to name our configuration properties in the application the same way they're named in the DB?
Currently every application just copy-pastes this configuration class and replaces the string literals and variable names; many of the values are unique in name and value, some are unique in value but are named the same between applications (and vice versa), and some are the same name and value for each application, but because the stored procedure fetches values based on application, redundant db entries are necessary (despite that many such values are supposed to be the same at all times, and any change to one needs to be performed on the other versions as well). Would it make sense to create a core library class that can construct any of the proposed 'broken down' configuration classes? IE, every application needs some basic logging configurations that don't change across the applications. We already have a core library that's a dependency for each application, but I don't know whether it would make sense add all/some/none of the configuration classes to the core library...
Thanks for your help! Sorry for the abundance of questions!?
The cascading if-then-else might be eliminated by using a while loop to copy the database-query results into two maps: a Map[String, String] for the string-based configuration variables, and a Map[String, Integer] for the integer configuration variables. Then the class could provide the following operations:
public String lookupStringVariable(String name, String defaultValue) {
String value = stringMap.get(name);
if (value == null) {
return defaultValue;
} else {
return value;
}
}
public int lookupIntVariable(String name, int defaultValue) {
Integer value = intMap.get(name);
if (value == null) {
return defaultValue;
} else {
return value.intValue();
}
}
If there is a requirement (perhaps for runtime performance) to have the configuration values stored in fields of the configuration class, then the configuration class could make the above two operations private and use them to initialize fields. For example:
logLevel = lookupIntVariable("log_level", 2);
logDir = lookupStringVariable("log_dir", "/tmp");
An alternative (but complementary) suggestion is to write a code generator application that will query the DB table and generate a separate Java class for each value in the application column of the DB table. The implementation of a generated Java class would use whatever coding approach you like to query the DB table and retrieve the application-specific configuration variables. Once you have written this generator application, you can rerun it whenever the DB table is updated to add/modify configuration variables. If you decide to write such a generator, you can use print() statements to generate the Java code. Alternatively, you might use a template engine to reduce some of the verbosity associated with print() statements. An example of a template engine is Velocity, but the Comparison of web template engines Wikipedia article lists dozens more.
You would be better off separating the database access from the application initialisation. A basic definition would be Map<String,String> returned by querying for one application's settings:
Map<String,String> config = dbOps.getConfig("myappname");
// which populates a map from the config_name/config_value queries:
// AS: config.put(result.getString("config_name"), result.getString("config_value");
Your application code then can initialise from the single application settings:
void init(Map<String,String> config) {
myConfigurationValue1 = config.get("myConfig1");
myConfigurationValue2 = config.get("myConfig2");
}
A benefit of this decoupling is that you define test cases for your application by hardwiring the config for different permutations of Map settings without accessing a huge test database configurations, and can test the config loader independently of your application logic.
Once this is working, you might consider whether dbOps.getConfig("myappname") caches the per-application settings to avoid excessive queries (if they don't change on database), or whether to declare Config as a class backed by Map but with calls for getInt / get and default values, and which throw RuntimeException if missing keys:
void init(Config config) {
myConfigurationValue1 = config.get("myConfig1", "aDefaultVal");
myConfigurationInt2 = config.getInt("myConfig2", 100);
}

How to extract xpath list in camel

My requirement is as below:
I have a properties file which has values as:
/message/header/messagetype ='DATA'
So the XPaths are the keys and the values are the dates I want to check in Camel at runtime
I read an ActiveMQ queue which gets me an XML message. Now at runtime I need to check the respective XPaths from the properties file and check there respective values in the XML message I get from the queue. There could be any number of XPath checks defined in the properties file. This is defined by the business needs and the code should take care of it.
There is no standard way to read a properties file and "transform" it to XPath checks. However, you can always use a plain Java Bean and call it from your Camel route. For example like this:
from()
...
.bean(YourBean.class)
...
With this you can use Java code as a "component" in your Camel route.
For more details see the Camel docs about Bean binding and the Bean component.
Thank you for the help. I figured out how to do this by using Predicate functionality in Camel.So what I am doing now is, creating multiple Predicate objects based on my property file entries and adding them to 'PredicateBuilder' as below ::
PredicateBuilder.and(p1,p2....pn);
This returns me an object of Predicate which I can use in when() of Camel.
for eg. choice().
when(predicateBuilder()).

How to get Solr field type

Is there any way of getting the metadata for a solr core ?
For instance I know the core name, and can obtain a SolServer from that and I also know the field name.
Is there any way to determine the metadata though. Specifically I would like to know whether the field type is an int or a double.
Thanks
You can make a request to the luke request handler:
http://localhost:8983/solr/corename/admin/luke?show=schema&wt=json&_=1453816769771
The output will include the schema for the core, along with the defined fields, their settings and their types:
{"fields":{"xyz":{"type":"string","flags":"I-S-M---OF-----l","copyDests":[],"copySources":[]}, .... }
A neat trick to find these endpoints is to watch the 'network' tab when browsing the admin interface to Solr, as the admin interface is just a static HTML / Javascript frontend that makes all the requests for actual content from the Solr server behind the scenes.

Namespaces in the Google App Engine Datastore

Because of the nature of my application, I need to "namespace" the datastore.
This is the code I see in the docs:
// Set the namepace temporarily to "abc"
String oldNamespace = NamespaceManager.get();
NamespaceManager.set("abc");
try {
... perform operation using current namespace ...
} finally {
NamespaceManager.set(oldNamespace);
}
However, I'm not sure where the namespace must be set to the XML before you can use it or you can create namespace dynamically in code?
Also I see with the MemcacheService there is a setNamespace method (although deprecated already); how about the DatastoreService is there a way to namespace a given service instance we get from the DatastoreServiceFactory factory, so we don't have to set namespace back-and-forth with our code?
You don't have to declare namespaces to use them. If you want to make a multi-tenant application then namespaces are a perfect fit. Basically, you just have to set the namespace once at the beginning of your request. That namespace setting automatically applies to all your API calls during that request. Switching back and forth as shown in the docs will only be necessary for accessing data that's shared by all tenants.

What are attributes?

Could anyone please clarify the defination of attribute?
for example, in the following code, what is an attribute:
request.setAttribute("ja",new foo.Employee());
Is the attribute in the above code an object of type foo.Employee(), or it is key/value pair, or it is actually "ja"?
Request attributes are values indexed by a key (in your case "ja") which are shared in the life of the request object. In Java filter, servlet, jsp, include and forward use same request object so for example you can push an object in a servlet and pull it in a JSP.
The same approach is for session and application scopes
Request attributes are (or at least act like) a map of objects, in this case the key is "ja" and the value is a new foo.Employee.
The session, page, and application have the same data structure.
From the servlet API specification:
Attributes are objects associated with a request. Attributes may be set by the
container to express information that otherwise could not be expressed via the API,
or may be set by a servlet to communicate information to another servlet (via the
RequestDispatcher). Only one attribute value may be associated with an attribute name.
Here an attribute is a custom piece of information (here a new foo.Employee) added to your request (in a Map,Object> . This information will last as long as this request is processed and it can be used later in the process, for example by a JSP.
It's a key value pair
From the docs:
setAttribute
public void
setAttribute(java.lang.String name,
java.lang.Object o)
Stores an attribute in this request. Attributes are reset between
requests. This method is most often
used in conjunction with
RequestDispatcher.
Attribute names should follow the same conventions as package names.
Names beginning with java., javax.,
and com.sun.*, are reserved for use by
Sun Microsystems.
If the value passed in is null, the effect is the same as calling
removeAttribute(java.lang.String).

Categories

Resources