How to add an image into Liferay 7 Control Menu - liferay

I am working on Liferay 7 and want to add an image in the centre of the Control Menu. How can this be done?
I have followed the steps mentioned over the official website on how to customise the Control Menu.
Few specific questions I have are:
Is there a defined template of JSP file that needs to be used?
Is there a defined name of the JSP file that needs to be used?
The code I am using is:
package portlet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osgi.service.component.annotations.Component;
import com.liferay.product.navigation.control.menu.BaseJSPProductNavigationControlMenuEntry;
import com.liferay.product.navigation.control.menu.BaseProductNavigationControlMenuEntry;
import com.liferay.product.navigation.control.menu.ProductNavigationControlMenuEntry;
import com.liferay.product.navigation.control.menu.constants.ProductNavigationControlMenuCategoryKeys;
#Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=category.sample",
"product.navigation.control.menu.category.key=" + ProductNavigationControlMenuCategoryKeys.TOOLS,
"product.navigation.control.menu.category.order:Integer=19",
"com.liferay.portlet.instanceable=true",
"javax.portlet.security-role-ref=power-user,user",
"javax.portlet.display-name=Customproductnavigationcontrolmenuentry Portlet"
},
service = ProductNavigationControlMenuEntry.class
)
public class CustomproductnavigationcontrolmenuentryPortlet extends BaseJSPProductNavigationControlMenuEntry implements ProductNavigationControlMenuEntry {
#Override
public boolean includeIcon(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
RequestDispatcher requestdispacher = request.getRequestDispatcher("/view.jsp");
try{
requestdispacher.include(request, response);
}
catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
public boolean includeBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
RequestDispatcher requestdispacher = request.getRequestDispatcher("/view.jsp");
try{
requestdispacher.include(request, response);
}
catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
public String getIconJspPath() {
// TODO Auto-generated method stub
return null;
}
}
And on deploying this on the server, I get the following error:
ERROR [http-nio-8080-exec-10][IncludeTag:128] Current URL /web/guest generates exception: java.lang.NullPointerException
java.lang.NullPointerException
at com.liferay.product.navigation.control.menu.BaseJSPProductNavigationControlMenuEntry.include(BaseJSPProductNavigationControlMenuEntry.java:84)
at com.liferay.product.navigation.control.menu.BaseJSPProductNavigationControlMenuEntry.includeIcon(BaseJSPProductNavigationControlMenuEntry.java:68)
at org.apache.jsp.control_005fmen.....

Related

How to generate extent report for cucumber + testng framework

How to generate extent report for cucumber + testng framework in such a way that on each scenario failure I can get the screen shot captured, without repeating the code with every scenario in step definition file
I have setup the Testing framework using Cucumber+Testng. However, I need extent reporting but not sure how to achieve it through testNG runner class without actually repeating the code with every scenario of step definition. So the idea is to write code in one place just like using cucumber hooks which will run for each and every scenario.
I Have already tried the approach with TestNG listener with Extent report but with this the drawback is I have to write the code every time for each and every scenario. LIke below I have ITestListnerImpl.java, ExtentReportListner and YouTubeChannelValidationStepDef where for each scenario I have to repeat the loginfo and screencapture methods
Code: ItestListerner.java
package com.testuatomation.Listeners;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
public class ITestListenerImpl extends ExtentReportListener implements ITestListener {
private static ExtentReports extent;
#Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
extent.flush();
System.out.println("Execution completed on UAT env ......");
}
#Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
extent = setUp();
System.out.println("Execution started on UAT env ......");
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0){
// TODO Auto-generated method stub
}
#Override
public void onTestFailure(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("FAILURE");
}
#Override
public void onTestSkipped(ITestResult arg0) {
System.out.println("SKIP");
}
#Override
public void onTestStart(ITestResult arg0) {
System.out.println("STARTED");
}
#Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("PASS-----");
}
}
ExtentReportListener. java
package com.testuatomation.Listeners;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentReportListener {
public static ExtentHtmlReporter report = null;
public static ExtentReports extent = null;
public static ExtentTest test = null;
public static ExtentReports setUp() {
String reportLocation = "./Reports/Extent_Report.html";
report = new ExtentHtmlReporter(reportLocation);
report.config().setDocumentTitle("Automation Test Report");
report.config().setReportName("Automation Test Report");
report.config().setTheme(Theme.STANDARD);
System.out.println("Extent Report location initialized . . .");
report.start();
extent = new ExtentReports();
extent.attachReporter(report);
extent.setSystemInfo("Application", "Youtube");
extent.setSystemInfo("Operating System", System.getProperty("os.name"));
extent.setSystemInfo("User Name", System.getProperty("user.name"));
System.out.println("System Info. set in Extent Report");
return extent;
}
public static void testStepHandle(String teststatus,WebDriver driver,ExtentTest extenttest,Throwable throwable) {
switch (teststatus) {
case "FAIL":
extenttest.fail(MarkupHelper.createLabel("Test Case is Failed : ", ExtentColor.RED));
extenttest.error(throwable.fillInStackTrace());
try {
extenttest.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (IOException e) {
e.printStackTrace();
}
if (driver != null) {
driver.quit();
}
break;
case "PASS":
extenttest.pass(MarkupHelper.createLabel("Test Case is Passed : ", ExtentColor.GREEN));
break;
default:
break;
}
}
public static String captureScreenShot(WebDriver driver) throws IOException {
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest = "C:\\Users\\Prateek.Nehra\\workspace\\SeleniumCucumberBDDFramework\\screenshots\\" + getcurrentdateandtime() + ".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
private static String getcurrentdateandtime() {
String str = null;
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
Date date = new Date();
str = dateFormat.format(date);
str = str.replace(" ", "").replaceAll("/", "").replaceAll(":", "");
} catch (Exception e) {
}
return str;
}
}
YoutubeChannelValidationsStepDef.java
package com.testautomation.StepDef;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Feature;
import com.aventstack.extentreports.gherkin.model.Scenario;
import com.testuatomation.Listeners.ExtentReportListener;
import com.testautomation.PageObjects.YoutubeChannelPage;
import com.testautomation.PageObjects.YoutubeResultPage;
import com.testautomation.PageObjects.YoutubeSearchPage;
import com.testautomation.Utility.BrowserUtility;
import com.testautomation.Utility.PropertiesFileReader;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class YoutubeChannelValidationsStepDef extends ExtentReportListener
{
PropertiesFileReader obj= new PropertiesFileReader();
private WebDriver driver;
#Given("^Open Chrome browser with URL$")
public void open_Chrome_browser_with_URL() throws Throwable
{
ExtentTest logInfo=null;
try {
test = extent.createTest(Feature.class, "Youtube channel name validation");
test=test.createNode(Scenario.class, "Youtube channel name validations");
logInfo=test.createNode(new GherkinKeyword("Given"), "open_Chrome_browser_with_URL");
Properties properties=obj.getProperty();
driver=BrowserUtility.OpenBrowser(driver, properties.getProperty("browser.name"), properties.getProperty("browser.baseURL"));
logInfo.pass("Opened chrome browser and entered url");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial$")
public void search_selenium_tutorial() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "search_selenium_tutorial");
new YoutubeSearchPage(driver).NavigateToResultPage("selenium by bakkappa n");
logInfo.pass("Searching selenium tutorial");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial \"([^\"]*)\"$")
public void search_selenium_tutorial(String searchString) throws Throwable
{
new YoutubeSearchPage(driver).NavigateToResultPage(searchString);
}
#When("^Click on channel name$")
public void click_on_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "click_on_channel_name");
new YoutubeResultPage(driver).NavigateToChannel();
logInfo.pass("Clicked on the channel name");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#Then("^Validate channel name$")
public void validate_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("Then"), "validate_channel_name");
String expectedChannelName="1Selenium Java TestNG Tutorials - Bakkappa N - YouTube";
String actualChannelName=new YoutubeChannelPage(driver).getTitle();
Assert.assertEquals(actualChannelName, expectedChannelName,"Channel names are not matching"); //
logInfo.pass("Validated channel title");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
System.out.println("closing browser");
driver.quit();
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
}
Your lofInfo is null, should be something like this
#Then("Open Chrome browser with URL")
public void open_Chrome_browser_with_URL() {
try {
logInfo = test.createNode(new GherkinKeyword("Then"), "open_Chrome_browser_with_URL");
//YOUR CODE HERE
logInfo.pass("Chrome opens URL");
}
catch (AssertionError | Exception e) {testStepHandle("FAIL", d, logInfo, e);
}
}

