SMPP SMS Send Long SMS - smpp

I have a java code to submit long SMS to SMPP but while excecution I'm getting "length must be less than or equal to 254. Actual length is 270" error. When using a lengthy string or any arabic characters.
Can anyone help me to identify the cause and suggest me how to fix the problem.
Below is the code that I'm trying.
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GeneralDataCoding;
import org.jsmpp.bean.MessageClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.bean.OptionalParameters;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.util.AbsoluteTimeFormatter;
import org.jsmpp.util.TimeFormatter;
public class SendLongSMSMessage
{
private static TimeFormatter timeFormatter = new AbsoluteTimeFormatter();
public String[] submitLongSMS(String MSISDN, String senderAddr, String message) throws Exception
{
SMPPSession session = getSession();
String[] msgId = null;
int splitSize = 135;
int totalSize = 140;
int totalSegments = 0;
RegisteredDelivery registeredDelivery = new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT);
GeneralDataCoding dataCoding = new GeneralDataCoding(false, false, MessageClass.CLASS1,
Alphabet.ALPHA_8_BIT);
ESMClass esmClass = new ESMClass();
if (message != null && message.length() > totalSize)
{
totalSegments = getTotalSegmentsForTextMessage(message);
}
Random random = new Random();
OptionalParameter sarMsgRefNum = OptionalParameters.newSarMsgRefNum((short) random.nextInt());
OptionalParameter sarTotalSegments = OptionalParameters.newSarTotalSegments(totalSegments);
String[] segmentData = splitIntoStringArray(message, splitSize, totalSegments);
msgId = new String[totalSegments];
for (int i = 0, seqNum = 0; i < totalSegments; i++)
{
seqNum = i + 1;
OptionalParameter sarSegmentSeqnum = OptionalParameters.newSarSegmentSeqnum(seqNum);
try
{ byte[] byteText = segmentData[i].getBytes("UTF-16BE");
msgId[i] = session.submitShortMessage("", TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN, "9999999999", TypeOfNumber.NATIONAL,
NumberingPlanIndicator.ISDN, MSISDN, esmClass, (byte) 0, (byte) 0, timeFormatter
.format(new Date()), null, registeredDelivery, (byte) 0, dataCoding, (byte) 0, byteText, sarMsgRefNum, sarSegmentSeqnum, sarTotalSegments);
System.out.println("Message id for segment " + seqNum + " out of totalsegment "
+ totalSegments + "is" + msgId[i]);
}
catch (PDUException e)
{
System.out.println("PDUException has occured" + e.getMessage());
}
catch (ResponseTimeoutException e)
{
System.out.println("ResponseTimeoutException has occured" + e.getMessage());
}
catch (InvalidResponseException e)
{
System.out.println("InvalidResponseException has occured" + e.getMessage());
}
catch (NegativeResponseException e)
{
System.out.println("NegativeResponseException has occured" + e.getMessage());
}
catch (IOException e)
{
System.out.println("IOException has occured" + e.getMessage());
}
}
session.unbindAndClose();
return msgId;
}
private SMPPSession getSession() throws Exception
{
return newSession();
}
private SMPPSession newSession() throws Exception
{
BindParameter bindParam = new BindParameter(BindType.BIND_TX, "<user_name>", "<pass_word>", "tdd",
TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null);
return new SMPPSession("17.1.1.1", 6666, bindParam);
}
public int getTotalSegmentsForTextMessage(String message)
{
int splitPos = 135;
int totalsegments = 1;
if (message.length() > splitPos)
{
totalsegments = (message.length() / splitPos) + ((message.length() % splitPos > 0) ? 1 : 0);
}
return totalsegments;
}
public String[] splitIntoStringArray(String msg, int pos, int totalSegments)
{
String[] segmentData = new String[totalSegments];
if (totalSegments > 1)
{
int splitPos = pos;
int startIndex = 0;
segmentData[startIndex] = new String();
segmentData[startIndex] = msg.substring(startIndex, splitPos);
for (int i = 1; i < totalSegments; i++)
{
segmentData[i] = new String();
startIndex = splitPos;
if (msg.length() - startIndex <= pos)
{
segmentData[i] = msg.substring(startIndex, msg.length());
}
else
{
splitPos = startIndex + pos;
segmentData[i] = msg.substring(startIndex, splitPos);
}
}
}
return segmentData;
}
public static void main(String[] args) throws Exception
{
SendLongSMSMessage slSMS = new SendLongSMSMessage();
String message = "Tech Dive heralds the arrival of a community of Developers "
+ "who share, collaborate and exchange ideas, concepts, technical know-how. "
+ "This forum lets you take a deep dive in technical topics that are hot and happening as well as on legacy systems."
+ "The idea of the forum is to ensure collaboration amongst developers through exchange of ideas/concepts "
+ "so their technical skills are enhanced."
+ "We plan to bring in experienced professionals on board so content/blog written is authentic and precise."
+ "Come, join us and be a part of new way of collaboration!";
String MSISDN = "9500000000";
String senderAddr = "8500000000";
slSMS.submitLongSMS(MSISDN, senderAddr, message);
}
}

