/**
  * Returns true if the nonce was generated usig <code>generateNonce</code> and if this is the
  * first check for that nonce.
  *
  * @param nonce the nonce to be checked
  * @return true if the nonce if the nonce was generated and this is the first check for that nonce
  */
 public boolean isValidNonce(String nonce) {
   Long time = nonceCache.remove(nonce);
   if (time == null) {
     return false;
   }
   return System.currentTimeMillis() - time < JiveConstants.MINUTE;
 }
Example #2
0
  private String ReadWholeFileToString(String filename) {

    File file = new File(filename);
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // show file contents here
    return contents.toString();
  }
  protected void setUp() {

    Map<String, String> envs = System.getenv();
    Set<String> keys = envs.keySet();

    Iterator<String> it = keys.iterator();
    boolean hashost = false;
    while (it.hasNext()) {
      String key = (String) it.next();

      if (key.compareTo(HOSTVAR) == 0) {
        SLING_URL = SLING_URL + (String) envs.get(key);
        hashost = true;
      }
    }

    if (hashost == false) SLING_URL = SLING_URL + HOSTPREDEF;

    client = new HttpClient();
    title = "IT col";
    schema = "default";
    slug = "it_col";
    subtitle = "subtitle it";
    extern_storage = "on";

    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    PostMethod post_create = new PostMethod(SLING_URL + COLLECTION_URL + slug);

    post_create.setDoAuthentication(true);

    NameValuePair[] data_create = {
      new NameValuePair("sling:resourceType", "gad/collection"),
      new NameValuePair("title", title),
      new NameValuePair("schema", schema),
      new NameValuePair("subtitle", subtitle),
      new NameValuePair("extern_storage", extern_storage),
      new NameValuePair("picture", ""),
      new NameValuePair("jcr:created", ""),
      new NameValuePair("jcr:createdBy", ""),
      new NameValuePair("jcr:lastModified", ""),
      new NameValuePair("jcr:lastModifiedBy", "")
    };
    post_create.setRequestBody(data_create);

    try {
      client.executeMethod(post_create);
    } catch (HttpException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    post_create.releaseConnection();
  }
 /**
  * Generates a new nonce. The <code>isValidNonce</code> method will return true when using nonces
  * generated by this method.
  *
  * @return a unique nonce
  */
 public String generateNonce() {
   String nonce = String.valueOf(nonceGenerator.nextLong());
   nonceCache.put(nonce, System.currentTimeMillis());
   return nonce;
 }
 public String getFiveDigitRandomNo() {
   Random r = new Random(System.currentTimeMillis());
   int tempRandomVal = 10000 + r.nextInt(20000);
   return String.valueOf(tempRandomVal);
 }
Example #6
0
  /**
   * @param since last modified time to use
   * @param req
   * @param url if null, ignored
   * @param redirCount number of redirs we've done
   */
  public static HttpData getDataOnce(
      HttpServletRequest req,
      HttpServletResponse res,
      long since,
      String surl,
      int redirCount,
      int timeout)
      throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.

      if (res != null) {
        res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
        }
    */

    try {

      // TODO: [2002-01-09 bloch] cope with cache-control
      // response headers (no-store, no-cache, must-revalidate,
      // proxy-revalidate).

      if (surl == null) {
        surl = getURL(req);
      }
      if (surl == null || surl.equals("")) {
        throw new MalformedURLException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="url is empty or null"
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-312"));
      }

      String reqType = "";
      String headers = "";

      if (req != null) {
        reqType = req.getParameter("reqtype");
        headers = req.getParameter("headers");
      }

      boolean isPost = false;
      mLogger.debug("reqtype = " + reqType);

      if (reqType != null && reqType.equals("POST")) {
        request = new LZPostMethod();
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        isPost = true;
        mLogger.debug("setting POST req method");
      } else if (reqType != null && reqType.equals("PUT")) {
        request = new LZPutMethod();
        // todo [hqm 2007] treat PUT like POST?
        isPost = true;
        mLogger.debug("setting PUT req method");
      } else if (reqType != null && reqType.equals("DELETE")) {
        request = new LZDeleteMethod();
        mLogger.debug("setting DELETE req method");
      } else {
        mLogger.debug("setting GET (default) req method");
        request = new LZGetMethod();
      }

      request.setHttp11(mUseHttp11);

      // Proxy the request headers
      if (req != null) {
        LZHttpUtils.proxyRequestHeaders(req, request);
      }

      // Set headers from query string
      if (headers != null && headers.length() > 0) {
        StringTokenizer st = new StringTokenizer(headers, "\n");
        while (st.hasMoreTokens()) {
          String h = st.nextToken();
          int i = h.indexOf(":");
          if (i > -1) {
            String n = h.substring(0, i);
            String v = h.substring(i + 2, h.length());
            request.setRequestHeader(n, v);
            mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting header " + p[0] + "=" + p[1]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-359", new Object[] {n, v}));
          }
        }
      }

      mLogger.debug("Parsing url");
      URI uri = LZHttpUtils.newURI(surl);
      try {
        hcfg.setHost(uri);
      } catch (Exception e) {
        throw new MalformedURLException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="can't form uri from " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-376", new Object[] {surl}));
      }

      // This gets us the url-encoded (escaped) path and query string
      String path = uri.getEscapedPath();
      String query = uri.getEscapedQuery();
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="encoded path:  " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-389", new Object[] {path}));
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="encoded query: " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-397", new Object[] {query}));

      // This call takes a decoded (unescaped) path
      request.setPath(path);

      boolean hasQuery = (query != null && query.length() > 0);

      String rawcontent = null;
      // Newer rawpost protocol puts lzpostbody as a separate
      // top level query arg in the request.
      rawcontent = req.getParameter("lzpostbody");

      if (isPost) {
        // Older rawpost protocol put the "lzpostbody" arg
        // embedded in the "url" args's query args
        if (rawcontent == null && hasQuery) {
          rawcontent = findQueryArg("lzpostbody", query);
        }
        if (rawcontent != null) {
          // Get the unescaped query string
          ((EntityEnclosingMethod) request).setRequestBody(rawcontent);
        } else if (hasQuery) {
          StringTokenizer st = new StringTokenizer(query, "&");
          while (st.hasMoreTokens()) {
            String it = st.nextToken();
            int i = it.indexOf("=");
            if (i > 0) {
              String n = it.substring(0, i);
              String v = it.substring(i + 1, it.length());
              // POST encodes values during request
              ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
            } else {
              mLogger.warn(
                  /* (non-Javadoc)
                   * @i18n.test
                   * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                   */
                  org.openlaszlo.i18n.LaszloMessages.getMessage(
                      HTTPDataSource.class.getName(), "051018-429", new Object[] {it}));
            }
          }
        }
      } else {
        // This call takes an encoded (escaped) query string
        request.setQueryString(query);
      }

      // Put in the If-Modified-Since headers
      if (since != -1) {
        String lms = LZHttpUtils.getDateString(since);
        request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="proxying lms: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-450", new Object[] {lms}));
      }

      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="setting up http client"
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-460"));
      HttpClient htc = null;
      if (mConnectionMgr != null) {
        htc = new HttpClient(mConnectionMgr);
      } else {
        htc = new HttpClient();
      }

      htc.setHostConfiguration(hcfg);

      // This is the data timeout
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="timeout set to " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-478", new Object[] {new Integer(timeout)}));
      htc.setTimeout(timeout);

      // Set connection timeout the same
      htc.setConnectionTimeout(mConnectionTimeout);

      // Set timeout for getting a connection
      htc.setHttpConnectionFactoryTimeout(mConnectionPoolTimeout);

      // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
      if (!isPost) {
        request.setFollowRedirects(mFollowRedirects > 0);
      }

      long t1 = System.currentTimeMillis();
      mLogger.debug("starting remote request");
      int rc = htc.executeMethod(hcfg, request);
      String status = HttpStatus.getStatusText(rc);
      if (status == null) {
        status = "" + rc;
      }
      mLogger.debug(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="remote response status: " + p[0]
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(), "051018-504", new Object[] {status}));

      HttpData data = null;
      if (isRedirect(rc) && mFollowRedirects > redirCount) {
        String loc = request.getResponseHeader("Location").toString();
        String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
        mLogger.info(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="Following URL from redirect: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-517", new Object[] {hostURI}));
        long t2 = System.currentTimeMillis();
        if (timeout > 0) {
          timeout -= (t2 - t1);
          if (timeout < 0) {
            throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-529", new Object[] {surl, loc}));
          }
        }

        data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
      } else {
        data = new HttpData(request, rc);
      }

      if (req != null && res != null) {
        // proxy response headers
        LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
      }

      return data;

    } catch (ConnectTimeoutException ce) {
      // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
      if (request != null) {
        request.releaseConnection();
      }
      throw new InterruptedIOException(
          /* (non-Javadoc)
           * @i18n.test
           * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
           */
          org.openlaszlo.i18n.LaszloMessages.getMessage(
              HTTPDataSource.class.getName(),
              "051018-557",
              new Object[] {
                hcfg.getHost(), new Integer(hcfg.getPort()), new Integer(mConnectionTimeout)
              }));
    } catch (HttpRecoverableException hre) {
      if (request != null) {
        request.releaseConnection();
      }
      throw hre;
    } catch (HttpException e) {
      if (request != null) {
        request.releaseConnection();
      }
      throw e;
    } catch (IOException ie) {
      if (request != null) {
        request.releaseConnection();
      }
      throw ie;
    } catch (RuntimeException e) {
      if (request != null) {
        request.releaseConnection();
      }
      throw e;
    }
  }
Example #7
0
  public static Data getHTTPData(
      HttpServletRequest req, HttpServletResponse res, String surl, long since)
      throws DataSourceException, IOException {

    int tries = 1;

    // timeout msecs of time we're allowed in this routine
    // we must return or throw an exception.  0 means infinite.
    int timeout = mTimeout;
    if (req != null) {
      String timeoutParm = req.getParameter("timeout");
      if (timeoutParm != null) {
        timeout = Integer.parseInt(timeoutParm);
      }
    }

    long t1 = System.currentTimeMillis();
    long elapsed = 0;
    if (surl == null) {
      surl = getURL(req);
    }

    while (true) {
      String m = null;

      long tout;
      if (timeout > 0) {
        tout = timeout - elapsed;
        if (tout <= 0) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes=p[0] + " timed out"
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-194", new Object[] {surl}));
        }
      } else {
        tout = 0;
      }

      try {
        HttpData data = getDataOnce(req, res, since, surl, 0, (int) tout);
        if (data.code >= 400) {
          data.release();
          throw new DataSourceException(errorMessage(data.code));
        }
        return data;
      } catch (HttpRecoverableException e) {
        // This type of exception should be retried.
        if (tries++ > mMaxRetries) {
          throw new InterruptedIOException(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes="too many retries, exception: " + p[0]
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  HTTPDataSource.class.getName(), "051018-217", new Object[] {e.getMessage()}));
        }
        mLogger.warn(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="retrying a recoverable exception: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-226", new Object[] {e.getMessage()}));
      } catch (HttpException e) {
        String msg =
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()});
        throw new IOException(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="HttpException: " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                HTTPDataSource.class.getName(), "051018-235", new Object[] {e.getMessage()}));
      } catch (IOException e) {

        try {
          Class ssle = Class.forName("javax.net.ssl.SSLException");
          if (ssle.isAssignableFrom(e.getClass())) {
            throw new DataSourceException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="SSL exception: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(
                    HTTPDataSource.class.getName(), "051018-256", new Object[] {e.getMessage()}));
          }
        } catch (ClassNotFoundException cfne) {
        }

        throw e;
      }

      long t2 = System.currentTimeMillis();
      elapsed = (t2 - t1);
    }
  }
Example #8
0
 private void ExitBtnMouseClicked(
     java.awt.event.MouseEvent evt) { // GEN-FIRST:event_ExitBtnMouseClicked
   // TODO add your handling code here:
   System.exit(0);
 } // GEN-LAST:event_ExitBtnMouseClicked
Example #9
0
 private void quitProgram() {
   _task.shutdown();
   System.exit(0);
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      address = PAConfiguration.getAddress();
      port = PAConfiguration.getPort(instantiation);
      poslAddress = PAConfiguration.getPOSL(instantiation, topic);
      rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
      messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
      System.out.println("5 Publicty Chair Servlet");
      System.out.println(response.toString());

      BufferedReader brd = request.getReader();

      String input = "";
      String message = "";

      while (!input.equals("</RuleML>")) {

        input = brd.readLine();

        message = message + input;
      }
      String[] varOrder = getVariableOrder(message);
      System.out.println("Received Message: " + message);

      //	BackwardReasoner br = new BackwardReasoner();
      //   Iterator solit =null;
      //   DefiniteClause dc = null;
      //   SymbolTable.reset();

      POSLParser pp = new POSLParser();
      // String contents = "c(a).\nc(b).\nc(c).";

      Date t1 = new GregorianCalendar().getTime();
      System.out.println(t1.getHours() + ":" + t1.getMinutes());
      // append time to contents

      System.out.println("day: " + t1.getDay());
      System.out.println("day: " + t1.getYear());
      System.out.println("day: " + t1.getMonth());

      // time
      String time = "time(" + t1.getHours() + ":integer).";
      System.out.println(time);

      String url = poslAddress;

      // String url = "http://www.jdrew.org/oojdrew/test.posl";
      String contents = "";

      // day of the week
      int day = t1.getDay();
      boolean weekday = true;

      if (day == 0 || day == 6) {
        weekday = false;
      }

      String dayOfWeek;

      if (weekday) {
        dayOfWeek = "day(weekday).";
      } else {
        dayOfWeek = "day(weekend).";
      }
      // full date
      Calendar cal = new GregorianCalendar();

      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH) + 1;
      int day2 = cal.get(Calendar.DAY_OF_MONTH);

      String date;

      String day3 = "" + day2;

      if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7
          || day2 == 8 || day2 == 9) {

        day3 = "0" + day2;
      }

      if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3;
      else date = "" + year + "0" + month + day3;

      date = "date(" + date + ":integer).";

      System.out.println(date);

      String url2 = rdfAddress;
      HttpClient client2 = new HttpClient();
      GetMethod method2 = new GetMethod(url2);
      method2.setFollowRedirects(true);
      String typestr = "";
      // Execute the GET method
      int statusCode2 = client2.executeMethod(method2);
      if (statusCode2 != -1) {
        typestr = method2.getResponseBodyAsString();
      }
      System.out.println("Types: " + typestr);
      Types.reset();
      RDFSParser.parseRDFSString(typestr);

      try {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        method.setFollowRedirects(true);

        // Execute the GET method
        int statusCode = client.executeMethod(method);
        if (statusCode != -1) {
          contents = method.getResponseBodyAsString();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      contents = contents + "\n" + time;
      contents = contents + "\n" + dayOfWeek;
      contents = contents + "\n" + date;

      BackwardReasoner br = new BackwardReasoner();
      Iterator solit = null;
      DefiniteClause dc = null;
      SymbolTable.reset();

      pp.parseDefiniteClauses(contents);

      br.loadClauses(pp.iterator());
      System.out.println("TEST");
      Iterator it = pp.iterator();
      while (it.hasNext()) {
        DefiniteClause d = (DefiniteClause) it.next();
        System.out.println("Loaded clause: " + d.toPOSLString());
      }

      br = new BackwardReasoner(br.clauses, br.oids);

      MessageParser m = new MessageParser(message);
      Element atom = null;

      try {

        atom = m.parseForContent();

      } catch (Exception e) {

        System.out.println("Invalid Message");
        // out.flush();

      }

      QueryBuilder q = new QueryBuilder(atom);
      String query = q.generateDoc();
      System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
      RuleMLParser qp = new RuleMLParser();

      try {

        dc = qp.parseRuleMLQuery(query);

      } catch (Exception e) {
        System.out.println("Invalid Query");
        // out.flush();
      }

      // solit = br.iterativeDepthFirstSolutionIterator(dc);

      solit = br.iterativeDepthFirstSolutionIterator(dc);

      int varSize = 0;

      while (solit.hasNext()) {

        Vector data = new Vector();

        BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

        Hashtable varbind = gl.varBindings;
        javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
        root.setAllowsChildren(true);

        javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

        int i = 0;
        Object[][] rowdata = new Object[varbind.size()][2];
        varSize = varbind.size();

        Enumeration e = varbind.keys();
        while (e.hasMoreElements()) {
          Object k = e.nextElement();
          Object val = varbind.get(k);
          String ks = (String) k;
          rowdata[i][0] = ks;
          rowdata[i][1] = val;
          i++;
        }

        data.addElement(rowdata);
        String[] messages = new String[data.size()];
        MessageGenerator g =
            new MessageGenerator(
                data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder);
        messages = g.Messages2();

        String appender = "";

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        for (int i1 = 0; i1 < data.size(); i1++) {
          System.out.println(i1 + ")" + messages[i1].toString());
          props.put("text", messages[i1].toString());
          InputStream in = msg.sendGetMessage(props);
        }
        System.out.println("NEXT MESSAGE");
      }

      MessageGenerator g =
          new MessageGenerator(
              null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel());

      URL sender = new URL(address + ":" + port);
      HttpMessage msg = new HttpMessage(sender);
      Properties props = new Properties();

      String finalMessage = g.finalMessage(query);

      System.out.println(finalMessage);

      props.put("text", finalMessage);
      InputStream in = msg.sendGetMessage(props);

      System.out.println("Stop_Communication");

    } catch (Exception e) {
      System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
  }
public class RuleML2008LiaisonChair extends HttpServlet {

  public static final String FS = System.getProperty("file.separator");

  private final String instantiation = "SymposiumPlanner08";
  private final String topic = "LiaisonChair";
  private String address;
  private String port;
  private String poslAddress;
  private String rdfAddress;
  private String messageEndpoint;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  /////////////////////////

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    System.out.println("Publicty Chair Servlet RuleML-2009");
    out.println("Publicty Chair Servlet RuleML-2009");

    Calendar cal = new GregorianCalendar();

    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);

    String date;

    if (month == 10 || month == 11 || month == 12) date = "" + year + month + day;
    else date = "" + year + "0" + month + day;

    date = "date(" + date + ":integer).";
    System.out.println("Publicty Chair Servlet Console update:");
    System.out.println(date);
  }

  /////////////////////////

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      address = PAConfiguration.getAddress();
      port = PAConfiguration.getPort(instantiation);
      poslAddress = PAConfiguration.getPOSL(instantiation, topic);
      rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
      messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
      System.out.println("5 Publicty Chair Servlet");
      System.out.println(response.toString());

      BufferedReader brd = request.getReader();

      String input = "";
      String message = "";

      while (!input.equals("</RuleML>")) {

        input = brd.readLine();

        message = message + input;
      }
      String[] varOrder = getVariableOrder(message);
      System.out.println("Received Message: " + message);

      //	BackwardReasoner br = new BackwardReasoner();
      //   Iterator solit =null;
      //   DefiniteClause dc = null;
      //   SymbolTable.reset();

      POSLParser pp = new POSLParser();
      // String contents = "c(a).\nc(b).\nc(c).";

      Date t1 = new GregorianCalendar().getTime();
      System.out.println(t1.getHours() + ":" + t1.getMinutes());
      // append time to contents

      System.out.println("day: " + t1.getDay());
      System.out.println("day: " + t1.getYear());
      System.out.println("day: " + t1.getMonth());

      // time
      String time = "time(" + t1.getHours() + ":integer).";
      System.out.println(time);

      String url = poslAddress;

      // String url = "http://www.jdrew.org/oojdrew/test.posl";
      String contents = "";

      // day of the week
      int day = t1.getDay();
      boolean weekday = true;

      if (day == 0 || day == 6) {
        weekday = false;
      }

      String dayOfWeek;

      if (weekday) {
        dayOfWeek = "day(weekday).";
      } else {
        dayOfWeek = "day(weekend).";
      }
      // full date
      Calendar cal = new GregorianCalendar();

      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH) + 1;
      int day2 = cal.get(Calendar.DAY_OF_MONTH);

      String date;

      String day3 = "" + day2;

      if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7
          || day2 == 8 || day2 == 9) {

        day3 = "0" + day2;
      }

      if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3;
      else date = "" + year + "0" + month + day3;

      date = "date(" + date + ":integer).";

      System.out.println(date);

      String url2 = rdfAddress;
      HttpClient client2 = new HttpClient();
      GetMethod method2 = new GetMethod(url2);
      method2.setFollowRedirects(true);
      String typestr = "";
      // Execute the GET method
      int statusCode2 = client2.executeMethod(method2);
      if (statusCode2 != -1) {
        typestr = method2.getResponseBodyAsString();
      }
      System.out.println("Types: " + typestr);
      Types.reset();
      RDFSParser.parseRDFSString(typestr);

      try {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        method.setFollowRedirects(true);

        // Execute the GET method
        int statusCode = client.executeMethod(method);
        if (statusCode != -1) {
          contents = method.getResponseBodyAsString();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      contents = contents + "\n" + time;
      contents = contents + "\n" + dayOfWeek;
      contents = contents + "\n" + date;

      BackwardReasoner br = new BackwardReasoner();
      Iterator solit = null;
      DefiniteClause dc = null;
      SymbolTable.reset();

      pp.parseDefiniteClauses(contents);

      br.loadClauses(pp.iterator());
      System.out.println("TEST");
      Iterator it = pp.iterator();
      while (it.hasNext()) {
        DefiniteClause d = (DefiniteClause) it.next();
        System.out.println("Loaded clause: " + d.toPOSLString());
      }

      br = new BackwardReasoner(br.clauses, br.oids);

      MessageParser m = new MessageParser(message);
      Element atom = null;

      try {

        atom = m.parseForContent();

      } catch (Exception e) {

        System.out.println("Invalid Message");
        // out.flush();

      }

      QueryBuilder q = new QueryBuilder(atom);
      String query = q.generateDoc();
      System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
      RuleMLParser qp = new RuleMLParser();

      try {

        dc = qp.parseRuleMLQuery(query);

      } catch (Exception e) {
        System.out.println("Invalid Query");
        // out.flush();
      }

      // solit = br.iterativeDepthFirstSolutionIterator(dc);

      solit = br.iterativeDepthFirstSolutionIterator(dc);

      int varSize = 0;

      while (solit.hasNext()) {

        Vector data = new Vector();

        BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

        Hashtable varbind = gl.varBindings;
        javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
        root.setAllowsChildren(true);

        javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

        int i = 0;
        Object[][] rowdata = new Object[varbind.size()][2];
        varSize = varbind.size();

        Enumeration e = varbind.keys();
        while (e.hasMoreElements()) {
          Object k = e.nextElement();
          Object val = varbind.get(k);
          String ks = (String) k;
          rowdata[i][0] = ks;
          rowdata[i][1] = val;
          i++;
        }

        data.addElement(rowdata);
        String[] messages = new String[data.size()];
        MessageGenerator g =
            new MessageGenerator(
                data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder);
        messages = g.Messages2();

        String appender = "";

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        for (int i1 = 0; i1 < data.size(); i1++) {
          System.out.println(i1 + ")" + messages[i1].toString());
          props.put("text", messages[i1].toString());
          InputStream in = msg.sendGetMessage(props);
        }
        System.out.println("NEXT MESSAGE");
      }

      MessageGenerator g =
          new MessageGenerator(
              null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel());

      URL sender = new URL(address + ":" + port);
      HttpMessage msg = new HttpMessage(sender);
      Properties props = new Properties();

      String finalMessage = g.finalMessage(query);

      System.out.println(finalMessage);

      props.put("text", finalMessage);
      InputStream in = msg.sendGetMessage(props);

      System.out.println("Stop_Communication");

    } catch (Exception e) {
      System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
  }

  // Get parameters from the request URL.
  String getRequestParam(HttpServletRequest request, String param) {
    if (request != null) {
      String paramVal = request.getParameter(param);
      return paramVal;
    }
    return null;
  }
  /**
   * Is used to remember the order of variables so that the message returned to the OA does not
   * contain randomly ordered data.
   *
   * @param message The RuleML message
   * @return An array containing the order of the variables.
   */
  public static String[] getVariableOrder(String message) {
    Vector<String> variables = new Vector<String>();
    String[] variableList;
    // Break string up
    StringTokenizer st = new StringTokenizer(message, "<");

    String temp = ""; // Temporary storage
    String tempVar = ""; // Temporary variable storage

    // While information remains
    while (st.hasMoreTokens()) {
      temp = st.nextToken();
      // If it is a variable
      if (temp.startsWith("Var>")) {
        tempVar = "";
        // Get the name of the variable
        for (int i = 4; i < temp.length(); i++) {
          if (temp.charAt(i) == '<') break;
          else tempVar = tempVar + temp.charAt(i);
        }
        variables.addElement(tempVar); // Store the variable name
      }
    }
    // Convert the vector to an array
    variableList = new String[variables.size()];
    for (int i = 0; i < variables.size(); i++) {
      variableList[i] = variables.elementAt(i);
    }
    return variableList;
  }
  // End getVariableOrder() method
}