Why is batik can't save .svg file using OutputStream?

I want to manipulate with existing .svg file from file system using library Batik by Apache. My goal is load .svg file, draw some shapes on it and than save final result on file system.
Now I have two classes. First class is able to load file .svg and draw shape on it, but don't able to save result. Second class is able to draw shape on new canvas and save result on file system.
This first class. I try to save final result using OutputStream, but it didn't work.
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.svg.GVTTreeBuilderAdapter;
import org.apache.batik.swing.svg.GVTTreeBuilderEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.concurrent.atomic.AtomicBoolean;
public class RedrawingSVG extends JFrame {
protected AtomicBoolean shown = new AtomicBoolean(false);
public static void main(String[] args) throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
RedrawingSVG redrawingSVG = new RedrawingSVG();
redrawingSVG.drawSvg();
}
public void drawSvg() throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
final JSVGCanvas canvas = new JSVGCanvas();
canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // to update it
canvas.setURI(new File("/home/ekuntsevich/Downloads/img.svg").toURI().toURL().toString());
canvas.addGVTTreeBuilderListener(new GVTTreeBuilderAdapter() {
public void gvtBuildCompleted(GVTTreeBuilderEvent e) {
synchronized (shown) {
shown.set(true); // No modifications be fore!!
shown.notifyAll();
}
}
});
getContentPane().add(canvas);
setSize(800, 400);
setVisible(true);
synchronized (shown) { // Strictly required to wait
while (shown.get() == false) {
try {
shown.wait(0);
} catch (Exception e) {
}
}
}
Document doc = canvas.getSVGDocument();
SVGGraphics2D svgGenerator = new SVGGraphics2D(doc);
svgGenerator.setPaint(Color.red);
svgGenerator.fill(new Rectangle(100, 100, 1000, 1000));
Element root = doc.getDocumentElement();
svgGenerator.getRoot(root);
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img2.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, true);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This second class.
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
public class TestSVGGen {
public void paint(Graphics2D g2d) {
g2d.setPaint(Color.red);
g2d.fill(new Rectangle(10, 10, 100, 100));
}
public static void main(String[] args) throws IOException {
// Get a DOMImplementation.
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// Ask the test to render into the SVG Graphics2D implementation.
TestSVGGen test = new TestSVGGen();
test.paint(svgGenerator);
// Finally, stream out SVG to the standard output using
// UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img3.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, useCSS);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Finally I want to combine capabilities this two classes. I want to have code for: loading .svg image -> drawing something over this image -> save result as .svg image on file system.
I resolved my issue. I looked through different signatures for method stream from class SVGGraphics2D and found out that there is has method with parameters suitable for my case. I used next method stream(Element svgRoot, Writer writer) for saving .svg image. Finally, instead svgGenerator.stream(out, true); I used svgGenerator.stream(root, out);. It works for me.
Fastest way to save SVGDOcument to File [for future generations :) ]
public static void saveSvgDocumentToFile(SVGDocument document, File file)
throws FileNotFoundException, IOException {
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8")) {
svgGenerator.stream(document.getDocumentElement(), out);
}
}

