Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » Plugin Development Environment (PDE) » Simple Plugin - Know the path of a file
Simple Plugin - Know the path of a file [message #660550] Sat, 19 March 2011 09:02 Go to next message
Giancarlo is currently offline GiancarloFriend
Messages: 5
Registered: March 2011
Junior Member
Hello!!!
I'm new with Eclipse plugin development !!!
I'm studying this tutorial : http:// www.vogella.de/articles/EclipsePlugIn/article.html#contribut e , but I'd like to create a plugin so when I right-click on a file (for example an html file) and choose for example the Option "Modify HTML" (that I've created), I can open and modify that file.
I think I need only to know the path of the file that I right-click, and so I can open and modify that file using other java-classes.

The code used in this tutorial is :
public class Convert extends AbstractHandler {
	private QualifiedName path = new QualifiedName("html", "path");

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil
				.getActiveMenuSelection(event);
		DirectoryDialog fileDialog = new DirectoryDialog(HandlerUtil
				.getActiveShell(event));
		String directory = "";
		Object firstElement = selection.getFirstElement();
		if (firstElement instanceof ICompilationUnit) {
			ICompilationUnit cu = (ICompilationUnit) firstElement;
			IResource res = cu.getResource();
			boolean newDirectory = true;
			directory = getPersistentProperty(res, path);

			if (directory != null && directory.length() > 0) {
				newDirectory = !(MessageDialog.openQuestion(HandlerUtil
						.getActiveShell(event), "Question",
						"Use the previous output directory?"));
			}
			if (newDirectory) {
				directory = fileDialog.open();

			}
			if (directory != null && directory.length() > 0) {
				analyze(cu);
				setPersistentProperty(res, path, directory);
				write(directory, cu);
			}

		} else {
			MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
					"Information", "Please select a Java source file");
		}

		// iterator.next();

		// }
		return null;
	}

	protected String getPersistentProperty(IResource res, QualifiedName qn) {
		try {
			return (String) res.getPersistentProperty(qn);
		} catch (CoreException e) {
			return "";
		}
	}

	// TODO: Include this in the HTML output

	private void analyze(ICompilationUnit cu) {
		// Cool JDT allows you to analyze the code easily
		// I don't see really a use case here but I just wanted to do this here
		// as I consider this as cool and
		// what to have a place where I can store the data
		try {

			IType type = null;
			IType[] allTypes;
			allTypes = cu.getAllTypes();
			/**
			 * Search the public class
			 */
			for (int t = 0; t < allTypes.length; t++) {
				if (Flags.isPublic((allTypes[t].getFlags()))) {
					type = allTypes[t];
					break;
				}
			}

			String classname = type.getFullyQualifiedName();
			IMethod[] methods = type.getMethods();
		} catch (JavaModelException e) {
			e.printStackTrace();
		}

	}

	protected void setPersistentProperty(IResource res, QualifiedName qn,
			String value) {
		try {
			res.setPersistentProperty(qn, value);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	private void write(String dir, ICompilationUnit cu) {
		try {
			cu.getCorrespondingResource().getName();
			String test = cu.getCorrespondingResource().getName();
			// Need
			String[] name = test.split("\\.");
			System.out.println(test);
			System.out.println(name.length);
			String htmlFile = dir + "\\" + name[0] + ".html";

			System.out.println(htmlFile);
			FileWriter output = new FileWriter(htmlFile);
			BufferedWriter writer = new BufferedWriter(output);
			writer.write("<html>");
			writer.write("<head>");
			writer.write("</head>");
			writer.write("<body>");
			writer.write("<pre>");
			writer.write(cu.getSource());
			writer.write("</pre>");
			writer.write("</body>");
			writer.write("</html>");
			writer.flush();
		} catch (JavaModelException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}



The example given in the tutorial is similar, but with that code I can only open java files.
I think the problem is ICompilationUnit that represents an entire Java compilation unit, but I hadn't understood how I can modify that code to re-use it.

Who can help me ????

Thanks.

[Updated on: Sun, 20 March 2011 11:54]

Report message to a moderator

Re: Simple Plugin - Know the path of a file [message #660697 is a reply to message #660550] Mon, 21 March 2011 09:19 Go to previous messageGo to next message
Giancarlo is currently offline GiancarloFriend
Messages: 5
Registered: March 2011
Junior Member
Probably I don't need the path of that file, but I need each code-line of the HTML page that I select (right-click on a file in the Package Explorer and choose for example the option "Modify" I've created).

Does anyone know how can I write this plug-in ???

Which classes should I use to read that file ?

Thank you very much !!!
Re: Simple Plugin - Know the path of a file [message #660808 is a reply to message #660550] Mon, 21 March 2011 16:52 Go to previous messageGo to next message
Giancarlo is currently offline GiancarloFriend
Messages: 5
Registered: March 2011
Junior Member
I've partially resolved.

public class Convert extends AbstractHandler { 
 @Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil
			.getActiveMenuSelection(event);

Object firstElement = selection.getFirstElement();

if (firstElement instanceof ICompilationUnit) {
			
			ICompilationUnit cu = (ICompilationUnit) firstElement;
			
			IPath url;
			IResource risorsa= cu.getResource();
			url=risorsa.getRawLocation();
			
			System.out.println("l'url del file selezionato è : "+ url);
			
			File file=new File(url.toString());

try{
	            InputStreamReader reader = new InputStreamReader (System.in);
	            	            
	            String str= url.toString();
	            
	            FileInputStream fstream = new FileInputStream(str);
	            DataInputStream in = new DataInputStream(fstream);
	            BufferedReader br = new BufferedReader(new InputStreamReader(in));
	            String strLine;
	            int i=1;
	            
	            while ((strLine = br.readLine()) != null){
	                System.out.println (i+" " + strLine);
	                i++;
	            }
	            in.close();
	        }catch (Exception e){
	            System.err.println("Errore: " + e.getMessage());
	        }
}
		return null;
	} }




But it reads only java files. I need to read html files.
I think the problem is ICompilationUnit.
How can I resolve it ???

Thanks.
Re: Simple Plugin - Know the path of a file [message #661876 is a reply to message #660550] Mon, 28 March 2011 11:24 Go to previous messageGo to next message
Paul Webster is currently offline Paul WebsterFriend
Messages: 6859
Registered: July 2009
Location: Ottawa
Senior Member

On 03/19/2011 05:03 AM, giancarlo.capone@yahoo.com wrote:
> Hello!!!
> I'm new with Eclipse plugin development !!!
> I'm studying this tutorial :
> http://www.vogella.de/articles/EclipsePlugIn/article.html#co ntribute ,
> but I'd like to create a plugin so when I right-click on a file (for
> example an html file) and choose for example the Option "Modify HTML"
> (that I've created), I can open and modify that file. I think I need
> only to know the path of the file that I right-click, and so I can open
> and modify that file using other java-classes.

You always deal with IFiles for files within a workspace. In the
example, because they knew it was an ICompilationUnit they could get the
resource:
IResource res = cu.getResource();

The other way is to adapt to the resource, using the adapter manager:
org.eclipse.core.runtime.Platform.getAdapterManager().getAda pter(firstElement,
IFile.class);

If you want to *write* your output in the same directory ... don't use
that example, that's not what it is doing. Use the IFile to get the
parent directory, and then create a new IFile and write to that.

Later,
PW


--
Paul Webster
http://wiki.eclipse.org/Platform_Command_Framework
http://wiki.eclipse.org/Command_Core_Expressions
http://wiki.eclipse.org/Platform_Expression_Framework
http://wiki.eclipse.org/Menu_Contributions
http://wiki.eclipse.org/Menus_Extension_Mapping
http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse. platform.doc.isv/guide/workbench.htm


Re: Simple Plugin - Know the path of a file [message #661902 is a reply to message #661876] Mon, 28 March 2011 13:33 Go to previous messageGo to next message
Giancarlo is currently offline GiancarloFriend
Messages: 5
Registered: March 2011
Junior Member
Dear Paul,
I've used the following code (It's only an example... I have only found a way to read each line of the html file and show it in output) :

public class Convert extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil
			.getActiveMenuSelection(event);
		
		Object firstElement = selection.getFirstElement();
		
		System.out.println("Object first element vale : "+firstElement.toString());
			
		if (firstElement instanceof Object) {
			
			System.out.println("Sono nel ciclo if ");
			
			IFile risorsa=(IFile) firstElement;
			
			System.out.println("risorsa vale : "+risorsa.toString());
			
			IPath url;
			
			url=risorsa.getRawLocation();
			
			System.out.println("l'url del file selezionato è : "+ url);
			
			File file=new File(url.toString());
			
			System.out.println("Il nome del file è "+file.getName()+"\n");

			try{
					InputStreamReader reader = new InputStreamReader (System.in);
	            	            
					String str= url.toString();
	            
					FileInputStream fstream = new FileInputStream(str);
					DataInputStream in = new DataInputStream(fstream);
					BufferedReader br = new BufferedReader(new InputStreamReader(in));
					String strLine;
					int i=1;
	            
					while ((strLine = br.readLine()) != null){
							System.out.println (i+" " + strLine);
							i++;
					}// fine while
					
					in.close();
					
	        } catch (Exception e){
	            System.err.println("Errore: " + e.getMessage());
	        }// fine catch
.

It works fine !!!

Thank you very much !!!!
Re: Simple Plugin - Know the path of a file [message #661932 is a reply to message #661902] Mon, 28 March 2011 14:35 Go to previous messageGo to next message
Paul Webster is currently offline Paul WebsterFriend
Messages: 6859
Registered: July 2009
Location: Ottawa
Senior Member

On 03/28/2011 09:33 AM, Giancarlo wrote:
> Dear Paul,
> I've used the following code (It's only an example... I have only found
> a way to read each line of the html file and show it in output) :

Unfortunately, that's a bad idea.


>
> IFile risorsa=(IFile) firstElement;

That's a blind cast ... verboten. But this might just be your example.

You have to at least check instanceof, and if you expect to work with
the Package Explorer, you need to adapt that object to IResource/IFile.
Casting won't work reliably in the Package Explorer case, and would
case a ClassCastException if you tried this on a java file.

>
> File file=new File(url.toString());

You already have an IFile ... use the getContents() method to get the
original input stream, instead of trying to find the absolute path just
to run it through an InputStream.

Later,
PW


--
Paul Webster
http://wiki.eclipse.org/Platform_Command_Framework
http://wiki.eclipse.org/Command_Core_Expressions
http://wiki.eclipse.org/Platform_Expression_Framework
http://wiki.eclipse.org/Menu_Contributions
http://wiki.eclipse.org/Menus_Extension_Mapping
http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse. platform.doc.isv/guide/workbench.htm


Re: Simple Plugin - Know the path of a file [message #662927 is a reply to message #661932] Fri, 01 April 2011 14:00 Go to previous messageGo to next message
Giancarlo is currently offline GiancarloFriend
Messages: 5
Registered: March 2011
Junior Member
Dear Paul,
I've modified the code following your suggestions. I hope now it's better.

> You have to at least check instanceof, and if you expect to work with
> the Package Explorer, you need to adapt that object to IResource/IFile.
> Casting won't work reliably in the Package Explorer case, and would
> case a ClassCastException if you tried this on a java file.

I expect to work with the Package Explorer.
How can I make it works also with java files or other files ??? In witch way can I understand witch kind of file is it ? (Java file, Html file, ...)

public class Convert extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil
			.getActiveMenuSelection(event);
		
		IFile risorsa = (IFile) selection.getFirstElement();
		System.out.println("IFile risorsa vale : "+risorsa.toString());
			
		if (risorsa instanceof IResource) {
			
			System.out.println("Sono nel ciclo if ");
			System.out.println("risorsa vale : "+risorsa.toString());
			int input=0; 
                        int i=1;
			boolean finefile= false; 
			
			try {
				InputStream is=risorsa.getContents();
				InputStreamReader isr= new InputStreamReader(is);
				BufferedReader d = new BufferedReader(isr);
				
				while(!finefile) // finchè non si è raggiunta la fine del file
					{
						try {
								input = d.read();
								if (input == -1) // si è alla fine del file
									finefile = true;
								else{ 
								
									try {
										System.out.println(i+"-> "+d.readLine());
										i++;
									} catch (IOException e) {
								
										e.printStackTrace();
									}
								} // fine else
					
						} catch (IOException e) {
								e.printStackTrace();
						}
				
				} // fine while
			
				try {
					d.close();
					} catch (IOException e) {
							e.printStackTrace();
							}
			} catch (CoreException e1) {
				e1.printStackTrace();
				}

		} // fine if
	return null;
	} // fine metodo execute
	
	} // fine class Convert


Re: Simple Plugin - Know the path of a file [message #663228 is a reply to message #662927] Mon, 04 April 2011 12:09 Go to previous messageGo to next message
Paul Webster is currently offline Paul WebsterFriend
Messages: 6859
Registered: July 2009
Location: Ottawa
Senior Member

On 04/01/2011 10:00 AM, Giancarlo wrote:
> IFile risorsa = (IFile) selection.getFirstElement();

That's a blind cast:
Object obj = selection.getFirstElement();
IFile file = null;
if (obj instanceof IFile) {
file = (IFile) obj;
} else if (obj instanceof IAdaptable) {
file = (IFile) ((IAdaptable)obj).getAdapter(IFile.class);
}
if (file == null) {
file = (IFile) Platform.getAdapterManager()
.getAdapter(obj, IFile.class);
}
if (file!=null) {
// do whatever
}

PW

--
Paul Webster
http://wiki.eclipse.org/Platform_Command_Framework
http://wiki.eclipse.org/Command_Core_Expressions
http://wiki.eclipse.org/Platform_Expression_Framework
http://wiki.eclipse.org/Menu_Contributions
http://wiki.eclipse.org/Menus_Extension_Mapping
http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse. platform.doc.isv/guide/workbench.htm


Re: Simple Plugin - Know the path of a file [message #668085 is a reply to message #660550] Tue, 03 May 2011 16:55 Go to previous message
Riccardo  is currently offline Riccardo Friend
Messages: 6
Registered: March 2011
Junior Member
I tried to follow vogella guides, but it don't run... and i haven't error... probabilly i did wrong something...

Can you send me source code of this sample project?

Previous Topic:External launch on different thread
Next Topic:How can I call save method in eclipse plugin development programticaly
Goto Forum:
  


Current Time: Wed Aug 12 16:33:43 GMT 2020

Powered by FUDForum. Page generated in 0.02224 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top