The best source to solve these kinds of problems is to use SMPP official documentation:
https://smpp.org/SMPP_v3_4_Issue1_2.pdf
To send SubmitSm with long messages, you need to use optional_parameter called message_payload instead of common short_message parameter.
You can read this information in documentation too:
The maximum message length which can be specified in sm_length field
is 254 octets. If an ESME wishes to submit a message of length greater
than 254 octets, the sm_length field must be set to NULL and the
message_payload optional parameter must be populated with the message
length value and user data.
To solve your problem, you need to check each time you are sending a message, how many bytes are in it, and if it is more than 254, add message_payload as your optional_parameter instead of short_message.
With cloudhopper library you can do it like this :
if (length > 254) {
submitSm.setOptionalParameter(new Tlv(
SmppConstants.TAG_MESSAGE_PAYLOAD,
CharsetUtil.encode(messageBody, CharsetUtil.CHARSET_UCS_2),
"message_payload"));
} else {
submitSm.setShortMessage(CharsetUtil.encode(messageBody, CharsetUtil.CHARSET_UCS_2));
}

Related

outofDirectMemory exception with redisson

i'm trying to learn Redis through Redisson. Here is my code to insert into redis using multiple threads.
package redisson
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
import org.redisson.Redisson;
import org.redisson.api.RBatch;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
public class RedisTest extends Thread {
static RMap<String, String> dMap = null;
static RMap<String, String> wMap = null;
static RMap<String, String> mMap = null;
static RedissonClient redisson = null;
public static void main(String[] args) throws Exception {
Config config = Config.fromJSON(new File("C:\\Users\\neon-workspace\\RedisProject\\src\\main\\resources\\SingleNodeConfig.json"));
RedissonClient redisson = Redisson.create(config);
dMap = redisson.getMap("Daily");
wMap = redisson.getMap("Weekly");
mMap = redisson.getMap("Monthly");
connectHbse(dMap,wMap,mMap,redisson);
redisson.shutdown();
}
public static void connectHbse(RMap<String, String> dMap,RMap<String, String> wMap,RMap<String, String> mMap,RedissonClient redisson) {
int totalSize=500000;
int totalThread=2;
int chunkSize = totalSize/totalThread;
AtomicInteger total = new AtomicInteger(chunkSize);
RedisTest test1[] = new RedisTest[totalThread];
for (int i = 0; i < test1.length; i++) {
test1[i] = new RedisTest(total,dMap,wMap,mMap,redisson);
total.set(total.intValue()+chunkSize);
}
long t1 = System.currentTimeMillis();
for (int i = 0; i < test1.length; i++) {
test1[i].start();
}
try {
for (int i = 0; i < test1.length; i++) {
test1[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Total Time Taken ::>>>>>>>>>>>>>>>>> " + ((System.currentTimeMillis() - t1))+"ms");
}
private AtomicInteger total = null;
public RedisTest(AtomicInteger total,RMap<String, String> dMap,RMap<String, String> wMap,RMap<String, String> mMap,RedissonClient redisson) {
this.total = new AtomicInteger(total.intValue());
this.dMap = dMap;
this.wMap = wMap;
this.mMap = mMap;
this.redisson = redisson;
}
public static int getRandomInteger(int maximum, int minimum) {
return ((int) (Math.random() * (maximum - minimum))) + minimum;
}
public void run() {
try {
long t1 = System.currentTimeMillis();
dMap.clear();
wMap.clear();
mMap.clear();
RBatch batch = redisson.createBatch();
for (;total.decrementAndGet()>=0;) {
String dvalue = ""+getRandomInteger(100,200);
String wvalue = "" +getRandomInteger(200, 300);
String mvalue = "" +getRandomInteger(300, 400);
batch.getMap("Daily").fastPutAsync(""+total.get(), dvalue);
batch.getMap("Weekly").fastPutAsync(""+total.get(), wvalue);
batch.getMap("Monthly").fastPutAsync(""+total.get(), mvalue);
synchronized (total) {
if(total.get()%100==0)
System.out.println(total.get()+" Records in Seconds:::::" + ((System.currentTimeMillis() - t1))/1000);
}
}
batch.execute();
System.out.println("Time Taken for completion::::: " + ((System.currentTimeMillis() - t1))+" by thread:::::"+Thread.currentThread().getName());
System.out.println("Done !!!");
} catch (Exception e) {
System.out.println("Done !!!" + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
This code works fine until totalSize=400000.
When i put the totalSize=500000, its throwing the following exception.
io.netty.handler.codec.EncoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 16777216 byte(s) of direct memory (used: 939524096, max: 954466304)
at io.netty.handler.codec.MessageToByteEncoder.write(MessageToByteEncoder.java:125)
at org.redisson.client.handler.CommandBatchEncoder.write(CommandBatchEncoder.java:45)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)
... 25 more
Caused by: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 16777216 byte(s) of direct memory (used: 939524096, max: 954466304)
at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:627)
at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:581)
at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:764)
at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:740)
at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:244)
at io.netty.buffer.PoolArena.allocate(PoolArena.java:226)
at io.netty.buffer.PoolArena.reallocate(PoolArena.java:397)
at io.netty.buffer.PooledByteBuf.capacity(PooledByteBuf.java:118)
at io.netty.buffer.AbstractByteBuf.ensureWritable0(AbstractByteBuf.java:285)
at io.netty.buffer.AbstractByteBuf.ensureWritable(AbstractByteBuf.java:265)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1046)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1054)
at org.redisson.client.handler.CommandEncoder.writeArgument(CommandEncoder.java:169)
at org.redisson.client.handler.CommandEncoder.encode(CommandEncoder.java:110)
at org.redisson.client.handler.CommandBatchEncoder.encode(CommandBatchEncoder.java:52)
at org.redisson.client.handler.CommandBatchEncoder.encode(CommandBatchEncoder.java:32)
at io.netty.handler.codec.MessageToByteEncoder.write(MessageToByteEncoder.java:107)
... 27 more
But i have about 7Gb ram free.
Can someone explain to me the reason i'm getting this exception?
It seems i should provide more memory to my JVM instance using -Xmx which solved the issue for me.