how to validate an xml string in java?

I have seen some examples here, which show how to validate an xml File (It´s workking), but my question is: How can I modify this code to validate an String
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.List;
import java.io.*;
import java.util.LinkedList;
import java.net.URL;
import java.sql.Clob;
import java.sql.SQLException;
public class Validate {
public String validaXML(){
try {
Source xmlFile = new StreamSource(new File("C:\\Users\\Desktop\\info.xml"));
URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
final List exceptions = new LinkedList();
validator.setErrorHandler(new ErrorHandler()
{
#Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
#Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
validator.validate(xmlFile);
} catch (SAXException ex) {
System.out.println( ex.getMessage());
return ex.getMessage().toString();
} catch (IOException e) {
System.out.println( e.getMessage());
return e.getMessage().toString();
}
return "Valid";
}
public static void main(String[] args) {
String res;
Validate val = new Validate();
res=val.validaXML();
System.out.println(res);
}
}
I have tried with this:
Source xmlFile = new StreamSource("<Project><Name>sample</Name></Project>");
It compiles, but I got this:
"no protocol: sample"
Thanks for reading I´ll apreciate you opinion
The reason why that doesnt work is the constructor your using is StreamSource(String systemId). The String constructor on StreamSource doesnt take xml.
Use the constructor StreamSource(Reader reader) and make an reader, such as
new StreamSource(new StringReader("xml here"))
or you can use the constructor StreamSource(InputStream inputStream) as
new StreamSource(new ByteArrayInputStream("xml here".getBytes()))

How to generate Castor mapping.xml file from given multiple XSDs?

How to generate Castor mapping.xml file from given multiple XSDs?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
//import org.exolab.castor.builder.SourceGenerator;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.tools.MappingTool;
public class CastorMappingToolUtil {
public static void generate() throws MappingException, FileNotFoundException {
MappingTool tool = new MappingTool();
tool.setInternalContext(new org.castor.xml.BackwardCompatibilityContext());
tool.addClass(ClassType.class);
OutputStream file = new FileOutputStream("/path/to/xmlFile/gen_mapping.xml" );
Writer writer = new OutputStreamWriter(file);
tool.write(writer);
//SourceGenerator.main(options);
}
/**
* #param args
*/
public static void main(String[] args) {
try {
CastorMappingToolUtil.generate();
} catch (MappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

LWUIT and kXML Parser

Uncaught exception: java.lang.Error: Static initializer: java.lang.NullPointerException, 0
- java.lang.Class.throwError(), bci=57
- java.lang.Class.initialize(), bci=221
- com.sun.lwuit.Component.<init>(), bci=5
- com.sun.lwuit.Container.<init>(), bci=1
- com.sun.lwuit.Form.<init>(), bci=8
- com.sun.lwuit.Form.<init>(), bci=1
- com.midlet.RSSMidlet.<init>(), bci=11
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=9
- com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=4
- com.sun.midp.appmanager.SelectorBase.run(), bci=33
- java.lang.Thread.run(), bci=11
Coding:
package com.midlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
//import com.sun.lwuit.list.ListModel;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class RSSMidlet extends MIDlet implements ActionListener{
public Vector feedVector;
public String rssFeed;
private Command cmdSelect;
private Command cmdExit;
private Form form1 = new Form("Feeds List");
// private Form form2 = new Form("Feed Description");
// private Vector feed_Title;
private List resultList;
// private List feedTitle;
public RSSModel model = new RSSModel();
class ReadXML extends Thread{
public void run(){
try{
rssFeed = "http://www.rottentomatoes.com/syndication/rss/top_news.xml";
HttpConnection httpConnection = (HttpConnection) Connector.open(rssFeed);
KXmlParser parser = new KXmlParser();
parser.setInput(new InputStreamReader(httpConnection.openInputStream()));
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, null);
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, "channel");
readXMLData(parser);
parser.require(XmlPullParser.END_TAG, null, "channel");
}
parser.require(XmlPullParser.END_TAG, null, "rss");
parser.next();
parser.require(XmlPullParser.END_DOCUMENT, null, null);
}catch(Exception e){
}
}
}
public RSSMidlet() {
// TODO Auto-generated constructor stub
Display.init(this);
Resources r;
try{
r = Resources.open("/LWUITtheme.res");
UIManager.getInstance().setThemeProps(r.getTheme("LWUITDefault"));
}catch(IOException e){
//e.printStackTrace();
}
resultList = new List();
for(int i=0; i<feedVector.size();i++){
model = (RSSModel) feedVector.elementAt(i);
resultList.addItem(model.getTitle().toString());
}
form1.addComponent(BorderLayout.CENTER,resultList);
form1.addCommand(cmdExit);
form1.addCommand(cmdSelect);
form1.setScrollable(true);
//form1.addCommandListener((ActionListener) this);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
new ReadXML().start();
}
public void readXMLData(KXmlParser parser) throws IOException, XmlPullParserException{
while(!"item".equals(parser.getName()) ){
/** Check if document doesn't include any item tags */
if( parser.next() == XmlPullParser.END_DOCUMENT )
throw new IOException("No items in RSS feed!");
}
parser.require(XmlPullParser.START_TAG, null, "item");
while(parser.nextTag() != XmlPullParser.END_TAG){
parser.require(XmlPullParser.START_TAG, null, null);
String name = parser.getName();
String text = parser.nextText();
//System.out.println ("<"+name+">"+text);
if(name.equals("pubDate")){
model.setPubDate(text);
}else if(name.equals("title")){
model.setTitle(text);
}else if(name.equals("link")){
model.setLink(text);
}else if(name.equals("description")){
model.setDescription(text);
}
parser.require(XmlPullParser.END_TAG, null, name);
}
feedVector.addElement(model);
parser.require(XmlPullParser.END_TAG, null, "item");
}
public void actionPerformed(ActionEvent evt) {
// TODO Auto-generated method stub
if(evt.getCommand() == cmdExit){
notifyDestroyed();
}else if(evt.getCommand() == cmdSelect){
}
}
}
This is my codes. I can't seem to get LWUIT running with kXML. There is a forum post that says that I need to initialize graphics objects after the Display.init(this) line. But where that line should lie? Please assist me...
The Display.init(your_midlet) is responsible for initializing the Display for LWUIT, no need to do it yourself. Only restriction is, you have to initialize the Display BEFORE you use any Form.
Move the line
form1 = new Form("Feeds List")
after the line
Display.init(this);
so you initialize the Form in the Constructor after initializing the Display!

Resources