java.lang.ClassCastException: org.apache.log4j.Logger cannot be cast - log4j

I extended org.apache.log4j.Logger for implementing logging for method starts and exists.
It works fine, when I don't set the loglevel for a class in my log4j.properties.
When I set
log4j.logger.de.martinm.tools.UniCredit.ExportOperator=INFO
I get an exception:
Exception in thread "main" java.lang.ClassCastException: org.apache.log4j.Logger cannot be cast to de.martinm.tools.Logging.MMLogger
at de.martinm.tools.UniCredit.ExportOperator.(ExportOperator.java:21)
at de.martinm.tools.UniCredit.ExportOperator.main(ExportOperator.java:330)
public class MMLogger extends Logger {
private static MyLoggerFactory myFactory = new MyLoggerFactory();
public MMLogger(String name) {
super(name);
}
public static Category getInstance(String name) {
return Logger.getLogger(name, myFactory);
}
public static Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
public void enter(Logger logger, String method) {
super.debug(method+" enter");
}
public void exit(Logger logger, String method) {
super.debug(method+" exit");
}
public void debug(Logger logger, String method, String text) {
super.debug(method+" "+text);
}
public void warn(Logger logger, String method, String text) {
super.warn(method+" "+text);
}
public void info(Logger logger, String method, String text) {
super.info(method+" "+text);
}
public void error(Logger logger, String method, String text) {
super.error(method+" "+text);
}
}
public class MyLoggerFactory implements LoggerFactory {
/**
The constructor should be public as it will be called by
configurators in different packages. */
public
MyLoggerFactory() {
}
public
Logger makeNewLoggerInstance(String name) {
return new MMLogger(name);
}
}
Here is part of my code
public class ExportOperator {
//public static Logger logger = Logger.getLogger(ExportOperator.class.getName());
public MMLogger Mylogger = (MMLogger) MMLogger.getLogger(ExportOperator.class.getName());
public Connection db_con;
static Utils my_utils = new Utils();
public Properties props = new Properties();
public String output_dir;
public int mid;
public String admin_id;
public int op_id;

Related

Model mapper mapping Map<String,Object> to class which extends another generic class not working for list field

I am trying to create my custom configuration object from Map using model mapper. Everything gets mapped properly excepts the fields property which is coming fro Generic super class.
My target object is
public class ADParserConfig extends CustomParserConfig<ADParserConfigField> {
private String pattern;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
This extends generic class CustomParserConfig
public class CustomParserConfig<T extends CustomParserConfigField> {
protected List<T> fields;
protected String timeStampField;
public List<T> getFields() {
return fields;
}
public void setFields(List<T> fields) {
this.fields = fields;
}
public String getTimeStampField() {
return timeStampField;
}
public void setTimeStampField(String timeStampField) {
this.timeStampField = timeStampField;
}
}
Where CustomParserConfigField is
public class CustomParserConfigField {
protected String name;
protected Integer index;
protected String type;
protected String format;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
I am trying to map Map using below function
ADParserConfig adParserConfig = getConfig(map,ADParserConfig.class);
public <T extends CustomParserConfig> T getConfig(Map<String,Object> configObject, Class<T> classType){
ModelMapper modelMapper = new ModelMapper();
return modelMapper.map(configObject,classType);
}
Everything excepts fields gets mapped properly for the below map.
{fields=[{name=timeStamp, type=timestamp, format=dd/mm/yyyy HH:MM:SS a}, {name=logName, type=string}], pattern=(?<timeStamp>\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\s[AMPMampm]{2})?\s(LogName=(?<logName>[\w\s\W]+))?\sSourceName=(?<sourceName>[\w\s\W]+)\sEventCode=(?<eventCode>[0-9]*), timeStampField=timestamp}
Please help. Why is issue happens only for fields object ? Do I need to specify something else in mapper configurations ?
It looks like a bug and it had been fixed by #370

NLog how to use class member variable in log?

I am writing a program and I use NLog in it. I have several classes and in all of them I have the property
public string DeviceName { get; set; }
I want the logger to put this in front of my log message, so if for instance I have two classes
class A
{
public DeviceName {get;set;} = "HMP20"
public void methodOne()
{
logger.Info("Something");
}
}
class B
{
public DeviceName {get;set;} = "HMP30"
public void methodOne()
{
logger.Info("Something");
}
}
then the output in the log file should be
HMP20: Something
HMP30: Something
How does one achieve this?
The fast solution is to use the logger-name as device-name:
public class A
{
public string DeviceName {get => logger.Name; set => logger = NLog.LogManager.GetLogger(value); }
private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
}
public class B
{
public string DeviceName {get => logger.Name; set => logger = NLog.LogManager.GetLogger(value); }
private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
}
Then you can use the following layout-renderer: ${logger:shortname=true}

JaxB Marshaling in camel

I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?
I have the following POJO class
public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}
following is my camel code for jaxb implementation
JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
jaxbMarshal.setContextPath("com.test");
jaxbMarshal.setPartClass("com.test.MyPojo");
from("direct:javaObjects") //this direct having the list of MYPojo Objects
.marshal(jaxbMarshal)
.to("src/output");
I am getting below exception(I added maven dependency for jaxb in classpath)
Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat#3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
I have created the jaxb.index file(new->File from eclipse). the content of the file should be annotation class name
In our case it should be
MyPojo
and its needs to be placed in context path. in our case it should be placed in
com.test location
and the annotated Pojo class is
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public class MyPojo {
#XmlElement
private int groupId;
#XmlElement
private int memberId;
#XmlElement
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}
You can use your pojo with some annotations:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="MY-POJO")
#XmlType(propOrder = {"groupId", "memberId", "details"})
public class MyPojo {
#XmlElement(name = "groupId")
private int groupId;
#XmlElement(name = "memberId")
private int memberId;
#XmlElement(name = "details")
private String details;
public int getgroupId() {
return groupId;
}
public void setgroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getdetails() {
return details;
}
public void setdetails(String details) {
this.details = details;
}}

#XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML

how to pick the value of an attribute 'name' which is a PriceEventName class type in the below case, FYI if i put #XmlAttribute above it this is turn out to an exception "an error #XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML"
I looking heavily on the internet but I didn't find something similar to my case
PriceEvent class
package somepackage
import ...
import
#XmlAccessorType(XmlAccessType.FIELD)
public class PriceEvent {
#XmlElement(name="Message",namespace="someValue")
private String color;
private PriceEventName name;// this is an attribute
.
.
}
PriceEventName class
Imports ...
public class PriceEventName {
public static final int PRICEUPDATE_TYPE = 0;
public static final PriceEventName PRICEUPDATE = new PriceEventName(PRICEUPDATE_TYPE, "X-mas");
private static java.util.Hashtable _memberTable = init();
private static java.util.Hashtable init() {
Hashtable members = new Hashtable();
members.put("X-mas", PRICEUPDATE);
return members;
}
private final int type;
private java.lang.String stringValue = null;
public PriceEventName(final int type, final java.lang.String value) {
this.type = type;
this.stringValue = value;
}
public static PriceEventName valueOf(final java.lang.String string) {
java.lang.Object obj = null;
if (string != null) {
obj = _memberTable.get(string);
}
if (obj == null) {
String err = "" + string + " is not a valid PriceEventName";
throw new IllegalArgumentException(err);
}
return (PriceEventName) obj;
}
}
This is how you declare the field as an attribute with an adapter:
#XmlJavaTypeAdapter(PenAdapter.class)
#XmlAttribute
protected PriceEventName name;
public PriceEventName getName() { return name; }
public void setName(PriceEventName value) { this.name = value; }
Add you'll need to add a getter to PriceEventName:
public String getStringValue(){ return stringValue; }
And here is the adapter class:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PenAdapter extends XmlAdapter<String,PriceEventName> {
public PriceEventName unmarshal(String v) throws Exception {
return PriceEventName.valueOf( v );
}
public String marshal(PriceEventName v) throws Exception {
return v.getStringValue();
}
}

JAVA/JAXB : Marshal/UnMarshal using attributes in the xml or class members

I have XML as follows
<request type="1">
<request-header/>
<request-details>
<!-- Some more tags -->
</request-details>
</request>
For mapping this XML I have class structure as follows :
public class Request1
{
private RequestDetail_1;
//other members
}
public class Request2
{
private RequestDetail_2;
//other members
}
public class RequestDetail_1
{
//members
}
public class RequestDetail_2
{
//Members
}
What I want to do is ... If attribute type is 1 then I need to create object of type Request_1 , if type is 2 then object type will be Request_2 and so on.
I have gone through this link for reference but still couldn't figure out a way to do this. I want to use pure JAXB and not MOXY or any other such frame works... :( .
Partial code :
#XmlJavaTypeAdapter(RequestAdaptor.class)
#XmlRootElement(name="request")
public class AuthRequest extends Request
{
private AuthRequestDetails requestDetails;
public RequestDetails getRequestDetails()
{
return requestDetails;
}
#Override
public void setRequestDetails(RequestDetails requestDetails)
{
this.requestDetails = (AuthRequestDetails)requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class AuthRequestDetails extends RequestDetails
{
#XmlElement(name="user-name")
private String userName;
#XmlElement(name="password")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RequestAdaptor.class)
public abstract class Request
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
protected RequestHeader requestHeader;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public abstract void setRequestDetails(RequestDetails requestDetails);
public abstract RequestDetails getRequestDetails();
}
public class RequestAdaptor extends XmlAdapter<RequestDTO, Request>
{
#Override
public RequestDTO marshal(Request v) throws Exception
{
System.out.println("marshal");
RequestDTO lRequestDTO= new RequestDTO();
lRequestDTO.setRequestHeader(v.getRequestHeader());
lRequestDTO.setType(v.getType());
if(v.getType().equals("5"))
{
AuthRequest lRequest = (AuthRequest)v;
}
else
{
PingRequest lRequest = (PingRequest)v;
}
return lRequestDTO;
}
#Override
public Request unmarshal(RequestDTO v) throws Exception
{
System.out.println("unmarshal");
if(v.getType().equals("5"))
{
AuthRequest lRequest = new AuthRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
else
{
PingRequest lRequest = new PingRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestDTO
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
private RequestHeader requestHeader;
#XmlElement(name="request-details")
private RequestDetails requestDetails;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RequestDetails getRequestDetails() {
return requestDetails;
}
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestHeader
{
#XmlElement(name="name")
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
First thing is : Marshal and Unmarshal of Adaptor is not getting called. I am stuck at this point.
You can use a StAX XmlStreamReader to parse the XML. Then advance it to the root element. When it's at the root element event check the value of the type attribute. Use this value to determine which Class you should pass to the unmarshal method that takes a Class and XmlStreamReader to get the result you are looking for.

Resources