Exemple #1
1
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    PrintWriter out = response.getWriter();
    StringBuilder sb = new StringBuilder();

    HashMap<String, String> userInfo = (HashMap<String, String>) session.getAttribute("userInfo");
    String ticket = request.getParameter("ticket");

    if (userInfo == null) {
      response.sendRedirect(response.encodeRedirectUrl(request.getContextPath() + "/SignIn"));
    } else {
      if (userInfo.get("role").equals("technician")) {
        sb.append(LayoutProvider.getInstance().getLoggedInHeader(userInfo.get("name")));
        sb.append("<div id=\"body\">");
        sb.append(
            "<h3>Schedule Confirmation</h3><p>You have scheduled <strong>ticket # "
                + ticket
                + "</strong></p>");
        if (ticket != null) {
          List<String> tickets;
          try {
            if (userInfo.get("tickets").equals("")) {
              tickets = null;
            } else {
              tickets = Arrays.asList(userInfo.get("tickets").split("\\,"));
            }
          } catch (Exception ex) {
            System.out.println("PayBill: error splitting tickets");
            tickets = null;
          }
          String remaining = "";
          if (tickets != null && tickets.size() > 0) {
            for (String t : tickets) {
              if (!t.equals(ticket)) {
                remaining += t + ",";
              }
            }
            if (remaining.length() > 0) remaining = remaining.substring(0, remaining.length() - 1);
          } else {
            remaining = "";
          }
          userInfo.put("tickets", remaining);
        }
        sb.append("</div>");
      } else {
        sb.append("<h2>Error</h2>");
        sb.append("<p>You do not have access to this page.</p>");
        sb.append("</div>");
      }
    }
    out.println(sb.toString());
    out.close();
  }
  /**
   * Gathers the parameters in the request as a HTTP URL string. to form request parameters and
   * policy advice String array. It collects all the parameters from the original request except the
   * original goto url and any advice parameters. Note: All the paramters will be url decoded by
   * default., we should make sure that these values are encoded again
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @return An String array, index 0 is policy advice, index 1 is rest of the request parameters
   */
  private String[] parseRequestParams(HttpServletRequest request) {
    StringBuilder adviceList = null;
    StringBuilder parameterString = new StringBuilder(100);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paramName = (String) e.nextElement();
      if (adviceParams.contains(paramName.toLowerCase())) {
        if (adviceList == null) {
          adviceList = new StringBuilder();
        } else {
          adviceList.append(AMPERSAND);
        }
        String[] values = request.getParameterValues(paramName);
        for (int i = 0; values != null && i < values.length; i++) {
          adviceList.append(paramName).append(EQUAL_TO).append(values[i]);
        }
      } else {
        if (!paramName.equals(GOTO_PARAMETER)) {
          String[] values = request.getParameterValues(paramName);
          for (int i = 0; values != null && i < values.length; i++) {
            parameterString
                .append(AMPERSAND)
                .append(paramName)
                .append(EQUAL_TO)
                .append(URLEncDec.encode(values[i]));
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.parseRequestParams:" + "Advice List is = " + adviceList);
      debug.message(
          "CDCClientServlet.parseRequestParams:"
              + "Parameter String is = "
              + parameterString.toString());
    }

    String policyAdviceList;
    String requestParams;

    if (adviceList == null) {
      policyAdviceList = null;
    } else {
      policyAdviceList = adviceList.toString();
    }

    if (parameterString.length() > 0) {
      requestParams = (parameterString.deleteCharAt(0).toString());
    } else {
      requestParams = parameterString.toString();
    }

    return new String[] {policyAdviceList, requestParams};
  }
 // Get cookies string from HTTP request object
 private String getCookiesFromRequest(HttpServletRequest request) {
   Cookie cookies[] = CookieUtils.getCookieArrayFromReq(request);
   // above call would return pure sid in iPlanetDirectoryPro cookie
   // independent of container encoding
   StringBuilder cookieStr = null;
   String strCookies = null;
   if (cookies != null) {
     for (int nCookie = 0; nCookie < cookies.length; nCookie++) {
       String cookieName = cookies[nCookie].getName();
       String cookieVal = cookies[nCookie].getValue();
       if (cookieName.equals(CookieUtils.getAmCookieName()) && cookieEncoding) {
         cookieVal = URLEncDec.encode(cookieVal);
       }
       if (debug.messageEnabled()) {
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
       }
       if (cookieStr == null) {
         cookieStr = new StringBuilder();
       } else {
         cookieStr.append(SEMI_COLON).append(SPACE);
       }
       cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
     }
   }
   if (cookieStr != null) {
     strCookies = cookieStr.toString();
   }
   return strCookies;
 }
Exemple #4
0
 private String getAuthorizeUrl() {
   StringBuilder url = new StringBuilder();
   url.append(this.service_.getAuthorizationEndpoint());
   boolean hasQuery = url.toString().indexOf('?') != -1;
   url.append(hasQuery ? '&' : '?')
       .append("client_id=")
       .append(Utils.urlEncode(this.service_.getClientId()))
       .append("&redirect_uri=")
       .append(Utils.urlEncode(this.service_.getGenerateRedirectEndpoint()))
       .append("&scope=")
       .append(Utils.urlEncode(this.scope_))
       .append("&response_type=code")
       .append("&state=")
       .append(Utils.urlEncode(this.oAuthState_));
   return url.toString();
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
 // !!! IDEA reports this as unused, but it is called from JSP
 public static String getStyle(LoginInfo loginInfo) {
   StringBuilder bld = new StringBuilder();
   bld.append("<style media=\"screen\" type=\"text/css\">\n\n");
   if (loginInfo == null) {
     bld.append(Config.getConfig().defaultStyle);
   } else {
     bld.append(loginInfo.style); // ttt3 detect broken styles and return default
   }
   bld.append("</style>\n");
   return bld.toString();
 }
 String srvUrlStem(String host) {
   if (host == null) {
     return null;
   }
   StringBuilder sb = new StringBuilder();
   sb.append(reqURL.getProtocol());
   sb.append("://");
   sb.append(host);
   sb.append(':');
   sb.append(reqURL.getPort());
   return sb.toString();
 }
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
Exemple #9
0
 void requestToken(String authorizationCode) {
   try {
     String url = this.service_.getTokenEndpoint();
     StringBuilder ss = new StringBuilder();
     ss.append("grant_type=authorization_code")
         .append("&client_id=")
         .append(Utils.urlEncode(this.service_.getClientId()))
         .append("&client_secret=")
         .append(Utils.urlEncode(this.service_.getClientSecret()))
         .append("&redirect_uri=")
         .append(Utils.urlEncode(this.service_.getGenerateRedirectEndpoint()))
         .append("&code=")
         .append(authorizationCode);
     HttpClient client = new HttpClient(this);
     client.setTimeout(15);
     client
         .done()
         .addListener(
             this,
             new Signal2.Listener<Exception, HttpMessage>() {
               public void trigger(Exception event1, HttpMessage event2) {
                 OAuthProcess.this.handleToken(event1, event2);
               }
             });
     Method m = this.service_.getTokenRequestMethod();
     if (m == Method.Get) {
       boolean hasQuery = url.indexOf('?') != -1;
       url += (hasQuery ? '&' : '?') + ss.toString();
       client.get(url);
     } else {
       HttpMessage post = new HttpMessage();
       post.setHeader("Content-Type", "application/x-www-form-urlencoded");
       post.addBodyText(ss.toString());
       client.post(url, post);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append(getClass().getSimpleName());
    sb.append("[");
    sb.append(_contextUri);

    if (_queryString != null) sb.append("?").append(_queryString);

    sb.append("]");

    return sb.toString();
  }
Exemple #11
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   PrintWriter out = response.getWriter();
   StringBuilder sb = new StringBuilder();
   sb.append("<html>");
   sb.append("<body>");
   sb.append("<h1>Hi! Click the button below to turn on the server!</h1>");
   sb.append("<form ACTION=\"/wake/perform\" METHOD=\"POST\">");
   sb.append("<input name=\"send\"  type=\"submit\"  value=\"Wake Server\" />");
   sb.append("</form>");
   sb.append("</body>");
   sb.append("</html>");
   out.println(sb.toString());
 }
 public String toXML() {
   StringBuilder sb = new StringBuilder("<httpSample");
   addAttribute(sb, "t", elapsedTime);
   addAttribute(sb, "lt", latency);
   addAttribute(sb, "ts", requestTimeStamp);
   addAttribute(sb, "s", success);
   addAttribute(sb, "lb", label);
   addAttribute(sb, "rc", returnCode);
   addAttribute(sb, "rm", returnMessage);
   addAttribute(sb, "tn", sampleName);
   addAttribute(sb, "dt", dataType);
   addAttribute(sb, "by", responseContentLength);
   sb.append(" />");
   return sb.toString();
 }
  public static String showSecurity(HttpServletRequest req, String role) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Security Info\n");
    sbuff.append(" req.getRemoteUser(): ").append(req.getRemoteUser()).append("\n");
    sbuff.append(" req.getUserPrincipal(): ").append(req.getUserPrincipal()).append("\n");
    sbuff
        .append(" req.isUserInRole(")
        .append(role)
        .append("):")
        .append(req.isUserInRole(role))
        .append("\n");
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
 public static String showRequestHeaders(HttpServletRequest req) {
   StringBuilder sbuff = new StringBuilder();
   sbuff.append("Request Headers:\n");
   Enumeration names = req.getHeaderNames();
   while (names.hasMoreElements()) {
     String name = (String) names.nextElement();
     Enumeration values = req.getHeaders(name); // support multiple values
     if (values != null) {
       while (values.hasMoreElements()) {
         String value = (String) values.nextElement();
         sbuff.append("  ").append(name).append(": ").append(value).append("\n");
       }
     }
   }
   return sbuff.toString();
 }
Exemple #15
0
 private void crawlPluginRegistries() {
   StringBuilder sb = new StringBuilder();
   for (ArchivalUnit au : pluginMgr.getAllRegistryAus()) {
     sb.append(au.getName());
     sb.append(": ");
     try {
       startCrawl(au, true, false);
       sb.append("Queued.");
     } catch (CrawlManagerImpl.NotEligibleException e) {
       sb.append("Failed: ");
       sb.append(e.getMessage());
     }
     sb.append("\n");
   }
   statusMsg = sb.toString();
 }
Exemple #16
0
  @Nullable
  public String getMapping() {
    final StringBuilder sb = new StringBuilder();

    for (Map.Entry<Pattern, ScopeMapping> patternAndMapping : _patternToMapping.entrySet()) {
      if (patternAndMapping.getKey() != null) {
        if (sb.length() > 0) {
          sb.append(",\n");
        }
        sb.append(patternAndMapping.getKey())
            .append('>')
            .append(patternAndMapping.getValue().getDefaultName());
      }
    }

    return sb.length() > 0 ? sb.toString() : null;
  }
 /**
  * Return a button that invokes the javascript submit routine with the specified action, first
  * storing the value in the specified form prop.
  */
 protected Element submitButton(String label, String action, String prop, String value) {
   StringBuilder sb = new StringBuilder(40);
   sb.append("lockssButton(this, '");
   sb.append(action);
   sb.append("'");
   if (prop != null && value != null) {
     sb.append(", '");
     sb.append(prop);
     sb.append("', '");
     sb.append(value);
     sb.append("'");
   }
   sb.append(")");
   Input btn = jsButton(label, sb.toString());
   btn.attribute("id", "lsb." + (++submitButtonNumber));
   return btn;
 }
  /**
   * A more elegant string representing all users that this bookmark "belongs" to.
   *
   * @return the string.
   */
  public String getCommaDelimitedList(Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String string : strings) {
      buf.append(string);
      buf.append(",");
    }

    String returnStr = buf.toString();
    if (returnStr.endsWith(",")) {
      returnStr = returnStr.substring(0, returnStr.length() - 1);
    }

    if (!SparkUtil.hasLength(returnStr)) {
      returnStr = "&nbsp;";
    }
    return returnStr;
  }
Exemple #19
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    // Actual logic goes here.

    // System.out.print("Test");

    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line).append('\n');
      }
    }

    try {
      JSONObject jsonObject = new JSONObject(sb.toString());

      JSONObject message = jsonObject.getJSONObject("message");
      String command = message.getString("text");
      if (BotHelper.command(command, "/echo")) {
        functions.echo(jsonObject);
      } else if (BotHelper.command(command, "/engage")) {
        functions.engage(jsonObject);
      } else if (BotHelper.command(command, "/debug")) {
        functions.debugjson(jsonObject);
      } else if (BotHelper.command(command, "/amazon")) {
        functions.searchAmazon(jsonObject);
      } else if (BotHelper.command(command, "/decide")) {
        functions.decide(jsonObject);
      } else if (BotHelper.command(command, "/ohkadsewasessenwirheute")) {
        functions.ohkadsewasessenwirheute(jsonObject);
      } else if (BotHelper.command(command, "/ohmagischekadse")) {
        functions.ohmagischekadse(jsonObject);
      } else if (BotHelper.command(command, "/otherchat")) {
        functions.otherChat(jsonObject);
      } else if ((BotHelper.command(command, "/help")) || (BotHelper.command(command, "/?"))) {
        functions.help(jsonObject);
      } else {
        functions.unknown(jsonObject);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @SuppressWarnings("unchecked")
 private String getRequestLabel(HttpServletRequest request) {
   StringBuilder sb = new StringBuilder();
   sb.append(request.getServletPath().substring(1));
   String methodToCall = request.getParameter("methodToCall");
   if (methodToCall != null) {
     addMethodToCall(sb, methodToCall);
   } else {
     Enumeration<String> nameEnum = request.getParameterNames();
     while (nameEnum.hasMoreElements()) {
       String parmName = nameEnum.nextElement();
       if (parmName.startsWith("methodToCall.")) {
         addMethodToCall(sb, parmName.substring("methodToCall.".length()));
         break;
       }
     }
   }
   return sb.toString();
 }
 /**
  * Construct servlet URL, with params as necessary. Avoid generating a hostname different from
  * that used in the original request, or browsers will prompt again for login
  */
 String srvURLFromStem(String stem, ServletDescr d, String params) {
   if (d.isPathIsUrl()) {
     return d.getPath();
   }
   StringBuilder sb = new StringBuilder(80);
   if (stem != null) {
     sb.append(stem);
     if (stem.charAt(stem.length() - 1) != '/') {
       sb.append('/');
     }
   } else {
     // ensure absolute path even if no scheme/host/port
     sb.append('/');
   }
   sb.append(d.getPath());
   if (params != null) {
     sb.append('?');
     sb.append(params);
   }
   return sb.toString();
 }
Exemple #22
0
  /**
   * Generate the percentage graph and returns HTML representation string of the same.
   *
   * @param perc The percentage value for which graph is to be generated
   * @param width The width of the display table
   * @return HTML String representation of the percentage graph
   * @throws IOException
   */
  public static String percentageGraph(int perc, int width) throws IOException {
    assert perc >= 0;
    assert perc <= 100;

    StringBuilder builder = new StringBuilder();

    builder.append("<table border=\"1px\" width=\"");
    builder.append(width);
    builder.append("px\"><tr>");
    if (perc > 0) {
      builder.append("<td cellspacing=\"0\" class=\"perc_filled\" width=\"");
      builder.append(perc);
      builder.append("%\"></td>");
    }
    if (perc < 100) {
      builder.append("<td cellspacing=\"0\" class=\"perc_nonfilled\" width=\"");
      builder.append(100 - perc);
      builder.append("%\"></td>");
    }
    builder.append("</tr></table>");
    return builder.toString();
  }
  /** @throws IOException If failed. */
  private void initDefaultPage() throws IOException {
    assert dfltPage == null;

    InputStream in = getClass().getResourceAsStream("rest.html");

    if (in != null) {
      LineNumberReader rdr = new LineNumberReader(new InputStreamReader(in));

      try {
        StringBuilder buf = new StringBuilder(2048);

        for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
          buf.append(line);

          if (!line.endsWith(" ")) buf.append(" ");
        }

        dfltPage = buf.toString();
      } finally {
        U.closeQuiet(rdr);
      }
    }
  }
Exemple #24
0
 /**
  * Connects an implementation to start an authentication process to a signal.
  *
  * <p>If JavaScript is available, this method connects a JavaScript function to the <code>signal
  * </code>, otherwise {@link OAuthProcess#startAuthenticate() startAuthenticate()} is connected to
  * <code>signal</code>.
  */
 public void connectStartAuthenticate(AbstractEventSignal s) {
   if (WApplication.getInstance().getEnvironment().hasJavaScript()) {
     StringBuilder js = new StringBuilder();
     js.append("function(object, event) {")
         .append("Wt3_2_3.PopupWindow(Wt3_2_3")
         .append(",")
         .append(WWebWidget.jsStringLiteral(this.getAuthorizeUrl()))
         .append(", ")
         .append(this.service_.getPopupWidth())
         .append(", ")
         .append(this.service_.getPopupHeight())
         .append(");")
         .append("}");
     s.addListener(js.toString());
   }
   s.addListener(
       this,
       new Signal.Listener() {
         public void trigger() {
           OAuthProcess.this.startAuthenticate();
         }
       });
 }
Exemple #25
0
 /**
  * Replace occurrences of "%ab" with the character represented by the hex value. Strings of
  * escaped characters are treated as UTF-8 byte sequences and decoded appropriately.
  */
 private static String decode(String s) {
   int length = s.length();
   StringBuilder str = new StringBuilder(length);
   Matcher matcher = PATTERN.matcher(s);
   int offset = 0;
   byte[] bb = null;
   while (matcher.find(offset)) {
     int count = matcher.groupCount();
     for (int i = 0; i < count; i++) {
       String match = matcher.group(0);
       int num = match.length() / 3;
       if (bb == null || bb.length < num) {
         bb = new byte[num];
       }
       for (int j = 0; j < num; j++) {
         int head = j * 3 + 1;
         int tail = head + 2;
         bb[j] = (byte) Integer.parseInt(match.substring(head, tail), 16);
       }
       try {
         String text = new String(bb, "UTF-8");
         str.append(s.substring(offset, matcher.start()));
         str.append(text);
       } catch (UnsupportedEncodingException e) {
         // NOTE: This should *never* be thrown because all
         //       JVMs are required to support UTF-8. I mean,
         //       the strings in the .class file are all in
         //       a modified UTF-8, for pete's sake! :)
       }
     }
     offset = matcher.end();
   }
   if (offset < length) {
     str.append(s.substring(offset));
   }
   return str.toString();
 }
  @Override
  protected boolean checkEnforce(ServletContext context) throws IOException {
    /*
     * Rely on the SolrResourceLoader to locate the solr home directory.
     */

    int httpsPort = getHttpsPort();

    if (httpsPort > -1) {
      setHttpsPort(httpsPort);
    }

    String solrHome = SolrResourceLoader.locateSolrHome();

    if (logger.isDebugEnabled()) {
      logger.debug("solrHome:" + solrHome);
    }

    /*
     * Find the active cores.
     */
    List<File> cores = new ArrayList();
    findCores(new File(solrHome), cores);

    /*
     * Get the alfresco.secureComms value for each core.
     */
    Set<String> secureCommsSet = new HashSet();
    for (File core : cores) {
      collectSecureComms(core, secureCommsSet);
    }

    /*
     * alfresco.secureComms values should be in sync for each core
     */

    if (secureCommsSet.size() > 1) {
      StringBuilder buf = new StringBuilder();
      int i = 0;
      for (String s : secureCommsSet) {
        if (i > 0) {
          buf.append(" | ");
        }
        buf.append(s);
        i++;
      }

      throw new IOException(
          "More then one distinct value found for alfresco.secureComms:"
              + buf.toString()
              + ". All alfresco.secureComms values must be set to the same value.");
    }

    if (secureCommsSet.size() == 0) {
      // No secureComms were found.
      return false;
    }

    String secureComms = secureCommsSet.iterator().next();

    if (logger.isDebugEnabled()) {
      logger.debug("secureComms:" + secureComms);
    }

    if ("none".equals(secureComms)) {
      return false;
    } else {
      return true;
    }
  }
 private ByteArrayOutputStream getCsvData(
     JSONArray src, JSONArray store, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   StringBuilder resSB = new StringBuilder();
   JSONObject temp = null;
   int fieldListLength = 0;
   try {
     String header = "";
     temp =
         new JSONObject(
             "{data:[Project Start,Baseline Start,Actual Start,"
                 + "Start Variance,Project Finish,Baseline Finish,Actual Finish,Finish Variance,"
                 + "Scheduled,Baseline,Variance,Remaining,Actual,Scheduled,Baseline,Variance,"
                 + "Remaining,Actual,Scheduled,Baseline,Variance,Remaining,Actual,Percent Complete,"
                 + "Task not yet Started,Task in progress,Task Completed,Parent Tasks, Total Tasks]}");
     JSONArray colHeader = temp.getJSONArray("data");
     temp =
         new JSONObject(
             "{data:[Project Start Date,Baseline Start Date,Project Actual Start Date,"
                 + "Start Variance,Project End Date,Baseline End Date,Project End Date,End Variance,"
                 + "Scheduled Duration,Baseline Duration,Duration Variance,Remaining Duration,"
                 + "Actual Duration,Scheduled Cost,Baseline Cost,Cost Variance,Remaining Cost,Actual Cost,"
                 + "Scheduled Work,Baseline Work,Work Variance,Remaining Work,Actual Work,Percent Complete,"
                 + "Unstarted Tasks,Inprogress Tasks,Completed Tasks,Parent Tasks,Total Tasks]}");
     JSONArray fieldList = temp.getJSONArray("data");
     fieldListLength = fieldList.length();
     for (int i = 0; i < src.length(); i++) {
       colHeader.put(src.getJSONObject(i).getString("type"));
       fieldList.put("count");
     }
     fieldList.put("Total Resources");
     colHeader.put("Total Resources");
     for (int i = 0; i < colHeader.length(); i++) {
       header += "\"" + colHeader.get(i).toString() + "\",";
     }
     header = header.substring(0, (header.length() - 1));
     header += "\n";
     resSB.append(header);
     String dataIndexArrStr[] = new String[fieldList.length()];
     for (int i = 0; i < fieldList.length(); i++) dataIndexArrStr[i] = fieldList.get(i).toString();
     for (int i = 0; i < store.length(); i++) {
       temp = store.getJSONObject(i);
       String dstr = "";
       for (int j = 0; j < fieldListLength; j++)
         dstr += "\"" + temp.getString(dataIndexArrStr[j]) + "\",";
       dstr = dstr.substring(0, (dstr.length() - 1));
       dstr += "\n";
       resSB.append(dstr);
     }
     for (int i = 0; i < src.length(); i++) {
       temp = src.getJSONObject(i);
       String dstr = "";
       dstr += "\"" + temp.getString("count") + "\",";
       dstr = dstr.substring(0, (dstr.length() - 1));
       resSB.append(dstr);
     }
     String dstr = "";
     dstr += "\"" + store.getJSONObject(0).getString("Total Resources") + "\",";
     resSB.append(dstr);
     baos.write(resSB.toString().getBytes());
     baos.close();
   } catch (IOException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
   }
   return baos;
 }
Exemple #28
0
 protected void paintEvent(WPaintDevice paintDevice) {
   if (!(this.chart_ != null) || !this.chart_.cObjCreated_) {
     return;
   }
   if (this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.LineSeries
       && this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.CurveSeries) {
     if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
       StringBuilder ss = new StringBuilder();
       ss.append("jQuery.removeData(").append(this.getJsRef()).append(",'sobj');");
       ss.append("\nif (")
           .append(this.getObjJsRef())
           .append(") {")
           .append(this.getObjJsRef())
           .append(".canvas.style.cursor = 'auto';")
           .append("setTimeout(")
           .append(this.getObjJsRef())
           .append(".repaint,0);}\n");
       this.doJavaScript(ss.toString());
     }
     logger.error(
         new StringWriter()
             .append("WAxisSliderWidget is not associated with a line or curve series.")
             .toString());
     return;
   }
   WPainter painter = new WPainter(paintDevice);
   boolean horizontal = this.chart_.getOrientation() == Orientation.Vertical;
   double w = horizontal ? this.getWidth().getValue() : this.getHeight().getValue();
   double h = horizontal ? this.getHeight().getValue() : this.getWidth().getValue();
   boolean autoPadding = this.autoPadding_;
   if (autoPadding
       && EnumUtils.mask(paintDevice.getFeatures(), WPaintDevice.FeatureFlag.HasFontMetrics)
           .equals(0)
       && this.labelsEnabled_) {
     logger.error(
         new StringWriter()
             .append(
                 "setAutoLayout(): device does not have font metrics (not even server-side font metrics).")
             .toString());
     autoPadding = false;
   }
   if (autoPadding) {
     if (horizontal) {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                     + 10),
             EnumSet.of(Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                         / 2,
                     10.0),
             EnumSet.of(Side.Left, Side.Right));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Left, Side.Right, Side.Bottom));
       }
     } else {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                         / 2,
                     10.0),
             EnumSet.of(Side.Top, Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                     + 10),
             EnumSet.of(Side.Left));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Top, Side.Bottom, Side.Left));
       }
     }
   }
   double left =
       horizontal
           ? this.getSelectionAreaPadding(Side.Left)
           : this.getSelectionAreaPadding(Side.Top);
   double right =
       horizontal
           ? this.getSelectionAreaPadding(Side.Right)
           : this.getSelectionAreaPadding(Side.Bottom);
   double top =
       horizontal
           ? this.getSelectionAreaPadding(Side.Top)
           : this.getSelectionAreaPadding(Side.Right);
   double bottom =
       horizontal
           ? this.getSelectionAreaPadding(Side.Bottom)
           : this.getSelectionAreaPadding(Side.Left);
   double maxW = w - left - right;
   WRectF drawArea = new WRectF(left, 0, maxW, h);
   List<WAxis.Segment> segmentsBak =
       new ArrayList<WAxis.Segment>(this.chart_.getAxis(Axis.XAxis).segments_);
   double renderIntervalBak = this.chart_.getAxis(Axis.XAxis).renderInterval_;
   this.chart_
       .getAxis(Axis.XAxis)
       .prepareRender(
           horizontal ? Orientation.Horizontal : Orientation.Vertical, drawArea.getWidth());
   final WRectF chartArea = this.chart_.chartArea_;
   WRectF selectionRect = null;
   {
     double u =
         -this.chart_.xTransformHandle_.getValue().getDx()
             / (chartArea.getWidth() * this.chart_.xTransformHandle_.getValue().getM11());
     selectionRect = new WRectF(0, top, maxW, h - (top + bottom));
     this.transform_.setValue(
         new WTransform(
             1 / this.chart_.xTransformHandle_.getValue().getM11(), 0, 0, 1, u * maxW, 0));
   }
   WRectF seriesArea = new WRectF(left, top + 5, maxW, h - (top + bottom + 5));
   WTransform selectionTransform =
       this.hv(new WTransform(1, 0, 0, 1, left, 0).multiply(this.transform_.getValue()));
   WRectF rect = selectionTransform.map(this.hv(selectionRect));
   painter.fillRect(this.hv(new WRectF(left, top, maxW, h - top - bottom)), this.background_);
   painter.fillRect(rect, this.selectedAreaBrush_);
   final double TICK_LENGTH = 5;
   final double ANGLE1 = 15;
   final double ANGLE2 = 80;
   double tickStart = 0.0;
   double tickEnd = 0.0;
   double labelPos = 0.0;
   AlignmentFlag labelHFlag = AlignmentFlag.AlignCenter;
   AlignmentFlag labelVFlag = AlignmentFlag.AlignMiddle;
   final WAxis axis = this.chart_.getAxis(Axis.XAxis);
   if (horizontal) {
     tickStart = 0;
     tickEnd = TICK_LENGTH;
     labelPos = TICK_LENGTH;
     labelVFlag = AlignmentFlag.AlignTop;
   } else {
     tickStart = -TICK_LENGTH;
     tickEnd = 0;
     labelPos = -TICK_LENGTH;
     labelHFlag = AlignmentFlag.AlignRight;
   }
   if (horizontal) {
     if (axis.getLabelAngle() > ANGLE1) {
       labelHFlag = AlignmentFlag.AlignRight;
       if (axis.getLabelAngle() > ANGLE2) {
         labelVFlag = AlignmentFlag.AlignMiddle;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelHFlag = AlignmentFlag.AlignLeft;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelVFlag = AlignmentFlag.AlignMiddle;
         }
       }
     }
   } else {
     if (axis.getLabelAngle() > ANGLE1) {
       labelVFlag = AlignmentFlag.AlignBottom;
       if (axis.getLabelAngle() > ANGLE2) {
         labelHFlag = AlignmentFlag.AlignCenter;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelVFlag = AlignmentFlag.AlignTop;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelHFlag = AlignmentFlag.AlignCenter;
         }
       }
     }
   }
   EnumSet<AxisProperty> axisProperties = EnumSet.of(AxisProperty.Line);
   if (this.labelsEnabled_) {
     axisProperties.add(AxisProperty.Labels);
   }
   if (horizontal) {
     axis.render(
         painter,
         axisProperties,
         new WPointF(drawArea.getLeft(), h - bottom),
         new WPointF(drawArea.getRight(), h - bottom),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(drawArea.getLeft() + 0.5, h - (bottom - 0.5));
     line.lineTo(drawArea.getRight(), h - (bottom - 0.5));
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   } else {
     axis.render(
         painter,
         axisProperties,
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getLeft()),
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getRight()),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getLeft() + 0.5);
     line.lineTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getRight());
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   }
   WPainterPath curve = new WPainterPath();
   {
     WTransform t =
         new WTransform(1, 0, 0, 1, seriesArea.getLeft(), seriesArea.getTop())
             .multiply(
                 new WTransform(
                     seriesArea.getWidth() / chartArea.getWidth(),
                     0,
                     0,
                     seriesArea.getHeight() / chartArea.getHeight(),
                     0,
                     0))
             .multiply(new WTransform(1, 0, 0, 1, -chartArea.getLeft(), -chartArea.getTop()));
     if (!horizontal) {
       t.assign(
           new WTransform(
                   0,
                   1,
                   1,
                   0,
                   this.getSelectionAreaPadding(Side.Left)
                       - this.getSelectionAreaPadding(Side.Right)
                       - 5,
                   0)
               .multiply(t)
               .multiply(new WTransform(0, 1, 1, 0, 0, 0)));
     }
     curve.assign(t.map(this.chart_.pathForSeries(this.seriesColumn_)));
   }
   {
     WRectF leftHandle = this.hv(new WRectF(-5, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopLeft())));
     painter.fillRect(this.hv(t).map(leftHandle), this.handleBrush_);
   }
   {
     WRectF rightHandle = this.hv(new WRectF(0, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopRight())));
     painter.fillRect(this.hv(t).map(rightHandle), this.handleBrush_);
   }
   if (this.selectedSeriesPen_ != this.seriesPen_
       && !this.selectedSeriesPen_.equals(this.seriesPen_)) {
     WPainterPath clipPath = new WPainterPath();
     clipPath.addRect(this.hv(selectionRect));
     painter.setClipPath(selectionTransform.map(clipPath));
     painter.setClipping(true);
     painter.setPen(this.getSelectedSeriesPen());
     painter.drawPath(curve);
     WPainterPath leftClipPath = new WPainterPath();
     leftClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, -selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left, -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopLeft()))))
             .map(leftClipPath));
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
     WPainterPath rightClipPath = new WPainterPath();
     rightClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left - selectionRect.getRight(), -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopRight()))))
             .map(rightClipPath));
     painter.drawPath(curve);
     painter.setClipping(false);
   } else {
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
   }
   if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
     WApplication app = WApplication.getInstance();
     StringBuilder ss = new StringBuilder();
     ss.append("new Wt3_3_5.WAxisSliderWidget(")
         .append(app.getJavaScriptClass())
         .append(",")
         .append(this.getJsRef())
         .append(",")
         .append(this.getObjJsRef())
         .append(",")
         .append("{chart:")
         .append(this.chart_.getCObjJsRef())
         .append(",transform:")
         .append(this.transform_.getJsRef())
         .append(",rect:function(){return ")
         .append(rect.getJsRef())
         .append("},drawArea:")
         .append(drawArea.getJsRef())
         .append(",series:")
         .append(this.seriesColumn_)
         .append("});");
     this.doJavaScript(ss.toString());
   }
   Utils.copyList(segmentsBak, this.chart_.getAxis(Axis.XAxis).segments_);
   this.chart_.getAxis(Axis.XAxis).renderInterval_ = renderIntervalBak;
 }
  /**
   * This the main method of this servlet which takes in the request opens a URLConnection to the
   * CDCServlet endpoint in the OpenAM, and tunnels the request content to it. It parses the
   * Response received and if the HTTP_STATUS is "HTTP_OK" or "HTTP_MOVED_TEMP" POSTs the received
   * Liberty Authn Response to the goto URL specified in the original request.
   */
  private void sendAuthnRequest(
      HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws ServletException, IOException {
    SessionID sessid = new SessionID(request);
    URL CDCServletURL = null;
    URL sessionServiceURL = null;
    try {
      sessionServiceURL = Session.getSessionServiceURL(sessid);
    } catch (SessionException se) {
      debug.error(
          "CDCClientServlet.sendAuthnRequest: Cannot locate" + " OpenAM instance to forward to.",
          se);
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    if (sessionServiceURL == null) {
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    // replace "sessionservice" by cdcservlet in obtained URL
    // we use naming so that we get the URL of the exact server
    // where the session is located and get the right deployment
    // descriptor.
    String sessionServiceURLString = sessionServiceURL.toString();
    int serviceNameIndex =
        sessionServiceURLString.lastIndexOf(
            "/", sessionServiceURLString.length() - 2); // avoiding trailing "/"
    // if any
    StringBuilder buffer = new StringBuilder(150);
    buffer
        .append(sessionServiceURLString.substring(0, serviceNameIndex))
        .append(CDCURI)
        .append(QUESTION_MARK)
        .append(request.getQueryString()); // add query string to
    // CDCServletURL

    CDCServletURL = new URL(buffer.toString());

    // save the go to URL of the agent side to ultimately
    // POST to.
    try {
      HttpURLConnection connection = HttpURLConnectionManager.getConnection(CDCServletURL);
      connection.setRequestMethod("GET");
      connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      // replay cookies
      String strCookies = getCookiesFromRequest(request);
      if (strCookies != null) {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.sendAuthnRequest:Setting " + "cookies = " + strCookies);
        }
        connection.setRequestProperty("Cookie", strCookies);
      }
      // dont wish to follow redirect to agent, since
      // the response needs to go via the CDCClientServlet.
      HttpURLConnection.setFollowRedirects(false);

      // Receiving input from CDCServlet on the AM server instance
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Getting " + "response back from  " + CDCServletURL);
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response " + "Code " + connection.getResponseCode());
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response "
                + "Message= "
                + connection.getResponseMessage());
      }

      // Check response code
      if ((connection.getResponseCode() == HttpURLConnection.HTTP_OK)
          || (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)) {
        /**
         * Read the response back from CDCServlet, got a redirect since this response contains the
         * "LARES" ( Liberty authn response, which needs to be posted back to the dest url (agent).
         */
        StringBuilder inBuf = new StringBuilder();
        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
          inBuf.append(buf, 0, len);
        }
        String inString = inBuf.toString();
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnRequest:" + "Received response data = " + inString);
        }
        // put the received Liberty Auth Response
        // in the servlet's response.
        sendAuthnResponse(request, response, inString);
      } else {
        debug.error("CDCClientServlet.sendAuthnRequest: Response " + "code NOT OK/MOVED_TEMP ");
        showError(
            response,
            "ERROR: Received HTTP error code "
                + connection.getResponseCode()
                + " from "
                + CDCServletURL);
      }
    } catch (ConnectException ce) {
      // Debug the exception
      if (debug.warningEnabled()) {
        debug.warning(
            "CDCClientServlet.sendAuthnRequest: " + "Connection Exception to " + CDCServletURL, ce);
      }
      showError(
          response, "Could not connect to CDCServlet at " + CDCServletURL + ":" + ce.getMessage());
    }
  }
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }