001: /*
002: * submitServlet.java
003: *
004: * Created on August 8, 2002, 11:14 AM
005: */
006:
007: package com.sun.im.portal.servlet;
008:
009: import javax.servlet.*;
010: import javax.servlet.http.*;
011: import java.io.*;
012: import java.util.*;
013: import java.util.logging.Logger;
014: import java.util.logging.Level;
015: import java.net.*;
016: import com.iplanet.am.util.*;
017: import com.sun.portal.log.common.PortalLogger;
018:
019: /**
020: *
021: * @author Rahul
022: * @version
023: */
024:
025: public class submitServlet extends HttpServlet {
026:
027: class Timer extends Thread {
028:
029: long RDMGR_TIMER = 2 * 60 * 1000;
030:
031: Timer(long time) {
032: RDMGR_TIMER = time;
033: }
034:
035: Timer() {
036: }
037:
038: public void run() {
039: debugLogger.log(Level.FINER, "PSIC_CSIPS0001", Long
040: .toString(RDMGR_TIMER));
041: while (true) {
042: String cmd;
043: try {
044: debugLogger.finer("PSIC_CSIPS0002");
045: retry(" -V ", indexFile, INDEX_RETRIES);
046: retry(" -d ", deleteFile, DELETE_RETRIES);
047: } catch (Exception e) {
048: debugLogger.log(Level.INFO, "PSIC_CSIPS0003", e);
049: } finally {
050: try {
051: Thread.sleep(RDMGR_TIMER);
052: } catch (InterruptedException e) {
053: debugLogger
054: .log(Level.INFO, "PSIC_CSIPS0004", e);
055: }
056: }
057: }
058: }
059: }
060:
061: static String baseDir, instancePath;
062: java.io.PrintWriter out;
063:
064: static String RDMGR;
065: static Timer t;
066:
067: static String logFile = "IMArchiveSubmit.log";
068:
069: static String submitFile;
070: static String indexFile;
071: static String deleteFile;
072:
073: static final int SUBMIT_RETRIES = 3;
074: static final int INDEX_RETRIES = 3;
075: static final int DELETE_RETRIES = 3;
076:
077: static String CGI_URL = null;
078:
079: // Create a logger for this class
080: private static Logger debugLogger = PortalLogger
081: .getLogger("com.sun.portal.im.servlet");
082:
083: /** Initializes the servlet.
084: */
085: public void init(ServletConfig config) throws ServletException {
086: super .init(config);
087: String serverInstance = com.iplanet.am.util.SystemProperties
088: .get("com.iplanet.am.server.host");
089: try {
090: baseDir = getServletContext().getInitParameter(
091: "portal.base.dir");
092: instancePath = getServletContext().getInitParameter(
093: "server.root") + '/';
094: String productDir = getServletContext().getInitParameter(
095: "portal.product.dir");
096: RDMGR = instancePath + "run-cs-cli " + baseDir + '/'
097: + productDir + "/bin/rdmgr";
098: submitFile = instancePath + "logs/IMArchiveSubmit.soif";
099: indexFile = instancePath + "logs/IMArchiveIndex.soif";
100: deleteFile = instancePath + "logs/IMArchiveDelete.soif";
101:
102: t = new Timer();
103: t.start();
104: } catch (Exception e) {
105: debugLogger.log(Level.INFO, "PSIC_CSIPS0004", e);
106: }
107: }
108:
109: private void retry(String cmd, String file, int N) throws Exception {
110: retry(cmd, file, N, false);
111: }
112:
113: /** Runs the cmd. If the cmd fails then it retries it for N times.
114: */
115: private void retry(String arg, String file, int N, boolean submit)
116: throws Exception {
117: for (int i = N; i >= 0; i--) {
118: File f;
119: if (i == 0) {
120: if (!(new File(file)).exists())
121: continue;
122: else
123: debugLogger
124: .log(Level.FINER, "PSIC_CSIPS0005", file);
125: f = File.createTempFile("RDs", null);
126: append(file, f.getAbsolutePath(), true);
127: } else {
128: if (!(new File(file + ".try" + i)).exists())
129: continue;
130: else
131: debugLogger.log(Level.FINER, "PSIC_CSIPS0006",
132: new Object[] { file, Integer.toString(i) });
133: f = File.createTempFile("RDs", null);
134: append(file + ".try" + i, f.getAbsolutePath(), true);
135: }
136: int exitValue = 0;
137: if (CGI_URL != null) {
138: exitValue = callCGI(URLEncoder.encode(arg
139: + f.getAbsolutePath()));
140: } else {
141: Process p = Runtime.getRuntime().exec(
142: RDMGR + arg + f.getAbsolutePath());
143: p.waitFor();
144: exitValue = p.exitValue();
145: }
146: if (exitValue != 0) {
147: debugLogger.finer("PSIC_CSIPS0007");
148: if (i == N) {
149: append(f.getAbsolutePath(), file + ".corrupted",
150: true);
151: debugLogger.finer("PSIC_CSIPS0008");
152: } else {
153: append(f.getAbsolutePath(),
154: file + ".try" + (i + 1), true);
155: debugLogger.log(Level.FINER, "PSIC_CSIPS0009",
156: Integer.toString((i + 1)));
157: }
158: } else {
159: if (submit) {
160: append(f.getAbsolutePath(), indexFile, true);
161: } else
162: f.delete();
163: }
164: }
165: }
166:
167: /** Append the contents of source to the destination
168: *@param source source file name
169: *@param destination destination file name. If the destination file is not present then it will be created.
170: *@param delete true if the source file is to be deleted after append. false otherwise.
171: */
172: private synchronized void append(String source, String destination,
173: boolean delete) {
174: try {
175: File sourceFile = new File(source);
176: if (!sourceFile.exists())
177: return;
178: FileOutputStream fos = new FileOutputStream(destination,
179: true);
180: byte[] b = readFile(sourceFile);
181: if (b != null)
182: fos.write(b);
183: if (delete)
184: sourceFile.delete();
185: } catch (Exception e) {
186: debugLogger.log(Level.INFO, "PSIC_CSIPS0004", e);
187: }
188: }
189:
190: /** Calls the cgi script instead of directly calling rdmgr.
191: */
192: private int callCGI(String arg) {
193: try {
194: HttpURLConnection conn = openConnection(arg);
195: BufferedReader inStream = new BufferedReader(
196: new InputStreamReader(conn.getInputStream(),
197: "UTF-8"));
198: String currentLine = null;
199: while (null != (currentLine = inStream.readLine())) {
200: debugLogger.log(Level.FINER, "PSIC_CSIPS0010",
201: currentLine);
202: if (currentLine.equals("Error")) {
203: debugLogger.finer("PSIC_CSIPS0011");
204: return 1;
205: }
206: }
207: inStream.close();
208: inStream = null;
209: } catch (Exception e) {
210: debugLogger.log(Level.INFO, "PSIC_CSIPS0012", e);
211: return 1;
212: }
213: return 0;
214: }
215:
216: /** Opens the URL connection.
217: */
218: private HttpURLConnection openConnection(String arg)
219: throws Exception {
220: URL url = new URL(CGI_URL + "?" + arg);
221: debugLogger.log(Level.FINER, "PSIC_CSIPS0013", url.toString());
222: HttpURLConnection conn = (HttpURLConnection) url
223: .openConnection();
224: conn.setDoOutput(true);
225: conn.setDoInput(true);
226: DataOutputStream outStream = null;
227: outStream = new DataOutputStream(conn.getOutputStream());
228: outStream.writeBytes("\r\n");
229: if (outStream != null)
230: outStream.close();
231: outStream = null;
232: conn.connect();
233: return conn;
234: }
235:
236: /** Destroys the servlet.
237: */
238: public void destroy() {
239:
240: }
241:
242: // needs to be same exact string as in IMPSArchive.java
243: private static String BOUNDARY = "\r\n-----------------------------soimsoif--\r\n";
244:
245: /** Processes requests for both HTTP <code>GET</code> and
246: * <code>POST</code> methods.
247: * @param request servlet request
248: * @param response servlet response
249: */
250: protected void processRequest(HttpServletRequest request,
251: HttpServletResponse response) throws ServletException,
252: java.io.IOException {
253: PrintWriter out = response.getWriter();
254: InputStream is;
255: boolean mimeBody = false;
256: try {
257: long startTime = System.currentTimeMillis();
258: String urlData = request.getParameter("data");
259: String operation = request.getParameter("op");
260: if (operation == null) {
261: operation = "";
262: mimeBody = true;
263: }
264: String user = request.getParameter("user");
265: if (user == null)
266: user = "";
267:
268: if (!mimeBody) {
269: debugLogger.log(Level.FINER, "PSIC_CSIPS0014",
270: new Object[] { urlData, operation, user });
271: }
272:
273: // read the data from the body - skip mime headers
274: is = request.getInputStream();
275:
276: debugLogger.log(Level.FINER, "PSIC_CSIPS0015", Integer
277: .toString(request.getContentLength()));
278:
279: String cmd = "";
280: if ((operation.equals("get"))
281: || (operation.equals("removeacl"))) {
282: BufferedReader in;
283: if (CGI_URL != null) {
284: HttpURLConnection conn = openConnection(URLEncoder
285: .encode("-Q " + urlData));
286: in = new BufferedReader(new InputStreamReader(conn
287: .getInputStream(), "UTF-8"));
288: } else {
289: String[] cmdArray = { instancePath + "run-cs-cli",
290: RDMGR, "-Q", urlData };
291: Process p = Runtime.getRuntime().exec(cmdArray);
292: p.waitFor();
293: in = new BufferedReader(new InputStreamReader(p
294: .getInputStream(), "UTF-8"));
295: }
296: StringBuffer str = new StringBuffer();
297: for (;;) {
298: String line = in.readLine();
299: if (line == null)
300: break;
301: if (!((operation.equals("removeacl")) && (line
302: .indexOf(user) != -1))) {
303: str.append(line);
304: str.append("\n");
305: }
306: }
307:
308: if (operation.equals("get")) {
309: out.println(str.toString());
310: return;
311: } else {
312: // removeacl
313: is = new ByteArrayInputStream(str.toString()
314: .getBytes("UTF-8"));
315: operation = "";
316: // fall through so that the RD gets updated
317: }
318: }
319:
320: if (operation.equals("runrdmgr")) {
321: t.RDMGR_TIMER = Long.parseLong(urlData.trim());
322: if (!t.isAlive())
323: t.start();
324:
325: }
326: if (operation.equals("cgiurl")) {
327: CGI_URL = urlData.trim();
328: } else {
329:
330: String filename;
331: if (operation.equals("delete")) {
332: filename = deleteFile;
333: } else {
334: filename = submitFile;
335: }
336:
337: // skip MIME headers
338: byte[] b = new byte[1024];
339: if (mimeBody) {
340: ((ServletInputStream) is).readLine(b, 0, 1024); // boundary
341: ((ServletInputStream) is).readLine(b, 0, 1024); // content-type
342: ((ServletInputStream) is).readLine(b, 0, 1024); // content-disposition
343: ((ServletInputStream) is).readLine(b, 0, 1024); // blank line
344: }
345:
346: FileOutputStream soifos = new FileOutputStream(
347: filename, true);
348: int offset = 0;
349: for (;;) {
350: int len = 0;
351: try {
352: // we can get an IOException on EOF
353: len = is.available();
354: } catch (Exception e) {
355: debugLogger.log(Level.FINER, "PSIC_CSIPS0016",
356: new Object[] { e.toString(),
357: Integer.toString(offset) });
358: break; // EOF
359: }
360: if (len <= 0)
361: break;
362:
363: len = is.read(b, offset, 1024 - offset);
364: debugLogger.log(Level.FINER, "PSIC_CSIPS0017",
365: Integer.toString(len));
366: //message(new String(b, offset, len));
367:
368: // if mime body, do not copy closing MIME boundary
369: // leave out as many bytes
370: int wlen = len;
371: if (mimeBody) {
372: wlen = len + offset - BOUNDARY.length();
373: if (wlen < 0)
374: wlen = 0;
375: }
376:
377: if (wlen > 0) {
378: soifos.write(b, 0, wlen);
379: debugLogger.log(Level.FINER, "PSIC_CSIPS0018",
380: Integer.toString(wlen));
381: //message(new String(b, 0, wlen));
382: }
383:
384: if (mimeBody && wlen > 0) {
385: int i;
386: // shift the non-copied data to the beginning of the buffer
387: for (i = 0; i < len + offset - wlen; i++) {
388: b[i] = b[i + wlen];
389: }
390: offset = i;
391: debugLogger.log(Level.FINER, "PSIC_CSIPS0019",
392: Integer.toString(offset));
393: //message(new String(b, 0, offset));
394: }
395: // need to remove end boundary
396: }
397: soifos.close();
398:
399: retry(" -D ", submitFile, SUBMIT_RETRIES, true);
400: }
401:
402: out.println("Operation completed Successfully");
403: debugLogger
404: .log(
405: Level.FINER,
406: "PSIC_CSIPS0020",
407: Long
408: .toString((System
409: .currentTimeMillis() - startTime)));
410: } catch (Exception e) {
411: out.println("Error");
412: debugLogger.log(Level.INFO, "PSIC_CSIPS0021", e);
413: }
414: }
415:
416: private synchronized static byte[] readFile(File f)
417: throws Exception {
418: if (!f.exists())
419: return null;
420: byte[] b = new byte[(int) f.length()];
421: FileInputStream is = new FileInputStream(f);
422: int len = is.read(b);
423: //debugLogger.log(Level.FINER, "PSIC_CSIPS0022", String.valueOf(len));
424: is.close();
425: return b;
426: }
427:
428: /** Handles the HTTP <code>GET</code> method.
429: * @param request servlet request
430: * @param response servlet response
431: */
432: protected void doGet(HttpServletRequest request,
433: HttpServletResponse response) throws ServletException,
434: java.io.IOException {
435: processRequest(request, response);
436: }
437:
438: /** Handles the HTTP <code>POST</code> method.
439: * @param request servlet request
440: * @param response servlet response
441: */
442: protected void doPost(HttpServletRequest request,
443: HttpServletResponse response) throws ServletException,
444: java.io.IOException {
445: processRequest(request, response);
446: }
447:
448: /** Returns a short description of the servlet.
449: */
450: public String getServletInfo() {
451: return "Submits the resource descriptors to the portal server search database";
452: }
453:
454: }
|