package it.tref.eclipse.wicket.plugin;
import it.tref.eclipse.wicket.plugin.views.HTMLTag;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
/**
* Class that provide static methods for parsing html file
*
* @author tref.AF
*
*/
public final class HTMLWicketParser
{
private static String WICKET_ID = "wicket:id";
private static ArrayList<String> parseTags(String filepath)
{
ArrayList<String> tagList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(filepath)));
String htmlString;
StringBuilder temptag = new StringBuilder();
while((htmlString = reader.readLine()) != null)
{
for(int i=0; i<htmlString.length(); i++)
{
if(htmlString.charAt(i) == '<')
{
temptag = new StringBuilder();
}
else if(htmlString.charAt(i) == '>')
{
tagList.add(temptag.toString());
}
else
{
temptag.append(htmlString.charAt(i));
}
}
}
reader.close();
} catch (Exception e) {
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", e.getMessage());
}
return tagList;
}
/**
* Parse html file to wicket id tree tag object
*
* @param filepath file to parse
* @param root html root tag, childs will be attached to it
*/
public static void parse(String filepath, HTMLTag root)
{
HTMLTag parent = root;
for(String tag : parseTags(filepath))
{
if(tag.contains(WICKET_ID))
{
try {
HTMLTag htmltag = new HTMLTag(tag.substring(0, tag.indexOf(" ")));
int i1 = tag.indexOf("\"", tag.indexOf(WICKET_ID)) + 1;
int i2 = tag.indexOf("\"", i1);
htmltag.setId(tag.substring(i1, i2));
htmltag.setParent(parent);
parent.addChild(htmltag);
if(!tag.endsWith("/"))
parent = htmltag;
} catch(Exception e) {
continue;
}
}
else if(tag.startsWith("/"))
{
if(parent.getTag().equals(tag.substring(1)))
{
if(parent.getParent() != null)
parent = parent.getParent();
}
}
}
}
public static List<String> parseWicketIds(String filepath)
{
ArrayList<String> ids = new ArrayList<String>();
for(String tag : parseTags(filepath))
{
if(tag.contains(WICKET_ID))
{
int i1 = tag.indexOf("\"", tag.indexOf(WICKET_ID)) + 1;
int i2 = tag.indexOf("\"", i1);
ids.add(tag.substring(i1, i2));
}
}
return ids;
}
}