I'm having a problem calling the save method on a domain object. The error is:
groovy.lang.MissingMethodException: No signature of method: static my.awesome.Class.FeedHit.save() is applicable for argument types: () values: []
Possible solutions: save(), save(java.lang.Boolean), save(java.util.Map), wait(), any(), wait(long)
I'm going through an array of FeedHits, updating a flag, and then calling the save method:
void updateFeedHits(Set<FeedHit> list, FeedHitStatus status) {
for (FeedHit feedHit: list) {
feedHit.status = status
try {
feedHit.save()
} catch (Exception ex) {
log.info("unknown exception during update FeedHit", ex)
}
}
}
I've seen other StackOVerflow users have the same problem, but only during tests. This code is in normal release code.
Any help would be appreciated.
EDIT:
Here is the FeedHit object, slightly edited.
class FeedHit {
Feed feed
String title
String body
String url
FeedHitStatus status
String sourceId
String hash
Date publishedDate
Date dateCreated = new Date()
Integer pos = -1
static constraints = {
alert(nullable: true)
title(nullable: true)
body(nullable: true)
url(nullable: true)
status(nullable: true)
sourceId(nullable: true)
hash(nullable: true)
pos(nullable: true)
publishedDate(nullable: true)
dateCreated(nullable: true)
}
static mapping = {
table('alert_hit')
autoTimestamp false
version(false)
alert(column: 'alert_id')
body(sqlType: 'text')
url(sqlType: 'text')
sourceId(column: 'sourceId')
publishedDate(column: 'publishedDate')
dateCreated(column: 'dateCreated')
}
/**
* Generates a hash from title, body and url.
*/
public AlertHit generateHash() {
StringBuffer sb = new StringBuffer();
if (this.title != null) {
sb.append(this.title);
}
if (this.body != null) {
sb.append(this.body);
}
if (this.url != null) {
sb.append(this.url);
}
if (this.publishedDate != null) {
sb.append(this.publishedDate.getTime());
}
if (sb.length() > 0) {
hash = Md5Hash.hash(sb.toString());
}
this
}
#Override
public String toString() {
return "AlertHit{" +
"id=" + id +
", alert=" + alert +
", title='" + title + '\'' +
", body='" + body + '\'' +
", url='" + url + '\'' +
", status=" + status +
", sourceId='" + sourceId + '\'' +
", hash='" + hash + '\'' +
", publishedDate=" + publishedDate +
", dateCreated=" + dateCreated +
", pos=" + pos +
", version=" + version +
'}';
}
}
You need to annotate GORM functions, if you want to use domain class outside grails. See http://www.rimerosolutions.com/using-gorm-standalone-outside-grails/
I would recommend you to use another way than native threads. Try: Quartz-Plugin
Related
This is my code Provide me details where am going wrong so that am
getting only the part of the description available
========================================================================
http://code.dblock.org/jna-reading-windows-event-log-entries-in-java
#SuppressWarnings("unused")
public void testReadEventLogEntries() throws CharacterCodingException {
final Charset charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
final CharsetEncoder encoder = charset.newEncoder();
final CharsetDecoder decoder = charset.newDecoder();
int i = 0;// loop contro variable
String type = null; // Type of the event
String user = null;
String str[] = { "System", "Application" };
while (i < 2) {
System.out.println("\n\n" + str[i]);
HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, str[i]);
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
Memory buffer = new Memory(1024 * 64);
IntByReference pOldestRecord = new IntByReference();
int dwRecord = pOldestRecord.getValue();
int rc = 0;
while (true) { // Travesing the read log records
if (!Advapi32.INSTANCE.ReadEventLog(h,
WinNT.EVENTLOG_SEQUENTIAL_READ
| WinNT.EVENTLOG_FORWARDS_READ, 0, buffer,
(int) buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
continue;
}
break;
}
int dwRead = pnBytesRead.getValue();
Pointer pevlr = buffer;
while (dwRead > 0) {
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
EventLogRecord event = new EventLogRecord(pevlr);
org.hyperic.sigar.win32.EventLogRecord sigar;
EventLog log = new EventLog();
if (record.EventType.intValue() == 1)
type = "Error";
else if (record.EventType.intValue() == 10)
type = "Failure Audit";
else if (record.EventType.intValue() == 8)
type = "Sucess Audit";
else if (record.EventType.intValue() == 4)
type = "Information";
else
type = "Warning";
ByteBuffer names = pevlr
.getByteBuffer(
record.size(),
(record.UserSidLength.intValue() != 0 ? record.UserSidOffset
.intValue() : record.StringOffset
.intValue())
- record.size());
names.position(0);
CharBuffer namesBuf = names.asCharBuffer();
String[] splits = namesBuf.toString().split("\0");
if (record.UserSidLength.intValue() != 0) {
ByteBuffer usersid = pevlr.getByteBuffer(
record.UserSidOffset.intValue(),
record.UserSidLength.intValue());
usersid.position(0);
CharBuffer sidBuf = usersid.asCharBuffer();
String[] sp = sidBuf.toString().split("\0");
// System.out.println(sp[0] + sp[1] + sp[2]);
/*
* dst.get user= new String(dst);
*/
} else {
user = "N/A";
}
System.out.println(type + "\t" + toDate(record) + "\t"
+ event.getSource() + "\t" + record.EventCategory
+ "\t" + record.EventID.shortValue() + "\t" + user
+ "\t" + splits[1]);
ByteBuffer strings = pevlr.getByteBuffer(
record.StringOffset.longValue(),
record.DataOffset.intValue()
- record.StringOffset.intValue());
CharBuffer stringsBuf = strings.asCharBuffer();
System.out.println("Desc: " + stringsBuf.toString());
dwRecord++;
dwRead -= record.Length.intValue();
pevlr = pevlr.share(record.Length.intValue());
}
}
i++;
}
}
// Method to convert the timestamp to formated date
public Date toDate(EVENTLOGRECORD record) {
Timestamp stamp = new Timestamp(record.TimeWritten.longValue() * 1000);
Date date = new Date(stamp.getTime());
return date;
}
}
Finally I figured out the solution....The description returned by the
above code is just the insertion strings needed to build the message.
Instead of using jna I used WMI which is simple to use and more handy
/**
* #param args
*/
public static void main(String[] args) throws COMException {
String computerName = ".";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String Message = "";
String queryProcessor = "Select * from Win32_NTLogEvent where Logfile='System'or Logfile='Application'";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
if (wbemObject.get("Message") != null) {
Message = (String) wbemObject.get("Message");
} else {
Message = "The description for Event ID ("
+ wbemObject.get("EventCode")
+ " ) in Source ( "
+ wbemObject.get("SourceName")
+ ") cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.";
}
System.out.println(wbemObject.get("Logfile") + "\t"
+ wbemObject.get("Type") + "\t"
+ toDate(wbemObject.get("TimeGenerated").toString())
+ "\t"
+ toTime(wbemObject.get("TimeGenerated").toString())
+ "\t" + wbemObject.get("EventCode") + "\t"
+ wbemObject.get("ComputerName") + "\t" + Message);
// System.out.println(wbemObject.GetObjectText_(0));
}
} catch (COMException e) {
e.printStackTrace();
}
}
public static String toDate(String time) throws COMException {
String date = time.substring(6, 8) + "-" + time.substring(4, 6) + "-"
+ time.substring(0, 4);
return date;
}
public static String toTime(String time) throws COMException {
String Generatedtime = time.substring(8, 10) + ":"
+ time.substring(10, 12) + ":" + time.substring(12, 14) + ":"
+ time.substring(16, 21) + "-" + "GMT" + time.substring(21, 25);
return Generatedtime;
}
I am using java and twitter4j.
Issue : I do not get proper response from status.getText() method, link references comes as text
I have a problem. My method is as follow:
Twitter twitter = null;
String userName = "clientname";
int numberOfTweets = 0;
StringBuilder timeLineText = new StringBuilder();
try {
twitter = new TwitterFactory(new GetAuthenticConfiguration().getConfigObject()).getInstance();
ResponseList<Status> statuses = twitter.getUserTimeline(userName);
timeLineText.append("<li>");
for (Status status : statuses) {
numberOfTweets++;
if (numberOfTweets > 12) {
break;
}
int remainder = numberOfTweets % 3;
if (remainder == 0) {
timeLineText.append("</li><li>");
} else {
StringBuilder tempText = new StringBuilder();
try {
tempText.append("<p>");
tempText.append("<span>");
tempText.append("<img alt=\"" + status.getUser().getScreenName() + "\" src=\"" + status.getUser().getMiniProfileImageURL() + "\" />");
tempText.append("<b>" + status.getUser().getName() + "</b> #" + status.getUser().getScreenName() + " " + new SimpleDateFormat("dd MMM").format(status.getCreatedAt()));
tempText.append("</span>");
tempText.append("<p>" + status.getText() + "</p>");
tempText.append("</p>");
} catch (Exception e) {
System.out.println(e);
}
timeLineText.append(tempText);
}
}
timeLineText.append("</li>");
} catch (Exception te) {
System.out.println(te);
}
The response i get is :
Can you tell us which Rolls-Royce #engine powers this aircraft? #AvGeek http://t.co/t5tNXQuMFB
instead of
Can you tell us which Rolls-Royce <a href="/hashtag/engine?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>engine</b></a> powers this aircraft? <a href="/hashtag/AvGeek?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>AvGeek</b></a> <a href="http://t.co/t5tNXQuMFB" class="twitter-timeline-link u-isHiddenVisually" data-pre-embedded="true" dir="ltr" >pic.twitter.com/t5tNXQuMFB</a>
The issue is I am not getting the proper html . Can anyone tell me the reason of it please?
After doing lot of R & D, I have found out that Status.getText() method gives only plain text.
We have to manually convert it to links,hashtags and users.
Below is the method I have written to do that.
Just pass your getText() output to this method (tweet).
I hope this will help to many beginners of Twitter4J.
private String linkifyTweet(String tweet) {
Pattern pattern;
Matcher matcher;
String regex_url = "((https?://\\S+)|(www.\\S+))";
String regex_hashtag = "#(\\w+)";
String regex_user = "#(\\w+)";
//regex to apply links to all urls in the tweet
pattern = Pattern.compile(regex_url);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_url, "<a target=\"_blank\" href=\"$1\">$1</a>");
}
//regex to apply links to all hashtags in the tweet
pattern = Pattern.compile(regex_hashtag);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_hashtag, "<a target=\"_blank\" href=\"https://www.twitter.com/hashtag/$1?src=hash\">#$1</a>");
}
//regex to apply links to all users in the tweet
pattern = Pattern.compile(regex_user);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_user, "<a target=\"_blank\" href=\"https://www.twitter.com/$1\">#$1</a>");
}
//System.out.println(tweet);
return tweet;
}
I have an issue with Breezejs (1.4.2) q (0.9.7)
I want to add a computed property for an entity.
var doctorInitializer = function (doctor) {
doctor.FullName = ko.computed(function () {
return doctor.FirstName() + " " + doctor.MiddleName() + " " + doctor.LastName() + " " + doctor.SurName();
});
};
var doctorName = '/breeze/polyclinic',
doctorManager = new breeze.EntityManager(doctorName);
var store = doctorManager.metadataStore;
store.registerEntityTypeCtor("Doctor", null, doctorInitializer);
i try adding a knockout computed to the constructor
var doctor = function () {
self.FullName = ko.computed( {
read: function() {
return self.FirstName + " " + self.MiddleName + " " + self.LastName + " " + self.SurName;
},
deferEvaluation: true
});
};
store.registerEntityTypeCtor("Doctor", doctorInitializer);
in both cases only work if i remove the parenthesis but MiddleName and SurName is not required and instead of empty string i got null
this is the error i have http://screencast.com/t/bP9Xnmf9Jm
UPDATE
I try adding the error on console log and follow your example and i have the same error is not a function http://screencast.com/t/bQTyV8XGD0Pk
doctor.FullName = ko.computed(function () {
var fullName = "";
fullName += doctor.FirstName();
if (doctor.FirstName()) {
fullName += ' ' + doctor.FirstName();
}
fullName += ' ' + doctor.LastName();
if (doctor.SurName()) {
fullName += ' ' + doctor.SurName();
}
return fullName;
});
var query = breeze.EntityQuery.from("Doctors").orderBy("Id")
doctorManager.executeQuery(query)
.then(function (data) {
self.doctors.removeAll();
self.doctors(data.results);
})
.fail(function(error) {
console.log(error);
});
I hope someone can help me
The error you are seeing in the screenshot is because your query is throwing an error that you are not handling. Attach a .fail(failFunction) on the end of your entityQuery.
You can't call doctor.Surname() if there is no Surname function that is attached. Calling doctor.Surname just returns a function that doesn't give you a value.
Odds are, you don't 100% get why it's not working because you don't understand how Knockout works. You probably don't yet understand the meaning of what I am describing above either. You need to understand how Knockout works first, then try to learn Breeze.
If you want to just make it work without understand how or why put this in there and continue on. This assumes that there is a property returned called MiddleName and SurName that are just empty.
doctor.FullName = ko.computed(function () {
var fullName = "";
fullName += doctor.FirstName();
if (doctor.MiddleName()) { fullName += ' ' + doctor.MiddleName(); }
fullName += ' ' + doctor.LastName();
if (doctor.SurName()) { fullName += ' ' + doctor.SurName(); }
return fullName
});
Error Message:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I want to get Image Url from database if fileupload has null value(not change).
I mean if i change smallImage and not change LargeImage,then it should get largeImage value from DB.
[HttpPost]
public ActionResult Edit(Blog blog, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (ModelState.IsValid)
{
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = db.Blogs.Find(blog.ID).SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = db.Blogs.Find(blog.ID).LargeImage;
}
blog.PostDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
db.Entry(blog).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(blog);
}
Thank you.
You are both loading a copy of the blog
db.Blogs.Find(blog.ID)
and attaching another with the same id to the context
db.Entry(blog).State = EntityState.Modified;
meaning you have 2 copies of the same blog in the context (not allowed).
I'd recommend the replacing the one posted back with a viewmodel instead, something like
public ActionResult Edit(BlogViewModel viewModel, HttpPostedFileBase smallImage, HttpPostedFileBase largeImage)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var blog = db.Blogs.Find(viewModel.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength + "_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" + largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"), largeImage.ContentLength + "_" + largeImage.FileName);
largeImage.SaveAs(filepath);
}
blog.Title = viewModel.Title;
blog.Body = viewModel.Body; //etc
db.SaveChanges();
return RedirectToAction("Index");
}
Looks like issue here is that you load same blog twice.
Load it once instead, something like this:
Blog existingBlog = db.Blogs.Find(blog.ID);
if (smallImage != null)
{
blog.SmallImage = smallImage.ContentLength +
"_" + smallImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
smallImage.ContentLength + "_" + smallImage.FileName);
smallImage.SaveAs(filepath);
}
else
{
blog.SmallImage = existingBlog.SmallImage;
}
if (largeImage != null)
{
blog.LargeImage = largeImage.ContentLength + "_" +
largeImage.FileName;
string filepath = Path.Combine(Server.MapPath("~/Content/Blog/"),
largeImage.ContentLength + "_" +
largeImage.FileName);
largeImage.SaveAs(filepath);
}
else
{
blog.LargeImage = existingBlog.LargeImage;
}
I use Smack API to write my Google talk Client . Now i need to handle add request for this .
I set SubscriptionMode to manual & now I have to registering a listener for presence packets but i don't know how !!
can any body help ?
I have not tried it yet, but I guess the below should work. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of Presence.Type.subscribe.
First set the roster:
Roster roster = connection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
Then add a packet listner to the above connection, eg :
connection.addPacketListener(new SubscriptionListener(), new PacketFilter(){
public boolean accept(Packet packet) {
if(packet instanceof Presence)
if(((Presence)packet).getType().equals(Presence.Type.subscribe))
return true;
return false;
}});
The above code just returns true for all requests, But you can customize it i.e set it to true or false based on user GUI input.
public static void admitFriendsRequest() {
connection.getRoster().setSubscriptionMode(
Roster.SubscriptionMode.manual);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet paramPacket) {
System.out.println("\n\n");
if (paramPacket instanceof Presence) {
Presence presence = (Presence) paramPacket;
String email = presence.getFrom();
System.out.println("chat invite status changed by user: : "
+ email + " calling listner");
System.out.println("presence: " + presence.getFrom()
+ "; type: " + presence.getType() + "; to: "
+ presence.getTo() + "; " + presence.toXML());
Roster roster = connection.getRoster();
for (RosterEntry rosterEntry : roster.getEntries()) {
System.out.println("jid: " + rosterEntry.getUser()
+ "; type: " + rosterEntry.getType()
+ "; status: " + rosterEntry.getStatus());
}
System.out.println("\n\n\n");
if (presence.getType().equals(Presence.Type.subscribe)) {
Presence newp = new Presence(Presence.Type.subscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
Presence subscription = new Presence(
Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
connection.sendPacket(subscription);
} else if (presence.getType().equals(
Presence.Type.unsubscribe)) {
Presence newp = new Presence(Presence.Type.unsubscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
if (presence.getType().equals(Presence.Type.subscribed)
|| presence.getType().equals(
Presence.Type.subscribe)
|| presence.getType().equals(
Presence.Type.unsubscribed)
|| presence.getType().equals(
Presence.Type.unsubscribe)) {
return true;
}
}
return false;
}
});
connection.getRoster().addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
System.out.println(presence.getFrom() + "presenceChanged");
}
public void entriesUpdated(Collection<String> presence) {
System.out.println("entriesUpdated");
}
public void entriesDeleted(Collection<String> presence) {
System.out.println("entriesDeleted");
}
public void entriesAdded(Collection<String> presence) {
System.out.println("entriesAdded");
}
});
}