how to solve market data request for quickfixj - java

i am new using in fix transport i have try to create connection to my broker using java. i have problem for running my java application for marketdata request.
here my main class java
public class FastmatchMDRequest {
public static void main(String[] args) {
SocketInitiator socketInitiator = null;
try {
InputStream inputStream = null;
if (args.length == 0) {
inputStream = FastmatchMDRequest.class.getResourceAsStream("initiator.cfg");
} else if (args.length == 1) {
inputStream = new FileInputStream(args[0]);
}
if (inputStream == null) {
System.out.println("usage: " + FastmatchMDRequest.class.getName() + " [configFile].");
return;
}
SessionSettings settings = new SessionSettings(inputStream);
inputStream.close();
Application application = new TestMarketdataRequest();
FileStoreFactory fileStoreFactory = new FileStoreFactory(settings);
FileLogFactory logFactory = new FileLogFactory(settings);
MessageFactory messageFactory = new DefaultMessageFactory();
socketInitiator = new SocketInitiator(application,
fileStoreFactory, settings, logFactory,
messageFactory);
socketInitiator.start();
SessionID sessionId = socketInitiator.getSessions().get(0);
sendMarkeDataRequest(sessionId);
int i = 0;
do {
try {
Thread.sleep(1000);
System.out.println(socketInitiator.isLoggedOn());
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
} while ((!socketInitiator.isLoggedOn()) && (i < 30));
} catch (ConfigError e) {
e.printStackTrace();
} catch (SessionNotFound e) {
e.printStackTrace();
} catch (Exception exp) {
exp.printStackTrace();
} finally {
if (socketInitiator != null) {
socketInitiator.stop(true);
}
}
}
private static void sendMarkeDataRequest(SessionID sessionId)
throws SessionNotFound {
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
Message message = new Message();
quickfix.fix42.MarketDataRequest.NoMDEntryTypes group =
new quickfix.fix42.MarketDataRequest.NoMDEntryTypes();
quickfix.fix42.MarketDataRequest.NoRelatedSym group1 =
new quickfix.fix42.MarketDataRequest.NoRelatedSym();
MarketDataRequest marketdatarequest = new MarketDataRequest();
Header header = marketdatarequest.getHeader();
header.setField(new BeginString("FIX.4.2"));
header.setField(new SenderCompID("Mycomp"));
header.setField(new TargetCompID("mybroker"));
header.setField(new MsgType("V"));
message.setField(new MDReqID(randomUUIDString));
message.setField(new SubscriptionRequestType((char) 1));
message.setField(new MarketDepth(1));
message.setField(new NoMDEntryTypes(1));
group.setField(new MDEntryType((char) 1));
message.addGroup(group);
group1.setField(new Symbol("ALL"));
message.addGroup(group1);
try
{
Session.sendToTarget(message);
System.out.println("message" + message);
}catch (Exception ex)
{
System.out.println("error" + ex);
}
}}
and for application class
public class TestMarketdataRequest implements Application {
public void fromAdmin(quickfix.Message arg0, SessionID arg1)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon {
// TODO Auto-generated method stub
System.out.println("Successfully called fromAdmin for sessionId : "
+ arg0);
}
public void fromApp(quickfix.Message arg0, SessionID arg1)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
// TODO Auto-generated method stub
System.out.println("Successfully called fromApp for sessionId : "
+ arg0);
}
public void onCreate(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully called onCreate for sessionId : "
+ sessionID);
}
public void onLogon(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully logged on for sessionId : " + sessionID);
}
public void onLogout(SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Successfully logged out for sessionId : " + sessionID);
}
public void toAdmin(quickfix.Message message, SessionID sessionID) {
// TODO Auto-generated method stub
System.out.println("Inside toAdmin");
}
public void toApp(quickfix.Message message, SessionID sessionID) throws DoNotSend {
// TODO Auto-generated method stub
System.out.println("Message : " + message + " for sessionid : " + sessionID);
}
public void onMessage(MarketDataIncrementalRefresh message, SessionID sessionID)
throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
System.out.println("Inside onMessage for New Order Single" + message + sessionID);
}
public void MarketDataIncrementalRefresh (Message message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
}
public void MarketDataSnapshotFullRefresh (Message message, SessionID sessionID) throws FieldNotFound{
String Symbol = message.getField(new Symbol()).getValue();
NoMDEntries noMDEntries = new NoMDEntries();
message.getField(noMDEntries);
quickfix.fix42.MarketDataSnapshotFullRefresh.NoMDEntries group =
new quickfix.fix42.MarketDataSnapshotFullRefresh.NoMDEntries();
MDEntryType MDEntryType = new MDEntryType();
MDEntryPx MDEntryPx = new MDEntryPx();
MDEntrySize MDEntrySize = new MDEntrySize();
SendingTime sendingTime = new SendingTime();
message.getField(sendingTime);
message.getGroup(1, group);
group.get(MDEntryType);
group.get(MDEntryPx);
group.get(MDEntrySize);
message.getGroup(2, group);
group.get(MDEntryType);
group.get(MDEntryPx);
group.get(MDEntrySize);
System.out.printf("Symbol {0} Price {1}", Symbol, MDEntryPx);
}
i have add and artifact in my pom.xml for quickfixj and etc. but when i build as jar and run jar application i got an error like
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: quickfix/SessionNotFound
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: quickfix.SessionNotFound
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
... 7 more
how to fix my problem for build market data request ?
best regards,
Fuad

