iReport Barcode - local class incompatible: stream classdesc serialVersionUID - jasper-reports

I'm working with one problematic report and it always throws the same exception when client JRE is not the same as server's. This is an RMI app and the exception only occours with this report.
Report
It's a simple report, however it has an barcode component, and I've used 2 implementations offered by iReport 5.0.1 (Barbecue and Barcode4j) and both thrown the same exception:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
local class serialVersionUID = 5670834184508236790
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:191)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at $Proxy17.geraRelatorio(Unknown Source)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:151)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:139)
at jacad.gui.cadastros.curso.FrameCadastroPeriodoLetivo$30.executaAtividade(FrameCadastroPeriodoLetivo.java:1499)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:70)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:296)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at javax.swing.SwingWorker.run(SwingWorker.java:335)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
ocal class serialVersionUID = 5670834184508236790
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
I don't know what do now, I've tried everything I could to fix this, I don't believe that error was caused by Java code because this app have +- 300 reports, and only this one has a barcode. Here's a sample of Java code to call this report by RMI:
public JasperPrint executeReport(String reportFile, Map parameters) throws GenericException {
FileInputStream is = (FileInputStream) getReportFile(reportFile);
Connection conn = getConnection();
JasperPrint print = null;
try {
parameters.put("P_REPORTS_PATH", Application.getInstance().getReportsPath());
parameters.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));
print = JasperFillManager.fillReport(Application.getInstance().getReportsPath() + reportFile, parameters, conn);
} catch (JRException e1) {
e1.printStackTrace();
throw new GenericException(e1);
}
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return print;
}
Client side:
public static void view(final JasperPrint print) throws GenericException {
if (print == null) {
throw new GenericException("Nenhuma visualização do relatório foi informada.");
}
new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
JFrame viewer = new JFrame("Visualização do Relatório"); //$NON-NLS-1$
viewer.setPreferredSize(new Dimension(800, 600));
viewer.setLocationRelativeTo(null);
JasperViewer jrViewer = new JasperViewer(print, true);
viewer.getContentPane().add(jrViewer.getContentPane());
new FrameConfig(viewer);
return null;
}
}.execute();
}
public void showReport(String reportFile, Map parameters) throws GenericException {
if (reportFile == null)
throw new GenericException("Report file não pode ser nulo.");
ReportsManager rm;
try {
rm = (ReportsManager) FacadeFactoryLocal.newInstance(ReportsManager.class);
JasperPrint jasperPrint = rm.geraRelatorio(reportFile, parameters);
view(jasperPrint);
} catch (RemoteException e1) {
e1.printStackTrace();
throw new GenericException("Erro ao acessar o servidor para gerar o relatório.", e1.getStackTrace());
}
}
Does anyone have a solution for this?
Thanks in advance.

Don't serialize Swing components. There is a warning about that at the head of the Javadoc of every one of them. Serialized the underlying model.

Related

How to get the number of Active Connections for HikariCP

I was trying to log the number of current active connections. I am using com.zaxxer.hikari.HikariJNDIFactory as my data source factory.
final Context context = new InitialContext();
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDataSource((DataSource) ((Context)context.lookup("java:comp/env")).lookup("jdbc/mydb"));
HikariPool hikariPool = new HikariPool(hikariConfig);
LOGGER.log(Level.INFO, "The count is ::" + hikariPool.getActiveConnections());
But it is throwing the following exception:
java.lang.RuntimeException: java.lang.NullPointerException
at com.zaxxer.hikari.util.PoolUtilities.createInstance(PoolUtilities.java:105)
at com.zaxxer.hikari.metrics.MetricsFactory.createMetricsTracker(MetricsFactory.java:34)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:131)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:99)
at com.something.servlet.HikariConnectionCount.doGet(HikariConnectionCount.java:35)
Where HikariConnectionCount.java is the file I have written
Programatic access is documented here https://github.com/brettwooldridge/HikariCP/wiki/MBean-(JMX)-Monitoring-and-Management
Here's a dirty recipe:
import org.springframework.beans.DirectFieldAccessor;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
public class HikariDataSourcePoolDetail {
private final HikariDataSource dataSource;
public HikariDataSourcePoolDetail(HikariDataSource dataSource) {
this.dataSource = dataSource;
}
public HikariPool getHikariPool() {
return (HikariPool) new DirectFieldAccessor(dataSource).getPropertyValue("pool");
}
public int getActive() {
try {
return getHikariPool().getActiveConnections();
} catch (Exception ex) {
return -1;
}
}
public int getMax() {
return dataSource.getMaximumPoolSize();
}
}
Use it thus:
try {
HikariDataSourcePoolDetail dsd = new HikariDataSourcePoolDetail((HikariDataSource)dataSource);
log.info("HikariDataSource details: max={} active={}", dsd.getMax(), dsd.getActive());
} catch (Exception e) {
log.error("HikariDataSourcePoolDetail failed: ", e);
}

