Storing MQTT data into a Mongo database - java

I wrote a program which connects to a MQTT Broker and stores every MQTT message to a Mongo database. It works fine but I'm really not sure I've done it the right way. It opens lots of connections to the mongo server.
Here is the code :
public class MqttConnection {
private static final String BROKER_IP = Preferences.getProperty("mqttbroker-ip");
private static final String BROKER_PORT = Preferences.getProperty("mqttbroker-port");
private static final String BROKER_URI = "tcp://" + BROKER_IP + ":" + BROKER_PORT;
private static final String CLIENT_ID = Preferences.getProperty("mqttbroker-clientid");
private static final String USERNAME = Preferences.getProperty("mqttbroker-username");
private static final String PASSWORD = Preferences.getProperty("mqttbroker-password");
private static final String TOPIC = Preferences.getProperty("mqttbroker-topic");
private static final SimpleDateFormat SDF = new SimpleDateFormat("YYYYMMddHH:mm:ss");
private static MqttClient client;
private static final MqttConnectOptions options;
private static final MongoClient mongoClient;
public enum Type {
Double, Boolean, String;
}
static {
mongoClient = MongoConnection.getInstance();
try {
client = new MqttClient(BROKER_URI, CLIENT_ID);
} catch (MqttException ex) {
Logger.getLogger(MqttConnection.class.getName()).log(Level.SEVERE, null, ex);
}
options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
}
public static void connect() {
try {
if (Preferences.getProperty("mqttbroker-isAuth").equalsIgnoreCase("true")) {
client.connect(options);
} else {
client.connect();
}
System.out.println(SDF.format(new Date()) + " - MQTT - Connecté au broker");
client.setCallback(new ConnectionCallback());
client.subscribe(TOPIC);
} catch (MqttException ex) {
System.out.println(SDF.format(new Date()) + " - MQTT - Erreur de connexion... Nouvelle tentative dans 5 secondes...");
if (!client.isConnected()) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex1) {
Logger.getLogger(MqttConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
connect();
}
}
}
static class ConnectionCallback implements MqttCallback {
#Override
public void connectionLost(Throwable thrwbl) {
System.out.println(SDF.format(new Date()) + " - MQTT - Perte de connexion... Tentative de reconnexion...");
connect();
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
new Thread(new Runnable() {
#Override
public void run() {
String[] tab = topic.split("/", 2);
String dbName = tab[0];
String collName = (tab.length > 1) ? tab[1] : tab[0];
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection collection = db.getCollection(collName);
Document doc = (Document) collection.find().sort(Sorts.descending("date")).first();
Object value = (doc != null) ? doc.get("value") : null;
Type type = checkType(message.toString());
switch (type) {
case Double :
if (doc == null || !((Double) value).equals(Double.valueOf(message.toString()))) {
collection.insertOne(new Document()
.append("date", SDF.format(new Date()))
.append("value", Double.valueOf(message.toString())));
}
break;
case Boolean :
if (doc == null || !((Boolean) value).equals(Boolean.valueOf(message.toString()))) {
collection.insertOne(new Document()
.append("date", SDF.format(new Date()))
.append("value", Boolean.valueOf(message.toString())));
}
break;
case String :
if (doc == null || !((String) value).equals(message.toString())) {
collection.insertOne(new Document()
.append("date", SDF.format(new Date()))
.append("value", message.toString()));
}
break;
}
}
private Type checkType(String str) {
if (str.equalsIgnoreCase("true") || str.equalsIgnoreCase("false"))
return Type.Boolean;
else {
try {
Double.valueOf(str);
return Type.Double;
} catch (NumberFormatException e) {
return Type.String;
}
}
}
}).start();
}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Thanks

Related

SMPP java server connect to SMSC or SMPP Client can receive SMS via SMPP?

i have 3rd party smpp connection.
so i created java smpp client and its working fine.
how i can create smpp server connect to 3rd party smpp connection and need to send sms via that created smpp server. my problem is i doesn't know how to connect smpp server to smsc/smpp 3rd party connection
please help to me connect this smpp server to smpp 3rd party server for send sms..
public class SMPPServerSimulator extends ServerResponseDeliveryAdapter implements Runnable, ServerMessageReceiverListener {
private static final Logger log = LoggerFactory.getLogger(SMPPServerSimulator.class);
private static final String QUERYSM_NOT_IMPLEMENTED = "query_sm not implemented";
private static final String CANCELSM_NOT_IMPLEMENTED = "cancel_sm not implemented";
private static final String DATASM_NOT_IMPLEMENTED = "data_sm not implemented";
private static final String REPLACESM_NOT_IMPLEMENTED = "replace_sm not implemented";
private static final String BROADCASTSM_NOT_IMPLEMENTED = "broadcast_sm not implemented";
private static final String CANCELBROADCASTSM_NOT_IMPLEMENTED = "cancel_broadcast_sm not implemented";
private static final String QUERYBROADCASTSM_NOT_IMPLEMENTED = "query_broadcast_sm not implemented";
private static final Integer DEFAULT_PORT = 2775;
private static final String DEFAULT_SYSID = "twtest";
private static final String DEFAULT_PASSWORD = "test123";
private static final String SMSC_SYSTEMID = "sys";
private final ExecutorService execService = Executors.newFixedThreadPool(5);
private final ExecutorService execServiceDelReceipt = Executors.newFixedThreadPool(100);
private final MessageIDGenerator messageIDGenerator = new RandomMessageIDGenerator();
private final boolean useSsl;
private final int port;
private final String systemId;
private final String password;
public SMPPServerSimulator(boolean useSsl, int port, String systemId, String password) {
this.useSsl = useSsl;
this.port = port;
this.systemId = systemId;
this.password = password;
}
#Override
public void run() {
boolean running = true;
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
try (SMPPServerSessionListener sessionListener = useSsl ?
new SMPPServerSessionListener(port, new KeyStoreSSLServerSocketConnectionFactory())
: new SMPPServerSessionListener(port)) {
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
log.info("Listening on port {}{}", port, useSsl ? " (SSL)" : "");
while (running) {
System.out.println("running");
SMPPServerSession serverSession = sessionListener.accept();
log.info("Accepted connection with session {}", serverSession.getSessionId());
serverSession.setMessageReceiverListener(this);
serverSession.setResponseDeliveryListener(this);
Future<Boolean> bindResult = execService.submit(new WaitBindTask(serverSession, 30000, systemId, password));
try {
boolean bound = bindResult.get();
System.out.println(bound+" sss");
if (bound) {
// Could start deliver_sm to ESME
log.info("The session is now in state {}", serverSession.getSessionState());
serverSession.deliverShortMessage("CMT",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "94712320529",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "TWTEST",
new ESMClass(0), (byte) 0x00, (byte) 0x00, new RegisteredDelivery(), DataCodings.ZERO,
"Hello Worldxxxxxxxxxxx".getBytes());
}
} catch (InterruptedException e){
log.info("Interrupted WaitBind task: {}", e.getMessage());
Thread.currentThread().interrupt();
running = false;
} catch (ExecutionException e){
log.info("Exception on execute WaitBind task: {}", e.getMessage());
running = false;
} catch (NegativeResponseException | ResponseTimeoutException | PDUException | InvalidResponseException e){
log.info("Could not send deliver_sm: {}", e.getMessage());
}
}
} catch (IOException e) {
log.error("IO error occurred", e);
}
}
#Override
public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException {
log.info("QuerySm not implemented");
throw new ProcessRequestException(QUERYSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RINVCMDID);
}
#Override
public SubmitSmResult onAcceptSubmitSm(SubmitSm submitSm,
SMPPServerSession source) throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.info("Receiving submit_sm '{}', and return message id {}", new String(submitSm.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitSm.getRegisteredDelivery()) || SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitSm.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitSm, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitSmResult(messageId, new OptionalParameter[]{ congestionState });
}
return new SubmitSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onSubmitSmRespSent(SubmitSmResult submitSmResult,
SMPPServerSession source) {
log.debug("submit_sm_resp with message_id {} has been sent", submitSmResult.getMessageId());
}
#Override
public SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving submit_multi_sm '{}', and return message id {}",
new String(submitMulti.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitMulti.getRegisteredDelivery())
|| SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitMulti.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitMulti, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[]{ congestionState });
}
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[0]);
}
#Override
public DataSmResult onAcceptDataSm(DataSm dataSm, Session source)
throws ProcessRequestException {
log.info("Accepting data_sm, but not implemented");
throw new ProcessRequestException(DATASM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RSYSERR);
}
#Override
public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_sm, but not implemented");
throw new ProcessRequestException(CANCELSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RCANCELFAIL);
}
#Override
public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting replace_sm, but not implemented");
throw new ProcessRequestException(REPLACESM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RREPLACEFAIL);
}
#Override
public BroadcastSmResult onAcceptBroadcastSm(final BroadcastSm broadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving broadcast_sm '{}', and return message id {}",
new String(broadcastSm.getOptionalParameter(OptionalParameter.Tag.MESSAGE_PAYLOAD).serialize()), messageId);
return new BroadcastSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onAcceptCancelBroadcastSm(final CancelBroadcastSm cancelBroadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_broadcast_sm, but not implemented");
throw new ProcessRequestException(CANCELBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTCANCELFAIL);
}
#Override
public QueryBroadcastSmResult onAcceptQueryBroadcastSm(final QueryBroadcastSm queryBroadcastSm,
final SMPPServerSession source) throws ProcessRequestException {
log.info("Accepting query_broadcast_sm, but not implemented");
throw new ProcessRequestException(QUERYBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTQUERYFAIL);
}
private static class WaitBindTask implements Callable<Boolean> {
private final SMPPServerSession serverSession;
private final long timeout;
private final String systemId;
private final String password;
public WaitBindTask(SMPPServerSession serverSession, long timeout, String systemId, String password) {
this.serverSession = serverSession;
this.timeout = timeout;
this.systemId = systemId;
this.password = password;
}
#Override
public Boolean call() {
try {
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
BindRequest bindRequest = serverSession.waitForBind(timeout);
try {
if (BindType.BIND_TRX.equals(bindRequest.getBindType())) {
if (systemId.equals(bindRequest.getSystemId())) {
if (password.equals(bindRequest.getPassword())) {
log.info("Accepting bind for session {}, interface version {}", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
serverSession.setInterfaceVersion(InterfaceVersion.IF_50.min(bindRequest.getInterfaceVersion()));
// The systemId identifies the SMSC to the ESME.
bindRequest.accept(SMSC_SYSTEMID, InterfaceVersion.IF_50);
return true;
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid password", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVPASWD);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid system id", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVSYSID);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, only accept transceiver", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RBINDFAIL);
}
} catch (PDUStringException e) {
log.error("Invalid system id: " + SMSC_SYSTEMID, e);
bindRequest.reject(SMPPConstant.STAT_ESME_RSYSERR);
}
} catch (IllegalStateException e) {
log.error("System error", e);
} catch (TimeoutException e) {
log.warn("Wait for bind has reach timeout", e);
} catch (IOException e) {
log.error("Failed accepting bind request for session {}", serverSession.getSessionId());
}
return false;
}
}
private static class DeliveryReceiptTask implements Runnable {
private final SMPPServerSession session;
private final MessageId messageId;
private final TypeOfNumber sourceAddrTon;
private final NumberingPlanIndicator sourceAddrNpi;
private final String sourceAddress;
private final TypeOfNumber destAddrTon;
private final NumberingPlanIndicator destAddrNpi;
private final String destAddress;
private final int totalSubmitted;
private final int totalDelivered;
private final byte[] shortMessage;
public DeliveryReceiptTask(SMPPServerSession session,
SubmitSm submitSm, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// reversing destination to source
sourceAddrTon = TypeOfNumber.valueOf(submitSm.getDestAddrTon());
sourceAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi());
sourceAddress = submitSm.getDestAddress();
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitSm.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi());
destAddress = submitSm.getSourceAddr();
totalSubmitted = totalDelivered = 1;
shortMessage = submitSm.getShortMessage();
}
public DeliveryReceiptTask(SMPPServerSession session,
SubmitMulti submitMulti, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// set to unknown and null, since it was submit_multi
sourceAddrTon = TypeOfNumber.UNKNOWN;
sourceAddrNpi = NumberingPlanIndicator.UNKNOWN;
sourceAddress = null;
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitMulti.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitMulti.getSourceAddrNpi());
destAddress = submitMulti.getSourceAddr();
// distribution list assumed only contains single address
totalSubmitted = totalDelivered = submitMulti.getDestAddresses().length;
shortMessage = submitMulti.getShortMessage();
}
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Interrupted", e);
//re-interrupt the current thread
Thread.currentThread().interrupt();
}
SessionState state = session.getSessionState();
if (!state.isReceivable()) {
log.debug("Not sending delivery receipt for message id {} since session state is {}", messageId, state);
return;
}
String stringValue = Integer.valueOf(messageId.getValue(), 16).toString();
try {
DeliveryReceipt delRec = new DeliveryReceipt(stringValue, totalSubmitted, totalDelivered, new Date(), new Date(), DeliveryReceiptState.DELIVRD, "000", new String(shortMessage));
session.deliverShortMessage(
"mc",
sourceAddrTon, sourceAddrNpi, sourceAddress,
destAddrTon, destAddrNpi, destAddress,
new ESMClass(MessageMode.DEFAULT, MessageType.SMSC_DEL_RECEIPT, GSMSpecificFeature.DEFAULT),
(byte)0,
(byte)0,
new RegisteredDelivery(0),
DataCodings.ZERO,
delRec.toString().getBytes());
log.debug("Sending delivery receipt for message id {}: {}", messageId, stringValue);
} catch (Exception e) {
log.error("Failed sending delivery_receipt for message id " + messageId + ":" + stringValue, e);
}
}
}
public static void main(String[] args) {
// System.setProperty("javax.net.debug", "ssl");
/*
* To use SSL, add -Djsmpp.simulator.ssl=true
* To debug SSL, add -Djavax.net.debug=ssl
*/
String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID);
String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD);
int port;
try {
port = Integer.parseInt(System.getProperty("jsmpp.simulator.port", DEFAULT_PORT.toString()));
} catch (NumberFormatException e) {
port = DEFAULT_PORT;
}
boolean useSsl = Boolean.parseBoolean(System.getProperty("jsmpp.simulator.ssl", "false"));
SMPPServerSimulator smppServerSim = new SMPPServerSimulator(useSsl, port, systemId, password);
smppServerSim.run();
}
}

