How ActiveMQ save message in database field MSG? - activemq

i tried to get message text from database as needed for some internal statistics, i used TextMessage but i cant get object from MSG field in database.
WireFormat wireFormat = new OpenWireFormat();
ActiveMQTextMessage answer = new ActiveMQTextMessage();
String testString = "... BLOB(hex) data from MSG field used for test ...";
byte[] test = new BigInteger(testString,16).toByteArray();
answer = (ActiveMQTextMessage) wireFormat.unmarshal(new ByteSequence(test));
and wireFormat always return null object.
On the server side i used also TextMessages and OpenWireFormat, and when convert BLOB to String i see id queue name and other data but not eye well formated
What to do to get ActiveMQTextMessage from this field?

Related

Power Builder 10.5 user object array to datawindow table

I am new to Power Builder and I would like to ask how can I represent my objects in a table form. For example, given an ArrayList in java I have implemented the code like this:
table = new JTable();
scrollPane.setViewportView(table);
DefaultTableModel tableModel =
new DefaultTableModel(
new String[] {
"ScheduleNo",
"Start Date",
"End Date",
"No of days",
"Principal Expected",
"Interest Expected",
"EMI amount",
"Factor",
"MeanFactor"}
, 0);
for (Schedule s : pf.getSchedules()){
Integer schNo = s.getScheduleNo();
String startDate = df.format(s.getStartDate());
String endDate = df.format(s.getEndDate());
Integer noofdays = s.getNoOfDays();
String prinExp = String.format("%.2f", s.getPrincipalAmt());
String intExp = String.format("%.2f", s.getInterestAmt());
String emi = String.format("%.2f", s.getAmortizedAmount());
String factor = String.format("%.6f", s.getFactor());
String mean = String.format("%.6f", s.getProductByFactor());
Object[]data = {schNo, startDate, endDate, noofdays, prinExp, intExp,
emi, factor, mean};
tableModel.addRow(data);
}
table.setModel(tableModel);
But I cannot find a way to do it in PowerBuilder without having a connection to a database and pick the data from there which is totally not the case.
The data come from an User Object array[] and have exactly the same form like in the Java example above.
Without really knowing what you are trying to accomplish it appears to me that you could use a 'normal' PowerBuilder datawindow but when you define it you make it's datasource as external. This type of datawindow does not require a connection to a database. You define the 'fields' of the datasource as strings, numeric, etc. when you create it.
In code you can create a datawindow (or datastore for that matter) control, assign the external datasource datawindow object to it, insert a row, then populate the fields with data of the corresponding datatype.
Example usage:
datawindow ldw
long llrow
ldw = CREATE datawindow
ldw.dataobject = 'myExternalDatawindowObject'
llrow = ldw.insertrow(0)
ldw.setitem(llrow,'stringcolumn','my example string')
ldw.setitem(llrow,'numericcolumn',1234)
It's been a while since I used PowerBuilder, but IIRC you should be able to use a DataStore without having a database connection.

NSJSONSerialization.JSONObjectWithData changes field type

I'm getting the following JSON response from the server:
{
"userId":"123456789",
"displayName":"display name"
}
When I use NSJSONSerialization.JSONObjectWithData and then prints the result NSDictionary I see in the console the following:
userId = 123456789
displayName = "display name"
Why do JSONObjectWithData changes the userId field type from String to a number?
It doesn't. The JSON deserialisation respects the data type and will maintain it. You can't tell the data type from a simple description log, you need to actually interrogate the class. The description log will quote some things if it makes more sense for the human reader, like spaces in the description, but it also omits quotes in some cases.
It doesn't.
Don't infer a variable type from its log representation, just test. Fire a Playground with this, for example:
let str = "{\"userId\":\"123456789\",\"displayName\":\"display name\"}"
if let data = str.dataUsingEncoding(NSUTF8StringEncoding),
jsonResult = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
jsonObject = jsonResult as? [String:String],
id = jsonObject["userId"] {
print("User ID is " + id)
}

Windows8: device identifier