Junit testing for database conection

Is there a way to test below code.Here I am connecting to database with JNDI.I am new to mockito and not getting a way to test the same.
#SuppressWarnings("unused")
public Connection getJNDIConnection() {
Connection result = null;
try {
InitialContext initialContext = new InitialContext();
if (initialContext == null) {
LOGGER.info("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource) initialContext.lookup(jndiName);
if (datasource != null) {
result = datasource.getConnection();
} else {
LOGGER.info("Failed to lookup datasource.");
}
} catch (NamingException ex) {
LOGGER.error("Cannot get connection: " + ex);
} catch (SQLException ex) {
LOGGER.error("Cannot get connection: " + ex);
}
return result;
}
Of course, you can to do it, but I think you should read the documentation yourself. The main points here is:
InitialContext initialContext = mock(InitialContext.class);
DataSource dataSource = mock(DataSource.class);
Connection expected = mock(Connection.class);
whenNew(InitialContext.class).withNoArguments().thenReturn(initialContext);
when(initialContext.lookup(jndiName)).thenReturn(dataSource);
when(initialContext.getConnection()).thenReturn(connection);
Connection result = intatnceOfCalss.getJNDIConnection();
assertSame("Should be equals", expected, result);
Also you should use PowerMock to mock constructors and static methods. To have deal with Logger, just add this code:
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(logger);
}
Don't forget about annotations:
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
Try to read this doc http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

Titan 0.5.1 Customize object in my node

I have a problem with Titan 0.5.1. I try to upgrade Titan 0.4.4 to 0.5.1. Currently, I use berkeleyje and i configure like this :
BaseConfiguration conf = new BaseConfiguration();
// Storage info
conf.setProperty("storage.directory", directory + File.separator + DB_NAME);
conf.setProperty("storage.backend", "berkeleyje");
// Class info storage
conf.setProperty("attributes.allow-all", "true");
conf.setProperty("attributes.custom.attribute1.attribute-class", "model.Property");
conf.setProperty("attributes.custom.attribute1.serializer-class", "PropertySerializer");
TitanGraph graph = TitanFactory.open(conf);
For serialize my object i use :
public class PropertySerializer implements AttributeSerializer<Property> {
#Override
public Property read(ScanBuffer buffer) {
Property object = null;
ArrayList<Byte> records = new ArrayList<Byte>();
try {
while (buffer.hasRemaining()) {
records.add(Byte.valueOf(buffer.getByte()));
}
Byte[] bytes = records.toArray(new Byte[records.size()]);
ByteArrayInputStream bis = new ByteArrayInputStream(ArrayUtils.toPrimitive(bytes));
ObjectInput in = new ObjectInputStream(bis);
object = (Property) in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
#Override
public void write(WriteBuffer out, Property attribute) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput outobj;
outobj = new ObjectOutputStream(bos);
outobj.writeObject(attribute);
byte[] propertybyte = bos.toByteArray();
for (int i = 0; i < propertybyte.length; i++) {
out.putByte(propertybyte[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void verifyAttribute(Property value) {
// TODO Auto-generated method stub
}
#Override
public Property convert(Object value) {
// TODO Auto-generated method stub
return null;
}
}
Typically, i add a property like this :
Vertex r = this.model.addVertex(null);
Property p = new Property();
r.setProperty("object", p);
this.model.commit();
But i obtain this error :
Exception in thread "main"
com.thinkaurelius.titan.core.TitanException: Could not commit
transaction due to exception during persistence at
com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx.commit(StandardTitanTx.java:1310)
at
com.thinkaurelius.titan.graphdb.blueprints.TitanBlueprintsGraph.commit(TitanBlueprintsGraph.java:60)
Caused by: com.thinkaurelius.titan.core.TitanException: Serializer
Restriction: Cannot serialize object of type: class
.model.Property at
com.thinkaurelius.titan.graphdb.database.serialize.StandardSerializer$StandardDataOutput.writeClassAndObject(StandardSerializer.java:160)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writePropertyValue(EdgeSerializer.java:383)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writePropertyValue(EdgeSerializer.java:377)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writeRelation(EdgeSerializer.java:293)
at
com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.prepareCommit(StandardTitanGraph.java:485)
at
com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.commit(StandardTitanGraph.java:613)
at
com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx.commit(StandardTitanTx.java:1299)
Can you help me please ? Because, with 0.4.4 version it worked. The new documentation don't help me.
Thanks in advance

Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file

I'm new to JMS and I'm studying the following example
public class SendRecvClient
{
static CountDown done = new CountDown(1);
QueueConnection conn;
QueueSession session;
Queue que;
public static class ExListener
implements MessageListener
{
public void onMessage(Message msg)
{
done.release();
TextMessage tm = (TextMessage) msg;
try {
System.out.println("onMessage, recv text=" + tm.getText());
} catch(Throwable t) {
t.printStackTrace();
}
}
}
public void setupPTP()
throws JMSException,
NamingException
{
InitialContext iniCtx = new InitialContext();
Object tmp = iniCtx.lookup("ConnectionFactory");
QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
conn = qcf.createQueueConnection();
que = (Queue) iniCtx.lookup("queue/testQueue");
session = conn.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
conn.start();
}
public void sendRecvAsync(String text)
throws JMSException,
NamingException
{
System.out.println("Begin sendRecvAsync");
// Setup the PTP connection, session
setupPTP();
// Set the async listener
QueueReceiver recv = session.createReceiver(que);
recv.setMessageListener(new ExListener());
// Send a text msg
QueueSender send = session.createSender(que);
TextMessage tm = session.createTextMessage(text);
send.send(tm);
System.out.println("sendRecvAsync, sent text=" + tm.getText());
send.close();
System.out.println("End sendRecvAsync");
}
public void stop()
throws JMSException
{
conn.stop();
session.close();
conn.close();
}
public static void main(String args[])
throws Exception
{
SendRecvClient client = new SendRecvClient();
client.sendRecvAsync("A text msg");
client.done.acquire();
client.stop();
System.exit(0);
}
}
I ran this in JBoss and it gave the following exception
Begin sendRecvAsync
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at se.cambio.jms.SendRecvClient.setupPTP(SendRecvClient.java:53)
at se.cambio.jms.SendRecvClient.sendRecvAsync(SendRecvClient.java:68)
at se.cambio.jms.SendRecvClient.main(SendRecvClient.java:95)
I think this is an error with JNDI name, but I couldn't find which xml file to edit in JBOSS to over come this problem. Please some one help me.

webservice SOAP message Monitor or logging

Could some one tell me how to capture SOAP messages passed between the client and the server webservice applications.
I tried using both tools.
pocket soap
http://www.pocketsoap.com/pocketsoap/
Fiddler
http://www.fiddlertool.com/fiddler/
I may miss some settings, it is not working for me.
help will be more appreciated.
Try tcpmon.
soapUI integrates with tcpmon, and may provide a nicer interface for you.
See also; You can try the MS Visual Roundtrip Analyzer analyzer as well.
if you're interested, you can write a handler in Java which extends the GenericSOAPHandler class, and print the output to wherever you like. In this (simple) case, the server log:
#SuppressWarnings("rawtypes")
public class MyHandler extends GenericSOAPHandler {
private void print(InputStream input, OutputStream out) throws Exception {
try {
DocumentBuilder parser;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newDocumentBuilder();
Document document = parser.parse(input);
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
serializer.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
// A fatal error occurred
throw new Exception(e);
}
}
#Override
protected boolean handleInbound(MessageContext msgContext) {
SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;
SOAPMessage soapMessage = soapMessageCtx.getMessage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
soapMessage.writeTo(outputStream);
byte[] array = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
System.out.println("SOAP request message:\n");
print(inputStream, System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
protected boolean handleOutbound(MessageContext msgContext) {
SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;
SOAPMessage soapMessage = soapMessageCtx.getMessage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
soapMessage.writeTo(outputStream);
byte[] array = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
System.out.println("SOAP response message:\n");
print(inputStream, System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
You also need to make sure your handler is included in the jaxws-handlers-server.xml of your server implementation:
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee javaee_web_services_1_2.xsd">
<handler-chain>
<protocol-bindings>##SOAP11_HTTP</protocol-bindings>
<handler>
<handler-name>DebugHandler</handler-name>
<handler-class>handlers.MyHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
Here my code in C++ for retrieve xml message using Soap Toolkit 3.0 before sending.
.
.
.
Serializer->EndEnvelope();
/* ___________________ */
char * bufferxml = NULL;
_variant_t punt = _variant_t((IUnknown*)Serializer);
punt.lVal += 48;
_variant_t punt1 = *punt.ppunkVal;
punt1.lVal += 32;
_variant_t punt2 = *punt1.ppunkVal;
punt2.lVal += 4;
memcpy(&bufferxml, (char *) *punt2.ppunkVal, sizeof(char *));
punt2.lVal += 4;
int lengxml = *(punt2.pintVal);
bufferxml[lengxml] = '\0';
/* ___________________ */
// Send the message to the web service
Connector->EndMessage();
.
.
.
punt.Detach();
punt1.Detach();
punt2.Detach();
punt.Clear();
punt1.Clear();
punt2.Clear();
Serializer.Release();
.
.
.
I hope really help you, it´s my design and it had worked for me.
There is also TCP/IP Monitor which comes bundled with WTP plugin for eclipse which allows you to set up a monitor on a port to look into the SOAP requests.