Can't compile Lucene project with Eclipse - eclipse

Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.index.CorruptIndexException;
public class Main
{
public static void main()
{
//Index index = new Index();
String[] titleAndContent = parseFile("files/methode.txt");
Index index = new Index("files",null);
try
{
index.openIndex(true);
index.addDocument(titleAndContent[0], titleAndContent[1], "files/methode.txt");
}
catch (CorruptIndexException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String[] parseFile(String path)
{
String[] titleAndContent = new String[2];
File file = new File(path);
try
{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = new String();
String content = new String();
try
{
while((line = br.readLine()) != null)
{
if (line.substring(0,min(6,line.length())).equals("title:"))
{
titleAndContent[0] = line.substring(6,line.length());
}
else
{
if (line.substring(0,min(8,line.length())).equals("content:"))
{
content += line.substring(8,line.length())+"\n";
}
else
{
content += line+"\n";
}
}
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
titleAndContent[1] = content;
try
{
fr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return titleAndContent;
}
public static int max (int a, int b)
{
if (a<b)
{
return b;
}
return a;
}
public static int min (int a, int b)
{
if (a<b)
{
return a;
}
return b;
}
}
The problem is, I can't compile my Lucene projet under Eclipse. It keeps telling me:
ERROR: index path not specified
Usage: java org.apache.lucene.index.CheckIndex pathToIndex [-fix] [-segment X] [-segment Y]
-fix: actually write a new segments_N file, removing any problematic segments
-segment X: only check the specified segments. This can be specified multiple
times, to check more than one segment, eg '-segment _2 -segment _a'.
You can't use this with the -fix option
**WARNING**: -fix should only be used on an emergency basis as it will cause
documents (perhaps many) to be permanently removed from the index. Always make
a backup copy of your index before running this! Do not run this tool on an index
that is actively being written to. You have been warned!
Run without -fix, this tool will open the index, report version information
and report any exceptions it hits and what action it would take if -fix were
specified. With -fix, this tool will remove any segments that have issues and
write a new segments_N file. This means all documents contained in the affected
segments will be removed.
This tool exits with exit code 1 if the index cannot be opened or has any
corruption, else 0.
I tried everything to make it work, and as the whole web says, I used
-ea:org.apache.lucene... pathToIndex -fix
as argument of compilation. But whatever I put instead of pathToIndex, it keeps telling me
Unexpected argument pathToIndex (or whatever instead)
How can I get this f... project work?
Thank you in advance.
Edit: Of course I've imported all Lucene JARs.

Actually, I started the project over by creating a simple Main class and a main method inside it and tried to compile it immediately. And it worked fine, this time. Note you should show the Main class on your screen tab before compiling in Eclipse.

Related

What is strict mode policy violation in Android

public static void write(byte[] aInput, String aOutputFileName, String dirName) {
(new File(dirName)).mkdir();
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(dirName + "/" + aOutputFileName));
output.write(aInput);
} finally {
output.close();
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println(ex);
}
}
The code above is from a library i'm using and it is supposed to create an output file and write a byte array to it. I checked logcat and saw the Strict Mode Policy violation Write.toDisk. I understand what it is supposed to be for my questions are: (1) Does Strict mode prevent you from doing disk reads and write on the main thread? (2) Does that mean that the file or folder were not actually created? (3) How then would I go about creating a folder or file within my App that doesn't trigger this? (4) What is the recommended way to handle disk read / write off the main ui thread, a real world example would be appreciated
Thanks in Advance
(1) It turns out that Strict mode doesn't actually prevent you from making writes to the disk it just gives a warning. From Android Developer "StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them". https://developer.android.com/reference/android/os/StrictMode
(2) The files were actually being created it's just that I was just not familiar with writing and reading from disk
(3) There are numerous ways to go about creating files (i) first you get a hold of a file directory to write the file to:
context.getFilesDir()
(ii) then you get an outputstream writer (iii) then you write out the data with the writer
public void makeFile(String filename){
//Create temp file for filename
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filename));
fos.write(filename.getBytes());//Write the contents of the file to app folder
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(iv) finally you close the outputstream writer
(4) The recommended way is to use either an AsyncTask or some other background running class like FutureTask or to use Threads or Runnable:
public class DownloadFileThread implements Runnable{
public void run(){
//your code here
}
}

PropertyChangeListener validation

i'm try to implemente a view from eclipse preference page and in some fields this method (performStringSubstitution) not work because the StringFieldEditor do the validation before and don't give a permission to label.setText(), i'll appreciate any help. `
public void propertyChange(PropertyChangeEvent event)
{
/*Solve Eclipse variable method (${workspace_loc},${project_loc},...)*/
String dir = Activator.getDefault().getPreferenceStore()
.getString(event.getNewValue().toString());
IStringVariableManager manager = VariablesPlugin.getDefault()
.getStringVariableManager();
try {
String solvePathUpdate = manager.performStringSubstitution(dir);
label.setText(solvePathUpdate);
}
catch (CoreException e)
{
// TODO Auto-generated catch block
/* Creating the method print console */
}
}

Launching Dialog Box with Data from TableView Row

I'm attempting to launch an Edit Customer Window with text fields filled with reference from the rows of a table. The Table and Dialog both have different controller classes.
Here's the code snippet from the table in question that gives us the required customerID when a user double clicks on a row.
Table Controller: CustomersController:
#Override
public void initialize(URL location, ResourceBundle resources) {
populateCustomerTable();
tableListeners(null);
}
void tableListeners(CustomerData customerData){
tblcustomer.setRowFactory(tr -> {
TableRow<CustomerData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
int selectedCustomerID = row.getItem().getCustomerID();
System.out.println("A certain row: " + selectedCustomerID + " has been clicked!");
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader();
try {
Parent root = loader.load(getClass().getResource("../view/popups/edit_customer.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("Editing Existing Customer's Details");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(btnEditCustomer.getScene().getWindow());
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return row;
});
}
I want selectedCustomerID from the above piece of code to be parsed into the EditCustomerController class hence when the dialog launches, it's text fields should be prepoulated with values suppled from the select query that queries the database with the where condition being tht selectedCustomerID from the CustomersController class.
Code snippet from EditCustomerController class:
#Override
public void initialize(URL location, ResourceBundle resources) {
//populateEditCustomerFields(1);
}
void populateEditCustomerFields(int customerID){
this.customer_ID=customerID;
System.out.println(customer_ID);
try {
con = DatabaseConnection.getConnected();
stmt = con.createStatement();
rs = con.createStatement().executeQuery("SELECT * FROM `h_customers` WHERE `customerID`=" + customer_ID);
while (rs.next()) {
title.setText(rs.getString("title"));
firstName.setText(rs.getString("firstName"));
lastName.setText(rs.getString("lastName"));
nationalID.setText(String.valueOf(rs.getInt("nationalID")));
//dob.setText(rs.getString("DOB"));
mobilePhone.setText(rs.getString("mobilePhone"));
workPhone.setText(rs.getString("workPhone"));
email.setText(rs.getString("email"));
}
} catch (SQLException ex) {
Logger.getLogger(NewRoomController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
The Idea here is to parse selectedCustomerID from CustomersController into the initialize method of EditCustomerController so the Dialog can launch with the customer details that require editing. I've searched for solutions all over the web and here on StackOverflow, some come close to answering me, some are too complex for my newbie mind, but none has helped. Any solution would be highly appreciated. I will provide any further clarification required.
You can get the controller class and invoke its necessary methods. See this answer for getting controller, then do
editCustomerController.populateEditCustomerFields(selectedCustomerID);
on table row double click.
Further to improve performance, you can load the edit_customer.fxml only once and when the user double clicks, refresh its rendered data with editCustomerController.populateEditCustomerFields(selectedCustomerID).

Socket implementation with ObjectInputStream - can't read object

For a Java class I am taking, I need to use sockets to pass data back and forth between client and server. While I can get examples to work passing string data, I need to be able to pass custom class objects (i.e. a product) and lists of these objects back and forth. I cannot get the server piece to successfully read the input. I tried to create a simple example of my code to see if anyone can pinpoint the issue. I do understand that I don't have the code complete, but I cannot even get the server to read the object the the class is writing to the stream (in this case, I am writing a string just in an attempt to get it to work, but need to read/write objects). Here is my code. I have spent hours and hours trying this and researching other people's questions and answere, but still can't get this to work.
Here the sample code:
simple server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class simpleServer {
public static final int PORT_NO = 8888;
static ObjectInputStream serverReader = null;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = new ServerSocket(PORT_NO);
System.out.println("... server is accepting request");
Object myObject = null;
while (true) {
Socket socket = serverSocket.accept();
System.out.println("creating reader");
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
serverReader = new ObjectInputStream(socket.getInputStream());
System.out.println("created reader");
try {
System.out.println("try to read");
myObject = serverReader.readObject();
System.out.println("read it");
System.out.println(myObject);
if (myObject != null) objOut.writeUTF("Got something");
else objOut.writeUTF("got nothing");
if ("quit".equals(myObject.toString())) serverSocket.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("cath for readobject");
}
catch (Exception e) {
System.out.println("other error");
System.out.println(e.getMessage());
}
}
}
}
simple client:
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket("localhost", ProductDBServer.PORT_NO);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeUTF("loadProductsFromDisk");
objOut.flush();
String myString = objIn.toString();
//System.out.println(myString);
if (!"quit".equals(objIn.toString().trim())) {
//System.out.println("reading line 1");
String line;
try {
line = (String)objIn.readObject();
//System.out.println("line is " + line);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
objIn.close();
//System.out.println("result: " + line);
}
System.out.println("closing socket");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Unknownhostexception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("ioexception");
e.printStackTrace();
}
}
The code appears to run to the point on the server side where it trys to read the object I sent, and then dies. Can someone see what I am doing wrong? This seems to be such a simple thing to do, and yet I can't seem to get it to work. Thanks for any help!
To write objects to an ObjectOutputStream you need to call writeObject().
Not writeUTF().
To read objects from an ObjectInputStream you need to call readObject().
Not toString().
See in your code:
// Simple Client
objOut.writeUTF("loadProductsFromDisk"); // Line 8
You are sending the String "loadProductsFromDisk" in the UTF-8 format towards the server side.
So in order to receive it and read it over the server side, you will need something like this:
String clientReq = serverReader.readUTF();
Where, serverReader is your ObjectInputStream object.
Otherwise, if you wish to send and receive objects you must use the
writeObject() & readObject() methods respectively.

Deploy exploded bundle to Apache Felix using an Eclipse launch task

I am looking for a way to (re)deploy an exploded bundle (meaning not jarred but in a folder) to a running Apache Felix OSGi container from within Eclipse, preferably using a launch task.
I found this question, which has an answer that comes close but it depends on typing commands into a Gogo shell, which is not convenient for long-term development use. I'd like to use Eclipse's launch task mechanism for this, but if there are alternatives that are equally fast and convenient I am open to that as well.
Now I think that if I can fire Gogo shell commands from an Eclipse launch tasks, that would be a solution, but I also can't get my head around how to do that. I presume I need the Remote Shell bundle for that right?
I am starting to think about writing a telnet client in Java that can connect to the Remote Shell bundle and execute Gogo commands in an automated fashion. I have seen some example of that already which I can modify to suit my needs... However I am getting a 'reinventing the wheel' kind of feeling from that. Surely there is a better way?
Some background to help you understand what I am doing:
I have set up an Eclipse 'OSGiContainer' project which basically contains the Apache Felix jar and the third party bundles I want to deploy (like Gogo shell), similar to the project setup described here. Then I created a second 'MyBundle' project that contains my bundle. I want to start the OSGi container by launching the OSGiContainer project, and then just develop on my bundle and test my changes by launching the MyBundle project into the OSGiContainer that I just want to keep running the whole time during development.
Project layout:
OSGiContainer
bin (contains felix jar)
bundles (third party bundles)
conf (Felix' config.properties file)
MyBundle
src
target
classes
I am then able to deploy my bundle to the OSGi container by invoking these commands on the Gogo shell:
install reference:file:../MyBundle/target/classes
start <bundleId>
To re-deploy, I invoke these commands:
stop <bundleId>
uninstall <bundleId>
install reference:file:../MyBundle/target/classes
start <bundleId>
You can imagine having to invoke 4 commands on the shell each time is not that much fun... So even if you can give me a way to boil this down to less commands to type it would be a great improvement already.
UPDATE
I hacked around a bit and came up with the class below. It's an adaptation of the telnet example with some small changes and a main method with the necessary commands to uninstall a bundle and then re-install and start it. The path to the bundle should be given as an argument to the program and would look like:
reference:file:../MyBundle/target/classes
I still very much welcome answers to this question, as I don't really like this solution at all. I have however verified that this works:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.TelnetClient;
public class GogoDeployer {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final GogoDeployer checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(GogoDeployer checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
System.out.println("Responder stopped.");
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private boolean isKeepRunning = true;
private final GogoDeployer checker;
private final TelnetClient tc;
TelnetReader(GogoDeployer checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
if (instr.available() > 0) {
ret_read = instr.read(buff);
}
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
ret_read = 0;
}
} while (isKeepRunning && (ret_read >= 0));
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private static final String prompt = "g!";
private static GogoDeployer client;
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public GogoDeployer(String host, int port) {
this.host = host;
this.port = port;
}
public void stop() {
responder.isKeepRunning = false;
reader.isKeepRunning = false;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
responder.interrupt();
reader.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws SocketException, IOException {
tc = new TelnetClient();
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
private static String exec(String cmd) {
String result = "";
System.out.println(cmd);
client.send(cmd);
result = client.waitFor(prompt);
return result;
}
public static void main(String[] args) {
try {
String project = args[0];
client = new GogoDeployer("localhost", 6666);
client.connect();
System.out.println(client.waitFor(prompt));
System.out.println(exec("uninstall " + project));
String result = exec("install " + project);
System.out.println(result);
int start = result.indexOf(":");
int stop = result.indexOf(prompt);
String bundleId = result.substring(start + 1, stop).trim();
System.out.println(exec("start " + bundleId));
client.stop();
} catch (SocketException e) {
System.err.println("Unable to conect to Gogo remote shell: " + e.getMessage());
} catch (IOException e) {
System.err.println("Unable to conect to Gogo remote shell: " + e.getMessage());
}
}
}
When I met the same requirement (deploy bundle from target/classes as fast as I can) my first thought was also extending my container with some shell functionality. My second thought was, however, to write a simple bundle that opens up an always-on-top window and I can simply drag-and-drop any project(s) from Eclipse (or total commander or whatever) to that window. The code than checks if the folder(s) that was dropped has a target/classes folder and if it has it will be deployed.
The source code is available at https://github.com/everit-org/osgi-richconsole
The dependency is available from the maven-central.
The dependency is:
<dependency>
<groupId>org.everit.osgi.dev</groupId>
<artifactId>org.everit.osgi.dev.richconsole</artifactId>
<version>1.2.0</version>
</dependency>
You can use the bundle it while you develop and remove it when you set up your live server. However it is not necessary as if the container is running in a headless mode the pop-up window is not shown.
I called it richconsole as I would like to have more features in the future (not just deployment) :)