Good afternoon all, I have an issue with IBM MQ, I'm supposed to use JMS to connect to a defined queue then send an XML file to the defined queue. Any help with this problem is gladly appreciated.
In this image it shows that no message is received even though in eclipse IDE it states other wise:
I have a coded application that should work it sends and receives a message the problem is that when I check my IBM MQ explorer and my linux MQ server nothing appears so I'm not sure if its the server configurations that are wrong.
Here is the code I was referring to :
package mqtest;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JmsIOPutGet {
// System exit status value (assume unset value to be 1)
private static int status = 1;
// Create variables for the connection to MQ
private static final String HOST = "13.246.126.217"; // Host name or IP address
private static final int PORT = 1416; // Listener port for your queue manager
private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
private static final String QMGR = "qm5"; // Queue manager name
private static final String APP_USER = "mqm"; // Windows user name that application uses to connect to MQ
private static final String APP_PASSWORD = "Kion2018"; // Windows user password associated with APP_USER
private static final String QUEUE_NAME = "Q2"; // Queue that the application uses to put and get messages to and from
/**
* Main method
*
* #param args
*/
public static void main(String[] args) {
// Variables
JMSContext context = null;
Destination destination = null;
JMSProducer producer = null;
JMSConsumer consumer = null;
try {
// Create a connection factory
JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactory cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
cf.setStringProperty(WMQConstants.USERID, APP_USER);
cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
//cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");
// Create JMS objects
context = cf.createContext();
destination = context.createQueue("queue:///" + QUEUE_NAME);
// Read given file
File myObj = new File("C:\\Users\\Lesego\\OneDrive\\Documents\\Test Files\\application.xml");
Scanner myReader = new Scanner(myObj);
String msg = "";
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
msg = msg + data;
}
myReader.close();
TextMessage message = context.createTextMessage(msg);
producer = context.createProducer();
producer.send(destination, message);
System.out.println("Sent message:\n" + message);
consumer = context.createConsumer(destination); // autoclosable
String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds
System.out.println("\nReceived message:\n" + receivedMessage);
recordSuccess();
} catch (JMSException jmsex) {
recordFailure(jmsex);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
System.exit(status);
} // end main()
/**
* Record this run as successful.
*/
private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
return;
}
/**
* Record this run as failure.
*
* #param ex
*/
private static void recordFailure(Exception ex) {
if (ex != null) {
if (ex instanceof JMSException) {
processJMSException((JMSException) ex);
} else {
System.out.println(ex);
}
}
System.out.println("FAILURE");
status = -1;
return;
}
/**
* Process a JMSException and any associated inner exceptions.
*
* #param jmsex
*/
private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if (innerException != null) {
System.out.println("Inner exception(s):");
}
while (innerException != null) {
System.out.println(innerException);
innerException = innerException.getCause();
}
return;
}
Related
I'm using snmp4j 3.4.2 inside my java application (full code below)
I'm trying to execute a snmpget with snmpv3, security DES and auth MD5 and custom OID (python script, which is executed by snmp's extend funtionality). To create better understanding I used SnmpConstants.sysUpTime in the example below.
The SNMP resource has this user configured:
defSecurityName demo
defSecurityLevel authPriv
defAuthType MD5
defPrivType DES
defAuthPassphrase pass
defPrivPassphrase pass
I'm already using this user and resource to successfully perform the snmpget with python (pysnmp) and bash (snmpget), so I can definitely tell that my setup works and the java code is the problem.
I have two java classes (Listener.java and ServerStatusHelper.java)
Listener.java contains main and calls the snmpGet inside ServerStatusHelper.java, other code of Listener is excluded as its not neccessary.
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent response = agent.snmpGetOperation(SnmpConstants.sysUpTime);
if (response != null) {
System.out.println(
"response null - error: "+ response.getError() +
"peerAddress: " + response.getPeerAddress() +
"source: " + response.getSource().toString() +
"request: " + response.getRequest());
}
} catch (
IOException e) {
e.printStackTrace();
}
}
}
ServerStatusHelper.java
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthGeneric;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.PrivacyGeneric;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class ServerStatusHelper {
private Address nmsIP;
private String user;
private String securityName;
private String privacyPassword;
private String authorizationPassword;
private AuthGeneric authProtocol;
private PrivacyGeneric privacyProtocol;
private String protocol;
private boolean encryption;
private long timeOut = 1000;
private int noOfRetries = 10;
private Snmp snmp;
private UserTarget target;
private CommunityTarget v1target;
ServerStatusHelper(String ip, String protocol, int snmpPort, String username, String securityName,
String privacyPassword, String authPassowrd, AuthGeneric authProtocol, PrivacyGeneric privacyProtocol,
boolean encryption) {
nmsIP = GenericAddress.parse(protocol + ":" + ip + "/" + snmpPort);
System.out.println("NMS IP set : " + nmsIP.toString());
this.protocol = protocol;
this.user = username;
this.securityName = securityName;
this.privacyPassword = privacyPassword;
this.authorizationPassword = authPassowrd;
this.authProtocol = authProtocol;
this.privacyProtocol = privacyProtocol;
this.encryption = encryption;
SecurityProtocols.getInstance().addAuthenticationProtocol(new AuthMD5());
SecurityProtocols.getInstance().addPrivacyProtocol(new PrivDES());
}
public void startAgent() throws IOException {
if (snmp == null) {
TransportMapping<? extends TransportIpAddress> transport = null;
if (protocol.equalsIgnoreCase("udp")) {
System.out.println("UDP Protocol selected.");
transport = new DefaultUdpTransportMapping();
} else {
System.out.println("TCP Protocol selected.");
transport = new DefaultTcpTransportMapping();
}
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
snmp.getUSM().addUser(new OctetString(user),
new UsmUser(new OctetString(securityName), authProtocol.getID(),
new OctetString(authorizationPassword), privacyProtocol.getID(),
new OctetString(privacyPassword)));
if (encryption)
target = createUserTarget();
else
v1target = createUserTargetWithoutEncryption();
}
}
public ResponseEvent snmpSetOperation(VariableBinding[] vars) throws IOException {
PDU setPdu = new ScopedPDU();
for (VariableBinding variableBinding : vars) {
setPdu.add(variableBinding);
}
return snmp.send(setPdu, target);
}
public ResponseEvent snmpGetOperation(OID oid) throws IOException {
if (encryption) {
PDU getPdu = new ScopedPDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(ScopedPDU.GET);
return snmp.get(getPdu, target);
} else {
PDU getPdu = new PDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(PDU.GET);
return snmp.get(getPdu, v1target);
}
}
private UserTarget createUserTarget() {
UserTarget target = new UserTarget();
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString(securityName));
return target;
}
private CommunityTarget createUserTargetWithoutEncryption() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version1);
return target;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public int getNoOfRetries() {
return noOfRetries;
}
public void setNoOfRetries(int noOfRetries) {
this.noOfRetries = noOfRetries;
}
}
The execution of the program exits with
NMS IP set : **IPREMOVED**/161
UDP Protocol selected.
response null - error: nullpeerAddress: **IPREMOVED**/161source: org.snmp4j.Snmp#e580929 request: GET[{contextEngineID=80:00:1f:88:80:5e:2e:49:07:2f:68:44:57:00:00:00:00, contextName=}, requestID=588252045, errorStatus=0, errorIndex=0, VBS[1.3.6.1.2.1.1.3.0 = Null]]
Anyone has an idea what I'm doing wrong?
Edit:
From the servers syslog I can see, that the request arrives at the resource:
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
#i-shm I think you are doing everything ok.
The only problem in your code could be just the line in which you evaluate the response variable. Your are indicating response != null when it should be actually response == null. I mean:
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent event = agent.snmpGetOperation(SnmpConstants.sysUpTime);
final PDU response = event.getResponse();
if (response == null) {
System.out.println(
"response null - error: "+ event.getError() +
"peerAddress: " + event.getPeerAddress() +
"source: " + event.getSource().toString() +
"request: " + event.getRequest());
} else {
System.out.println("Response PDU:" + response.toString());
// Process the response as you need, maybe something like this:
long sysUpTime = response.get(0).getVariable().toLong();
// You can find relevant information in the javadocs of the library:
// https://agentpp.com/doc/snmp4j/index.html?org/snmp4j/package-summary.html
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is why you do not receive errors in the java code and your syslog indicates that the requests were actually sent.
I have been trying out to invoke and querying transactions from the Java SDK for the BYFN network in Hyperledger Fabric v1.4.4
So far i have started the network (which has two peers in two orgs, an orderer and chaincode mycc installed).
The network starts successfully, and scripts and tests complete (As per the end of execution the values of a and b after the byfn.sh scripts runs is 90 and 210 respectively)
Now I have my Java SDK, through which the query proposal response works correctly (returns 90 and 210), but after moving (doing the invoke) request and then querying the value returned is still 90, there is no change, I am not sure what I am doing wrong here.
My code:
public class sdksample {
// Main program to simply call the client, Am i making some mistake here ?? persistency ?
public static void main(String[] args) throws Exception {
// create fabric-ca client
BlockChainHFClient.getInstance().setupCryptoMaterialsForClient();
BlockChainHFClient.getInstance().initChannel();
// get HFC client instance
BlockChainHFClient client = BlockChainHFClient.getInstance();
System.out.println(client);
}
}
HFClient
import static java.lang.String.format;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.hyperledger.fabric.protos.ledger.rwset.kvrwset.KvRwset;
import org.hyperledger.fabric.sdk.BlockInfo;
import org.hyperledger.fabric.sdk.BlockInfo.EnvelopeType;
import org.hyperledger.fabric.sdk.ChaincodeID;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.ProposalResponse;
import org.hyperledger.fabric.sdk.QueryByChaincodeRequest;
import org.hyperledger.fabric.sdk.SDKUtils;
import org.hyperledger.fabric.sdk.TransactionProposalRequest;
import org.hyperledger.fabric.sdk.TxReadWriteSetInfo;
import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.exception.BaseException;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import com.google.protobuf.InvalidProtocolBufferException;
public class BlockChainHFClient {
private static BlockChainHFClient instance;
/**
* Client instance constructor
*/
private BlockChainHFClient() {
}
/**
* Returns an instance of the Fabric client
*
* #return instance
*/
public static synchronized BlockChainHFClient getInstance() {
if (instance == null) {
instance = new BlockChainHFClient();
}
return instance;
}
/**
* Fabric client object
*/
final HFClient hfClient = HFClient.createNewInstance();
/**
* Crypto config folder location . keep crypto-config folder in user/home
*/
final String CRYPTO_CONFIG_HOME_DIR = System.getProperty("user.home");
/**
* Grpcs URL
*/
final String GRPCS = "grpcs://";
/**
* Dot for utility
*/
final String DOT = ".";
/**
* MSP ID Root
*/
final String ROOT_MSP_ID = "Org1MSP";
/**
* Admin user
*/
final String PEER_ADMIN = "PeerAdmin";
/**
* Channel object
*/
Channel channel;
/**
* Channel initialize timeout values
*/
final Long ChannelBuilderOptionkeepAliveMinutes = 15L;
final Long ChannelBuilderOptionkeepAliveSeconds = 15L;
/**
* Get channel instance
*
* #return channel
*/
public Channel getChannel() {
return channel;
}
/**
* Get HF client
*
* #return HF client
*/
public HFClient getClient() {
return hfClient;
}
/**
* Set up User contexts by using Crypto materials - Private key and cert files
*
* #throws CryptoException
* #throws InvalidArgumentException
* #throws IllegalAccessException
* #throws InstantiationException
* #throws ClassNotFoundException
* #throws NoSuchMethodException
* #throws InvocationTargetException
*/
public void setupCryptoMaterialsForClient()
throws CryptoException, InvalidArgumentException, IllegalAccessException, InstantiationException,
ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
hfClient.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
hfClient.setUserContext(new User() {
public String getName() {
return PEER_ADMIN;
}
public Set<String> getRoles() {
return null;
}
public String getAccount() {
return null;
}
public String getAffiliation() {
return null;
}
public Enrollment getEnrollment() {
return new Enrollment() {
public PrivateKey getKey() {
PrivateKey privateKey = null;
File privateKeyFile = findFileSk(
"D:\\Hyperledger Fabric_Research_Blockchain\\Fabric1.4.4\\fabric-samples\\first-network\\crypto-config\\peerOrganizations\\org1.example.com\\users\\Admin#org1.example.com\\msp\\keystore");
try {
privateKey = getPrivateKeyFromBytes(
IOUtils.toByteArray(new FileInputStream(privateKeyFile)));
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return privateKey;
}
public String getCert() {
String certificate = null;
try {
File certificateFile = new File(
"D:\\Hyperledger Fabric_Research_Blockchain\\Fabric1.4.4\\fabric-samples\\first-network\\crypto-config\\peerOrganizations\\org1.example.com\\users\\Admin#org1.example.com\\msp\\signcerts\\Admin#org1.example.com-cert.pem");
certificate = new String(IOUtils.toByteArray(new FileInputStream(certificateFile)),
"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return certificate;
}
};
}
public String getMspId() {
return ROOT_MSP_ID;
}
});
}
public void initChannel() throws Exception {
Properties peerProperties = new Properties();
peerProperties.setProperty("pemFile",
"D:\\Hyperledger Fabric_Research_Blockchain\\Fabric1.4.4\\fabric-samples\\first-network\\crypto-config\\peerOrganizations\\org1.example.com\\peers\\peer0.org1.example.com\\tls\\server.crt");
peerProperties.setProperty("trustServerCertificate", "true"); // testing environment only NOT FOR PRODUCTION!
peerProperties.setProperty("hostnameOverride", "peer0.org1.example.com");
peerProperties.setProperty("sslProvider", "openSSL");
peerProperties.setProperty("negotiationType", "TLS");
peerProperties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000);
Peer peer = hfClient.newPeer("peer0.org1.example.com", "grpc://localhost:7051");
Properties ordererProperties = new Properties();
ordererProperties.setProperty("pemFile",
"D:\\Hyperledger Fabric_Research_Blockchain\\Fabric1.4.4\\fabric-samples\\first-network\\crypto-config\\ordererOrganizations\\example.com\\orderers\\orderer.example.com\\tls\\server.crt");
ordererProperties.setProperty("trustServerCertificate", "true"); // testing environment only NOT FOR PRODUCTION!
ordererProperties.setProperty("hostnameOverride", "orderer.example.com");
ordererProperties.setProperty("sslProvider", "openSSL");
ordererProperties.setProperty("negotiationType", "TLS");
ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] { 5L, TimeUnit.MINUTES });
ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] { 8L, TimeUnit.SECONDS });
Orderer orderer = hfClient.newOrderer("orderer.example.com", "grpc://localhost:7050");
Channel channel = hfClient.newChannel("mychannel");
channel.addPeer(peer);
channel.addOrderer(orderer);
channel.initialize();
moveUnits(hfClient);
queryBlockChain(hfClient);
}
private String printableString(String string) {
int maxLogStringLength = 10000;
if (string == null || string.length() == 0) {
return string;
}
String ret = string.replaceAll("[^\\p{Print}]", "\n");
ret = ret.substring(0, Math.min(ret.length(), maxLogStringLength))
+ (ret.length() > maxLogStringLength ? "..." : "");
return ret;
}
void queryBlockChain(HFClient client) throws ProposalException, InvalidArgumentException {
// get channel instance from client
Channel channel = client.getChannel("mychannel");
// create chaincode request
QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
// build cc id providing the chaincode name. Version is omitted here.
ChaincodeID cid = ChaincodeID.newBuilder().setName("mycc").build();
qpr.setChaincodeID(cid);
// CC function to be called
qpr.setFcn("query");
qpr.setArgs(new String[] { "a" });
Collection<ProposalResponse> res = channel.queryByChaincode(qpr);
// display response
for (ProposalResponse pres : res) {
String stringResponse = new String(pres.getChaincodeActionResponsePayload());
System.out.println(stringResponse);
}
}
void moveUnits(HFClient client)
throws Exception {
Channel channel = client.getChannel("mychannel");
TransactionProposalRequest req = client.newTransactionProposalRequest();
ChaincodeID cid = ChaincodeID.newBuilder().setName("mycc").setVersion("1.0").build();
req.setChaincodeID(cid);
req.setFcn("invoke");
req.setArgs(new String[] {"a","b","50"});
Collection<ProposalResponse> resps = channel.sendTransactionProposal(req);
channel.sendTransaction(resps);
}
/**
* Utility method to get private key from bytes using Bouncy Castle Security
* Provider
*
* #param data
* #return privateKey
* #throws IOException
* #throws NoSuchProviderException
* #throws NoSuchAlgorithmException
* #throws InvalidKeySpecException
*/
private PrivateKey getPrivateKeyFromBytes(byte[] data)
throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
final Reader pemReader = new StringReader(new String(data));
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final PrivateKeyInfo pemPair;
try (PEMParser pemParser = new PEMParser(pemReader)) {
pemPair = (PrivateKeyInfo) pemParser.readObject();
}
PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
.getPrivateKey(pemPair);
return privateKey;
}
/**
* Find files ending with _sk
*
* #param directorys
* #return file
*/
private File findFileSk(String directorys) {
File directory = new File(directorys);
File[] matches = directory.listFiles((dir, name) -> name.endsWith("_sk"));
if (null == matches) {
throw new RuntimeException(
format("Matches returned null does %s directory exist?", directory.getAbsoluteFile().getName()));
}
if (matches.length != 1) {
throw new RuntimeException(format("Expected in %s only 1 sk file but found %d",
directory.getAbsoluteFile().getName(), matches.length));
}
return matches[0];
}
}
There seems to be no errors, the moveUnits function seems to work.
But the query returns the same values.
Suggestions? Thanks !
Worked. apparently i had to add another peer (peer0.org2.example.com) to the channel so as to satisfy the endorsement policy that two peers had to validate. The invoke then worked !
I've tested JMS messages sending serially and concurrently(5 threads send jms messages concurrently from the producer).
When I send 100 messages concurrently, few messages payload at the receiving end are NULL. When sent serially there is no issue.
Do I need to setup a session pool or use MDB at the consumer side to handle the messages concurrently? The setup of the JMS is good, because we are receiving messages. Am I missing anything here?
Short description of the pproject setup:
Publisher is a stateless session bean
Weblogic 8.1 jms server connection factory and destination are retrieved through
JNDI
Consumer is a java class which subscribes to this server JMS queue
and performs the tasks. (this is not a MDB or a Threaded class, listens to the queue
asynchronously)
EDITED
JmsConsumer
package net;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Hashtable;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class ReadJMS implements MessageListener, ExceptionListener {
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
public final static String PROVIDER_URL = "t3://address:7003";
public final static String JMS_FACTORY = "MSS.QueueConnectionFactory";
public final static String QUEUE = "jms.queue";
#SuppressWarnings("null")
public void receiveMessage() throws Exception {
// System.out.println("receiveMessage()..");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
// Define queue
QueueReceiver qreceiver = null;
QueueSession qsession = null;
QueueConnection qcon = null;
ReadJMS async = new ReadJMS();
try {
InitialContext ctx = new InitialContext(env);
QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx
.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qcon.setExceptionListener(async);
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) ctx.lookup(QUEUE);
qreceiver = qsession.createReceiver(queue);
qreceiver.setMessageListener(async);
qcon.start();
System.out.println("readingMessage()..");
// TextMessage msg = (TextMessage) qreceiver.receive();
// System.out.println("Message read from " + QUEUE + " : "
// + msg.getText());
// msg.acknowledge();
} catch (Exception ex) {
ex.printStackTrace();
}
// } finally {
// if (qreceiver != null)
// qreceiver.close();
// if (qsession != null)
// qsession.close();
// if (qcon != null)
// qcon.close();
// }
}
public static void main(String[] args) throws Exception {
ReadJMS test = new ReadJMS();
System.out.println("init");
test.receiveMessage();
while (true) {
Thread.sleep(10000);
}
}
public void onException(JMSException arg0) {
System.err.println("Exception: " + arg0.getLocalizedMessage());
}
public synchronized void onMessage(Message arg0) {
try {
if(((TextMessage)arg0).getText() == null || ((TextMessage)arg0).getText().trim().length()==0){
System.out.println(" " + QUEUE + " : "
+ ((TextMessage) arg0).getText());
}
System.out.print(".");
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("Output.txt", true)));
Date now = new Date();
out.println("message: "+now.toString()+ " - "+((TextMessage)arg0).getText()+"");
out.close();
} catch (JMSException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteJms
package net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
public class WriteJMS {
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
public final static String PROVIDER_URL = "t3://url:7003";
public final static String JMS_FACTORY = "MSS.QueueConnectionFactory";
public final static String QUEUE = "jms.queue";
#SuppressWarnings("unchecked")
public void sendMessage() throws Exception {
#SuppressWarnings("rawtypes")
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
// Define queue
QueueSender qsender = null;
QueueSession qsession = null;
QueueConnection qcon = null;
try {
InitialContext ctx = new InitialContext(env);
QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx
.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) ctx.lookup(QUEUE);
TextMessage msg = qsession.createTextMessage();
msg.setText("<eventMessage><eventId>123</eventId><eventName>123</eventName><documentNumber>123</documentNumber><customerId>123</customerId><actDDTaskDate>123</actDDTaskDate><taskStatusErrorMessage>123</taskStatusErrorMessage></eventMessage>");
qsender = qsession.createSender(queue);
qsender.send(msg);
System.out.println("Message [" + msg.getText()
+ "] sent to Queue: " + QUEUE);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (qsender != null)
qsender.close();
if (qsession != null)
qsession.close();
if (qcon != null)
qcon.close();
}
}
}
Reusing a session across multiple threads is notoriously forbidden. But you don't do this. You create everything (connection session and producer) anew for each message. That is inefficient, but not incorrect and should not cause these errors. The code you give us looks good to me.
I am a little surprised that no exceptions occur at the sending side. Can you give some more details about the JMS implementation? Perhaps there's more information in the message broker's log?
Have you counted the messages and does the number received equal the amount sent? Could someone else be sending messages to the same queue?
I want to use FTP to upload a file with a Java application, but it's not working.
The problem is that if I do the FTPUploader class in my main class, it works perfectly, but if I do like it's in here, it doesn't work. Can you guys help me out?
My code is:
Main Thread:
package restrictedareamanager;
import java.io.File;
import java.io.IOException;
public class RestrictedAreaManager {
File path = new File ("C:\\Área Restrita");
File lista[] = path.listFiles();
public void processa () throws IOException {
String titulo, subtitulo, nomeArq, aux;
for (File s : this.lista) {
aux = s.getName();
//String work
titulo = aux.substring (0, aux.indexOf ("-"));
aux = aux.substring (aux.indexOf ("-")+1);
subtitulo = aux.substring (0, aux.indexOf ("-"));
aux = aux.substring (aux.indexOf ("-")+1);
nomeArq = aux.substring (0);
//Create new file to be copied
final File dest = new File (path + "\\" + nomeArq);
//Copy File
FileCopier copiador = new FileCopier();
copiador.copiaArquivo(s, dest);
//Send file via FTP
FTPUploader ftp = new FTPUploader("**********", "********", "*********", titulo, subtitulo, dest);
ftp.execute();
}
}
public static void main(String[] args) throws IOException {
RestrictedAreaManager ram = new RestrictedAreaManager();
ram.processa();
}
}
FTPUploader class:
package restrictedareamanager;
import java.awt.HeadlessException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader extends SwingWorker <Object,Object> {
private String servidor;
private String usuario;
private String senha;
private String titulo;
private String subtitulo;
private File dest;
public FTPUploader (String servidor, String usuario, String senha, String titulo, String subtitulo, File dest) {
this.servidor = servidor;
this.usuario = usuario;
this.senha = senha;
this.titulo = titulo;
this.subtitulo = subtitulo;
this.dest = dest;
}
#Override
protected Object doInBackground() throws Exception {
FTPClient ftp = new FTPClient ();
try {
ftp.connect("servidor");
//verifica se conectou com sucesso!
if( FTPReply.isPositiveCompletion( ftp.getReplyCode() ) ) {
ftp.login ("usuario", "senha");
} else {
//erro ao se conectar
ftp.disconnect();
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao se conectar com o servidor FTP", "Erro", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/download");
ftp.changeWorkingDirectory(this.titulo);
ftp.changeWorkingDirectory (this.subtitulo);
ftp.storeFile (dest.getName(), new FileInputStream (dest.getPath().toString()));
System.out.println ("Done");
ftp.logout();
ftp.disconnect();
} catch( IOException | HeadlessException e ) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao enviar o arquivo.", "Erro", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
return null;
}
}
You may want to check into JSch library - it handles all the ugliness of FTP and sFTP connection in java.
http://www.jcraft.com/jsch/
Here's a sample implementation (from live production code):
package com.somecompany.productfeed;
import net.snakedoc.jutils.ConfigException;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SFTP {
// setup logger
private static final Logger LOG = Logger.getLogger(SFTP.class.getName());
private JSch jsch;
private ChannelSftp sftpChannel;
private Session session;
private String username;
private String password;
private String host;
private int port;
// singleton
private volatile static SFTP instance = null;
/**
* Private constructor used in Singleton pattern.
* All variables populated via properties file upon
* object instantiation. Since we only need FTP to one server,
* object variables are immutable after instantiation.
*
* #throws ConfigException
* #throws NumberFormatException
*/
private SFTP() throws ConfigException, NumberFormatException {
this.jsch = new JSch();
this.username = Config.getInstance().getConfig("SFTP_USER");
this.password = Config.getInstance().getConfig("SFTP_PASS");
this.host = Config.getInstance().getConfig("SFTP_HOST");
this.port = Integer.parseInt(Config.getInstance().getConfig("SFTP_PORT"));
}
/**
* Create or Return SFTP Object using Singleton pattern.
*
* #return Singleton of SFTP Object.
* #throws NumberFormatException
* #throws ConfigException
*/
public static SFTP getInstance() throws NumberFormatException, ConfigException {
if (SFTP.instance == null) {
synchronized (SFTP.class) {
if (SFTP.instance == null) {
SFTP.instance = new SFTP();
}
}
}
return SFTP.instance;
}
/**
* If connection is not already open/connected, open connection.
*
* #throws JSchException
*/
public void openConnection() throws JSchException {
LOG.info("Opening SFTP Connection");
if (null == getSession() || ! getSession().isConnected()) {
setSession(jsch.getSession(this.username, this.host, this.port));
getSession().setConfig("StrictHostKeyChecking", "no");
getSession().setPassword(this.password);
getSession().connect();
Channel channel = getSession().openChannel("sftp");
channel.connect();
setSftpChannel((ChannelSftp) channel);
} else {
LOG.info("SFTP Connection already open");
}
LOG.debug("Success");
}
/**
* Closes connection.
*/
public void closeConnection() {
LOG.info("Closing SFTP connection");
getSftpChannel().exit();
getSession().disconnect();
LOG.debug("SFTP Connection closed");
}
/**
* Checks if SFTP Connection is open.
*
* #return TRUE if connection is open, FALSE if connection is closed
*/
public boolean isOpen() {
if (getSession().isConnected()) {
return true;
} else {
return false;
}
}
/**
* Gets SFTP Channel
*
* #return SFTP Channel (<code>ChannelSftp</code>)
*/
private ChannelSftp getSftpChannel() {
return this.sftpChannel;
}
/**
* Returns current <code>Session</code>
*
* #return <code>Session</code>
*/
private Session getSession() {
return this.session;
}
/**
* Sets SFTP Channel (<code>ChannelSftp</code>)
*
* #param sftpChannel Channel to set this object's <code>ChannelSftp</code>
*/
private void setSftpChannel(ChannelSftp sftpChannel) {
this.sftpChannel = sftpChannel;
}
/**
* Sets current <code>Session</code>
*
* #param session Sets this object's <code>Session</code>
*/
private void setSession(Session session) {
this.session = session;
}
/**
* Pushes local file to remote location
*
* #param local String representation of filepath + filename (ex: /some_local_directory/somefile.txt)
* #param remote String representation of filepath + filename (ex: /some_remote_directory/somefile.txt)
* #throws SftpException
*/
public void push(String local, String remote) throws SftpException {
LOG.info("Sending file: " + local + " to remote: " + remote);
getSftpChannel().put(local, remote);
LOG.debug("Success");
}
/**
* Gets remote file to local location
*
* #param remote String representation of filepath + filename (ex: /some_remote_directory/somefile.txt)
* #param local String representation of filepath + filename (ex: /some_local_directory/somefile.txt)
* #throws SftpException
*/
public void get(String remote, String local) throws SftpException {
LOG.info("Retrieving file: " + remote + " saving to: " + local);
getSftpChannel().get(remote, local);
LOG.debug("Success");
}
}
I wrote a Java application that reads and sends SMS messages from a USB GSM modem. I'm using SMSLib (which uses JavaCommAPI), and it runs on Windows. I need to pass in the COM PORT, that the modem appears to be connected to.
So far, I've been looking up the COM PORT manually using the Windows Device Manager, and write it into a properties file. I'm wondering if there's a way to detect which COM PORT, the modem is connected to programmatically?
It'll save the trouble of looking it up every time
The port number changes if I unplug/replug it sometimes
Thanks!!
package com.cubepro.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Formatter;
import org.apache.log4j.Logger;
import org.smslib.helper.CommPortIdentifier;
import com.cubepro.general.CommonConstants;
import com.cubepro.util.SendMessage;
public class CommPortTester {
private static final String _NO_DEVICE_FOUND = " no device found";
private final static Formatter _formatter = new Formatter(System.out);
private static Logger log = Logger.getLogger(CommPortTester.class);
static CommPortIdentifier portId;
static Enumeration<CommPortIdentifier> portList;
static int bauds[] = { 9600, 14400, 19200, 28800, 33600, 38400, 56000,
57600, 115200 };
public static final String MAINCLASS = "org.smslib.Service";
public CommPortTester() throws Exception {
Class.forName(MAINCLASS);
}
/**
* Wrapper around {#link CommPortIdentifier#getPortIdentifiers()} to be
* avoid unchecked warnings.
*/
private static Enumeration<CommPortIdentifier> getCleanPortIdentifiers() {
return CommPortIdentifier.getPortIdentifiers();
}
public String testAndQualifyPort() throws Exception {
String status = CommonConstants.MODEM_STATUS_ERROR;
SendMessage sendMessage = new SendMessage();
log.debug("\nSearching for devices...");
portList = getCleanPortIdentifiers();
while (portList.hasMoreElements()) {
portId = portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
_formatter.format("%nFound port: %-5s%n", portId.getName());
try {
if(portId.getName()
boolean comPortSuccess = sendMessage.doIt(portId.getName());
if(comPortSuccess == true){
return portId.getName();
}
} catch (final Exception e) {
log.debug(" Modem error occured -",e);
}
}
}
log.debug("\nTest complete.");
return status;
}
public static void main(String[]args){
try{
CommPortTester tester = new CommPortTester();
tester.testAndQualifyPort();
}catch(Exception e){
e.printStackTrace();
}
}
}