DOM parsing error in RSS FEED - parsing

I need to parse the this xml file and need to display in the list view but I got the problem while running this code.
Any one please help me over come this problem
Thank you in advance
This is XML file from the source http://purl.org/dc/elements/1.1/" version="2.0"
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>MobileNations</title>
<description>
Mobile Nations brings to you the very best of Android Central, CrackBerry.com, PreCentral.net, TiPb.com, and WPCentral
</description>
<link>http://www.mobilenations.com/</link>
<language>en-us</language>
<lastBuildDate>Wed, 07 Aug 2013 06:15:01 -0400</lastBuildDate>
<pubDate>Wed, 07 Aug 2013 06:15:01 -0400</pubDate>
<item>
<title>
AT&T activates new 4G LTE markets, expands coverage in others
</title>
<description>
<p class="rtecenter"><img alt="AT&T" class="lightbox2 imagecache-w680h550 aligncenter" src="http://cdn.androidcentral.com/sites/androidcentral.com/files/imagecache/w680h550/postimages/108579/att-store-2.jpg" /></p> <h3> Six new markets, expanded coverage in Washington, D.C. and San Francisco areas</h3> <p>AT&T sends word that it's switched on 4G LTE service in six new markets, while expanding coverage in two major cities.</p> <p>From today, AT&T LTE should be available in —</p> <p>read more</p>
</description>
<link>
http://www.androidcentral.com/att-activates-new-4g-lte-markets-expands-coverage-others
</link>
<pubDate>Wed, 07 Aug 2013 09:48:24 +0000</pubDate>
<category domain="http://www.androidcentral.com/articles/news">News</category>
<category domain="http://www.androidcentral.com/tags/4g">4g</category>
<category domain="http://www.androidcentral.com/tags/att-0">at&t</category>
<category domain="http://www.androidcentral.com/tags/lte">lte</category>
<guid isPermaLink="false">32622 at http://www.androidcentral.com</guid>
<comments>
http://www.androidcentral.com/att-activates-new-4g-lte-markets-expands-coverage-others#comments
</comments>
<dc:creator>Alex Dobie</dc:creator>
</item>
My DOM parser code is
package com.wfwf.everestnewsapp.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.util.Log;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
Log.i("this is the test message"+length, xml);
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
Log.i("this is the test message total child nodes"+clength, xml);
// Get the required elements from each Item
// Ishwor changed the code j=0 and j= j+1
for (int j = 0; j < clength; j = j + 1) {
Log.i("first child node name is"+nchild.item(j).getNodeName(), xml);
Node thisNode = nchild.item(j);
String theString = null;
//ishwor changed as
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
if (theString != null) {
String nodeName = thisNode.getNodeName();
/*
String nodeName = thisNode.getNodeName();
//theString = nchild.item(j).getFirstChild().getNodeValue();
if(nchild.item(j).getFirstChild().getNodeValue()!=null){
//if (theString != null) {
//String nodeName = thisNode.getNodeName();
*/
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
Log.i("this is the test message"+theString, xml);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
Log.i("this is the test message"+theString, xml);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
MY log cat Error is
08-08 12:52:55.059: W/dalvikvm(3484): threadid=11: thread exiting with uncaught exception (group=0x41a692a0)
08-08 12:52:55.064: E/AndroidRuntime(3484): FATAL EXCEPTION: AsyncTask #1
08-08 12:52:55.064: E/AndroidRuntime(3484): java.lang.RuntimeException: An error occured while executing doInBackground()
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.lang.Thread.run(Thread.java:856)
08-08 12:52:55.064: E/AndroidRuntime(3484): Caused by: java.lang.NoClassDefFoundError: org.jsoup.Jsoup
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.parser.DOMParser.parseXml(DOMParser.java:102)
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.Splash$AsyncLoadXMLFeed.doInBackground(Splash.java:131)
08-08 12:52:55.064: E/AndroidRuntime(3484): at com.wfwf.everestnewsapp.Splash$AsyncLoadXMLFeed.doInBackground(Splash.java:1)
08-08 12:52:55.064: E/AndroidRuntime(3484): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-08 12:52:55.064: E/AndroidRuntime(3484): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-08 12:52:55.064: E/AndroidRuntime(3484): ... 5 more

Try This Example...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
try {
URL url = new URL(
"Your URL");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("title--", ""+ ((Node) nameList.item(0)).getNodeValue());
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
Log.v("description--", ""+ ((Node) websiteList.item(0)).getNodeValue());
description.add(""+ ((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(""+ ((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}

Related

Kafka Twitter streaming TwitterException error

I am trying the sample code on Kafka Twitter streaming from the following tutorial.
https://www.tutorialspoint.com/apache_kafka/apache_kafka_real_time_application.htm
Here is my code:
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import twitter4j.*;
import twitter4j.conf.*;
import twitter4j.StatusListener;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
public class KafkaTwitterProducer {
public static void main(String[] args) throws Exception {
LinkedBlockingQueue<Status> queue = new LinkedBlockingQueue<Status>(1000);
String consumerKey = “XXXXXXXXXXXXXXXXX”; //args[0].toString();
String consumerSecret = "XXXXXXXXXXXXXXXXX"; //args[1].toString();
String accessToken = "XXXXXXXXXXXXXXXXX" ; //args[2].toString();
String accessTokenSecret = "XXXXXXXXXXXXXXXXX" ; //args[3].toString();
String topicName = "twittertest" ; //args[4].toString();
//String[] arguments = args.clone();
String[] keyWords = {“Hello”,”Hi”,”Welcome”}; //Arrays.copyOfRange(arguments, 5, arguments.length);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
queue.offer(status);
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
// System.out.println("#" + status.getUser().getScreen-Name());
/*for(URLEntity urle : status.getURLEntities()) {
System.out.println(urle.getDisplayURL());
}*/
/*for(HashtagEntity hashtage : status.getHashtagEntities()) {
System.out.println(hashtage.getText());
}*/
}
#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:"
+ statusDeletionNotice.getStatusId());
}
#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" +
numberOfLimitedStatuses);
}
#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId +
"upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning warning) {
// System.out.println("Got stall warning:" + warning);
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
twitterStream.addListener(listener);
FilterQuery query = new FilterQuery().track(keyWords);
twitterStream.filter(query);
Thread.sleep(5000);
//Add Kafka producer config settings
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "SampleProducer");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//props.put("key.serializer",
// "org.apache.kafka.common.serialization.StringSerializer");
//props.put("value.serializer",
// "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
int i = 0;
int j = 0;
while(i < 10) {
Status ret = queue.poll();
if (ret == null) {
Thread.sleep(100);
i++;
}else {
for(HashtagEntity hashtage : ret.getHashtagEntities()) {
System.out.println("Hashtag: " + hashtage.getText());
producer.send(new ProducerRecord<String, String>(
topicName, Integer.toString(j++), hashtage.getText()));
}
}
}
producer.close();
Thread.sleep(5000);
twitterStream.shutdown();
}
}
When I run this as Java application, I am getting the following error: (this is not compile/build error)
Read timed out
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=1169356e or
http://www.google.co.jp/search?q=c04b39f0
TwitterException{exceptionCode=[1169356e-c04b39f0 c2863472-491bffd7], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:179)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
at twitter4j.TwitterStreamImpl.getFilterStream(TwitterStreamImpl.java:346)
at twitter4j.TwitterStreamImpl$8.getStream(TwitterStreamImpl.java:322)
at twitter4j.TwitterStreamImpl$TwitterStreamConsumer.run(TwitterStreamImpl.java:552)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at twitter4j.HttpResponseImpl.<init>(HttpResponseImpl.java:35)
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:143)
... 5 more
I am not sure what is the problem here. Could someone suggest me the solution or fix please?
Ok Update here: It is working now if key words are generic like String[] keyWords = {"USA","Basketball","Sports};
If I change this to my requirement with specific keywords like my company name, product name etc., for ex: String[] keyWords = {"XXX","YYY","ZZZ"}; then the java application is getting terminated. What could be the reason? How to fix it in this code? Please advise?
The Twitter4J source code shows that this exception is thrown because of Http connection time out.
I get similar exception by setting a low value for connection timeout.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret)
.setHttpStreamingReadTimeout(10);
This is the stack trace I get.
TwitterException{exceptionCode=[1169356e-c3c3770e 1169356e-c3c376e4], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.6}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:179)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
at twitter4j.TwitterStreamImpl.getFilterStream(TwitterStreamImpl.java:347)
at twitter4j.TwitterStreamImpl$8.getStream(TwitterStreamImpl.java:323)
at twitter4j.TwitterStreamImpl$TwitterStreamConsumer.run(TwitterStreamImpl.java:554)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1316)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:137)
... 5 more
For your example, please try setting a higher value for HttpStreamingReadTimeout. The default value in the code is 40 seconds. Try setting it to 120,000 (milliseconds) or higher. That should work.

