001: package vicazh.hyperpool.stream.net.http;
002:
003: import java.io.*;
004: import java.util.*;
005: import java.net.*;
006:
007: /**
008: * This class implements an http client stream
009: *
010: * @author Victor Zhigunov
011: * @version 0.4.0
012: */
013: public class PathStream extends ClientStream {
014:
015: public PathStream() {
016: }
017:
018: /**
019: * @param session
020: * parent session
021: * @param outputstream
022: * linked output stream
023: */
024: public PathStream(Session session, OutputStream outputstream) {
025: super (session, outputstream);
026: }
027:
028: static public String[] getPath(String url)
029: throws MalformedURLException {
030: URL u = null;
031: try {
032: u = new URL(url);
033: } catch (MalformedURLException e) {
034: u = new URL("https://" + url);
035: }
036: List<String> list = new ArrayList<String>();
037: list.add(u.getProtocol());
038: list.add(u.getAuthority());
039: String s = u.getPath();
040: StringTokenizer st = new StringTokenizer(s, "/");
041: while (st.hasMoreTokens()) {
042: String t = st.nextToken();
043: if (t.equals(".."))
044: list.remove(list.size() - 1);
045: else if (!t.equals("."))
046: list.add(t);
047: }
048: String q = u.getQuery();
049: if (q != null)
050: if (s == "" || s.endsWith("/"))
051: list.add('?' + q);
052: else
053: list.set(list.size() - 1, list.get(list.size() - 1)
054: + '?' + q);
055: else if (s == "" || s.endsWith("/"))
056: list.add("index.html");
057: return list.toArray(new String[] {});
058: }
059:
060: /**
061: * The file path
062: */
063: public String[] path;
064:
065: public void head(String method, String file, String version)
066: throws IOException {
067: path = getPath(file);
068: super .head(method, file, version);
069: }
070:
071: /**
072: * Return url
073: *
074: * @param file
075: * the http file
076: */
077: public String getURL(String file) throws MalformedURLException {
078: String s;
079: try {
080: new URL(file);
081: s = file;
082: } catch (Exception e) {
083: if (file.startsWith("//"))
084: s = path[0] + ':' + file;
085: else {
086: s = path[0] + "://" + path[1];
087: if (file.startsWith("/"))
088: s += file;
089: else {
090: for (int i = 2; i < path.length - 1; i++)
091: s += '/' + path[i];
092: s += '/' + file;
093: }
094: }
095: }
096: String[] o = getPath(s);
097: int j = s.endsWith("/") ? o.length - 1 : o.length;
098: s = o[0] + "://" + o[1];
099: for (int i = 2; i < j; i++)
100: s += '/' + o[i];
101: return j == o.length ? s : s + '/';
102: }
103: }
|