I am having a rough time trying to wrap my head around the Lucene library. This is what I have so far:
public void shingleMe()
{
try
{
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
FileReader reader = new FileReader("test.txt");
ShingleAnalyzerWrapper shingleAnalyzer = new ShingleAnalyzerWrapper(analyzer, 2);
shingleAnalyzer.setOutputUnigrams(false);
TokenStream stream = shingleAnalyzer.tokenStream("contents", reader);
CharTermAttribute charTermAttribute = stream.getAttribute(CharTermAttribute.class);
while (stream.incrementToken())
{
System.out.println(charTermAttribute.toString());
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It fails at stream.incrementToken(). It's my understanding that the ShingleAnalyzerWrapper uses another Analyzer to create a shingle analyzer object. From there, I convert it to a token stream which is then parsed using an attribute filter. However, it always results in this exception:
Exception in thread "main" java.lang.AbstractMethodError: org.apache.lucene.analysis.TokenStream.incrementToken()Z
Thoughts? Thanks in advance!
AbstractMethodError cannot occur as a result of wrong API usage -- it must be the result of compiling against one JAR and then running against a different one. Since you are using both Lucene Core and Lucene Analyzers JAR here, double-check your compile-time and runtime JAR classpaths.
Related
def expectError() {
StepVerifier.create(readDB())
.expectError(RuntimeException.class)
.verify();
}
private Mono<String> readDB() {
// try {
return Mono.just(externalService.get())
.onErrorResume(throwable -> Mono.error(throwable));
// } catch (Exception e) {
// return Mono.error(e);
// }
}
unable to make it work if externalService.get throws Exception instead of return Mono.error. Is is always recommended to transform to Mono/Flow using try catch or is there any better way to verify such thrown exception?
Most of the time, if the user-provided code that throws an exception is provided as a lambda, exceptions can be translated to onError. But here you're directly throwing in the main thread, so that cannot happen
I am using java 8 stream and I can not throw the exceptions inside the foreach of stream.
stream.forEach(m -> {
try {
if (isInitial) {
isInitial = false;
String outputName = new SimpleDateFormat(Constants.HMDBConstants.HMDB_SDF_FILE_NAME).format(new Date());
if (location.endsWith(Constants.LOCATION_SEPARATOR)) {
savedPath = location + outputName;
} else {
savedPath = location + Constants.LOCATION_SEPARATOR + outputName;
}
File output = new File(savedPath);
FileWriter fileWriter = null;
fileWriter = new FileWriter(output);
writer = new SDFWriter(fileWriter);
}
writer.write(m);
} catch (IOException e) {
throw new ChemIDException(e.getMessage(),e);
}
});
and this is my exception class
public class ChemIDException extends Exception {
public ChemIDException(String message, Exception e) {
super(message, e);
}
}
I am using loggers to log the errors in upper level. So I want to throw the exception to top. Thanks
Try extending RuntimeException instead. The method that is created to feed to the foreach does not have that type as throwable, so you need something that is runtime throwable.
WARNING: THIS IS PROBABLY NOT A VERY GOOD IDEA
But it will probably work.
Why are you using forEach, a method designed to process every element, when all you want to do, is to process the first element? Instead of realizing that forEach is the wrong method for the job (or that there are more methods in the Stream API than forEach), you are kludging this with an isInitial flag.
Just consider:
Optional<String> o = stream.findFirst();
if(o.isPresent()) try {
String outputName = new SimpleDateFormat(Constants.HMDBConstants.HMDB_SDF_FILE_NAME)
.format(new Date());
if (location.endsWith(Constants.LOCATION_SEPARATOR)) {
savedPath = location + outputName;
} else {
savedPath = location + Constants.LOCATION_SEPARATOR + outputName;
}
File output = new File(savedPath);
FileWriter fileWriter = null;
fileWriter = new FileWriter(output);
writer = new SDFWriter(fileWriter);
writer.write(o.get());
} catch (IOException e) {
throw new ChemIDException(e.getMessage(),e);
}
which has no issues with exception handling. This example assumes that the Stream’s element type is String. Otherwise, you have to adapt the Optional<String> type.
If, however, your isInitial flag is supposed to change more than once during the stream processing, you are definitely using the wrong tool for your job. You should have read and understood the “Stateless behaviors” and “Side-effects” sections of the Stream API documentation, as well as the “Non-interference” section, before using Streams. Just converting loops to forEach invocations on a Stream doesn’t improve the code.
I am currently adding a config properties file to my test code. It works fine on my local machine but when I move it to Jenkins it fails. I think I know the problem but I am looking for the best solution. Here is my code:
public static void main(String [] args) throws IOException{
File file = new File("C:\\Users\\Test\\Regrassion_Framework\\src\\main\\java\\GUI\\config.properties");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties prop = new Properties();
//load properties file
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}
System.err.println(prop.getProperty("url"));
}
}
I think the problem is that I specify my config file locally. Should I edit this when I move my code to jenkins and how? Should I do this manually or can this be done an easier way without the chance of human error causing propblems
If this properties file is only used with this one project, you can package it with your test code. You can load the resource like this:
InputStream is = YourTestClassName.class.getClassLoader().getResourceAsStream("your/package/name/testFiles/config.properties")
If it's used in multiple projects, consider putting it in a shared directory or storing it in source control.
I've cobbled together some code to test a lexer/parser grammar but I'm a stuck on how to create the appropriate file input / stream objects to parse a file. My code is as follows, and I'm getting an error about giving the BasicLexer class constructor an ANTLRInputStream instead of a CharStream, and a similar message with giving the BasicParser a CommonTokenStream (it expects TokenStream). Any ideas on where I've gone wrong?
public static void main(String[] args) throws Exception {
String filename = args[0];
InputStream is;
try {
is = new FileInputStream(filename);
//is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ANTLRInputStream in = new ANTLRInputStream(is);
BasicLexer lexer = new BasicLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
BasicParser parser = new BasicParser(tokens);
parser.eval();
}
When I try to serialize and deserialize an ArrayList wrapped in Collections.synchronizedList using beans.XMLEncoder and beans.XMLDecoder, I get the following error:
java.lang.reflect.InvocationTargetException
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject*Collections$SynchronizedRandomAccessList);
Continuing ...
Since the program I am working on is a multithreaded music library client/server application, I need the synchronization. If using an ordinary ArrayList, the serialization/deserialization works fine. I really don't want to use Vector, since it contains a lot of legacy operations.
Here are my methods to serialize and deserialize:
/**
* Serializes library into an XML file
* #param xmlFileLocation - location of XML file
*/
public void saveLibrary (String xmlFileLocation) {
FileOutputStream fos;
try {
fos = new FileOutputStream(xmlFileLocation);
XMLEncoder encoder = new XMLEncoder(fos);
encoder.writeObject(lib);
encoder.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Constructor for Library, deserializes XML file
* #param xmlFileLocation - location of XML file
*/
#SuppressWarnings("unchecked")
public Library(String xmlFileLocation) {
FileInputStream fis;
try {
fis = new FileInputStream(xmlFileLocation);
XMLDecoder decoder = new XMLDecoder(fis);
Object o = decoder.readObject();
if (o instanceof List)
setLib((List<MusicDescription>) o);
decoder.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
As I stated, I really don't want to use Vector, since it contains a lot of legacy operations.