Source Code Cross Referenced for HTTPTools.java in  » Database-ORM » Speedo_1.4.5 » org » objectweb » speedo » j2eedo » common » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database ORM » Speedo_1.4.5 » org.objectweb.speedo.j2eedo.common 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Speedo: an implementation of JDO compliant personality on top of JORM generic
003:         * I/O sub-system.
004:         * Copyright (C) 2001-2004 France Telecom R&D
005:         *
006:         * This library is free software; you can redistribute it and/or
007:         * modify it under the terms of the GNU Lesser General Public
008:         * License as published by the Free Software Foundation; either
009:         * version 2 of the License, or (at your option) any later version.
010:         *
011:         * This library is distributed in the hope that it will be useful,
012:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
013:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014:         * Lesser General Public License for more details.
015:         *
016:         * You should have received a copy of the GNU Lesser General Public
017:         * License along with this library; if not, write to the Free Software
018:         * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
019:         *
020:         *
021:         */
022:        package org.objectweb.speedo.j2eedo.common;
023:
024:        import java.io.BufferedReader;
025:        import java.io.InputStreamReader;
026:        import java.io.OutputStream;
027:        import java.net.HttpURLConnection;
028:        import java.net.URL;
029:        import java.net.URLConnection;
030:        import java.util.Enumeration;
031:        import java.util.Hashtable;
032:        import java.util.StringTokenizer;
033:
034:        import org.objectweb.util.monolog.api.BasicLevel;
035:        import org.objectweb.util.monolog.api.Logger;
036:
037:        /**
038:         * This class provides with a simple method to perform some HTTP requests
039:         * @author fmillevi@yahoo.com
040:         */
041:        public class HTTPTools {
042:            static String redirectURL;
043:
044:            /**
045:             * Liste des cookies
046:             */
047:            static Hashtable cookies = null;
048:            static TraceTime traceTime = new TraceTime();
049:
050:            /**
051:             * Method getURL. This static method provides with the way to get and http response.
052:             *
053:             * @param urlString is the URL to be invoked
054:             * @param paramString is the list of parameters like
055:             *            param1=value1&param2=value2&param3=....
056:             * @param method POST or GET
057:             * @return String flux HTTP de retour.
058:             * @throws Exception when the getURL method fails due to unfound URL, or server errors
059:             */
060:            public static String getURL(String urlString, String paramString,
061:                    String method, Logger logger) throws Exception {
062:                if (cookies == null) // C'est la premiere connection.
063:                {
064:                    // create the hashtable used to store cookies values
065:                    cookies = new Hashtable();
066:                    //getURL(urlString, paramString, method, logger);
067:                }
068:
069:                String s = "Ok"; // return string
070:
071:                try {
072:                    if (!method.equalsIgnoreCase("post")
073:                            && !paramString.equals("")) {
074:                        urlString = urlString + "?" + paramString;
075:                    }
076:
077:                    URL url = new URL(urlString);
078:
079:                    traceTime.startTask("openConnection");
080:                    HttpURLConnection conn = (HttpURLConnection) url
081:                            .openConnection();
082:                    traceTime.endTask();
083:
084:                    //String userPassword = "xxxx:yyyy";
085:                    //String encoding =
086:                    //	new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
087:                    //conn.setRequestProperty("Authorization", encoding);
088:                    //conn.setRequestProperty("Authorization", "Basic " + encoding);
089:                    conn.setRequestProperty("accept-language", "fr");
090:                    conn
091:                            .setRequestProperty("user-agent",
092:                                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)");
093:
094:                    conn.setRequestProperty("connection", "Keep-Alive");
095:                    //conn.setRequestProperty ("accept-encoding", "gzip, deflate");
096:
097:                    //accept http redirections
098:                    HttpURLConnection.setFollowRedirects(false);
099:                    //conn.setAllowUserInteraction(false);
100:                    conn.setUseCaches(false);
101:
102:                    setCookies(conn);
103:
104:                    if (method.equalsIgnoreCase("post")) {
105:                        traceTime.startTask("set post parameters");
106:                        byte[] bytes = paramString.getBytes();
107:                        conn.setDoOutput(true);
108:                        conn.setDoInput(true);
109:                        conn.setRequestMethod("POST");
110:                        conn.setRequestProperty("Content-length", String
111:                                .valueOf(bytes.length));
112:                        OutputStream out = conn.getOutputStream();
113:                        out.write(bytes);
114:                        out.flush();
115:                        traceTime.endTask();
116:                    }
117:
118:                    traceTime.startTask("getResponseCode");
119:                    s = "" + conn.getResponseCode();
120:                    traceTime.endTask();
121:
122:                    if (conn.getResponseCode() != 200
123:                            && conn.getResponseCode() != 302) {
124:                        logger.log(BasicLevel.ERROR, "error "
125:                                + conn.getResponseCode());
126:                    } else if (conn.getResponseCode() == 200) { //parse HTML response
127:                        //read HTML response
128:                        BufferedReader is = new BufferedReader(
129:                                new InputStreamReader(conn.getInputStream()));
130:                        String line = null;
131:                        StringBuffer sourceTxt = new StringBuffer("");
132:                        while ((line = is.readLine()) != null)
133:                            sourceTxt.append(line);
134:                        is.close();
135:                        s = sourceTxt.toString();
136:                    }
137:                    getCookies(conn);
138:                    logger.log(BasicLevel.DEBUG, urlString + "\treturns:"
139:                            + conn.getResponseCode() + " ");
140:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
141:                        logger.log(BasicLevel.DEBUG, traceTime.report());
142:                    }
143:
144:                    while (s.equals("302")) {
145:                        s = getURL(redirectURL, "", "", logger);
146:                    }
147:
148:                    if (conn.getResponseCode() == 500)
149:                        throw new Exception("the URL " + url + " fails.");
150:
151:                    if (conn.getResponseCode() == 404)
152:                        throw new Exception("the URL " + url + " not found.");
153:
154:                } catch (Exception ex) {
155:                    s = "";
156:                    logger.log(BasicLevel.DEBUG, urlString
157:                            + " throws Execption!", ex);
158:                    throw ex;
159:                } finally {
160:                    traceTime.reset();
161:                }
162:
163:                return s;
164:            }
165:
166:            /**
167:             * Method getCookies. Gets and stores in the Hashtable the cookies values found in the HTTP response.
168:             *
169:             * @param con HTTP Connexion
170:             */
171:            private static void getCookies(HttpURLConnection con) {
172:                int n = 1;
173:
174:                label0: for (boolean done = false; !done; n++) {
175:                    String headerKey = con.getHeaderFieldKey(n);
176:                    String headerVal = con.getHeaderField(n);
177:                    if (headerKey != null || headerVal != null) {
178:                        if ("location".equalsIgnoreCase(headerKey)) {
179:                            redirectURL = headerVal;
180:                        }
181:                        if (!"Set-Cookie".equals(headerKey))
182:                            continue;
183:                        StringTokenizer st = new StringTokenizer(headerVal, ";");
184:                        do {
185:                            if (!st.hasMoreTokens())
186:                                continue label0;
187:                            String pair = st.nextToken();
188:                            StringTokenizer stt = new StringTokenizer(pair, "=");
189:                            while (stt.hasMoreTokens()) {
190:                                String cookName = stt.nextToken();
191:                                String cookValue = "";
192:                                try {
193:                                    cookValue = stt.nextToken();
194:                                } catch (Exception exception) {
195:                                }
196:                                if (!cookName.trim().equalsIgnoreCase("path")
197:                                        && !cookName.trim().equalsIgnoreCase(
198:                                                "expires")) {
199:                                    //System.out.println("Set cookie :" + cookName +
200:                                    // ":" + cookValue);
201:                                    cookies.put(cookName.trim(), cookValue);
202:                                }
203:                            }
204:                        } while (true);
205:                    }
206:                    done = true;
207:                }
208:            }
209:
210:            /**
211:             * Method setCookies initialize the cookies values in the http request
212:             * using the values found in the Hashtable
213:             *
214:             * @param con HTTP Connexion
215:             */
216:            private static void setCookies(URLConnection con) {
217:                Enumeration en = cookies.keys();
218:                String cookieString;
219:                String key = "";
220:                String val = "";
221:                for (cookieString = ""; en.hasMoreElements(); cookieString = cookieString
222:                        + (key + "=" + val + ";")) {
223:                    key = (String) en.nextElement();
224:                    val = (String) cookies.get(key);
225:                }
226:                //System.out.println("Init cookies :" + cookieString);
227:                con.setRequestProperty("Cookie", cookieString);
228:            }
229:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.