KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ConvertURL


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/i18n/tool/ConvertURL.java,v 1.12 2006/04/15 03:57:15 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.12 $
5  * $Date: 2006/04/15 03:57:15 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding MyVietnam and MyVietnam CoreLib
12  * MUST remain intact in the scripts and source code.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  *
28  * Correspondence and Marketing Questions can be sent to:
29  * info at MyVietnam net
30  *
31  * @author: Minh Nguyen
32  * @author: Mai Nguyen
33  */

34 //package test;
35
import java.io.*;
36 import java.util.*;
37
38 public class ConvertURL {
39
40     static String JavaDoc convertURL(String JavaDoc href) {
41         StringBuffer JavaDoc output = new StringBuffer JavaDoc();
42
43         if (href.startsWith("http") == false &&
44             href.startsWith("javascript:") == false &&
45             href.startsWith("mailto:") == false &&
46             href.startsWith("aim:") == false &&
47             href.startsWith("<%=response.encodeURL") == false) {
48             href = href.replaceAll("<%=", "\" + ");
49             href = href.replaceAll("%>", " + \"");
50
51             boolean redundantEnd = false;
52             if (href.endsWith(" + \"")) {
53                 redundantEnd = true;
54                 //System.out.println("redundantEnd = true");
55
href = href.substring(0, href.length()-4);
56             }
57
58             boolean redundantBegin = false;
59             if (href.startsWith("\" + ")) {
60                 redundantBegin = true;
61                 //System.out.println("redundantBegin = true");
62
href = href.substring(4);
63             }
64
65             if (redundantBegin) {
66                 output.append("<%=response.encodeURL(");
67             }
68             else {
69                 output.append("<%=response.encodeURL(\"");
70             }
71
72             output.append(href);
73
74             if (redundantEnd) {
75                 output.append(")%>");
76             } else {
77                 output.append("\")%>");
78             }
79         } else {
80             return href;
81         }
82         return output.toString();
83     }
84
85     static String JavaDoc convertTagA(String JavaDoc tagA) throws IllegalArgumentException JavaDoc {
86         String JavaDoc output = "";
87         if (tagA.startsWith("<a ") == false) {
88             throw new IllegalArgumentException JavaDoc();
89         }
90         if (tagA.endsWith(">") == false) {
91             throw new IllegalArgumentException JavaDoc();
92         }
93
94         if (tagA.indexOf('>') != tagA.lastIndexOf('>')) {
95             //throw new IllegalArgumentException();
96
}
97         int firstIndex = tagA.indexOf("href=\"");
98         if (firstIndex == -1) {
99             System.out.println("WARNING: TagA does not have href: " + tagA);
100             return tagA;
101         }
102         int lastIndex = tagA.indexOf("\"", firstIndex + 6);
103
104         String JavaDoc begin = tagA.substring(0, firstIndex + 6);
105         String JavaDoc href = tagA.substring(firstIndex + 6, lastIndex);
106         String JavaDoc end = tagA.substring(lastIndex);
107
108 // System.out.println("begin = " + begin);
109
// System.out.println("href = " + href);
110
// System.out.println("end = " + end);
111

112         output = begin + convertURL(href) + end;
113
114         return output;
115     }
116
117     static String JavaDoc convertTagForm(String JavaDoc tagForm) throws IllegalArgumentException JavaDoc {
118         String JavaDoc output = "";
119         if (tagForm.startsWith("<form ") == false) {
120             throw new IllegalArgumentException JavaDoc();
121         }
122         if (tagForm.endsWith(">") == false) {
123             throw new IllegalArgumentException JavaDoc();
124         }
125
126         if (tagForm.indexOf('>') != tagForm.lastIndexOf('>')) {
127             //throw new IllegalArgumentException();
128
}
129         int firstIndex = tagForm.indexOf("action=\"");
130         if (firstIndex == -1) {
131             System.out.println("WARNING: TagForm does not have action: " + tagForm);
132             return tagForm;
133         }
134         int lastIndex = tagForm.indexOf("\"", firstIndex + 8);
135
136         String JavaDoc begin = tagForm.substring(0, firstIndex + 8);
137         String JavaDoc href = tagForm.substring(firstIndex + 8, lastIndex);
138         String JavaDoc end = tagForm.substring(lastIndex);
139
140 // System.out.println("begin = " + begin);
141
// System.out.println("action = " + href);
142
// System.out.println("end = " + end);
143

144         output = begin + convertURL(href) + end;
145
146         return output;
147     }
148
149     static String JavaDoc convertTagMeta(String JavaDoc tagMeta) throws IllegalArgumentException JavaDoc {
150         String JavaDoc output = "";
151         if (tagMeta.startsWith("<meta ") == false) {
152             throw new IllegalArgumentException JavaDoc();
153         }
154         if (tagMeta.endsWith(">") == false) {
155             throw new IllegalArgumentException JavaDoc();
156         }
157
158         if (tagMeta.indexOf('>') != tagMeta.lastIndexOf('>')) {
159             //throw new IllegalArgumentException();
160
}
161         int firstIndex = tagMeta.indexOf("url=");
162         if (firstIndex == -1) {
163             System.out.println("WARNING: TagMeta does not have url=: " + tagMeta);
164             return tagMeta;
165         }
166         int lastIndex = tagMeta.indexOf("'", firstIndex + 4);
167
168         String JavaDoc begin = tagMeta.substring(0, firstIndex + 4);
169         String JavaDoc href = tagMeta.substring(firstIndex + 4, lastIndex);
170         String JavaDoc end = tagMeta.substring(lastIndex);
171
172 // System.out.println("begin = " + begin);
173
// System.out.println("action = " + href);
174
// System.out.println("end = " + end);
175

176         output = begin + convertURL(href) + end;
177
178         return output;
179     }
180
181     static String JavaDoc convertLine(String JavaDoc line, String JavaDoc startToken, String JavaDoc endToken) throws IllegalArgumentException JavaDoc {
182         int startIndex = -1;
183         int endIndex = -1;
184 outer:
185         while (true) {
186             startIndex = line.indexOf(startToken, endIndex + 1);
187             if (startIndex < 0 || startIndex + 1 >= line.length()) {
188                 break;
189             }
190             int beginSearchEndIndex = startIndex + 1;
191             while (true) {
192                 endIndex = line.indexOf(endToken, beginSearchEndIndex);
193                 if (endIndex < 0) break;
194                 char charBefore = line.charAt(endIndex - 1);
195                 if (charBefore == '%') {
196                     beginSearchEndIndex = endIndex + 1;
197                 } else {
198                     break;
199                 }
200             }
201             if (endIndex < 0) {
202                 break;
203             }
204             String JavaDoc matches = line.substring(startIndex, endIndex+1);
205             //log("match = " + matches + " resource = " + (String) resourceMap.get(matches), Project.MSG_WARN);
206
//If there is a white space or = or :, then
207
//it isn't to be treated as a valid key.
208
for (int k = 0; k < matches.length(); k++) {
209                 /*
210                 char c = matches.charAt(k);
211                 if (c == ':' ||
212                     c == '=' ||
213                     Character.isSpaceChar(c)) {
214                     endIndex = endIndex - 1;
215                     continue outer;
216                 }
217             */

218             }
219             String JavaDoc replace = null;
220             if (startToken.equals("<a ")) {
221                 replace = (String JavaDoc) convertTagA(matches);
222             } else if (startToken.equals("<form ")) {
223                 replace = (String JavaDoc) convertTagForm(matches);
224             } else if (startToken.equals("<meta ")) {
225                 replace = (String JavaDoc) convertTagMeta(matches);
226             } else {
227                 throw new IllegalArgumentException JavaDoc();
228             }
229
230             //If the key hasn't been loaded into resourceMap,
231
//use the key itself as the value also.
232
if (replace == null) {
233                 //log("Warning: The key: " + matches + " hasn't been defined.", Project.MSG_WARN);
234
replace = matches;
235             }
236             line = line.substring(0, startIndex)
237                 + replace
238                 + line.substring(endIndex + 1);
239             // minhnn: I dont know if the original code has bug
240
// I changed from "+ 1" to "- 1" and it works well
241
endIndex = startIndex + replace.length() - 1;
242             if (endIndex + 1 >= line.length()) {
243                 break;
244             }
245         }
246         return line;
247     }
248
249     static String JavaDoc convertLine(String JavaDoc line) throws Exception JavaDoc {
250         try {
251             String JavaDoc linewithA = convertLine(line, "<a ", ">");
252             String JavaDoc linewithAandForm = convertLine(linewithA, "<form ", ">");
253             String JavaDoc linewithAandFormAndMeta = convertLine(linewithAandForm, "<meta ", ">");
254             return linewithAandFormAndMeta;
255         } catch (Exception JavaDoc ex) {
256             System.out.println("line = " + line);
257             throw ex;
258         }
259     }
260
261     /**
262      * @todo: return ArrayList of String
263      */

264     public static ArrayList getContent(String JavaDoc fileName) {
265         ArrayList arrLine= new ArrayList();
266         File file = new File(fileName);
267         if (!file.exists()) {
268             return null;
269         } else {
270             try {
271                 BufferedReader reader = new BufferedReader(new FileReader(file));
272                 String JavaDoc inLine = reader.readLine();
273                 while (inLine != null) {
274                     arrLine.add(inLine + "\n");
275                     //content += inLine + "\n";
276
inLine = reader.readLine();
277                 }
278                 reader.close();
279                 return arrLine;
280             } catch (IOException e) {
281                 e.printStackTrace();
282                 return null;
283             }
284         }
285     }
286
287     public static void convertFile(String JavaDoc srcFilename, String JavaDoc descFilename)
288         throws Exception JavaDoc {
289         ArrayList descArr = new ArrayList();
290         Collection tempArr = getContent(srcFilename);
291         for (Iterator iterator = tempArr.iterator(); iterator.hasNext(); ) {
292             descArr.add(convertLine((String JavaDoc) iterator.next()));
293         }
294         ExportContentToFile(descArr, descFilename);
295     }
296
297     public static void ExportContentToFile(ArrayList lines, String JavaDoc fileName) {
298         String JavaDoc curDir = System.getProperty("user.dir"); //Get Current dir
299
try {
300             BufferedWriter out = new BufferedWriter(new FileWriter(curDir + "/out/" + fileName));
301             for (Iterator iterator = lines.iterator(); iterator.hasNext(); ) {
302                 //System.out.print(convertLine((String)iterator.next()));
303
out.write((String JavaDoc) iterator.next());
304             }
305             out.close();
306         } catch (IOException e) {
307             System.out.print(e);
308         }
309     }
310
311     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
312         //String href = "index";
313
//String href = "index?forum=<%=forumid%>&a=true";
314
//String correctOutput = "<%=response.encodeURL(context + \"index\")%>";
315

316 // String tagA = "<a HREF=\"index?forum=<%=forumid%>&a=true\" class=\"topmenu\">";
317
// String tagA = "<a HREF=\"listmembers\" class=\"topmenu\">";
318
// String tagA = "<a HREF=\"<%=filename%>\" class=\"topmenu\">";
319
// String tagA = "<a HREF=\"#\">";
320
// String tagA = "<a HREF=\"javascript:smilie('[:&quot;>]')\">";
321
// System.out.println("tagA = " + tagA);
322
// System.out.println("output = " + convertTagA(tagA));
323

324 // String tagMeta = "<meta http-equiv='refresh' content='3; url=viewthread?thread=<%= threadID %>&offset=<%=offset%>'>";
325
// System.out.println("tagMeta = " + tagMeta);
326
// System.out.println("output = " + convertTagMeta(tagMeta));
327

328 // String tagForm = "<form action=\"addattachmentprocess\" method=\"post\" enctype=\"multipart/form-data\" name=\"submitform\">";
329
// System.out.println("tagForm = " + tagForm);
330
// System.out.println("output = " + convertTagForm(tagForm));
331

332
333         //String line = "link 1 <a HREF=\"listmembers\" class=\"topmenu\"> link 2 <a HREF=\"index?forum=<%=forumid%>&a=true\" class=\"topmenu\"> form ne` <form action=\"addattachmentprocess\" method=\"post\" enctype=\"multipart/form-data\" name=\"submitform\">";
334
// String line = "<td><a HREF=\"javascript:smilie('[:&quot;&gt;]')\"><img SRC=\"<%=contextPath%>/mvnplugin/mvnforum/images/emotion/blushing.gif\" alt=\"blushing\" border=\"0\"></a>&nbsp;</td>";
335
// System.out.println("line = " + line);
336
// System.out.println("output = " + convertLine(line));
337
//convertFile("listmembers.jsp","b.txt");
338

339         //convertFile("listrecentthreads.jsp","listrecentthreads.jsp");
340

341         try {
342             if (args[0].equals("all")) {
343                 String JavaDoc curDir = System.getProperty("user.dir"); //Get Current dir
344
File dir = new File(curDir);
345                 if (dir.isFile()) throw new IOException("IOException -> BadInputException: not a directory.");
346                 File[] files = dir.listFiles();
347                 if (files != null) {
348                     for (int i = 0; i < files.length; i++) {
349                         File file = files[i];
350                         if (file.isFile()) {
351                             String JavaDoc absPath = file.getAbsolutePath();
352                             if (absPath.endsWith(".jsp")) {
353                                 int lastIndex = absPath.lastIndexOf('\\');
354                                 String JavaDoc name = absPath.substring(lastIndex + 1);
355                                 System.out.println("name = " + name);
356                                 convertFile(name, name);
357                             }
358                         } else {
359                             System.out.println("get folder = " + file);
360                         }
361                     }
362                 }//if
363
dir.delete();
364             } else {
365                 convertFile(args[0], args[0]);
366             }
367         } catch (Exception JavaDoc ex) {
368             ex.printStackTrace();
369         }
370     }
371 }
372
Popular Tags