Sales force EMP connector, stops receiving notification after some time

I am performing a POC to check Streaming API stability, POC is as follows
Program 1 : subscribe to pushtopic created against Account object
Program 2 : create, update & delete single record after every 10 min interval
Both this programs were kept running for more than 12 hours (left overnight), after that I verified if all notification are received or not and found that after sometime (in this case it was nearly ~ 2 hours 45 min ) no notification were received, I repeated this twice and both case it stops getting notification after sometime.
Test code used
Streaming API client (using EMP connector)
public class SFPoc {
static Long count = 0L;
static Long Leadcount = 0L;
public static void main(String[] argv) throws Exception {
String userName = "<user_name>";
String password = "<pwd>";
String pushTopicName = "/topic/AccountPT";
String pushTopicNameLead = "/topic/Leadwhere";
long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;
String securityToken = "<token>";
BayeuxParameters custom = getBayeuxParamWithSpecifiedAPIVersion("37.0");
BayeuxParameters params = null;
try {
params = login(userName, password + securityToken, custom);
} catch (Exception e) {
e.printStackTrace();
}
Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++count));
Consumer<Map<String, Object>> consumerLead = event -> System.out.println(String.format("****** LEADS ***** Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++Leadcount));
EmpConnector connector = new EmpConnector(params);
connector.start().get(10, TimeUnit.SECONDS);
TopicSubscription subscription = connector.subscribe(pushTopicName, replayFrom, consumer).get(10, TimeUnit.SECONDS);
TopicSubscription subscriptionLead = connector.subscribe(pushTopicNameLead, replayFrom, consumerLead).get(10, TimeUnit.SECONDS);
System.out.println(String.format("Subscribed: %s", subscription));
System.out.println(String.format("Subscribed: %s", subscriptionLead));
}
private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
BayeuxParameters params = new BayeuxParameters() {
#Override
public String version() {
return apiVersion;
}
#Override
public String bearerToken() {
return null;
}
};
return params;
}
}
Code which is doing record create/update/delete periodically to generate events
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.time.LocalDateTime;
public class SFDCDataAdjustment {
static final String USERNAME = "<username>";
static final String PASSWORD = "<pwd&securitytoken>";
static EnterpriseConnection connection;
static Long count = 0L;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
// run the different examples
while (true) {
createAccounts();
updateAccounts();
deleteAccounts();
Thread.sleep(1 * 10 * 60 * 1000);
}
} catch (ConnectionException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// queries and displays the 5 newest contacts
private static void queryContacts() {
System.out.println("Querying for the 5 newest Contacts...");
try {
// query for the 5 newest contacts
QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name " +
"FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Contact
Contact c = (Contact)queryResults.getRecords()[i];
System.out.println("Id: " + c.getId() + " - Name: "+c.getFirstName()+" "+
c.getLastName()+" - Account: "+c.getAccount().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// create 5 test Accounts
private static void createAccounts() {
System.out.println("Creating a new test Account...");
Account[] records = new Account[1];
try {
// create 5 test accounts
for (int i=0;i<1;i++) {
Account a = new Account();
a.setName("OptyAccount "+i);
records[i] = a;
}
// create the records in Salesforce.com
SaveResult[] saveResults = connection.create(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR creating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// updates the 5 newly created Accounts
private static void updateAccounts() {
System.out.println("Update a new test Accounts...");
Account[] records = new Account[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
// modify the name of the Account
a.setName(a.getName()+" -- UPDATED");
records[i] = a;
}
}
// update the records in Salesforce.com
SaveResult[] saveResults = connection.update(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR updating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// delete the 5 newly created Account
private static void deleteAccounts() {
System.out.println("Deleting new test Accounts...");
String[] ids = new String[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
// add the Account Id to the array to be deleted
ids[i] = a.getId();
System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
}
}
// delete the records in Salesforce.com by passing an array of Ids
DeleteResult[] deleteResults = connection.delete(ids);
// check the results for any errors
for (int i=0; i< deleteResults.length; i++) {
if (deleteResults[i].isSuccess()) {
System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = deleteResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR deleting record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Further updates got below mentioned error after which notification were
2017-03-09T19:30:28.346 ERROR [com.salesforce.emp.connector.EmpConnector] - connection failure, reconnecting
org.cometd.common.TransportException: {httpCode=503}
at org.cometd.client.transport.LongPollingTransport$2.onComplete(LongPollingTransport.java:278)
at org.eclipse.jetty.client.ResponseNotifier.notifyComplete(ResponseNotifier.java:193)
After this reconnect also happened and handshake also happened but error seems to be in resubscribe() EMP connector seems to be not able to resubscribe for some reason
Note I am using "resubscribe-on-disconnect" branch of EMP connetor
We have determined there was a bug on the server side in a 403 case. The Streaming API uses a session routing cookie and this cookie periodically expires. When it expires, the session is routed to another server, and this responds with a 403. In the current version, this 403 response does not include connect advice, and the client does not attempt to reconnect. This has been fixed and the fix is currently live. My understanding is that this should fix the reconnect problem exhibited by the clients.

SQL query into JTable

I've found one totally working query, which gets columns and their data from Oracle DB and puts the output in console printout.
I've spent 3 hours trying to display this data in Swing JTable.
When I am trying to bind data with JTable:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
data, header
));
it keeps telling me that constructor is invalid. That's true, because I need arrays [] and [][] to make that. Any ideas how this can be implemented?
Here is the original query:
package com.javacoderanch.example.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class MetadataColumnExample {
private static final String DRIVER = "oracle.jdbc.OracleDriver";
private static final String URL = "jdbc:oracle:thin:#//XXX";
private static final String USERNAME = "XXX";
private static final String PASSWORD = "XXX";
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
//
// As the usual ritual, load the driver class and get connection
// from database.
//
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//
// In the statement below we'll select all records from users table
// and then try to find all the columns it has.
//
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select *\n"
+ "from booking\n"
+ "where TRACKING_NUMBER = 1000001741");
//
// The ResultSetMetaData is where all metadata related information
// for a result set is stored.
//
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
//
// To get the column names we do a loop for a number of column count
// returned above. And please remember a JDBC operation is 1-indexed
// so every index begin from 1 not 0 as in array.
//
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
//
// Later we use the collected column names to get the value of the
// column it self.
//
while (resultSet.next()) {
for (String columnName : columns) {
String value = resultSet.getString(columnName);
System.out.println(columnName + " = " + value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
}
}
}
Ok I found a bit better way adding SQL query to JTable without even using the ArrayList. Maybe will be helpful for someone, completely working:
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.image.BufferedImage;
public class report extends JFrame {
PreparedStatement ps;
Connection con;
ResultSet rs;
Statement st;
JLabel l1;
String bn;
int bid;
Date d1, d2;
int rows = 0;
Object data1[][];
JScrollPane scroller;
JTable table;
public report() {
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
setSize(600, 600);
setLocation(50, 50);
setLayout(new BorderLayout());
setTitle("Library Report");
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#XXXXX", "XXXXX", "XXXXX");
} catch (Exception e) {
}
try {
/*
* JDBC 2.0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all the rows
* So we add TYPE_SCROLL_INSENSITIVE & CONCUR_READ_ONLY
*/
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //Creating Statement Object
} catch (SQLException sqlex) {
System.out.println("!!!###");
}
try {
rs = st.executeQuery("select TRACKING_NUMBER, INCO_TERM_CODE, MODE_OF_TRANSPORT\n"
+ "from salog.booking\n"
+ "where rownum < 5");
// Counting rows
rs.last();
int rows = rs.getRow();
rs.beforeFirst();
System.out.println("cc " + rows);
ResultSetMetaData metaData = rs.getMetaData();
int colummm = metaData.getColumnCount();
System.out.println("colms =" + colummm);
Object[] Colheads = {"BookId", "BookName", "rtyry"};
if (Colheads.length != colummm) {
// System.out.println("EPT!!");
JOptionPane.showMessageDialog(rootPane, "Incorrect Column Headers quantity listed in array! The program will now exit.", "System Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
data1 = new Object[rows][Colheads.length];
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < Colheads.length; j1++) {
data1[i1][j1] = rs.getString(j1 + 1);
}
}
JTable table = new JTable(data1, Colheads);
JScrollPane jsp = new JScrollPane(table);
getContentPane().add(jsp);
} catch (Exception e) {
}
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
JFrame frm = new report();
frm.setSize(600, 600);
frm.setLocation(50, 50);
BufferedImage image = null;
frm.setIconImage(image);
frm.setVisible(true);
frm.show();
}
}

To Get the VM Created Date

I am new to the VMWare Sdk Programming,i have a requirement to get the Virtual Machine (VM) Deployed date.
I have written the below code to get the other required details.
package com.vmware.vim25.mo.samples;
import java.net.URL;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
public class HelloVM {
public static void main(String[] args) throws Exception
{
long start = System.currentTimeMillis();
int i;
ServiceInstance si = new ServiceInstance(new URL("https://bgl-clvs-vc.bgl.com/sdk"), "sbibi", "sibi_123", true);
long end = System.currentTimeMillis();
System.out.println("time taken:" + (end-start));
Folder rootFolder = si.getRootFolder();
String name = rootFolder.getName();
System.out.println("root:" + name);
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
System.out.println("No oF vm:" + mes.length);
if(mes==null || mes.length ==0)
{
return;
}
for(i=0;i<mes.length; i++){
VirtualMachine vm = (VirtualMachine) mes[i];
VirtualMachineConfigInfo vminfo = vm.getConfig();
VirtualMachineCapability vmc = vm.getCapability();
vm.getResourcePool();
System.out.println("VM Name " + vm.getName());
System.out.println("GuestOS: " + vminfo.getGuestFullName());
System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
System.out.println("Summary: " + vminfo.getDatastoreUrl());
}
si.getServerConnection().logout();
}
}
Can anyone help me how I can get the VM created date?
I have found the Vm Creation Date using the below codes.
EventFilterSpecByUsername uFilter =
new EventFilterSpecByUsername();
uFilter.setSystemUser(false);
uFilter.setUserList(new String[] {"administrator"});
Event[] events = evtMgr.queryEvents(efs);
// print each of the events
for(int i=0; events!=null && i<events.length; i++)
{
System.out.println("\nEvent #" + i);
printEvent(events[i]);
}
/**
* Only print an event as Event type.
*/
static void printEvent(Event evt)
{
String typeName = evt.getClass().getName();
int lastDot = typeName.lastIndexOf('.');
if(lastDot != -1)
{
typeName = typeName.substring(lastDot+1);
}
System.out.println("Time:" + evt.getCreatedTime().getTime());
}
Hope this code might help others.
private DateTime GetVMCreatedDate(VirtualMachine vm)
{
var date = DateTime. Now;
var userName = new EventFilterSpecByUsername ();
userName . SystemUser = false;
var filter = new EventFilterSpec ();
filter . UserName = userName;
filter . EventTypeId = ( new String [] { "VmCreatedEvent" , "VmBeingDeployedEvent" ,"VmRegisteredEvent" , "VmClonedEvent" });
var collector = vm .GetEntityOnlyEventsCollectorView(filter);
foreach (Event e in collector . ReadNextEvents(1 ))
{
Console .WriteLine(e . GetType(). ToString() + " :" + e. CreatedTime);
date = e. CreatedTime;
}
Console .WriteLine( "---------------------------------------------------" );
return date;
}

KeyTyped being called twice in this code?

There is a bug somewhere here. For some reason, when I am sending the message to the server, every message is received twice for any single keystroke! for instance, i type "a", and the server receives "INSERT 0 1 a" "INSERT 0 1 a". I'm not sure why it happens twice do you know?
package client;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class JTextAreaListen extends JFrame implements KeyListener,
CaretListener {
private static final long serialVersionUID = 6950001634065526391L;
private JTextArea textArea;
protected final PrintWriter out;
protected final int id;
protected final BufferedReader in;
protected static int caretPos;
private static int cMark;
protected static boolean text_selected;
/*
* Connecting to server. (1337 is the port we are going to use).
*
* socket = new Socket(InetAddress.getByName("127.0.0.1"), 1337);
*
* (Open a new outStream, you can save this instead of opening on every time
* you want to send a message. If the connection is lost your should to
* out.close();
*
* out = new PrintWriter(socket.getOutputStream(), true);
*
* out.print("message"); to send something to the server.
*/
public JTextAreaListen(PrintWriter out, BufferedReader in, int id) {
super("JTextAreaListen");
this.id = id;
this.out = out;
this.in = in;
TextEditor.document.addCaretListener(this);
TextEditor.document.addKeyListener(this);
}
// Listener methods
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
#Override
public void keyPressed(KeyEvent arg0) {
System.out.print("KeyPressedd");
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent ev) {
System.out.println(ev.KEY_PRESSED);
System.out.println("Sth happening!");
System.out.println(ev.getKeyCode());
int evID = ev.getID();
String keyString;
int keyCode;
if (evID == KeyEvent.KEY_TYPED) {
if (ev.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
keyCode = ev.getKeyCode();
if (keyCode == 8) {
if (text_selected) {
if (caretPos > cMark) {
for (int i = caretPos; i >= cMark; i--) {
System.out.println("sm1");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
} else if (caretPos < cMark) {
for (int i = caretPos; i >= cMark; i++) {
System.out.println("sm2");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
}
} else {
System.out.println("sm3");
sendMessage("DELETE" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos + 1));
}
}
} else {
char c = ev.getKeyChar();
boolean capital = ev.isShiftDown();
String charString = String.valueOf(c);
if (capital) {
charString.toUpperCase();
}
if (text_selected) {
if (caretPos > cMark) {
for (int i = caretPos; i >= cMark; i--) {
System.out.println("sm4");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
System.out.println("sm5");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(cMark) + " " + charString);
} else if (caretPos < cMark) {
for (int i = caretPos; i >= cMark; i++) {
System.out.println("sm6");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(caretPos + 1));
}
System.out.println("sm7");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos) + " " + charString);
}
} else {
System.out.println("sm8");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos) + " " + charString);
}
}
}
}
public void sendMessage(String s) {
System.out.println("smReal");
out.println(s);
}
#Override
public void caretUpdate(CaretEvent cev) {
int dot = cev.getDot();
int mark = cev.getMark();
caretPos = dot;
cMark = mark;
if (dot == mark) {
text_selected = false;
} else if ((dot < mark) | (dot > mark)) {
text_selected = true;
}
}
}
Here is the code for the client containing the TextArea which calls this Listener.
package client;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.text.DefaultEditorKit;
public class TextEditor extends JFrame {
private static final long serialVersionUID = 5991470239888613993L;
protected static JTextArea document = new JTextArea(20, 120);
private JFileChooser dialog = new JFileChooser(
System.getProperty("user.dir"));
private String currentFile = "Untitled";
private boolean changed = false;
private int id;
private final BufferedReader in;
private final PrintWriter out;
public TextEditor(final PrintWriter out, final BufferedReader in, int id) {
this.out = out;
this.in = in;
this.id = id;
document.setFont(new Font("Monospaced", Font.PLAIN, 12));
JScrollPane scroll = new JScrollPane(document,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.add(scroll, BorderLayout.CENTER);
JMenuBar JMB = new JMenuBar();
this.setJMenuBar(JMB);
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMB.add(file);
JMB.add(edit);
file.add(Open);
file.add(Save);
file.add(Quit);
file.add(SaveAs);
file.addSeparator();
for (int i = 0; i < 4; i++)
file.getItem(i).setIcon(null);
edit.add("Cut");
edit.add("Copy");
edit.add("Paste");
edit.getItem(0).setText("Cut");
edit.getItem(1).setText("Copy");
edit.getItem(2).setText("Paste");
JToolBar tool = new JToolBar();
this.add(tool, BorderLayout.NORTH);
tool.add(Open);
tool.add(Save);
tool.addSeparator();
JButton cut = tool.add(Cut), copy = tool.add(Copy), paste = tool
.add(Paste);
cut.setText(null);
cut.setIcon(new ImageIcon("cut.png"));
copy.setText(null);
copy.setIcon(new ImageIcon("copy.png"));
paste.setText(null);
paste.setIcon(new ImageIcon("paste.png"));
Save.setEnabled(false);
SaveAs.setEnabled(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
document.addKeyListener(new JTextAreaListen(out, in, id));
setTitle(currentFile);
setVisible(true);
final int id2 = id;
Thread t = new Thread(new Runnable() {
public void run() {
out.println("GET " + id2);
while (true) {
out.println("GET " + id2);
String line = null;
do {
try {
line = in.readLine();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Connection Lost", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(-1);
}
} while (line == null);
int temp = JTextAreaListen.caretPos;
document.setText(line);
document.setCaretPosition(temp);
}
}
});
t.start();
}
private KeyListener keyPressed = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
changed = true;
Save.setEnabled(true);
SaveAs.setEnabled(true);
}
};
Action Open = new AbstractAction("Open", new ImageIcon("open.png")) {
private static final long serialVersionUID = -474289105133169886L;
public void actionPerformed(ActionEvent e) {
saveOld();
if (dialog.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
readInFile(dialog.getSelectedFile().getAbsolutePath());
}
SaveAs.setEnabled(true);
}
};
Action Save = new AbstractAction("Save", new ImageIcon("save.png")) {
private static final long serialVersionUID = 2064233284536910855L;
public void actionPerformed(ActionEvent e) {
if (!currentFile.equals("Untitled"))
saveFile(currentFile);
else
saveFileAs();
}
};
Action SaveAs = new AbstractAction("Save as...") {
private static final long serialVersionUID = -5473532525926088880L;
public void actionPerformed(ActionEvent e) {
saveFileAs();
}
};
Action Quit = new AbstractAction("Quit") {
private static final long serialVersionUID = -5339245808869817726L;
public void actionPerformed(ActionEvent e) {
saveOld();
System.exit(0);
}
};
ActionMap m = document.getActionMap();
Action Cut = m.get(DefaultEditorKit.cutAction);
Action Copy = m.get(DefaultEditorKit.copyAction);
Action Paste = m.get(DefaultEditorKit.pasteAction);
private void saveFileAs() {
if (dialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
saveFile(dialog.getSelectedFile().getAbsolutePath());
}
private void saveOld() {
if (changed) {
if (JOptionPane.showConfirmDialog(this, "Save " + currentFile
+ " ?", "Save", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
saveFile(currentFile);
}
}
private void readInFile(String fileName) {
try {
FileReader r = new FileReader(fileName);
document.read(r, null);
r.close();
currentFile = fileName;
setTitle(currentFile);
changed = false;
} catch (IOException e) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(this, "Could not find " + fileName);
}
}
private void saveFile(String fileName) {
try {
FileWriter w = new FileWriter(fileName);
document.write(w);
w.close();
currentFile = fileName;
setTitle(currentFile);
changed = false;
Save.setEnabled(false);
} catch (IOException e) {
JOptionPane
.showMessageDialog(this,
"An error has occurred. Your document may not have been saved");
}
}
}