Try creating executable/fat jar with dependencies by adding below plugin in your pom.xml
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>

Related

How can I serialise and deserialise a custom type array rabbitMq

I have a simple parking-lot simulation which simulates the entry and exit of customers. A class called entrySimulation is used as the producer and the exitSimulation consumes the message and peforms checks to see if a customer should enter.The entry simulation class is as follows:
package parking.experiment_2;
public class entrySimulation implements Runnable {
public static void main(String[] args) {
ScheduledExecutorService entrySimulation = Executors.newScheduledThreadPool(1);
entrySimulation.scheduleAtFixedRate(new entrySimulation(), 2, 4, TimeUnit.SECONDS);
}
///PRODUCER CLASS
int numOfRuns = 100;//1000 runs
public securityGuard_exp_1 myGuard = new securityGuard_exp_1();
//System.out.println("Customer Exiting");
//Thread.sleep(randomTime.nextInt(5000));
public meterClass_exp_1 myMeter = new meterClass_exp_1();
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
//instantiation of the info generator class
public infoGenerator_exp_1 info = new infoGenerator_exp_1();
//Generating random Car info
//spot_exp_1 mySpot = new spot_exp_1();
//Use an iterator
public List<ticketClass_exp_1> ticketArray = new ArrayList<>();
Iterator<ticketClass_exp_1> iter = ticketArray.iterator();
public final spot_exp_1 availableSpot = new spot_exp_1();
//Random time generator
Random randomTime = new Random();
//List<Employee> empList = new ArrayList<>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
{
try {
oos = new ObjectOutputStream(bos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public List<ticketClass_exp_1> randomEntry() throws IOException, TimeoutException {
Gson gson = new GsonBuilder().create();
carClass_exp_2 car = null;
String queueName = "exitQueue";
String message = null;
for (int currentRuns = 0; currentRuns < numOfRuns; currentRuns++) {
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
myMeter.setPurchasedMinutes(randomTime.nextInt(30));
carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880));
ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//Generating details
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
//myTicket.getGuard().setguardName("Phill");
//myTicket.getGuard().setBadgeNumber("AF170");
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
message = gson.toJson(myTicket);
ticketArray.add(myTicket);
return ticketArray;
}
public void publishMessage( ticketClass_exp_1 tickArray ) throws IOException, TimeoutException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(tickArray);
///Direct exchange from enrtySimulation to exit simulation -Used to inform customer exit
//Topic exchange from entrySimulation to individual car park types . EG: Mercedes benz lot, SRT lot, ...
String exchangeName = "entryExchange";
String routingKey = "exitKey";
//Creating a connection factory
ConnectionFactory factory = new ConnectionFactory();
try(Connection conVar = factory.newConnection()){
Channel channelCon = conVar.createChannel();
//Exchange declaration
channelCon.exchangeDeclare(exchangeName,"customerEntry");
channelCon.basicPublish(exchangeName,routingKey,null,bos.toByteArray());
//System.out.println(message);
System.out.println("Customer Entered");
}catch(Exception e){}
}
#Override
public void run() {
ticketClass_exp_1 message = null;
try {
message = (ticketClass_exp_1) randomEntry();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
//Publishing message
try {
publishMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
}
The consumer then consumes the array as follows;
public class exitSimulation implements Runnable {
//public exitSimulation(Channel channel) {
//super(channel);
//String storedMessage;
//}
public String reciver() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
//Creat connection
Channel channel = connection.createChannel();
//create channel
String recievQueue = channel.queueDeclare().getQueue();
System.out.println(" Awaiting Cars");
consumeConvert consumer=new consumeConvert(channel);
channel.basicConsume(recievQueue,true,consumer);
// using
return consumer.getFormatMessage();
}
public class consumeConvert extends DefaultConsumer {
private String storedMessage;
public consumeConvert(Channel channelReceiver) {
super(channelReceiver);
}
public String getFormatMessage() {
return storedMessage;
}
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] messageBody)
throws IOException {
String message = new String(messageBody, "UTF-8");
System.out.println(" MSG RECIEVED: " + message + "'");
storedMessage = message; // store message here
}
}
public static void main(String[] args) {
//Receives message when customers are entering - Contains customer information e.g. customer x is entering.. details ....
// Adds them to a local array
// IF any customers checkParking(ExitCar, meterOut) == true : CUSTOMER EXITS
//
//
//Get the messages and pass as function inputs
/*
*
public class MyConsumer extends DefaultConsumer {
private String storedMessage;
public MyConsumer(Object channelRecv) {
super(channelRecv);
}
public String getStoredMessage() {
return storedMessage;
}
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
storedMessage = message; // store message here
}
}
*
*
* Perfrom checks and send exiting car
* */
//String qName = channelCon.queueDeclare().getQueue();
//Binding the queue
//channelCon.queueBind(qName, exchangeName, routingKey);
Collection<ticketClass_exp_2> ticketArray = new ArrayList<ticketClass_exp_2>();
int availableSpot = 0;
Random randomTime = new Random();
//System.out.println(availableSpot.getSpotNum());
for (ticketClass_exp_2 tick : ticketArray) {
if (ticketArray.size() != 0) {
meterClass_exp_2 meterOut = tick.getMeter();
carClass_exp_2 ExitCar = tick.getCar();
securityGuard_exp_2 myGuard2 = new securityGuard_exp_2();
//System.out.println("IND" + tick.slotNum);
if (myGuard2.checkParking(ExitCar, meterOut)) {
try {
Thread.sleep(randomTime.nextInt(2000));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("\nCustomer " + ExitCar.plateGetter() + " is exiting the carpark...");
double penaltyVal = tick.getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
}
}
if (availableSpot == 16) {
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Send a message
//System.out.println("Total Waiting customers: " + bouncedCustomers);
}
//} catch (Exception e) {
//}
//currentRuns += 1;
///Thread.join(5000);
}
}
The array recived is of type ticketArray. How can I make this work please?
Any enhancement recommendations are welcome

NullPointerException while invoking method getInputParameters()

I am doing Parameterized Java Mapping in SAP PI 7.5 with following parameters bound by the tag names specified in the Operation Mapping
(BS_NAME,CHANNEL_NAME,EMAIL).
On testing the below java mapping in the test tab of OM using the payload, it gives the following error:
NullPointerException while trying to invoke the method com.sap.aii.mapping.api.TransformationInput.getInputParameters() of a null object loaded from field of an object loaded from local variable "this**"
I debugged the code but didn't found the issue, any suggestions?
Please find below Java code for XmlNFe_To_Mail Class. BodyText Class is also used to fetch some content. The error is encountered in the XmlNFe_To_Mail Class.
public class XmlNFe_To_Mail extends AbstractTransformation {
private String prefixoSubject = new String();
private String emailFrom = new String();
private String prefixoDocumento = new String();
private String frase = new String();
private String gap = "\n\r";
private AbstractTrace trace = null;
private Map map = null;
private String BSSystem = "";
private String ComChannel = "";
private String Emails = "";
private final String NFE_EMPRESA = "NFE Company: ";
private final String NFe = "NFE";
private final String NFe_Mail = "nfe#company.com";
TransformationInput input = null;
TransformationOutput output = null;
public void execute(InputStream in , OutputStream out) throws StreamTransformationException {
// TODO Auto-generated method stub
{
BSSystem = input.getInputParameters().getString("BS_NAME");
ComChannel = input.getInputParameters().getString("CHANNEL_NAME");
Emails = input.getInputParameters().getString("EMAIL");
try {
configParamEmail();
BufferedReader inpxml = new BufferedReader(new InputStreamReader( in ));
StringBuffer buffer = new StringBuffer();
String line = "";
String quebra = System.getProperty("line.separator");
while ((line = inpxml.readLine()) != null) {
line.replaceAll("\r\n", "");
line.replaceAll(quebra, "");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
buffer.append(line);
}
String inptxml = buffer.toString();
inptxml = inptxml.replace("\r\n", "");
inptxml = inptxml.replaceAll(quebra, "");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
String idNFe = "";
String numeroNF = "";
String idEvent = "";
idNFe = inptxml.substring(inptxml.indexOf("<chNFe>") + 7, inptxml.indexOf("</chNFe>"));
numeroNF = idNFe.substring(25, 34);
if (inptxml.indexOf("infEvento") > 0) {
idEvent = inptxml.substring(inptxml.indexOf("<tpEvento>") + 10, inptxml.indexOf("</tpEvento>"));
if (idEvent.length() > 0) {
if (idEvent.equals("111111")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CancNFe"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "NFE CANCELADA"));
} else if (idEvent.equals("100000")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CCE"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "CCE"));
} else {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "ManDest"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "MANIFESTO"));
}
}
}
Channel chn = null;
RfcAccessor rfc = null;
String email = "";
String pdf = "";
chn = LookupService.getChannel(getBSystem(), getCChannel());
rfc = LookupService.getRfcAccessor(chn);
String req = "<ns0:TEST_NFE_MAIL_OPT xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><I_ACCESS_KEY>" +
idNFe + "<I_ACCESS_KEY></ns0:ZOTC_NFE_EMAIL_OUTPUT>";
InputStream inputRFC = new ByteArrayInputStream(req.getBytes("UTF-8"));
XmlPayload rfcPayload = LookupService.getXmlPayload(inputRFC);
XmlPayload result = rfc.call(rfcPayload);
InputStream resp = result.getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(resp);
Node node = (Node) doc.getElementsByTagName("E_EMAIL").item(0);
if (node.hasChildNodes() && !node.getFirstChild().getNodeValue().equals("")) {
email = node.getFirstChild().getNodeValue();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transform = tf.newTransformer();
Document docout = db.newDocument();
Element root = docout.createElement("ns0:Mail");
root.setAttribute("xmlns:ns0", "http://sap.com/xi/XI/Mail/30");
docout.appendChild(root);
Element subject = docout.createElement("Subject");
root.appendChild(subject);
Text subjectText = docout.createTextNode(getPrefixoSubject() + numeroNF);
subject.appendChild(subjectText);
Element from = docout.createElement("From");
root.appendChild(from);
Text fromText = docout.createTextNode(getEmailFrom());
from.appendChild(fromText);
if (email.length() > 0) {
email += ";";
} else {
email = this.getEmaillist();
}
Element to = docout.createElement("To");
root.appendChild(to);
Text toText = docout.createTextNode(email);
to.appendChild(toText);
Element contentType = docout.createElement("Content_Type");
root.appendChild(contentType);
Text contentTypeText = docout.createTextNode("multipart/mixed;boundary=--AaZz");
contentType.appendChild(contentTypeText);
BodyText texto = new BodyText(idNFe, getFrase(), inptxml, pdf);
Element content = docout.createElement("Content");
root.appendChild(content);
Text contentText = null;
if ("NFE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getnfeText());
} else if ("NFE CANCELADA Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getCnfeText());
} else if ("CCE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getcceText());
}
content.appendChild(contentText);
DOMSource domS = new DOMSource(docout);
transform.transform((domS), new StreamResult(out));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// Exception Handling }
}
}
}
public String getGap() {
return gap;
}
public void setGap(String gap) {
this.gap = gap;
}
public String getFrase() {
return frase;
}
public void setFrase(String frase) {
this.frase = frase;
}
public String getBSystem() {
return BSSystem;
}
public String getEmaillist() {
return Emails;
}
public String getCChannel() {
return ComChannel;
}
public String getPrefixoSubject() {
return prefixoSubject;
}
public void setPrefixoSubject(String prefixoSubject) {
this.prefixoSubject = prefixoSubject;
}
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
public String getPrefixoDocumento() {
return prefixoDocumento;
}
public void setPrefixoDocumento(String prefixoDocumento) {
this.prefixoDocumento = prefixoDocumento;
}
private void configParamEmail() {
setEmailFrom(NFe_Mail);
setPrefixoDocumento(NFe);
setPrefixoSubject(NFE_EMPRESA);
}
#Override
public void transform(TransformationInput in , TransformationOutput out) throws StreamTransformationException {
this.execute( in .getInputPayload().getInputStream(), out.getOutputPayload().getOutputStream());
}
/*public void setParameter(Map arg0) {
// TODO Auto-generated method stub
}*/
}
Kindly let me know what changes should be done.
Thanks.
It's missing instance from the TransformationInput/TransformationOutput classes because their variables are null,
TransformationInput input = null;
TransformationOutput output = null;
So you need to instance them or pass them as reference on some setter.

SNMP code that does not work with TCP

I got one example of SNMPV3 trap,it is working fine when i use DefaultUdpTransportMapping but when i use DefaultTcpTransportMapping ,it will return null response event.
I have also attached code below .
public class SnmpUtilSendTrapV3 {
private Snmp snmp = null;
private Address targetAddress = null;
// private TcpAddress targetAddress = null;
public void initComm() throws IOException {
targetAddress = new TcpAddress(Inet4Address.getLocalHost(), 162);
// targetAddress = GenericAddress.parse("127.0.0.1/162");
TransportMapping transport = new DefaultTcpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
}
/**
* send trap
*
* #throws IOException
*/
public void sendPDU() throws IOException {
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
// snmp version
target.setVersion(SnmpConstants.version3);
// target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
usm.setEngineDiscoveryEnabled(true);
SecurityModels.getInstance().addSecurityModel(usm);
UsmUser user = new UsmUser(new OctetString("MD5DES"), AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"), PrivDES.ID,
new OctetString("MD5DESUserPrivPassword"));
snmp.getUSM().addUser(new OctetString("MD5DES"), user);
// create PDU
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.0"),
new OctetString("DemoTrapv3")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0"),
new OctetString("Demo")));
pdu.setType(PDU.TRAP);
// send PDU to Agent and recieve Response
ResponseEvent respEvnt = snmp.send(pdu, target);
// analyze Response
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector<VariableBinding> variableBindings = (Vector<VariableBinding>) respEvnt
.getResponse().getVariableBindings();
Vector<VariableBinding> recVBs = variableBindings;
for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
System.out
.println(recVB.getOid() + " : " + recVB.getVariable());
}
}
snmp.close();
}
public static void main(String[] args) {
try {
SnmpUtilSendTrapV3 util = new SnmpUtilSendTrapV3();
util.initComm();
util.sendPDU();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MultiThreadedTrapReceiver implements CommandResponder {
private Address address = GenericAddress.parse("0.0.0.0/162");
private int numDispatcherThreads = 2;
private OID authProtocol = AuthMD5.ID;
private OID privProtocol = PrivDES.ID;
private OctetString securityName = new OctetString("MD5DES");
private OctetString privPassphrase = new OctetString(
"MD5DESUserPrivPassword");
private OctetString authPassphrase = new OctetString(
"MD5DESUserAuthPassword");
public MultiThreadedTrapReceiver() {
try {
listen();
} catch (IOException ex) {
System.out.println(ex);
}
}
public synchronized void listen() throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool",
numDispatcherThreads);
MessageDispatcher mtDispatcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mtDispatcher.addMessageProcessingModel(new MPv1());
mtDispatcher.addMessageProcessingModel(new MPv2c());
mtDispatcher.addMessageProcessingModel(new MPv3(new OctetString(MPv3
.createLocalEngineID()).getValue()));
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
Snmp snmp = new Snmp(mtDispatcher, transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
// Add the configured user to the USM
addUsmUser(snmp);
snmp.addCommandResponder(this);
transport.listen();
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private void addUsmUser(Snmp snmp) {
snmp.getUSM().addUser(
securityName,
new UsmUser(securityName, authProtocol, authPassphrase,
privProtocol, privPassphrase));
}
#Override
public void processPdu(CommandResponderEvent respEvnt) {
System.out.println(respEvnt.getPDU());
InetAddress pduAgentAddress = null;
// System.out.println(respEvnt.getPDU() + " recieved;");
// this.setPdu(respEvnt.getPDU());
OctetString community = new OctetString(respEvnt.getSecurityName());
System.out.println("community: " + community.toString());
// handle the SNMP v1
if (respEvnt.getPDU().getType() == PDU.V1TRAP) {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress()
+ "; port: " + nPort);
} else {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress()
+ "; port: " + nPort);
}
}
public static void main(String[] args) {
MultiThreadedTrapReceiver trap = new MultiThreadedTrapReceiver();
}
}
I have changed in SnmpUtilSendTrapV3 class,
.use TcpAddress targetAddress instead of Address targetAddress
use targetAddress = new TcpAddress(Inet4Address.getLocalHost(),
162); instead of targetAddress =
GenericAddress.parse("127.0.0.1/164");
TransportMapping transport = new DefaultTcpTransportMapping();
instead of TransportMapping transport = new
DefaultUdpTransportMapping();
after this implementation error is solved but , after sending pdu using snmp.send(pdu, target) everytime ResponseEvent have null value.
Anyone have a solution of this problem ,please help me

