Can't add custom parameter to STATUS property of VTODO component (ical4j) - java

I'm trying to add new XParameter for standard Status property with this code
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.io.IOException;
public class TestICal {
public static void main(String[] args) throws IOException {
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
prop.getParameters().add(new XParameter("X-TEST-PARAM", "TEST-VALUE")); // java.lang.UnsupportedOperationException
}
}
but following exception is thrown during its execution
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1016)
at net.fortuna.ical4j.model.ParameterList.add(ParameterList.java:157)
at TestICal.main(TestICal.java:18)
In a debugger I can see that inside ical4j package add() method is called on java.util.Collections$UnmodifiableRandomAccessList which, actually I can't find in API doc for some reason, and which implements java.util.List
The property can't be deleted or replaced and I can't see a method which would allow to replace or add another parameter list.
So now I think the field can't have parameters, at least if using ical4j.
Any idea?

Answering myself: it can be done by searching required property index and calling set() method of ArrayList which PropertyList extends
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.util.Iterator;
public class TestICal {
public static void main(String[] args) throws Exception {
// reading and parsing ICS
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
// checking the prop before
System.out.println(prop);
// preparing new param list and adding it to new created prop
ParameterList paramList = new ParameterList();
paramList.add(new XParameter("X-TEST-PARAM", "TEST-VALUE"));
PropertyFactoryImpl propFactory = PropertyFactoryImpl.getInstance();
Property myprop = propFactory.createProperty(Property.STATUS, paramList, "COMPLETED");
// and finally
PropertyList propList = vtodo.getProperties();
int index = propList.indexOf(prop);
propList.set(index, myprop);
// checking
System.out.println(vtodo.getProperties().getProperty(Property.STATUS));
}
}
result
STATUS:IN-PROCESS
STATUS;X-TEST-PARAM=TEST-VALUE:COMPLETED

Related

Nullpointer Exception While Using Trying to Read Excel in Selenium

Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.
Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx

Exception while calling Parser method outside main class

In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();

BIRT csv emitter plugin error: Required parameter Initiator is not set

I implemented the example from docs of this plugin, but I have an exception stating that a parameter Initiator is missed. I don't see this parameter at all.
My code is:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.emitter.csv.CSVRenderOption;
public class RunExport {
static void runReport() throws FileNotFoundException, BirtException {
String resourcePath = "C:\\Users\\hpsa\\workspace\\My Reports\\";
FileInputStream fs = new FileInputStream(resourcePath + "new_report_1.rptdesign");
IReportEngine engine = null;
EngineConfig config = new EngineConfig();
config.setLogConfig("C:\\birtre\\", Level.FINE);
config.setResourcePath(resourcePath);
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
engine.changeLogLevel(Level.FINE);
IReportRunnable design = engine.openReportDesign(fs);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
CSVRenderOption csvOption = new CSVRenderOption();
String format = CSVRenderOption.OUTPUT_FORMAT_CSV;
csvOption.setOutputFormat(format);
csvOption.setOutputFileName("newBIRTcsv.csv");
csvOption.setShowDatatypeInSecondRow(true);
csvOption.setExportTableByName("SecondTable");
csvOption.setDelimiter("\t");
csvOption.setReplaceDelimiterInsideTextWith("-");
task.setRenderOption(csvOption);
task.setEmitterID("org.eclipse.birt.report.engine.emitter.csv");
task.run();
task.close();
Platform.shutdown();
System.out.println("Report Generated Successfully!!");
}
public static void main(String[] args) {
try {
runReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have an exception:
org.eclipse.birt.report.engine.api.impl.ParameterValidationException: Required parameter Initiator is not set.
at org.eclipse.birt.report.engine.api.impl.EngineTask.validateAbstractScalarParameter(EngineTask.java:803)
at org.eclipse.birt.report.engine.api.impl.EngineTask.access$0(EngineTask.java:789)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterValidationVisitor.visitScalarParameter(EngineTask.java:706)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterVisitor.visit(EngineTask.java:1531)
at org.eclipse.birt.report.engine.api.impl.EngineTask.doValidateParameters(EngineTask.java:692)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:95)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
at com.demshin.RunExport.runReport(RunExport.java:44)
at com.demshin.RunExport.main(RunExport.java:54)
[1]: https://code.google.com/a/eclipselabs.org/p/csv-emitter-birt-plugin/
I tried to find this parameter in csvOption, but there is nothing like that.
What am I doing wrong?
It is not a parameter of the emitter. This exception means a report parameter named "Initiator" is defined in the report "new_report_1.rptdesign", and its property "required" is checked.
For example edit the report design, disable "required" for this parameter and set a default value instead.

How to get this property value in my java code?

I'm learning Java and sometimes I have some problem to retrieve the information I need from objects...
When I debug my code I can see in targetFile, a path property but I don't know how to get it in my code.
This is a screenshot:
(source: toile-libre.org)
This is my complete code:
package com.example.helloworld;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HelloWorld {
public static void main(String[] args) throws IOException {
nodejs();
}
public static void nodejs() throws IOException {
// Scrap the download url.
Document doc = Jsoup.connect("http://nodejs.org/download").get();
Element link = doc.select("div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)").first();
String url = link.attr("abs:href");
// Print the download url.
System.out.println(url);
// Download file via the scraped url.
URL download = new URL(url);
File target = new File("/home/lan/Desktop/");
WGet w = new WGet(download, target);
w.download();
// Get the targetFile property
// ???
}
}
How can I get this value?
I do not know your code but the field you are interested in may be encapsulated and thus not accessible in your code, but the debugger can see it at runtime :)
Update:
https://github.com/axet/wget/blob/master/src/main/java/com/github/axet/wget/WGet.java
The field is default package, you can only access it from within the package.
This can be frustrating at times, but you should ask yourself why the designers of this class decided to hide this field.

wrote code in java for nutch

hello:
I'm writing code in java for nutch(open source search engine) to remove the movments from arabic words in the indexer.
I don't know what is the error in it.
Tthis is the code:
package com.mycompany.nutch.indexing;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.getData().parse.getData();
public class InvalidUrlIndexFilter implements IndexingFilter {
private static final Logger LOGGER =
Logger.getLogger(InvalidUrlIndexFilter.class);
private Configuration conf;
public void addIndexBackendOptions(Configuration conf) {
// NOOP
return;
}
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
if (url == null) {
return null;
}
char[] parse.getData() = input.trim().toCharArray();
for(int p=0;p<parse.getData().length;p++)
if(!(parse.getData()[p]=='َ'||parse.getData()[p]=='ً'||parse.getData()[p]=='ُ'||parse.getData()[p]=='ِ'||parse.getData()[p]=='ٍ'||parse.getData()[p]=='ٌ' ||parse.getData()[p]=='ّ'||parse.getData()[p]=='ْ' ||parse.getData()[p]=='"' ))
new String.append(parse.getData()[p]);
return doc;
}
public Configuration getConf() {
return conf;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
}
I think that the error is in using parse.getdata() but I don't know what I should use instead of it?
The line
char[] parse.getData() = input.trim().toCharArray();
will give you a compile error because the left hand side is not a variable. Please replace parse.getData() by a unique variable name (e.g. parsedData) in this line and the following lines.
Second the import of
import org.apache.nutch.parse.getData().parse.getData();
will also fail. Looks a lot like a text replace issue.

Categories