How to use an object that got return in another class

I have this class, that returns an object, if the email, password and category (enum) are correct:
public class LoginManager {
private static LoginManager instance = new LoginManager();
private LoginManager() {
super();
}
public static LoginManager getInstance() {
return instance;
}
public ClientFacade login(String email, String password, ClientType clientType) throws SQLException {
if (clientType == ClientType.Administrator) {
AdminFacade adminFacade = new AdminFacade();
if (adminFacade.login(email, password) == true) {
return adminFacade;
} else {
return null;
}
} else if (clientType == ClientType.Company) {
CompanyFacade companyFacade = new CompanyFacade();
if (companyFacade.login(email, password) == true) {
return companyFacade;
} else {
return null;
}
} else if (clientType == ClientType.Customer) {
CustomerFacade customerFacade = new CustomerFacade();
if (customerFacade.login(email, password) == true) {
return customerFacade;
} else {
return null;
}
} else {
return null;
}
}
}
How do I use that object in another class?
This is the other class, that is supposed to use the object that return:
public class Test {
CouponsDBDAO coupDBD = new CouponsDBDAO();
CouponExpirationDailyJob dailyJob =
new CouponExpirationDailyJob(coupDBD, false);
LoginManager Log = LoginManager.getInstance();
public void testAll() {
try {
Log.login("admin#admin.com", "admin", ClientType.Administrator); {
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
How do I use now the adminFacade for example?
try
LoginManager Log = new LoginManager();
public void testAll() {
try {
ClientFacade facade = Log.login("admin#admin.com", "admin", ClientType.Administrator);
facade.DoSomethingUseful();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

My Storm Topology neither working(not generating output) nor failing (not generating errors or exceptions)

I have a topology in which I am trying to count word occurrences which are being generated by SimulatorSpout (not real Stream) and after that write to MySQL database table, the table scheme is very simple:
Field | Type | ...
ID | int(11) | Auto_icr
word | varchar(50) |
count | int(11) |
But I am facing weird problem(as I beforementioned)
I successfully submitted The Topology to my Storm Cluster which consists of 4 supervisors, and I can see the flow of the Topology in Storm Web UI
(no exceptions) but when I checked the MySQL table, to my surprise, the table is empty...
ANY COMMENTS, SUGGESTIONS ARE WELCOME...
Here are spouts and bolts:
public class MySQLConnection {
private static Connection conn = null;
private static String dbUrl = "jdbc:mysql://192.168.0.2:3306/test?";
private static String dbClass = "com.mysql.jdbc.Driver";
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(dbClass);
conn = DriverManager.getConnection(dbUrl, "root", "qwe123");
return conn;
}
}
============================= SentenceSpout ===============================
public class SentenceSpout extends BaseRichSpout{
private static final long serialVersionUID = 1L;
private boolean _completed = false;
private SpoutOutputCollector _collector;
private String [] sentences = {
"Obama delivered a powerfull speech against USA",
"I like cold beverages",
"RT http://www.turkeyairline.com Turkish Airlines has delayed some flights",
"don't have a cow man...",
"i don't think i like fleas"
};
private int index = 0;
public void open (Map config, TopologyContext context, SpoutOutputCollector collector) {
_collector = collector;
}
public void nextTuple () {
_collector.emit(new Values(sentences[index]));
index++;
if (index >= sentences.length) {
index = 0;
Utils.waitForSeconds(1);
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("sentence"));
}
public void ack(Object msgId) {
System.out.println("OK: " + msgId);
}
public void close() {}
public void fail(Object msgId) {
System.out.println("FAIL: " + msgId);
}
}
============================ SplitSentenceBolt ==============================
public class SplitSentenceBolt extends BaseRichBolt {
private static final long serialVersionUID = 1L;
private OutputCollector _collector;
public void prepare (Map config, TopologyContext context, OutputCollector collector) {
_collector = collector;
}
public void execute (Tuple tuple) {
String sentence = tuple.getStringByField("sentence");
String httpRegex = "((https?|ftp|telnet|gopher|file)):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*";
sentence = sentence.replaceAll(httpRegex, "").replaceAll("RT", "").replaceAll("[.|,]", "");
String[] words = sentence.split(" ");
for (String word : words) {
if (!word.isEmpty())
_collector.emit(new Values(word.trim()));
}
_collector.ack(tuple);
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
=========================== WordCountBolt =================================
public class WordCountBolt extends BaseRichBolt {
private static final long serialVersionUID = 1L;
private HashMap<String , Integer> counts = null;
private OutputCollector _collector;
private ResultSet resSet = null;
private Statement stmt = null;
private Connection _conn = null;
private String path = "/home/hduser/logOfStormTops/logger.txt";
String rLine = null;
public void prepare (Map config, TopologyContext context, OutputCollector collector) {
counts = new HashMap<String, Integer>();
_collector = collector;
}
public void execute (Tuple tuple) {
int insertResult = 0;
int updateResult = 0;
String word = tuple.getStringByField("word");
//----------------------------------------------------
if (!counts.containsKey(word)) {
counts.put(word, 1);
try {
insertResult = wordInsertIfNoExist(word);
if (insertResult == 1) {
_collector.ack(tuple);
} else {
_collector.fail(tuple);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
//-----------------------------------------------
counts.put(word, counts.get(word) + 1);
try {
// writing to db
updateResult = updateCountOfExistingWord(word);
if (updateResult == 1) {
_collector.ack(tuple);
} else {
_collector.fail(tuple);
}
// Writing to file
BufferedWriter buffer = new BufferedWriter(new FileWriter(path));
buffer.write("[ " + word + " : " + counts.get("word") + " ]");
buffer.newLine();
buffer.flush();
buffer.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("{word-" + word + " : count-" + counts.get(word) + "}");
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
// *****************************************************
public int wordInsertIfNoExist(String word) throws ClassNotFoundException, SQLException {
String query = "SELECT word FROM wordcount WHERE word=\"" + word + "\"";
String insert = "INSERT INTO wordcount (word, count) VALUES (\"" + word + "\", 1)";
_conn = MySQLConnection.getConnection();
stmt = _conn.createStatement();
resSet = stmt.executeQuery(query);
int res = 0;
if (!resSet.next()) {
res = stmt.executeUpdate(insert);
} else {
System.out.println("Yangi qiymatni kirityotrganda nimadir sodir bo'ldi");
}
resSet.close();
stmt.close();
_conn.close();
return res;
}
public int updateCountOfExistingWord(String word) throws ClassNotFoundException, SQLException {
String update = "UPDATE wordcount SET count=count+1 WHERE word=\"" + word + "\"";
_conn = MySQLConnection.getConnection();
stmt = _conn.createStatement();
int result = stmt.executeUpdate(update);
//System.out.println(word + "'s count has been updated (incremented)");
resSet.close();
stmt.close();
_conn.close();
return result;
}
}
========================= WordCountTopology ==============================
public class WordCountTopology {
private static final String SENTENCE_SPOUT_ID = "sentence-spout";
private static final String SPLIT_BOLT_ID = "split-bolt";
private static final String COUNT_BOLT_ID = "count-bolt";
private static final String TOPOLOGY_NAME = "NewWordCountTopology";
#SuppressWarnings("static-access")
public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException {
SentenceSpout spout = new SentenceSpout();
SplitSentenceBolt splitBolt = new SplitSentenceBolt();
WordCountBolt countBolt = new WordCountBolt();
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(SENTENCE_SPOUT_ID, spout, 2);
builder.setBolt(SPLIT_BOLT_ID, splitBolt, 4).shuffleGrouping(SENTENCE_SPOUT_ID);
builder.setBolt(COUNT_BOLT_ID, countBolt, 4).fieldsGrouping(SPLIT_BOLT_ID, new Fields("word"));
Config config = new Config();
config.setMaxSpoutPending(100);
config.setDebug(true);
StormSubmitter submitter = new StormSubmitter();
submitter.submitTopology(TOPOLOGY_NAME, config, builder.createTopology());
}
}
It is because the _collector.ack(tuple) is not being called when there is exception thrown. When there are too many pending tuple, spout will stop sending new tuples. Try throwing out RuntimeException instead of printStackTrace.

How to pass username and password at the time of handshaking to authenticate use in websocket?

i am devloping a group chat appication and i want to send username and password at the time of handshaking.
Here is my client side javascript code:
<script type="text/javascript">
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
alert("'Error: WebSocket is not supported by this browser.'")
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
Chat.socket.onopen = function() {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function() {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
Chat.socket.onmessage = function(message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
} else {
Chat.connect('wss://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
</script>
and i have used tomcat 7 as a server.
Here is my server side code:
#Deprecated
public class ChatWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private static final String GUEST_PREFIX = "Guest";
private final AtomicInteger connectionIds = new AtomicInteger(0);
private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>();
#Override
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {
return new ChatMessageInbound(connectionIds.incrementAndGet());
}
private final class ChatMessageInbound extends MessageInbound {
private final String nickname;
private ChatMessageInbound(int id) {
System.out.println("stage 1");
this.nickname = GUEST_PREFIX + id;
}
#Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
System.out.println("user:" + this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#Override
protected void onClose(int status) {
connections.remove(this);
String message = String.format("* %s %s", nickname,
"has disconnected.");
broadcast(message);
}
#Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
throw new UnsupportedOperationException(
"Binary message not supported.");
}
#Override
protected void onTextMessage(CharBuffer message) throws IOException {
// Never trust the client
String filteredMessage = String.format("%s: %s", nickname,
HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
private void broadcast(String message) {
for (ChatMessageInbound connection : connections) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {
// Ignore
}
}
}
}
}
Here i want to send User's credential before actual handshaking to authenticate user.
so how i can to in this?

update data from jTable to database -null pointer exception error

Im trying to read values from my jTable1
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
final String remark1 = (String) jTable1.getValueAt(row, 8);
final String remark2 = (String) jTable1.getValueAt(row, 9);
final String invoiceno = (String) jTable1.getValueAt(row, 11);
final String id=(String) jTable1.getValueAt(row, 12);
System.out.println(id + "id");
try{
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
System.out.println("try loop for update");
SentenceExec followinsert = new PreparedSentence(s
, "UPDATE FOLLOWUP SET REMARK1= ?, REMARK2=?, INVOICENO=? WHERE ID= ?"
, SerializerWriteParams.INSTANCE);
followinsert.exec(new DataParams() { public void writeValues() throws BasicException {
System.out.println("executing command");
setString(1, remark1);
setString(2, remark2);
setString(3, invoiceno);
setString(2, id);
//System.out.println(" after update line");
}});
return null;
}
};
t.execute(); //im getting null pointer exception here :(
}
catch (BasicException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.openbravo.data.loader.Transaction.execute(Transaction.java:42)
at com.openbravo.pos.followup.FollowUp.jcmdOKActionPerformed(FollowUp.java:679)
at com.openbravo.pos.followup.FollowUp.access$300(FollowUp.java:66)
at com.openbravo.pos.followup.FollowUp$5.actionPerformed(FollowUp.java:193)
Transaction.java is
public abstract class Transaction<T> {
private Session s;
/** Creates a new instance of Transaction */
public Transaction(Session s) {
this.s = s;
}
public final T execute() throws BasicException {
if (s.isTransaction()) {
return transact();
} else {
try {
try {
s.begin();
T result = transact();
s.commit();
return result;
} catch (BasicException e) {
s.rollback();
throw e;
}
} catch (SQLException eSQL) {
throw new BasicException("Transaction error", eSQL);
}
}
}
protected abstract T transact() throws BasicException;
}

Categories