ExceptionInInitializerError in jdk1.8 not in jdk1.6

5 with jdk1.8 when I run the project. I got an Exception ExceptionInInitializerError. But when I run the same project in jdk1.6. It is running successfully. That error message as
Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.ofbiz.entity.GenericDelegator.initEntityEcaHandler(GenericDelegator.java:339)
at org.ofbiz.entity.DelegatorFactory.getDelegator(DelegatorFactory.java:42)
at org.ofbiz.catalina.container.CatalinaContainer.init(CatalinaContainer.java:175)
at org.ofbiz.base.container.ContainerLoader.loadContainer(ContainerLoader.java:189)
at org.ofbiz.base.container.ContainerLoader.load(ContainerLoader.java:66)
at org.ofbiz.base.start.Start.initStartLoaders(Start.java:260)
at org.ofbiz.base.start.Start.init(Start.java:97)
at org.ofbiz.base.start.Start.main(Start.java:411)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:308)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:331)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.createClassInfoFromStream(AsmClassInfo.java:790)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:273)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getInterfaces(AsmClassInfo.java:619)
at org.codehaus.aspectwerkz.reflect.ClassInfoHelper.implementsInterface(ClassInfoHelper.java:56)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:237)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:208)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.initialize(AbstractJoinPointCompiler.java:149)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.(AbstractJoinPointCompiler.java:133)
at org.codehaus.aspectwerkz.transform.inlining.compiler.MethodExecutionJoinPointCompiler.(MethodExecutionJoinPointCompiler.java:33)
at org.codehaus.aspectwerkz.transform.inlining.compiler.JoinPointFactory.compileJoinPoint(JoinPointFactory.java:86)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager$CompiledJoinPoint.(JoinPointManager.java:262)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.compileJoinPoint(JoinPointManager.java:251)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.loadJoinPoint(JoinPointManager.java:118)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.aw$initJoinPoints(DelegatorEcaHandler.java)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.(DelegatorEcaHandler.java)
... 13 more"
I found two files are problem when I run the project in jdk1.8 that coding files are:
CatalinaContainer.java
/**
* CatalinaContainer - Tomcat 5
*
*/
public class CatalinaContainer implements Container {
public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
public static final String J2EE_SERVER = "OFBiz Container 3.1";
public static final String J2EE_APP = "OFBiz";
public static final String module = CatalinaContainer.class.getName();
protected static Map<String, String> mimeTypes = new HashMap<String, String>();
// load the JSSE propertes (set the trust store)
static {
SSLUtil.loadJsseProperties();
}
protected Delegator delegator = null;
protected Embedded embedded = null;
protected Map<String, ContainerConfig.Container.Property> clusterConfig = new HashMap<String, ContainerConfig.Container.Property>();
protected Map<String, Engine> engines = new HashMap<String, Engine>();
protected Map<String, Host> hosts = new HashMap<String, Host>();
protected boolean contextReloadable = false;
protected boolean crossContext = false;
protected boolean distribute = false;
protected boolean enableDefaultMimeTypes = true;
protected String catalinaRuntimeHome;
/**
* #see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
*/
public void init(String[] args, String configFile) throws ContainerException {
// get the container config
ContainerConfig.Container cc = ContainerConfig.getContainer("catalina-container", configFile);
if (cc == null) {
throw new ContainerException("No catalina-container configuration found in container config!");
}
// embedded properties
boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
//int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);
// grab some global context settings
this.delegator = DelegatorFactory.getDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default"));
this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);
this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");
// set catalina_home
System.setProperty("catalina.home", System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
// configure JNDI in the StandardServer
StandardServer server = (StandardServer) ServerFactory.getServer();
try {
server.setGlobalNamingContext(new InitialContext());
} catch (NamingException e) {
throw new ContainerException(e);
}
// create the instance of Embedded
embedded = new Embedded();
embedded.setUseNaming(useNaming);
// create the engines
List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
if (UtilValidate.isEmpty(engineProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no engines defined!");
}
for (ContainerConfig.Container.Property engineProp: engineProps) {
createEngine(engineProp);
}
// load the web applications
loadComponents();
// create the connectors
List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
if (UtilValidate.isEmpty(connectorProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
}
for (ContainerConfig.Container.Property connectorProp: connectorProps) {
createConnector(connectorProp);
}
try {
embedded.initialize();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
}
public boolean start() throws ContainerException {
// Start the embedded server
try {
embedded.start();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
for (Connector con: embedded.findConnectors()) {
ProtocolHandler ph = con.getProtocolHandler();
if (ph instanceof Http11Protocol) {
Http11Protocol hph = (Http11Protocol) ph;
Debug.logInfo("Connector " + hph.getProtocols() + " # " + hph.getPort() + " - " +
(hph.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
} else {
Debug.logInfo("Connector " + con.getProtocol() + " # " + con.getPort() + " - " +
(con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
}
}
Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
return true;
}
protected Engine createEngine(ContainerConfig.Container.Property engineConfig) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Engine without Embedded instance!");
}
ContainerConfig.Container.Property defaultHostProp = engineConfig.getProperty("default-host");
if (defaultHostProp == null) {
throw new ContainerException("default-host element of server property is required for catalina!");
}
String engineName = engineConfig.name;
String hostName = defaultHostProp.value;
StandardEngine engine = (StandardEngine) embedded.createEngine();
engine.setName(engineName);
engine.setDefaultHost(hostName);
// set the JVM Route property (JK/JK2)
String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
if (jvmRoute != null) {
engine.setJvmRoute(jvmRoute);
}
// create the default realm -- TODO: make this configurable
String dbConfigPath = "catalina-users.xml";
MemoryRealm realm = new MemoryRealm();
realm.setPathname(dbConfigPath);
engine.setRealm(realm);
// cache the engine
engines.put(engine.getName(), engine);
// create a default virtual host; others will be created as needed
Host host = createHost(engine, hostName);
hosts.put(engineName + "._DEFAULT", host);
// configure clustering
List<ContainerConfig.Container.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
if (clusterProps != null && clusterProps.size() > 1) {
throw new ContainerException("Only one cluster configuration allowed per engine");
}
if (UtilValidate.isNotEmpty(clusterProps)) {
ContainerConfig.Container.Property clusterProp = clusterProps.get(0);
createCluster(clusterProp, host);
clusterConfig.put(engineName, clusterProp);
}
// request dumper valve
boolean enableRequestDump = ContainerConfig.getPropertyValue(engineConfig, "enable-request-dump", false);
if (enableRequestDump) {
RequestDumperValve rdv = new RequestDumperValve();
engine.addValve(rdv);
}
// configure the CrossSubdomainSessionValve
boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
if (enableSessionValve) {
CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
engine.addValve(sessionValve);
}
// configure the access log valve
String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
AccessLogValve al = null;
if (logDir != null) {
al = new AccessLogValve();
if (!logDir.startsWith("/")) {
logDir = System.getProperty("ofbiz.home") + "/" + logDir;
}
File logFile = new File(logDir);
if (!logFile.isDirectory()) {
throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
}
al.setDirectory(logFile.getAbsolutePath());
}
// configure the SslAcceleratorValve
String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
engine.addValve(sslAcceleratorValve);
}
String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
if (al != null && !UtilValidate.isEmpty(alp2)) {
al.setPattern(alp2);
}
String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
if (al != null && !UtilValidate.isEmpty(alp3)) {
al.setPrefix(alp3);
}
boolean alp4 = ContainerConfig.getPropertyValue(engineConfig, "access-log-resolve", true);
if (al != null) {
al.setResolveHosts(alp4);
}
boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
if (al != null) {
al.setRotatable(alp5);
}
if (al != null) {
engine.addValve(al);
}
embedded.addEngine(engine);
return engine;
}
protected Host createHost(Engine engine, String hostName) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Host without Embedded instance!");
}
Host host = embedded.createHost(hostName, CATALINA_HOSTS_HOME);
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.setRealm(engine.getRealm());
engine.addChild(host);
hosts.put(engine.getName() + hostName, host);
return host;
}
protected Cluster createCluster(ContainerConfig.Container.Property clusterProps, Host host) throws ContainerException {
String defaultValveFilter = ".*.gif;.*.js;.*.jpg;.*.htm;.*.html;.*.txt;";
ReplicationValve clusterValve = new ReplicationValve();
clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));
String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);
if (mca == null || mcp == -1) {
throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
}
McastService mcast = new McastService();
if (mcb != null) {
mcast.setMcastBindAddress(mcb);
}
mcast.setAddress(mca);
mcast.setPort(mcp);
mcast.setMcastDropTime(mcd);
mcast.setFrequency(mcf);
String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
//String tls = getPropertyValue(clusterProps, "", "");
if (tlp == -1) {
throw new ContainerException("Cluster configuration requires tcp-listen-port property");
}
NioReceiver listener = new NioReceiver();
listener.setAddress(tla);
listener.setPort(tlp);
listener.setSelectorTimeout(tlt);
listener.setMaxThreads(tlc);
listener.setMinThreads(tlc);
//listener.setIsSenderSynchronized(false);
ReplicationTransmitter trans = new ReplicationTransmitter();
try {
MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
trans.setTransport(mps);
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
}
String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
//int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
// removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
// removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);
SimpleTcpCluster cluster = new SimpleTcpCluster();
cluster.setClusterName(clusterProps.name);
Manager manager = null;
try {
manager = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
//cluster.setManagerClassName(mgrClassName);
//host.setManager(manager);
//cluster.registerManager(manager);
cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
//cluster.setDebug(debug);
// removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
// removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);
GroupChannel channel = new GroupChannel();
channel.setChannelReceiver(listener);
channel.setChannelSender(trans);
channel.setMembershipService(mcast);
cluster.setChannel(channel);
cluster.addValve(clusterValve);
// removed since 5.5.9? cluster.setPrintToScreen(true);
// set the cluster to the host
host.setCluster(cluster);
Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);
return cluster;
}
protected Connector createConnector(ContainerConfig.Container.Property connectorProp) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Connector without Embedded instance!");
}
// need some standard properties
String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
String address = ContainerConfig.getPropertyValue(connectorProp, "address", "0.0.0.0");
int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0);
boolean secure = ContainerConfig.getPropertyValue(connectorProp, "secure", false);
if (protocol.toLowerCase().startsWith("ajp")) {
protocol = "ajp";
} else if ("memory".equals(protocol.toLowerCase())) {
protocol = "memory";
} else if (secure) {
protocol = "https";
} else {
protocol = "http";
}
Connector connector = null;
if (UtilValidate.isNotEmpty(connectorProp.properties)) {
connector = embedded.createConnector(address, port, protocol);
try {
for (ContainerConfig.Container.Property prop: connectorProp.properties.values()) {
connector.setProperty(prop.name, prop.value);
//connector.setAttribute(prop.name, prop.value);
}
embedded.addConnector(connector);
} catch (Exception e) {
throw new ContainerException(e);
}
}
return connector;
}
protected Context createContext(ComponentConfig.WebappInfo appInfo) throws ContainerException {
// webapp settings
Map<String, String> initParameters = appInfo.getInitParameters();
List<String> virtualHosts = appInfo.getVirtualHosts();
Engine engine = engines.get(appInfo.server);
if (engine == null) {
Debug.logWarning("Server with name [" + appInfo.server + "] not found; not mounting [" + appInfo.name + "]", module);
return null;
}
// set the root location (make sure we set the paths correctly)
String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
location = location.replace('\\', '/');
if (location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
// get the mount point
String mount = appInfo.mountPoint;
if (mount.endsWith("/*")) {
mount = mount.substring(0, mount.length() - 2);
}
// configure persistent sessions
Property clusterProp = clusterConfig.get(engine.getName());
Manager sessionMgr = null;
if (clusterProp != null) {
String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
try {
sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
} else {
sessionMgr = new StandardManager();
}
// create the web application context
StandardContext context = (StandardContext) embedded.createContext(mount, location);
context.setJ2EEApplication(J2EE_APP);
context.setJ2EEServer(J2EE_SERVER);
context.setLoader(embedded.createLoader(ClassLoaderContainer.getClassLoader()));
context.setCookies(appInfo.isSessionCookieAccepted());
context.addParameter("cookies", appInfo.isSessionCookieAccepted() ? "true" : "false");
context.setDisplayName(appInfo.name);
context.setDocBase(location);
context.setAllowLinking(true);
context.setReloadable(contextReloadable);
context.setDistributable(distribute);
context.setCrossContext(crossContext);
context.setPrivileged(appInfo.privileged);
context.setManager(sessionMgr);
context.getServletContext().setAttribute("_serverId", appInfo.server);
context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());
// create the Default Servlet instance to mount
StandardWrapper defaultServlet = new StandardWrapper();
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.setServletName("default");
defaultServlet.setLoadOnStartup(1);
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listing", "true");
defaultServlet.addMapping("/");
context.addChild(defaultServlet);
context.addServletMapping("/", "default");
// create the Jasper Servlet instance to mount
StandardWrapper jspServlet = new StandardWrapper();
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.setServletName("jsp");
jspServlet.setLoadOnStartup(1);
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "true");
jspServlet.addMapping("*.jsp");
jspServlet.addMapping("*.jspx");
context.addChild(jspServlet);
context.addServletMapping("*.jsp", "jsp");
// default mime-type mappings
configureMimeTypes(context);
// set the init parameters
for (Map.Entry<String, String> entry: initParameters.entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
if (UtilValidate.isEmpty(virtualHosts)) {
Host host = hosts.get(engine.getName() + "._DEFAULT");
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
} else {
// assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
Iterator<String> vhi = virtualHosts.iterator();
String hostName = vhi.next();
boolean newHost = false;
Host host = hosts.get(engine.getName() + "." + hostName);
if (host == null) {
host = createHost(engine, hostName);
newHost = true;
}
while (vhi.hasNext()) {
host.addAlias(vhi.next());
}
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
if (newHost) {
hosts.put(engine.getName() + "." + hostName, host);
}
}
return context;
}
protected void loadComponents() throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot load web applications without Embedded instance!");
}
// load the applications
List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
List<String> loadedMounts = FastList.newInstance();
if (webResourceInfos != null) {
for (int i = webResourceInfos.size(); i > 0; i--) {
ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
String mount = appInfo.getContextRoot();
if (!loadedMounts.contains(mount)) {
createContext(appInfo);
loadedMounts.add(mount);
} else {
appInfo.appBarDisplay = false; // disable app bar display on overrided apps
Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
}
}
}
}
public void stop() throws ContainerException {
try {
embedded.stop();
} catch (LifecycleException e) {
// don't throw this; or it will kill the rest of the shutdown process
Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
}
}
protected void configureMimeTypes(Context context) throws ContainerException {
Map<String, String> mimeTypes = CatalinaContainer.getMimeTypes();
if (UtilValidate.isNotEmpty(mimeTypes)) {
for (Map.Entry<String, String> entry: mimeTypes.entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
}
}
protected static synchronized Map<String, String> getMimeTypes() throws ContainerException {
if (UtilValidate.isNotEmpty(mimeTypes)) {
return mimeTypes;
}
if (mimeTypes == null) mimeTypes = new HashMap<String, String>();
URL xmlUrl = UtilURL.fromResource("mime-type.xml");
// read the document
Document mimeTypeDoc;
try {
mimeTypeDoc = UtilXml.readXmlDocument(xmlUrl, true);
} catch (SAXException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (ParserConfigurationException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (IOException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
}
if (mimeTypeDoc == null) {
Debug.logError("Null document returned for mime-type.xml", module);
return null;
}
// root element
Element root = mimeTypeDoc.getDocumentElement();
// mapppings
for (Element curElement: UtilXml.childElementList(root, "mime-mapping")) {
String extension = UtilXml.childElementValue(curElement, "extension");
String type = UtilXml.childElementValue(curElement, "mime-type");
mimeTypes.put(extension, type);
}
return mimeTypes;
}
}
Class.class file
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
I'm confused state. Please help me to recover this issue.
Thanks in advance.
In the stacktrace there is a
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747 at
org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
ASM is a tool to read and manipulate Java class files.
There have been changes to the class file format between JDK 6 and 8 and you (most probably) have an outdated version of ASM which runs into problems when reading Java 8 class files.
To solve the issue try to upgrade to the latest version of ASM (or Ofbiz).
EDIT: As commented by integratingweb Opentaps only supports JDK 6.

listen to incoming mails - JavaMail

I'm trying to write a class that is suppose to listen for incoming messages.
I had added a listener to my inbox.
I parse the messages in the inbox to look for a specific email, when that email is found I want my listener to stop listen to the inbox.
How can this be done?
This is my code:
public Map<String, Object> read(String id, Risk risk) {
setID(id);
try {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", email, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
inbox.addMessageCountListener(new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
setListenerExists(true);
boolean emailFound = false;
Message[] msgs = ev.getMessages();
System.out.println("Got " + msgs.length + " new messages");
if (msgs.length >= 1){
for (Message msg: msgs){
try {
Object o = msg.getContent();
if (o instanceof String){
hm = parser.parseMessage(adr, msg.getSubject(), msg.getContent(), getID());
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + msg.getContent());
}
else if (o instanceof Multipart){
Multipart mp = (Multipart) o;
BodyPart bp = mp.getBodyPart(0);
hm = parser.parseMessage(adr, msg.getSubject(), bp.getContent(), getID());
/*
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + bp.getContent());
*/
}
Iterator<Integer> it = hm.keySet().iterator();
while (it.hasNext()){
if (it.next() == 1){
map = extractValues(hm.get(1));
setMap(map);
//emailReceived = true;
//setEmailReceived(true);
//extractValues(hm.get(1));
}else{
/*
* TODO : remove listener
* setLisetn
*/
System.out.println("HM is Null!");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
while (emailFound == false){
for (Message msg : msgs){
try {
Object o = msg.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*/
}
});
// Check mail once in "freq" MILLIseconds
boolean supportsIdle = false;
try {
if (inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (;;) {
if (supportsIdle && inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(20000); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
inbox.getMessageCount();
}
}
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getMap();
}
public void setID(String id){
this.riskId = id;
}
public String getID(){
return riskId;
}
public void setMap(Map<String, Object> m){
this.map = m;
}
public Map<String, Object> getMap(){
return map;
}
public void setListenerExists(boolean exists){
this.listener = exists;
}
public boolean getListenerExists(){
return listener;
}
/** extracts values from hashmap received from the parser **/
public Map<String, Object> extractValues(HashMap<String, EmailData> h){
System.out.println("I'M Called");
Risk risk = new Risk();
String id = "";
String sender = "";
String answer = "";
HashMap<String, String> data;
Iterator<String> it = h.keySet().iterator();
while (it.hasNext()){
id = it.next();
EmailData ed = h.get(id);
sender = ed.getEmail();
answer = ed.getAnswer();
}
Map<String, Object> map = createVariablesToInsert(id, sender, answer);
return map;
}
public Map<String, Object> createVariablesToInsert(String id, String sender, String answer){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("I'M Called");
System.out.println("UUID : " + id);
System.out.println("USER : " + sender);
System.out.println("ANSWE : " + answer);
map.put("uuid", id);
map.put("user", sender);
map.put("ans", answer);
System.out.println("ID : " + map.get("uuid"));
System.out.println("USER : " + map.get("user"));
System.out.println("ANS : " + map.get("ans"));
System.out.println("ID in insert");
return map;
}
}
pay attention that you must declare two variables as final. it allow to access to those variables inside the implementation of MessageCountAdapter
final Folder inbox = store.getFolder("INBOX");
final MessageCountAdapter listener = new MessageCountAdapter() {
boolean emailFound = false;
// do something
if (emailFound) {
inbox.removeMessageCountListener(listener);
}
}
inbox.addMessageCountListener(listener);

Categories