i have some indexed docs and i wanna search in them using a query, i checked lucene documentation and made this code but somehow im getting "short cannot be dereferenced" in the QueryParser line, Im new to Java and to Lucene, im using Lucene 5.3.1
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.time.Clock.system;
import javax.management.Query;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import static sun.rmi.transport.TransportConstants.Version;
import static sun.rmi.transport.TransportConstants.Version;
public class Searcher
{
public static void main(String args[]) throws IOException{
String query="computer science";
Analyzer analyzer = new KeywordAnalyzer();
Query q = new QueryParser(Version.LUCENE_CURRENT, "W", analyzer).parse(query); //ERROR IS HERE
Path indexPath = Paths.get("MonIndex");
Directory directory = FSDirectory.open(indexPath);
DirectoryReader reader = DirectoryReader.open(directory);
IndexSearcher iSearcher = new IndexSearcher(reader);
TopDocs topdocs = iSearcher.search(q2, 100);
ScoreDoc[] resultsList = topdocs.scoreDocs;
for(int i = 0; i<resultsList.length; i++){
Document book = iSearcher.doc(resultsList[i].doc);
System.out.println(book.getField("I").stringValue());
}
}
}
The problem is Version.LUCENE_CURRENT. You are not importing Lucene's Version, but you do have sun.rmi.transport.TransportConstants.Version, which, while I'm not familiar with the library, it certainly does appear to be a short. So attempting to dereference that, by attempting to reference the nonexistent sun.rmi.transport.TransportConstants.Version.LUCENE_CURRENT is causing that error to be thrown.
However, in the version of Lucene you say you are using, the QueryParserctor no longer even accepts a Version argument, so just remove it:
Query q = new QueryParser("W", analyzer).parse(query);
Your next error: The Query that the queryparser returns is not a javax.management.Query.
Related
im developing my Java bot for discord. And I want to send an image. I tried using TextChannel.sendFile(File, Message), but it`s not that result that I want to get. I want this file to be displayed like a normal image.
The imports:
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.io.FileUtils;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
And the other code:
URL url = new URL(s.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(conn.getInputStream());
final List<String> files = new ArrayList<>();
while (reader.hasNext()) {
XMLEvent e = reader.nextEvent();
if (e.isStartElement()) {
StartElement se = e.asStartElement();
if (se.getName().getLocalPart().equals("post")) {
Attribute purl = se.getAttributeByName(new QName("file_url"));
files.add(purl.getValue());
}
}
}
int rid = ThreadLocalRandom.current().nextInt(files.size() - 1);
String p = files.get(rid);
files.clear();
URL u = new URL(p);
final String[] dots = p.split("\\.");
final String format = dots[dots.length - 1];
File f = new File("its not a porn." + format);
FileUtils.copyURLToFile(url, f);
Message m = new MessageBuilder().append("okay :)").build();
c.sendFile(f, m).queue();
}
I tried to find a solution somewhere but i haven found any info that could help.
At JDA 4.2.0_168
the message on sendFile() is the name of the file that you are sending to the discord servers, so it needs an extension
example:
File f = new File("image.png");
TextChannel.sendFile(f, "image.png").queue();
if you want comments in the message
File f = new File("image.png");
//the name doesn't need to be the same, just the same extension
TextChannel.sendFile(f, "another_name.png").append("okay :)").queue();
Result of last code
Reading through the docs, you need to create a MessageEmbed and add it to the message using m.setEmbed(..)
I'm a newbie here. I have a simple problem in ONE java source file: the row System.out.pritln(...) has been treated as an erroneous expression. Here's the code snippet:
package vk.gui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Properties;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class MatrixSheet1 {
Properties p;
File file;
Document document;
PdfWriter writer;
Image logo = null;
Image EANimg = null;
float mnoz = new Double(72/25.6).floatValue();
int IMG_WIDTH= new Double(35*mnoz).intValue();
int IMG_HEIGHT=new Double(35*mnoz).intValue();
String err=p.getProperty("cell.height");
System.out.println("Arrgh!"); ///-------------->ERROR!
float cell_Height = Float.parseFloat(p.getProperty("cell.height"))*mnoz;
float cell_Width = Float.parseFloat(p.getProperty("cell.width"))*mnoz;
The reported error is
Multiple markers at this line
Syntax error on token ""Arrgh!"", delete this token
Syntax error on token(s), misplaced construct(s)
The sout and sysout shortcuts do not work neither. In other existing source files of same package everything is OK, the shortcuts work and the expression does not trigger an error.
I tried to create another source file and copy/paste the content, but I got the same error. What and where went wrong?
I need the printing just for debugging, but this is a bit annoying symptom.
Thanks in advance.
This happens because you can use System.out.println() only inside methodes. If you would do something like this, it would work:
public class MatrixSheet1 {
Properties p;
File file;
Document document;
PdfWriter writer;
Image logo = null;
Image EANimg = null;
float mnoz = new Double(72/25.6).floatValue();
int IMG_WIDTH= new Double(35*mnoz).intValue();
int IMG_HEIGHT=new Double(35*mnoz).intValue();
String err=p.getProperty("cell.height");
systemMessage("Argh!");
float cell_Height = Float.parseFloat(p.getProperty("cell.height"))*mnoz;
float cell_Width = Float.parseFloat(p.getProperty("cell.width"))*mnoz;
private void systemMessage(String message){
System.out.println(message);
}
}
I am trying to use StopFilter in Lucene 5.5.0. I tried the following:
package lucenedemo;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import org.apache.lucene.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.en.EnglishAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.Version;
public class lucenedemo {
public static void main(String[] args) throws Exception {
System.out.println(removeStopWords("hello how are you? I am fine. This is a great day!"));
}
public static String removeStopWords(String strInput) throws Exception {
AttributeFactory factory = AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY;
StandardTokenizer tokenizer = new StandardTokenizer(factory);
tokenizer.setReader(new StringReader(strInput));
tokenizer.reset();
CharArraySet stopWords = EnglishAnalyzer.getDefaultStopSet();
TokenStream streamStop = new StopFilter(tokenizer, stopWords);
StringBuilder sb = new StringBuilder();
CharTermAttribute charTermAttribute = tokenizer.addAttribute(CharTermAttribute.class);
streamStop.reset();
while (streamStop.incrementToken()) {
String term = charTermAttribute.toString();
sb.append(term + " ");
}
streamStop.end();
streamStop.close();
tokenizer.close();
return sb.toString();
}
}
But it gives me the following error:
Exception in thread "main" java.lang.IllegalStateException: TokenStream contract violation: reset()/close() call missing, reset() called multiple times, or subclass does not call super.reset(). Please see Javadocs of TokenStream class for more information about the correct consuming workflow.
at org.apache.lucene.analysis.Tokenizer$1.read(Tokenizer.java:109)
at org.apache.lucene.analysis.standard.StandardTokenizerImpl.zzRefill(StandardTokenizerImpl.java:527)
at org.apache.lucene.analysis.standard.StandardTokenizerImpl.getNextToken(StandardTokenizerImpl.java:738)
at org.apache.lucene.analysis.standard.StandardTokenizer.incrementToken(StandardTokenizer.java:159)
at org.apache.lucene.analysis.util.FilteringTokenFilter.incrementToken(FilteringTokenFilter.java:51)
at lucenedemo.lucenedemo.removeStopWords(lucenedemo.java:42)
at lucenedemo.lucenedemo.main(lucenedemo.java:27)
What exactly am I doing wrong here? I have closed both the Tokeinzer and TokenStream clasess. Is there something else I am missing here?
Calling reset on a filter will, in turn, reset the underlying stream. Since you reset the tokenizer manually, and then create a StopFilter with the tokenizer it's underlying stream, and reset that, the Tokenizer is being reset twice.
So just remove this line:
tokenizer.reset();
So I am receiving error messages as the XSSFWorkbook import appears to be incompatible with the final line. The code as it is gives the error message that package "org.apache.poi.xssf.usermodel.XSSFWorkbook" does not exist. When I remove the import, the last line then gets the error message that I should create an XSSFWorkbook class. I am currently using the Apache 3.7 utilmodel file in order to import the XSSFWorkbook class. Any help would be most appreciated. I am trying to create a program that reads data from an excel file.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ReadExcel {
private static final String FILE_PATH =
"/Users/riveraaz/Desktop/FantasyPros_2015_Overall.numbers";
public static List getPlayersFromExcel() {
List PlayerList = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(FILE_PATH);
Workbook workbook = new XSSFWorkbook(fis);
I have a simple Query method that runs cypher queries as noted below. If I run the EXACT same query in the web console (yes, same db instance, correct path), I get a non-empty iterator in the console. Shouldn't I 1) not get that message and 2) get the results I see in my database?
This class has other methods that add data to the database and that functionality works well. This query method is not working...
Class:
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.collection.IteratorUtil;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.sql.*;
public class NeoProcessor {
//private GraphDatabaseService handle;
private static final String DB_PATH = "/usr/local/Cellar/neo4j/2.0.1/libexec/data/new_graph.db";
static GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
public NeoProcessor()
{
}
public void myQuery(String cypherText)
{
//System.out.println("executing the above query");
cypherText = "MATCH (n:Phone{id:'you'}) MATCH n-[r:calling]->m WHERE n<>m RETURN n, r, m";
ExecutionEngine engine = new ExecutionEngine( this.graphDb );
ExecutionResult result;
try ( Transaction ignored = graphDb.beginTx() )
{
result = engine.execute( cypherText + ";");
System.out.println(result);
ignored.success();
}
}
}
Below is a pic showing how the query rreturns results from the DB:
result = engine.execute(cypherText + ";");
System.out.println(result.dumpToString());
Specified by:
http://api.neo4j.org/2.0.3/org/neo4j/cypher/javacompat/ExecutionResult.html#dumpToString()
To consume the result you need to use the iterator. If you just want a string representation use the ExecutionResult.dumpToString(). Be aware this method exhausts the iterator.
You should be calling:
System.out.println(result.dumpToString)
Which will prettify it for you. Of course, there is always the possibility that your match returns no results. You shouuld also close the transaction in a finally block, although that won't matter much here.
EDIT: Taking a second look at this, your Cypher query is wrongly formed, It should be
MATCH (n:Phone) - [r:calling] -> (m)
WHERE n.id = `you'
RETURN n, r, m