001: /*
002: * <copyright>
003: *
004: * Copyright 1997-2004 BBNT Solutions, LLC
005: * under sponsorship of the Defense Advanced Research Projects
006: * Agency (DARPA).
007: *
008: * You can redistribute this software and/or modify it under the
009: * terms of the Cougaar Open Source License as published on the
010: * Cougaar Open Source Website (www.cougaar.org).
011: *
012: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
013: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
014: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
015: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
016: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
017: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
018: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
019: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
020: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
021: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
022: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
023: *
024: * </copyright>
025: */
026:
027: package org.cougaar.logistics.ui.inventory;
028:
029: import java.io.*;
030: import java.net.HttpURLConnection;
031: import java.net.MalformedURLException;
032: import java.net.URL;
033: import java.net.URLConnection;
034: import java.util.Hashtable;
035:
036: import org.cougaar.util.OptionPane;
037:
038: import org.cougaar.util.log.Logging;
039: import org.cougaar.util.log.Logger;
040:
041: import javax.swing.*;
042:
043: // This utility class could theoretically go in the util module.
044: // Note that this class is used in the datagrabber module,
045: // in the SD UI: RelationshipUILauncherFrame.java
046:
047: /**
048: * Creates connection between client and XML Plan Server.
049: */
050: public class ConnectionHelper {
051: private URL url;
052: private URLConnection connection;
053: static final String DebugPSP_package = "alpine/demo";
054: static final String DebugPSP_id = "DEBUG.PSP";
055: String clusterURL;
056: boolean isDebugPSP = false;
057:
058: private Logger logger;
059:
060: /**
061: * If you create a ConnectionHelper instance with 0 params. must
062: * call setConnection()... to intialize connection
063: **/
064: public ConnectionHelper() {
065: logger = Logging.getLogger(this );
066: }
067:
068: /**
069: Connects to the debug PSP at the specified cluster,
070: where cluster is specified by URL (host and port).
071: */
072:
073: public ConnectionHelper(String clusterURL)
074: throws MalformedURLException, IOException {
075: this (clusterURL, DebugPSP_package, DebugPSP_id);
076: isDebugPSP = true;
077: logger = Logging.getLogger(this );
078: }
079:
080: public ConnectionHelper(String clusterURL, String path)
081: throws MalformedURLException, IOException {
082: this .clusterURL = clusterURL;
083: logger = Logging.getLogger(this );
084: url = new URL(clusterURL + path);
085: connection = url.openConnection();
086: connection.setDoInput(true);
087: connection.setDoOutput(true);
088:
089: }
090:
091: /**
092: Connects to the specified PSP at the specified cluster,
093: where cluster is specified by URL (host and port).
094: */
095:
096: public ConnectionHelper(String clusterURL, String PSP_package,
097: String PSP_id) throws MalformedURLException, IOException {
098: this (clusterURL, PSP_package + "/" + PSP_id);
099: }
100:
101: public void setConnection(String completeURLString)
102: throws Exception {
103: if (connection != null) {
104: new RuntimeException(
105: "ConnectionHelper.connection already set!");
106: }
107: clusterURL = completeURLString; // messy -- but should be okay for now
108: url = new URL(completeURLString);
109: connection = url.openConnection();
110: connection.setDoInput(true);
111: connection.setDoOutput(true);
112: }
113:
114: /**
115: * getURL - returns URL for the connection
116: *
117: * @return URL for the connection
118: */
119: public URL getURL() {
120: return url;
121: }
122:
123: public void closeConnection() throws IOException {
124: getInputStream().close();
125: if (connection instanceof HttpURLConnection) {
126: ((HttpURLConnection) connection).disconnect();
127: }
128: }
129:
130: /**
131: Sends data on the connection.
132: */
133:
134: public void sendData(String s) throws IOException {
135: ((HttpURLConnection) connection).setRequestMethod("PUT");
136: PrintWriter pw = new PrintWriter(connection.getOutputStream());
137: pw.println(s);
138: pw.flush();
139: }
140:
141: /**
142: Returns input stream for the connection.
143: */
144:
145: public InputStream getInputStream() throws IOException {
146: return connection.getInputStream();
147: }
148:
149: public URLConnection getConnection() {
150: return connection;
151: }
152:
153: /**
154: Sends data and returns response in buffer.
155: */
156:
157: public byte[] getResponse() throws IOException {
158: ByteArrayOutputStream os = new ByteArrayOutputStream();
159: InputStream is = getInputStream();
160: byte b[] = new byte[512];
161: int len;
162: while ((len = is.read(b, 0, 512)) > -1)
163: os.write(b, 0, len);
164: return os.toByteArray();
165: }
166:
167: /**
168: Returns a list of cluster identifiers from the debug PSP
169: located at the cluster specified in this class's constructor.
170: */
171:
172: protected Hashtable getClusterIdsAndURLs(java.awt.Component parent,
173: String querySuffix, String agentPath, boolean addBackURLs)
174: throws MalformedURLException, ClassNotFoundException,
175: IOException {
176: Hashtable results = new Hashtable();
177:
178: /*
179: get host:port from clusterURL
180: open url connection to host:port/agents?all&text
181: get input stream from connection
182: wrap in BufferedReader
183: read lines of response into temporary ArrayLIst (get agent-names)
184: fill "results" with (agent-name, http://host:port/$ + agent-name + /)
185: return results
186:
187: */
188:
189: int p = clusterURL.lastIndexOf(":");
190: URL url = new URL(clusterURL + querySuffix);
191: //logger.debug(url.toString());
192: connection = null;
193: InputStream in;
194:
195: boolean triedLocal = false;
196:
197: while (results.isEmpty()) {
198: try {
199: connection = url.openConnection();
200: in = connection.getInputStream();
201: BufferedReader input = new BufferedReader(
202: new InputStreamReader(in));
203:
204: try {
205: if (addBackURLs) {
206: String iterPath = agentPath;
207: int dotIndex = iterPath.indexOf(".");
208: while ((dotIndex >= 0)
209: && (dotIndex + 1 < iterPath.length())) {
210: iterPath = iterPath.substring(dotIndex + 1);
211: String u = ((clusterURL.substring(0, p + 1))
212: + "8800/$." + iterPath + "/");
213: results.put("." + iterPath, u);
214: dotIndex = iterPath.indexOf(".");
215: }
216: results.put(".", ((clusterURL.substring(0,
217: p + 1)) + "8800/$./"));
218: }
219:
220: while (input != null) {
221: String n = input.readLine();
222: if (n == null)
223: break;
224: String u = ((clusterURL.substring(0, p + 1))
225: + "8800/$" + n + "/");
226: //logger.debug(u);
227: results.put(n, u);
228: }
229: input.close();
230: } catch (IOException e) {
231: if (logger.isErrorEnabled()) {
232: logger.error("Error reading agent list: "
233: + e.getMessage());
234: }
235: }
236: } catch (IOException e) {
237: if (logger.isErrorEnabled()) {
238: logger.error("Error reaching agents list: "
239: + e.getMessage());
240: }
241:
242: if ((results.isEmpty()) && (!triedLocal)) {
243: int yesOrNo = JOptionPane
244: .showConfirmDialog(
245: parent,
246: "Could not connect to gather all Society Organizations. Try local servlet?",
247: "Warning",
248: JOptionPane.YES_NO_CANCEL_OPTION,
249: JOptionPane.WARNING_MESSAGE);
250:
251: if (yesOrNo == JOptionPane.YES_OPTION) {
252: url = new URL(clusterURL + querySuffix);
253: triedLocal = true;
254: continue;
255: }
256: }
257: }
258: break;
259: }
260:
261: return results;
262: }
263:
264: /**
265: Returns a list of cluster identifiers from the debug PSP
266: located at the cluster specified in this class's constructor.
267: */
268:
269: public Hashtable getClusterIdsAndURLs(java.awt.Component parent,
270: String agentPath) throws MalformedURLException,
271: ClassNotFoundException, IOException {
272: return getClusterIdsAndURLs(parent,
273: "agents?format=text&suffix=" + agentPath, agentPath,
274: true);
275:
276: }
277:
278: /**
279: Returns a list of cluster identifiers from the debug PSP
280: located at the cluster specified in this class's constructor.
281: */
282:
283: public Hashtable getAllClusterIdsAndURLs(java.awt.Component parent)
284: throws MalformedURLException, ClassNotFoundException,
285: IOException {
286: return getClusterIdsAndURLs(parent, "agents?format=text", ".",
287: false);
288: }
289:
290: /**
291: * getClusterInfo - get the location of the cluster
292: * Only used when running in an application
293: */
294: public static String getClusterHostPort(java.awt.Component parent) {
295: return getClusterHostPort(parent,
296: "Enter location of a cluster.", "localhost", "8800");
297: }
298:
299: public static String getClusterHostPort(java.awt.Component parent,
300: Object msgString, String host, String port) {
301: return (String) OptionPane.showInputDialog(parent, msgString,
302: "Cluster Location", OptionPane.QUESTION_MESSAGE,
303: //null, null, "localhost:5555");
304: null, null, "http://" + host + ":" + port);
305:
306: }
307:
308: public static Hashtable getClusterInfo(java.awt.Component parent) {
309: return getClusterInfo(parent, "Enter location of a cluster.",
310: "localhost", "8800");
311: }
312:
313: public static Hashtable getClusterInfo(java.awt.Component parent,
314: Object msg, String hostName, String port) {
315: String host = getClusterHostPort(parent, msg, hostName, port);
316: if (host == null) {
317: return null;
318: }
319: try {
320: host = host.trim();
321: if (host.length() == 0) {
322: //host = "localhost:5555";
323: host = "http://" + "localhost:8800";
324: } else {
325: if (host.indexOf(':') < 0) {
326: //host += ":5555";
327: host += ":8800";
328: }
329: }
330: ConnectionHelper connection = new ConnectionHelper(host
331: + "/");
332: return connection.getClusterIdsAndURLs(parent, ".");
333: } catch (Exception e) {
334: return null;
335: }
336: }
337: }
|