/**
  * Rename file using prefix and suffix settings.
  *
  * @param path the path to rename
  */
 protected void renameFile(Path path) {
   // bail out if there's no in-writing settings
   if (!StringUtils.hasText(prefix) && !StringUtils.hasText(suffix)) {
     return;
   }
   String name = path.getName();
   if (StringUtils.startsWithIgnoreCase(name, prefix)) {
     name = name.substring(prefix.length());
   }
   if (StringUtils.endsWithIgnoreCase(name, suffix)) {
     name = name.substring(0, name.length() - suffix.length());
   }
   Path toPath = new Path(path.getParent(), name);
   try {
     FileSystem fs = path.getFileSystem(getConfiguration());
     if (!fs.rename(path, toPath)) {
       throw new StoreException(
           "Failed renaming from "
               + path
               + " to "
               + toPath
               + " with configuration "
               + getConfiguration());
     }
   } catch (IOException e) {
     log.error("Error renaming file", e);
     throw new StoreException("Error renaming file", e);
   }
 }
 /**
  * Return the path within the web application for the given request.
  *
  * <p>Detects include request URL if called within a RequestDispatcher include.
  *
  * @param request current HTTP request
  * @return the path within the web application
  */
 public String getPathWithinApplication(HttpServletRequest request) {
   String contextPath = getContextPath(request);
   String requestUri = getRequestUri(request);
   if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) {
     // Normal case: URI contains context path.
     String path = requestUri.substring(contextPath.length());
     return (StringUtils.hasText(path) ? path : "/");
   } else {
     // Special case: rather unusual.
     return requestUri;
   }
 }
  protected boolean canUseExistingTMSessionObject(String awardNumber) {
    String sessionObjectKey =
        GlobalVariables.getUserSession().getKualiSessionId()
            + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION;
    String prefix = null;

    TimeAndMoneyDocument tmDocFromSession =
        (TimeAndMoneyDocument) GlobalVariables.getUserSession().retrieveObject(sessionObjectKey);
    if (tmDocFromSession == null) {
      return false;
    }
    Map<String, AwardHierarchyNode> tmpNodes = tmDocFromSession.getAwardHierarchyNodes();
    if (tmpNodes != null && CollectionUtils.isNotEmpty(tmpNodes.keySet())) {
      for (String tempAwardNumber : tmpNodes.keySet()) {
        prefix = tempAwardNumber.substring(0, tempAwardNumber.indexOf("-"));
        if (!StringUtils.startsWithIgnoreCase(awardNumber, prefix)) {
          return false;
        }
      }
    }

    return true;
  }
 /**
  * Set the prefix used in mappings.
  *
  * @param prefix the prefix
  */
 public void setPrefix(String prefix) {
   Assert.isTrue(
       "".equals(prefix) || StringUtils.startsWithIgnoreCase(prefix, "/"),
       "prefix must start with '/'");
   this.prefix = prefix;
 }
  /**
   * Execute the given SQL script.
   *
   * <p>Statement separators and comments will be removed before executing individual statements
   * within the supplied script.
   *
   * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
   *
   * @param connection the JDBC connection to use to execute the script; already configured and
   *     ready to use
   * @param resource the resource (potentially associated with a specific encoding) to load the SQL
   *     script from
   * @param continueOnError whether or not to continue without throwing an exception in the event of
   *     an error
   * @param ignoreFailedDrops whether or not to continue in the event of specifically an error on a
   *     {@code DROP} statement
   * @param commentPrefix the prefix that identifies comments in the SQL script &mdash; typically
   *     "--"
   * @param separator the script statement separator; defaults to {@value
   *     #DEFAULT_STATEMENT_SEPARATOR} if not specified
   * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter; never {@code
   *     null} or empty
   * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter; never {@code null} or
   *     empty
   */
  public static void executeSqlScript(
      Connection connection,
      EncodedResource resource,
      boolean continueOnError,
      boolean ignoreFailedDrops,
      String commentPrefix,
      String separator,
      String blockCommentStartDelimiter,
      String blockCommentEndDelimiter)
      throws SQLException, ScriptException {

    if (logger.isInfoEnabled()) {
      logger.info("Executing SQL script from " + resource);
    }
    long startTime = System.currentTimeMillis();
    List<String> statements = new LinkedList<String>();
    String script;
    try {
      script = readScript(resource, commentPrefix, separator);
    } catch (IOException ex) {
      throw new CannotReadScriptException(resource, ex);
    }

    if (separator == null) {
      separator = DEFAULT_STATEMENT_SEPARATOR;
      if (!containsSqlScriptDelimiters(script, separator)) {
        separator = "\n";
      }
    }

    splitSqlScript(
        resource,
        script,
        separator,
        commentPrefix,
        blockCommentStartDelimiter,
        blockCommentEndDelimiter,
        statements);
    int lineNumber = 0;
    Statement stmt = connection.createStatement();
    try {
      for (String statement : statements) {
        lineNumber++;
        try {
          stmt.execute(statement);
          int rowsAffected = stmt.getUpdateCount();
          if (logger.isDebugEnabled()) {
            logger.debug(rowsAffected + " returned as updateCount for SQL: " + statement);
          }
        } catch (SQLException ex) {
          boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
          if (continueOnError || (dropStatement && ignoreFailedDrops)) {
            if (logger.isDebugEnabled()) {
              logger.debug(
                  "Failed to execute SQL script statement at line "
                      + lineNumber
                      + " of resource "
                      + resource
                      + ": "
                      + statement,
                  ex);
            }
          } else {
            throw new ScriptStatementFailedException(statement, lineNumber, resource, ex);
          }
        }
      }
    } finally {
      try {
        stmt.close();
      } catch (Throwable ex) {
        logger.debug("Could not close JDBC Statement", ex);
      }
    }

    long elapsedTime = System.currentTimeMillis() - startTime;
    if (logger.isInfoEnabled()) {
      logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
    }
  }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws IOException {
    HttpSession session = request.getSession();
    boolean redirect = false;

    if (session != null) {
      SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
      if (context != null) {
        if (context.getAuthentication() != null
            && context.getAuthentication().getPrincipal() != null
            && context.getAuthentication().getPrincipal() instanceof User) {
          User user = userService.getUserFromSecurityContext();

          String servletPath = request.getServletPath();

          if (!servletPath.startsWith("/auth")
              && !servletPath.startsWith("/resources")
              && user != null) {
            boolean skipValidation = false;

            if (user.isPasswordExpired()
                && !servletPath.startsWith("/profile/changePassword")
                && !servletPath.startsWith("/auth/forgotPassword")) {
              response.sendRedirect(request.getContextPath() + "/profile/changePassword");
              skipValidation = true;
              redirect = true;
            } else if (user.isPasswordExpired()
                && (servletPath.startsWith("/profile/changePassword")
                    || servletPath.startsWith("/auth/forgotPassword"))) {
              skipValidation = true;
            }

            if (!user.isActivated() && !servletPath.startsWith("/activate") && !skipValidation) {
              response.sendRedirect(request.getContextPath() + "/activate");
              redirect = true;
            }
          }
        }
      }
    }

    // We do not want the healthcheck to ever populate the WebRequest object
    if (request != null
        && !StringUtils.startsWithIgnoreCase(request.getServletPath(), "/healthcheck")) {
      String serverName;
      // If ApplicationDomain is set on the properties then use that as the server name, else use
      // what came off the request
      if (StringUtils.hasText(applicationDomain)
          && !("${" + SystemProperties.APPLICATION_DOMAIN + "}")
              .equalsIgnoreCase(applicationDomain)) {
        serverName = applicationDomain;
      } else {
        serverName = request.getServerName();
      }
      WebRequest.getInstance(
          request.getScheme(), serverName, request.getServerPort(), request.getContextPath());
    }

    if (redirect) {
      return false;
    }

    return true;
  }
 /**
  * Check whether the specified path indicates a resource in the protected WEB-INF or META-INF
  * directories.
  *
  * @param path the path to check
  */
 private static boolean isProtectedResource(String path) {
   return (StringUtils.startsWithIgnoreCase(path, "/WEB-INF")
       || StringUtils.startsWithIgnoreCase(path, "/META-INF"));
 }