I writng custom Agile Tab for JIRA server 7.0.2 with JIRA Agile 6.7.11

I writng custom Agile Tab for JIRA server 7.0.2 with JIRA Agile 6.7.11.
That I want list all Spitns to this Tab.
StringBuffer outputProjects = new StringBuffer();
ServiceOutcome<Collection<Sprint>> allsprints = sprintManager.getAllSprints();
Collection<Sprint> allsprintscollection = allsprints.getValue();
outputProjects.append("");
for (Iterator<Sprint> iterator = allsprintscollection.iterator(); iterator.hasNext();) {
Sprint sprint = iterator.next();
outputProjects.append("<tr>");
outputProjects.append("<td>"+sprint.getName()+"</td>");
outputProjects.append("<td>"+sprint.getId()+"</td>");
outputProjects.append("<td></td>");
outputProjects.append("<td></td>");
outputProjects.append("<td></td>");
outputProjects.append("</tr>");
}
Plugin plugin = pluginAccesor.getEnabledPlugin("com.i4ware.plugin.timesheet.timesheet");
PluginInformation pluginInformation = plugin.getPluginInformation();
String version = pluginInformation.getVersion();
tmpParams.put("sprintsHtml", outputProjects.toString());
tmpParams.put("project", context.getProject().getKey());
tmpParams.put("baseUrl",applicationProperties.getBaseUrl());
tmpParams.put("version",version);
return descriptor.getHtml("view",tmpParams);
But I got with error message log file:
2015-12-02 10:31:55,455 http-nio-8181-exec-12 WARN admin 631x1578x1 xhcbd 80.222.144.149,37.48.78.137 /projects/AD [c.atlassian.ozymandias.SafePluginPointAccess] Unable to run plugin code because of 'java.lang.NullPointerException - null'.
Okay I found a solution my self by help of Atlassian Developer Community.
Class:
import com.atlassian.greenhopper.service.sprint.SprintManager;
Is a privete so it must be loeded first like this:
import com.atlassian.greenhopper.service.sprint.SprintManager;
import com.atlassian.greenhopper.service.sprint.Sprint;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.greenhopper.service.ServiceOutcome;
import org.springframework.context.ApplicationContext;
import org.osgi.framework.InvalidSyntaxException;
import com.atlassian.plugin.osgi.container.OsgiContainerManager;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import com.atlassian.greenhopper.web.rapid.view.JqlHelper;
public class LoadSprintsForGanttServlet extends HttpServlet
{
private String jqlQuery;
private SprintManager getSprintManager() throws InvalidSyntaxException {
ApplicationContext appCtx = (ApplicationContext) getGreenHopperAppCtx();
if ( appCtx !=null ) {
return (SprintManager) appCtx.getBean( "sprintManagerImpl" );
}
return null;
}
private JqlHelper getJqlHelper() throws InvalidSyntaxException {
ApplicationContext appCtx = (ApplicationContext) getGreenHopperAppCtx();
if ( appCtx !=null ) {
return (JqlHelper) appCtx.getBean( "jqlHelper" );
}
return null;
}
private Object getGreenHopperAppCtx() throws InvalidSyntaxException {
OsgiContainerManager osgi = ComponentAccessor.getComponentOfType(OsgiContainerManager.class);
if ( osgi==null ) {
java.lang.System.out.println("OSGI Not Found");
return null;
}
Bundle[] bundles = osgi.getBundles();
for(int i=0;i<bundles.length;i++) {
Bundle bundle = bundles[i];
if ( "com.pyxis.greenhopper.jira".equals( bundle.getSymbolicName() ) ) {
BundleContext bctx = bundle.getBundleContext();
ServiceReference[] refs = bctx.getAllServiceReferences(null,null);
if ( refs!=null ) {
for(int j=0; j<refs.length;j++) {
Object prop = refs[j].getProperty("org.springframework.context.service.name");
if ( "com.pyxis.greenhopper.jira".equals(prop) ) {
return bctx.getService( refs[j] );
}
}
}
}
}
return null;
}
And it can be iterated like this:
try {
ServiceOutcome<Collection<Sprint>> allSprints = getSprintManager().getAllSprints();
sprints = allSprints.getValue();
pages = sprints.size();
}
catch (InvalidSyntaxException e)
{
System.out.println("Got an SearchException: " + e.getCause());
}
for (Iterator iteratorSprints = sprints.iterator(); iteratorSprints.hasNext();) {
Sprint sprint = (Sprint) iteratorSprints.next();
//your code here
}

javacv error (Has setFormat() been called?)_

hi i'm making program that record video with audio by javacv but i got some error. any suggestion?
lib version : jdk 1.8 javacv 0.8 opencv 2.4.9
Exception in thread "main" org.bytedeco.javacv.FrameGrabber$Exception: avformat_open_input() error -2: Could not open input "output.mp4". (Has setFormat() been called?)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:362)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:312)
at com.unomic.securobot.javacv.main(javacv.java:14)
my code
FFmpegFrameGrabber grabber1 = new FFmpegFrameGrabber("output.mp4");
FFmpegFrameGrabber grabber2 = new FFmpegFrameGrabber("test.mp3");
grabber1.setFormat("mp4");
grabber1.start();
grabber2.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("outputFinal.mp4",
grabber1.getImageWidth(), grabber1.getImageHeight(),
grabber2.getAudioChannels());
recorder.setFrameRate(grabber1.getFrameRate());
recorder.setSampleFormat(grabber2.getSampleFormat());
recorder.setSampleRate(grabber2.getSampleRate());
recorder.start();
Frame frame1;
Frame frame2 = null;
while ((frame1 = grabber1.grabFrame()) != null ||
(frame2 = grabber2.grabFrame()) != null) {
recorder.record(frame1);
recorder.record(frame2);
}
recorder.stop();
grabber1.stop();
grabber2.stop();
}
I was trying to get thumbnails from a videos using the framegrabber. I was getting the same error but then I just tried giving the full path of the files and voila it worked. Previously, I was using a relative path which was not working. When I gave the full path it started working.
package com.tape.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.OpenCVFrameGrabber;
public class VideoThumbTaker {
protected String ffmpegApp;
public VideoThumbTaker(String ffmpegApp)
{
this.ffmpegApp = ffmpegApp;
}
public void getThumb(String videoFilename, String thumbFilename, int width, int height,int hour, int min, float sec)
throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
"-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an", thumbFilename);
Process process = processBuilder.start();
InputStream stderr = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null);
process.waitFor();
}
public static void main(String[] args) throws Exception, IOException
{
//Both case work
FFmpegFrameGrabber g = new FFmpegFrameGrabber("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\videos\\vid.mp4");
g.setFormat("mp4");
g.start();
for (int i = 0 ; i < 50 ; i++) {
ImageIO.write(g.grab().getBufferedImage(), "png", new File("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\thumbnails\\video-frame-" + System.currentTimeMillis() + ".png"));
}
g.stop();
}
}