I am currently trying to retrieve a unique device identifier. Here is my code:
var token = Windows.System.Profile.HardwareIdentification.getPackageSpecificToken(null);
var reader = Windows.Storage.Streams.DataReader.fromBuffer(token.id);
reader.unicodeEncoding = true;
var identifier = reader.readString(reader.unconsumedBufferLength);
console.log(identifier);
But it raises following error:
The operation attempted to access data outside the valid range.
How can I retrieve the size of my token.id string? I also tried to use token.id.length, but result is the same.
I can't try to replicate what you're doing at the moment, but you might try reading it as bytes into array like this:
var array = new Array(token.id.length);
reader.readBytes(array);
And then convert the array to a string for the identifier.
See these posts for examples:
http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/1e2175e3-fe07-4094-9454-b3ecf1bf0381
http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/cdf72b9f-b3c0-488e-b607-b4445a5039b3

How to insert image in postgresql?

I am wondering how to insert an image on one of the fields in my postgresql table. I cannot find an appropriate tutorial re this matter. The dataype of the field is oid. Has anyone tried this? Thanks!
// All LargeObject API calls must be within a transaction
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
//create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
//open the large object for write
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
// Now open the file
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
// copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0)
{
obj.write(buf, 0, s);
tl += s;
}
// Close the large object
obj.close();
//Now insert the row into imagesLO
PreparedStatement ps = conn.prepareStatement("INSERT INTO imagesLO VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setInt(2, oid);
ps.executeUpdate();
ps.close();
fis.close();
Found that sample code from here. Really very good bunch of sql operations.
To quote this site,
PostgreSQL database has a special data type to store binary data
called bytea. This is a non-standard data type. The standard data type
in databases is BLOB.
You need to write a client to read the image file, for example
File img = new File("woman.jpg");
fin = new FileInputStream(img);
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("INSERT INTO images(data) VALUES(?)");
pst.setBinaryStream(1, fin, (int) img.length());
pst.executeUpdate();
You can either use the bytea type or the large objects facility. However note that depending on your use case it might not be a good idea to put your images in the DB because of additional load it may put on the DB server.
Rereading your question I notice you mentioned you have a field of type oid. If this is an application you are modifying it suggests to me it is using large objects. These objects get an oid which you then need to store in another table to keep track of them.

Index (zero based) must be greater than or... Working with the Bit.ly API

I'm working (actually more like playing) around with the Bit.ly API, and keep getting the error in the title of this question. So I'm going to show you the code and hopefuly someone can help me resolve this. First the client side code.
var x = service.GetClicks(url, service.BitlyLogin, service.BitlyAPIKey);
Console.WriteLine(x);
Console.ReadLine();
And this is the code that's being called
public List<int> GetClicks(string url, string login, string key)
{
List<int> clicks = new List<int>();
url = Uri.EscapeUriString(url);
string reqUri =
String.Format("http://api.bit.ly/v3/clicks?" +
"login={0}&apiKey={1}&shortUrl={2}&format=xml" +
login, key, url);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUri);
req.Timeout = 10000; // 10 seconds
Stream stm = req.GetResponse().GetResponseStream();
XmlDocument doc = new XmlDocument();
doc.Load(stm);
// error checking for xml
if (doc["response"]["status_code"].InnerText != "200")
throw new WebException(doc["response"]["status_txt"].InnerText);
XmlElement el = doc["response"]["data"]["clicks"];
clicks.Add(int.Parse(el["global_clicks"].InnerText));
clicks.Add(int.Parse(el["user_clicks"].InnerText));
return clicks;
}
As you can see it's very simple code, nothing complicated, and I can see nothing that causes this error. Anyone out there who has worked with(the full error is Index (zero based) must be greater than or equal to zero and less than the size of the argument list.) the Bit.ly API and can lend a hand?
Instead this
string reqUri =
String.Format("http://api.bit.ly/v3/clicks?" +
"login={0}&apiKey={1}&shortUrl={2}&format=xml" + login, key, url);
Use this
string reqUri = String.Format("http://api.bit.ly/v3/clicks?login={0}&apiKey={1}&shortUrl={2}&format=xml", login, key, url);
Notice that I just changed the plus sign with the comma before "login, key, url);" at the end of the String.Format().
I narrowed it down to a place where I was using string.Format to build an array and has less in the string.Format than what was supposed to. I had it go to Index 3 but only filled to Index 2
Not for your specific case, but I ran into this: make sure that, if you have multiple parameters, you send them as an array of objects instead of an IEnumerable:
IEnumerable<object> myArgs = ...;
string toFormat = "{0} xyz {1}";
String.Format(toFormat, myArgs);
// ERROR, since myArgs is one argument whereas the string template requires two
String.Format(toFormat, myArgs.ToArray());
// Valid, as the Format() accepts an array of objects to fill all arguments in the string