Get Image from client server & display on screen - blackberry java

I am trying to show image on screen by using client server, but I got exception
Protocol not found: net.rim.device.cldc.io.ftp.Protocol" , java.lang.IllegalArgumentException.
Here I have post the code where I get the exception(Currently on app I successfully login with client server, show folders & directories, now I want to click on any file it open on new screen.)
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.MainScreen;
public class ShowData extends MainScreen {
String connParams;
public ShowData() {
// Check Type of connection
CheckConnection obj1 = new CheckConnection();
connParams = obj1.getConnParam();
Bitmap listThumb;
String path = "ftp://dice:pAssw0rd#64.207.149.236:21/images/facebook.png"
+ connParams + "";
listThumb = getImage.getImageFromUrl(path);
BitmapField bitmapField1 = new BitmapField(listThumb);
add(bitmapField1);
}
}
getImage.java
package com.rim.samples.device.mapactiondemo;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import java.io.IOException;
import java.io.InputStream;
import java.lang.String;
import net.rim.device.api.system.Bitmap;
public final class getImage {
/**
* Fetches the content on the speicifed url. The url of the content to fetch
*/
public static Bitmap getImageFromUrl(String url) {
Bitmap bitmap = null;
try {
String bitmapData = getDataFromUrl(url);
bitmap = Bitmap.createBitmapFromBytes(bitmapData.getBytes(), 0,
bitmapData.length(), 1);
// Image.createImage(imageData.getBytes(), 0,imageData.length());
} catch (Exception e1) {
e1.printStackTrace();
System.out.println(e1);
}
return bitmap;
}
/**
* Fetches the content on the speicifed url. The url of the content to fetch
*/
private static String getDataFromUrl(String url) {
StringBuffer b = new StringBuffer();
InputStream is = null;
SocketConnection c = null;
long len = 0;
int ch = 0;
try {
c = (SocketConnection) Connector.open(url);
c.setSocketOption(SocketConnection.LINGER, 5);
c.setSocketOption(SocketConnection.DELAY, 5);
is = c.openInputStream();
//len = is.getLength();
if (len != -1) {
// Read exactly Content-Length bytes
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
// Read until the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
is.close();
c.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b.toString();
}
}
As far as I know ftp protocol is not implemented in BlackBerry Java SDK. Use http protocol instead of ftp.

Error with adding/removing smartgwt treegrid data: "this.data.isGroupedOutput' is null or not an object"

I have a treegrid for which I have operation add and remove. It works fine if I go to this page before any other page in my application. If I first visit some other page and than come to this page, here is the error that I receive:
13:39:46.403 [ERROR] [pifs] 13:39:46.402:XRP9:WARN:Log:Error:
''this.data.isGroupedOutput' is null or not an object'
in http://localhost:8080/pifs/pifs/sc/modules/ISC_Grids.js
at line 3065
ListGrid.regroup(_1=>undef)
ListGrid.dataChanged(_1=>"add", _2=>undef, _3=>24, _4=>Array[1], _5=>undef)
dataChangedObservation(operationType=>"add", originalRecord=>undef, rowNum=>24, updateData=>Array[1], filterChanged=>undef)
ResultSet.$e0(_1=>undef)
ResultSet.handleUpdate(_1=>"add", _2=>Array[1], _3=>false, _4=>Obj)
ResultSet.dataSourceDataChanged(_1=>Obj, _2=>Obj)
dataChangedObservation(dsResponse=>Obj, dsRequest=>Obj)
DataSource.updateCaches(_1=>Obj, _2=>Obj)
[c]DataSource.handleUpdate(_1=>Obj, _2=>Obj)
DataSource.fireResponseCallbacks(_1=>Obj, _2=>Obj, _3=>Obj, _4=>Obj)
DataSource.$65e(_1=>Array[1], _2=>Obj, _3=>Obj, _4=>Obj, _5=>Obj)
DataSource.$76b(_1=>Obj, _2=>Array[1], _3=>Obj)
[c]Class.fireCallback(_1=>Obj, _2=>"rpcResponse,data,rpcRequest", _3=>Array[3], _4=>[DataSource ID:lfm], _5=>undef) on [Class RPCManager]
Class.fireCallback(_1=>Obj, _2=>"rpcResponse,data,rpcRequest", _3=>Array[3], _4=>undef)
[c]RPCManager.__fireReplyCallback(_1=>Obj, _2=>Obj, _3=>Obj, _4=>Array[1])
[c]RPCManager.fireReplyCallbacks(_1=>Obj, _2=>Obj)
[c]RPCManager.performOperationReply(_1=>Obj, _2=>Obj)
[c]RPCManager.$67x(_1=>20)
[c]RPCManager.performTransactionReply(_1=>20, _2=>"//isc_RPCResponseStart-->[{data:[{id:637..."[248], _3=>undef)
callback(transactionNum=>20, results=>Obj, wd=>undef)
"isc.RPCManager.performTransactionReply(transactionNum,results,wd)"
** recursed on [c]Class.fireCallback
com.smartgwt.client.core.JsObject$SGWT_WARN: 13:39:46.402:XRP9:WARN:Log:Error:
''this.data.isGroupedOutput' is null or not an object'
in http://localhost:8080/pifs/pifs/sc/modules/ISC_Grids.js
at line 3065
ListGrid.regroup(_1=>undef)
ListGrid.dataChanged(_1=>"add", _2=>undef, _3=>24, _4=>Array[1], _5=>undef)
dataChangedObservation(operationType=>"add", originalRecord=>undef, rowNum=>24, updateData=>Array[1], filterChanged=>undef)
ResultSet.$e0(_1=>undef)
ResultSet.handleUpdate(_1=>"add", _2=>Array[1], _3=>false, _4=>Obj)
ResultSet.dataSourceDataChanged(_1=>Obj, _2=>Obj)
dataChangedObservation(dsResponse=>Obj, dsRequest=>Obj)
DataSource.updateCaches(_1=>Obj, _2=>Obj)
[c]DataSource.handleUpdate(_1=>Obj, _2=>Obj)
DataSource.fireResponseCallbacks(_1=>Obj, _2=>Obj, _3=>Obj, _4=>Obj)
DataSource.$65e(_1=>Array[1], _2=>Obj, _3=>Obj, _4=>Obj, _5=>Obj)
DataSource.$76b(_1=>Obj, _2=>Array[1], _3=>Obj)
[c]Class.fireCallback(_1=>Obj, _2=>"rpcResponse,data,rpcRequest", _3=>Array[3], _4=>[DataSource ID:lfm], _5=>undef) on [Class RPCManager]
Class.fireCallback(_1=>Obj, _2=>"rpcResponse,data,rpcRequest", _3=>Array[3], _4=>undef)
[c]RPCManager.__fireReplyCallback(_1=>Obj, _2=>Obj, _3=>Obj, _4=>Array[1])
[c]RPCManager.fireReplyCallbacks(_1=>Obj, _2=>Obj)
[c]RPCManager.performOperationReply(_1=>Obj, _2=>Obj)
[c]RPCManager.$67x(_1=>20)
[c]RPCManager.performTransactionReply(_1=>20, _2=>"//isc_RPCResponseStart-->[{data:[{id:637..."[248], _3=>undef)
callback(transactionNum=>20, results=>Obj, wd=>undef)
"isc.RPCManager.performTransactionReply(transactionNum,results,wd)"
** recursed on [c]Class.fireCallback
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:105)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Unknown Source)
PLEASE HELP! I tried everything, but thiserror is still here...
Here is the treeGrid code:
public Canvas getViewPanel() {
VLayout mainLayout = getMainVlayout();
setPanelTitle("Define LFM tree structure:", mainLayout);
lfmDataSource = DataSource.get("lfm");
ToolStrip gridEditControls = addToolStrip();
treeGrid = new TreeGrid();
treeGrid.setGridComponents(new Object[] {
ListGridComponent.HEADER,
ListGridComponent.BODY,
gridEditControls
});
treeGrid.setCanEdit(true);
treeGrid.setLoadDataOnDemand(false);
treeGrid.setWidth("100%");
treeGrid.setHeight("90%");
treeGrid.setNodeIcon(null);
treeGrid.setFolderIcon(null);
treeGrid.setShowOpenIcons(false);
treeGrid.setShowDropIcons(false);
treeGrid.setClosedIconSuffix("-");
treeGrid.setAlternateRecordStyles(true);
treeGrid.setWarnOnRemoval(true);
treeGrid.setEditEvent(ListGridEditEvent.DOUBLECLICK);
treeGrid.setDataSource(lfmDataSource);
treeGrid.setFetchOperation("firstFourLevelstFetch");
treeGrid.setAddOperation("addLfm");
treeGrid.setRemoveOperation("removeActivity");
Criteria criteria = new Criteria("project", getParentHolder()
.getProjectID());
criteria.addCriteria("project_phase", project_phase);
treeGrid.fetchData(criteria);
//treeGrid.getTree().openAll();
TreeGridField levelField = new TreeGridField("level", 250);
levelField.setCanEdit(false);
TreeGridField nameField = new TreeGridField("name");
TreeGridField level_pathField = new TreeGridField("level_path", 100);
treeGrid.setFields(levelField, level_pathField, nameField);
mainLayout.addMember(treeGrid);
return mainLayout;
}
private ToolStrip addToolStrip(){
ToolStrip gridEditControls = new ToolStrip();
gridEditControls.setWidth100();
gridEditControls.setHeight(24);
//totalsLabel = new Label();
//totalsLabel.setPadding(5);
LayoutSpacer spacer = new LayoutSpacer();
spacer.setWidth("*");
ToolStripButton newButton = new ToolStripButton();
newButton.setIcon("[SKIN]/actions/add.png");
newButton.setTitle("Add LFM tree node");
newButton.setPrompt("Add child node to the selected LFM tree node...");
newButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
ListGridRecord parentRecord = treeGrid.getSelectedRecord();
if (parentRecord == null) return;
if(parentRecord.getAttribute("level").equals("" +PifsProjectSettings.LFM_LEVEL_ACTIVITY)){
SC.warn("Can not create children node for Activity! Detail activities are defined in the budget....");
return;
}
Record newRecord = new Record();
newRecord.setAttribute("project", parentRecord.getAttribute("project"));
newRecord.setAttribute("project_phase", parentRecord.getAttribute("project_phase"));
int recordLfmLevel = (new Integer(parentRecord.getAttribute("level"))).intValue() + 1;
newRecord.setAttribute("level", recordLfmLevel);
newRecord.setAttribute("name", "...");
int parentRecordId = (new Integer(parentRecord.getAttribute("id"))).intValue() ;
newRecord.setAttribute("parent", parentRecordId);
int recordSublevel = (new Integer(parentRecord.getAttribute("num_children"))).intValue() + 1;
newRecord.setAttribute("sublevel", recordSublevel);
newRecord.setAttribute("num_children", 0);
parentRecord.setAttribute("num_children", recordSublevel);
String parentPath = parentRecord.getAttribute("level_path");
if(parentPath==null || parentPath.equals("")){
newRecord.setAttribute("level_path", ""+ recordSublevel);
}else{
newRecord.setAttribute("level_path", parentPath+"."+recordSublevel);
}
treeGrid.addData(newRecord);
treeGrid.markForRedraw();
treeGrid.setIsGroup(true);
}
});
ToolStripButton editButton = new ToolStripButton();
editButton.setIcon("[SKIN]/actions/edit.png");
editButton.setTitle("Edit LFM tree node");
editButton.setPrompt("Edit selected LFM tree node...");
editButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
ListGridRecord record = treeGrid.getSelectedRecord();
if (record == null) return;
treeGrid.startEditing(treeGrid.getDataAsRecordList().indexOf(record), 1, false);
}
});
ToolStripButton removeButton = new ToolStripButton();
removeButton.setIcon("[SKIN]/actions/remove.png");
removeButton.setTitle("Remove LFM tree node");
removeButton.setTitle("Remove selected LFM tree node...");
removeButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
ListGridRecord record = treeGrid.getSelectedRecord();
if (record == null) return;
String parentId = record.getAttribute("parent");
if(record.getAttribute("level").equals("" +PifsProjectSettings.LFM_LEVEL_GO)){
SC.warn("General objective can not be deleted!");
return;
}
treeGrid.removeSelectedData();
treeGrid.markForRedraw();
treeGrid.setIsGroup(true);
ListGridRecord[] allRecords = treeGrid.getRecords();
for(int i=0; i<allRecords.length; i++){
if(allRecords[i].getAttribute("id").equals(parentId)){
ListGridRecord parentRecord = allRecords[i];
int numChildren = (new Integer(parentRecord.getAttribute("num_children"))).intValue();
numChildren--;
if(numChildren<0){numChildren = 0;}
parentRecord.setAttribute("num_children", numChildren);
return;
}
}
}
});
gridEditControls.setMembers(newButton, spacer, editButton, removeButton);
return gridEditControls;
}
It's not clear how you can get this to happen (your code above won't do it), but we've added a null check just in case.
Try the next nightly 3.1d build (7.7.2012) from http://smartclient.com/builds and see if that fixes your problem.

Resources