public List<String> getSpecialLessons(String grade, String year) {
    List<String> lessons = new ArrayList<String>();
    lessons.addAll(standardSpecialLessons());

    if (StringUtils.equalsIgnoreCase(grade, SIXTH_GRADE)
        || StringUtils.equalsIgnoreCase(grade, FIFTH_GRADE)) {
      List<LessonPost> posts = postDAO.getByYearGradeLessonKeyword(year, grade, null);
      for (LessonPost post : posts) {
        String uuid = post.getUuid();
        if (StringUtils.containsIgnoreCase(uuid, SPECIAL_TAG)) {
          boolean contains = false;
          for (String special : standardSpecialLessons()) {
            if (StringUtils.containsIgnoreCase(uuid, special)) {
              contains = true;
            }
          }

          if (!contains) {
            int index = uuid.indexOf(SPECIAL_TAG) + SPECIAL_TAG.length() + 1;
            String name = uuid.substring(index);

            lessons.add(name);
          }
        }
      }
    }
    return lessons;
  }
  public List<String> getLessons(String grade, String year) {
    List<String> lessons = new ArrayList<String>();

    if (StringUtils.equalsIgnoreCase(grade, SIXTH_GRADE)) {
      int hi_friends = 2;

      for (String lesson : sixthGradeLessons()) {
        lessons.add(HI_FRIENDS_PREFIX + hi_friends + CONJUNCTION + lesson);
      }
    } else if (StringUtils.equalsIgnoreCase(grade, FIFTH_GRADE)) {
      int hi_friends = 1;

      for (String lesson : fifthGradeLessons()) {
        lessons.add(HI_FRIENDS_PREFIX + hi_friends + CONJUNCTION + lesson);
      }
    } else {
      List<String> grades = Arrays.asList(StringUtils.split(grade, CONJUNCTION));
      List<LessonPost> posts = postDAO.getByYearGradeLessonKeyword(year, grades, null);

      for (LessonPost post : posts) {
        String uuid = post.getUuid();
        if (StringUtils.containsIgnoreCase(uuid, LESSONS_PREFIX)) {
          int index = uuid.lastIndexOf(LESSONS_PREFIX) + LESSONS_PREFIX.length();
          String name = uuid.substring(index);

          lessons.add(name);
        }
      }
    }
    return lessons;
  }
  private ParamStruct processParameter(SMInputCursor ruleC) throws XMLStreamException {
    ParamStruct param = new ParamStruct();

    // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT
    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      param.key = StringUtils.trim(keyAttribute);
    }

    // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT
    String typeAttribute = ruleC.getAttrValue("type");
    if (StringUtils.isNotBlank(typeAttribute)) {
      param.type = RuleParamType.parse(typeAttribute);
    }

    SMInputCursor paramC = ruleC.childElementCursor();
    while (paramC.getNext() != null) {
      String propNodeName = paramC.getLocalName();
      String propText = StringUtils.trim(paramC.collectDescendantText(false));
      if (StringUtils.equalsIgnoreCase("key", propNodeName)) {
        param.key = propText;

      } else if (StringUtils.equalsIgnoreCase("description", propNodeName)) {
        param.description = propText;

      } else if (StringUtils.equalsIgnoreCase("type", propNodeName)) {
        param.type = RuleParamType.parse(propText);

      } else if (StringUtils.equalsIgnoreCase("defaultValue", propNodeName)) {
        param.defaultValue = propText;
      }
    }
    return param;
  }
Beispiel #4
0
  /**
   * Gets the payee's email address from KIM data if the payee type is Employee or Entity;
   * otherwise, returns the stored field value.
   *
   * @return Returns the payeeEmailAddress
   */
  public String getPayeeEmailAddress() {
    // for Employee, retrieve from Person table by employee ID
    if (StringUtils.equalsIgnoreCase(payeeIdentifierTypeCode, PayeeIdTypeCodes.EMPLOYEE)) {
      Person person =
          SpringContext.getBean(PersonService.class).getPersonByEmployeeId(payeeIdNumber);
      if (ObjectUtils.isNotNull(person)) {
        return person.getEmailAddress();
      }
    }
    // for Entity, retrieve from Entity table by entity ID then from Person table
    else if (StringUtils.equalsIgnoreCase(payeeIdentifierTypeCode, PayeeIdTypeCodes.ENTITY)) {
      if (ObjectUtils.isNotNull(payeeIdNumber)) {
        EntityDefault entity =
            KimApiServiceLocator.getIdentityService().getEntityDefault(payeeIdNumber);
        if (ObjectUtils.isNotNull(entity)) {
          List<Principal> principals = entity.getPrincipals();
          if (principals.size() > 0 && ObjectUtils.isNotNull(principals.get(0))) {
            String principalId = principals.get(0).getPrincipalId();
            Person person = SpringContext.getBean(PersonService.class).getPerson(principalId);
            if (ObjectUtils.isNotNull(person)) {
              return person.getEmailAddress();
            }
          }
        }
      }
    }

    // otherwise returns the field value
    return payeeEmailAddress;
  }
  /* (non-Javadoc)
   * @see com.appabc.datas.dao.urge.IUrgeVerifyDao#getNoDepositList(com.appabc.common.base.QueryContext)
   */
  @Override
  public QueryContext<UrgeVerifyInfo> getNoDepositList(QueryContext<UrgeVerifyInfo> qContext) {
    if (qContext == null) {
      return null;
    }
    StringBuilder sql = new StringBuilder(queryFieldSql);
    sql.append(" FROM (SELECT * FROM SYS_TASKS WHERE TYPE=22 AND FINISHED=1) task");
    sql.append(queryCountNumSql);

    String registtime =
        qContext.getParameters().get("registtime") != null
            ? (String) qContext.getParameters().get("registtime")
            : StringUtils.EMPTY;
    String verifytime =
        qContext.getParameters().get("verifytime") != null
            ? (String) qContext.getParameters().get("verifytime")
            : StringUtils.EMPTY;
    if (StringUtils.isNotEmpty(verifytime)) {
      if (StringUtils.equalsIgnoreCase("ALL", verifytime)) {
        sql.append(" ORDER BY LASTVERIFYDATE DESC ");
      } else {
        sql.append(" ORDER BY LASTVERIFYDATE " + verifytime);
      }
    } else if (StringUtils.isNotEmpty(registtime)) {
      if (StringUtils.equalsIgnoreCase("ALL", registtime)) {
        sql.append(" ORDER BY REGDATE DESC ");
      } else {
        sql.append(" ORDER BY REGDATE " + registtime);
      }
    } else {
      sql.append(" ORDER BY LASTVERIFYDATE DESC ");
    }
    Object[] args =
        CollectionUtils.isEmpty(qContext.getParamList()) ? null : qContext.getParamList().toArray();
    if (qContext.getPage().getPageIndex() <= 0) {
      log.info("The Query Sql Is  : " + sql);
      List<UrgeVerifyInfo> list = getJdbcTemplate().query(sql.toString(), args, rowMapper1);
      QueryResult<UrgeVerifyInfo> qr = qContext.getQueryResult();
      qr.setResult(list);
      qr.setTotalSize(list.size());
      qContext.setQueryResult(qr);
    } else {
      ISQLGenerator iSQLGenerator = PaginationInfoDataBaseBuiler.generateSQLGenerateFactory();
      String countSql = iSQLGenerator.generateCountSql(sql.toString());
      log.info("The Count Sql Is  : " + countSql);
      PageModel pm = qContext.getPage();
      QueryResult<UrgeVerifyInfo> qr = qContext.getQueryResult();
      String pageSql = iSQLGenerator.generatePageSql(sql.toString(), pm);
      log.info("The Page Sql Is  : " + pageSql);
      // 获取记录总数
      int count = getJdbcTemplate().queryForObject(countSql, args, Integer.class);
      qr.setTotalSize(count);
      pm.setTotalSize(count);
      // 获取分页后的记录数量
      List<UrgeVerifyInfo> list = getJdbcTemplate().query(pageSql, args, rowMapper1);
      qr.setResult(list);
    }
    return qContext;
  }
  public List<String> getYearlyItems(String grade) {
    List<String> items = new ArrayList<String>();

    if (StringUtils.equalsIgnoreCase(grade, SIXTH_GRADE)
        || StringUtils.equalsIgnoreCase(grade, FIFTH_GRADE)) {
      items.add(SYLLABUS);
      items.add(FULL_DOWNLOAD);
    }
    return items;
  }
 private CompressionMode determineCompressionMode(String fileCompressionMode) {
   CompressionMode compressionMode;
   if (StringUtils.equalsIgnoreCase(fileCompressionMode, "gz")) {
     compressionMode = CompressionMode.GZ;
   } else if (StringUtils.equalsIgnoreCase(fileCompressionMode, "zip")) {
     compressionMode = CompressionMode.ZIP;
   } else {
     compressionMode = CompressionMode.NONE;
   }
   return compressionMode;
 }
 /**
  * Returns the priority ordinal matching the specified warning type string.
  *
  * @param warningTypeString a string containing the warning type returned by a regular expression
  *     group matching it in the warnings output.
  * @return the priority
  */
 private Priority parsePriority(final String warningTypeString) {
   if (StringUtils.equalsIgnoreCase(warningTypeString, "notice")) {
     return Priority.LOW;
   } else if (StringUtils.equalsIgnoreCase(warningTypeString, "warning")) {
     return Priority.NORMAL;
   } else if (StringUtils.equalsIgnoreCase(warningTypeString, "error")) {
     return Priority.HIGH;
   } else {
     // empty label or other unexpected input
     return Priority.HIGH;
   }
 }
Beispiel #9
0
 public static String getRemoteIp(HttpServletRequest request) {
   String ip = request.getHeader("x-forwarded-for");
   if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase("unknown", ip)) {
     ip = request.getHeader("Proxy-Client-IP");
   }
   if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase("unknown", ip)) {
     ip = request.getHeader("WL-Proxy-Client-IP");
   }
   if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase("unknown", ip)) {
     ip = request.getRemoteAddr();
   }
   return ip;
 }
 protected boolean isManualProjectEvent(CoiDisclosure disclosure) {
   if (StringUtils.equalsIgnoreCase(
           CoiDisclosureEventType.MANUAL_AWARD, disclosure.getEventTypeCode())
       || StringUtils.equalsIgnoreCase(
           CoiDisclosureEventType.MANUAL_DEVELOPMENT_PROPOSAL, disclosure.getEventTypeCode())
       || StringUtils.equalsIgnoreCase(
           CoiDisclosureEventType.MANUAL_IRB_PROTOCOL, disclosure.getEventTypeCode())
       || StringUtils.equalsIgnoreCase(
           CoiDisclosureEventType.MANUAL_IACUC_PROTOCOL, disclosure.getEventTypeCode())) {
     return true;
   }
   return false;
 }
Beispiel #11
0
  private static void processRule(Rule rule, SMInputCursor ruleC) throws XMLStreamException {
    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      rule.setKey(StringUtils.trim(keyAttribute));
    }

    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
    String priorityAttribute = ruleC.getAttrValue("priority");
    if (StringUtils.isNotBlank(priorityAttribute)) {
      rule.setSeverity(RulePriority.valueOf(StringUtils.trim(priorityAttribute)));
    }

    List<String> tags = Lists.newArrayList();
    SMInputCursor cursor = ruleC.childElementCursor();

    while (cursor.getNext() != null) {
      String nodeName = cursor.getLocalName();

      if (StringUtils.equalsIgnoreCase("name", nodeName)) {
        rule.setName(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("description", nodeName)) {
        rule.setDescription(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("key", nodeName)) {
        rule.setKey(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("configKey", nodeName)) {
        rule.setConfigKey(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("priority", nodeName)) {
        rule.setSeverity(
            RulePriority.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));

      } else if (StringUtils.equalsIgnoreCase("cardinality", nodeName)) {
        rule.setCardinality(
            Cardinality.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));

      } else if (StringUtils.equalsIgnoreCase("status", nodeName)) {
        rule.setStatus(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("param", nodeName)) {
        processParameter(rule, cursor);

      } else if (StringUtils.equalsIgnoreCase("tag", nodeName)) {
        tags.add(StringUtils.trim(cursor.collectDescendantText(false)));
      }
    }
    if (Strings.isNullOrEmpty(rule.getKey())) {
      throw new SonarException("Node <key> is missing in <rule>");
    }
    rule.setTags(tags.toArray(new String[tags.size()]));
  }
  /**
   * Use this method to create a ServerContext from a remote git url. Note that this will require
   * server calls and should be done on a background thread.
   *
   * @param gitRemoteUrl
   * @return
   */
  public ServerContext createContextFromRemoteUrl(final String gitRemoteUrl) {
    assert !StringUtils.isEmpty(gitRemoteUrl);

    try {
      // Get matching context from manager
      ServerContext context = getActiveContext();
      if (context == ServerContext.NO_CONTEXT
          || context.getGitRepository() == null
          || !StringUtils.equalsIgnoreCase(
              context.getGitRepository().getRemoteUrl(), gitRemoteUrl)) {
        context = null;
      }

      if (context == null) {
        // Manager didn't have a matching context, so create one
        final AuthenticationProvider authenticationProvider =
            getAuthenticationProvider(gitRemoteUrl);
        final AuthenticationInfo authenticationInfo =
            AuthHelper.getAuthenticationInfoSynchronously(authenticationProvider, gitRemoteUrl);
        if (authenticationInfo != null) {
          // Create a new context object and store it back in the manager
          context = createServerContext(gitRemoteUrl, authenticationInfo);
        }
      }

      return context;
    } catch (Throwable ex) {
      throw new RuntimeException(ex.getLocalizedMessage(), ex);
    }
  }
  /** Populates the flight extra content */
  @Override
  public void populate(final Object source, final ContentViewData target) {
    // REVISIT:Changed to BasePackage
    final BasePackage packageModel = packageCartService.getBasePackage();
    final FlightExtraFacilityStore flightExtraStore =
        sessionService.getAttribute(SessionObjectKeys.FLIGHT_EXTRA_FACILITY_STORE);
    String flightMealCode = StringUtils.EMPTY;
    if (flightExtraStore != null) {
      String inventoryCode = StringUtils.EMPTY;
      final Map<String, List<ExtraFacility>> validExtraFacilitiesMap =
          flightExtraStore.getExtraFacilityFromAllLegsBasedOnCabinClass(
              packageModel.getId(), PackageUtilityService.getCabinClass(packageModel));
      for (final List<ExtraFacility> eachEntry : validExtraFacilitiesMap.values()) {
        inventoryCode = eachEntry.get(0).getExtraFacilityCategory().getInventoryCode();
        final String extraCode = eachEntry.get(0).getExtraFacilityCode();
        final String corporateCode = eachEntry.get(0).getCorporateCode();
        final List<DynamicContentConfigModel> dynamicContents =
            genericContentService.getDynamicContentConfig(inventoryCode, extraCode, corporateCode);

        getDynamicContents(target, dynamicContents);
      }
      if (StringUtils.equalsIgnoreCase(inventoryCode, "FM")) {
        flightMealCode = inventoryCode;
      }

      final Leg leg = getFlightLeg(packageModel);
      populateContentForShortHaul(target, leg);
      populateMealContent(flightMealCode, target);
    }
  }
    public boolean match(Request req) {
      HttpServletRequest hreq = req.httpRequest;
      boolean matched = false;

      // HTTP method
      String reqMethod = req.httpRequest.getMethod();
      for (String httpMethod : httpMethods) {
        if (StringUtils.equalsIgnoreCase(httpMethod, reqMethod)) {
          matched = true;
          break;
        }
      }
      if (!matched) return false;

      // URL
      matched = false;
      // String url = StringHelper.joinIgnoreNull(hreq.getServletPath(), hreq.getPathInfo());
      String url = StringUtils.trimToEmpty(hreq.getPathInfo());
      if (!url.startsWith("/")) url = "/" + url;

      for (String urlPatt : urlPatterns) {
        if (match(urlPatt, url, req)) {
          matched = true;
          break;
        }
      }

      return matched;
    }
  /**
   * When the "update geo data" button is clicked. <br>
   * Updates the login records with geodata for their IP's if found.<br>
   * This is done by a calling a web service from Hostinfo.org.<br>
   *
   * @param event
   * @throws InterruptedException
   */
  public void onClick$button_SecLoginlogList_UpdateGeoData(Event event)
      throws InterruptedException {

    final String str =
        InputConfirmBox.show(
            this.secLoginlogListWindow,
            Labels.getLabel("message.Information.InputSupervisorPassword"));

    if (StringUtils.equalsIgnoreCase(str, "yes we can")) {
      final int recCount = getGuiLoginLoggingService().updateFromHostLookUpMain();

      final String message =
          Labels.getLabel("message.Information.CountRecordsInsertedUpdated") + " " + recCount;
      final String title = Labels.getLabel("message.Information");
      MultiLineMessageBox.doSetTemplate();
      MultiLineMessageBox.show(message, title, MultiLineMessageBox.OK, "INFORMATION", true);

      // ++ create the searchObject and init sorting ++//
      final HibernateSearchObject<SecLoginlog> soSecLoginlog =
          new HibernateSearchObject<SecLoginlog>(SecLoginlog.class, getCountRows());
      // deeper loading of the relations to prevent the lazy
      // loading problem.
      soSecLoginlog.addFetch("ip2Country.countryCode");
      soSecLoginlog.addSort("lglLogtime", true);

      // Set the ListModel
      getPagedListWrapper().init(soSecLoginlog, this.listBoxSecUserlog, this.paging_SecUserLogList);

    } else {
      final String message = Labels.getLabel("message.error.falsePassword");
      final String title = Labels.getLabel("message.Error");
      MultiLineMessageBox.doSetTemplate();
      MultiLineMessageBox.show(message, title, MultiLineMessageBox.OK, "INFORMATION", true);
    }
  }
Beispiel #16
0
  public void removeOtherBookingsIfAny(String email, String bookingId) {
    final List<String> extraBookings = new ArrayList<String>();
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      final Document findCr = new Document();
      findCr.put(DBConstants.EMAIL, email);
      final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        if (!StringUtils.equalsIgnoreCase(bookingId, document.getString(DBConstants.BOOKING_ID))) {
          extraBookings.add(document.getString(DBConstants.BOOKING_ID));
        }
      }

      if (!extraBookings.isEmpty()) {
        QueryBuilder deleteQuery = new QueryBuilder();
        deleteQuery
            .put(DBConstants.BOOKING_ID)
            .in(extraBookings.toArray(new String[extraBookings.size()]));
        coll.deleteMany((Bson) deleteQuery.get());
      }
    } catch (Exception e) {
      e.printStackTrace();
      if (e instanceof com.mongodb.MongoTimeoutException) {
        throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
      }
      throw new ApplicationException(
          MessagesEnum.CLOSE_BOOKING_FAILED.getMessage(extraBookings.toString()), e);
    }
  }
 // this method should be invoked from within the transaction wrapper that covers the request
 // processing so
 // that the db-calls in this method do not each generate new transactions. If executed from within
 // the context
 // of display rendering, this logic will be quite expensive due to the number of new transactions
 // needed.
 @Override
 public Collection<CMT> getAssignmentCommittees(
     String protocolLeadUnit, String docRouteStatus, String currentCommitteeId) {
   Collection<CMT> assignmentCommittees = new ArrayList<CMT>();
   // get the initial list of all valid committees; some of them will be filtered out by the logic
   // below
   Collection<CMT> candidateCommittees = getCandidateCommittees();
   if (CollectionUtils.isNotEmpty(candidateCommittees)) {
     if (isSaved(docRouteStatus)) {
       // Use the lead unit of the protocol to determine committees
       Set<String> unitIds = getProtocolUnitIds(protocolLeadUnit);
       for (CMT committee : candidateCommittees) {
         if (StringUtils.equalsIgnoreCase(committee.getCommitteeDocument().getDocStatusCode(), "F")
             && unitIds.contains(committee.getHomeUnit().getUnitNumber())) {
           assignmentCommittees.add(committee);
         }
       }
     } else {
       // we check the current user's authorization to assign committees
       String principalId = GlobalVariables.getUserSession().getPerson().getPrincipalId();
       for (CMT committee : candidateCommittees) {
         if (isCurrentUserAuthorizedToAssignThisCommittee(principalId, committee)
             || committee.getCommitteeId().equals(currentCommitteeId)) {
           assignmentCommittees.add(committee);
         }
       }
     }
   }
   return assignmentCommittees;
 }
  /**
   * This method will check the current month and set the calendar to that month
   *
   * @param month, dayOfMonth month to set the calendar, dayOfMonth day of the month to set to
   * @return calendar calendar is set to the month selected
   */
  protected void setCalendarWithDays(Calendar calendar, String dayOfMonth) {
    int dayInMonthToSet;
    int calendarMonth = calendar.get(Calendar.MONTH);

    if (StringUtils.equalsIgnoreCase(
        dayOfMonth, EndowConstants.FrequencyMonthly.MONTH_END)) { // month end for the month so
      // need to get max days...
      dayInMonthToSet = checkMaximumDaysInMonth(calendar.get(Calendar.MONTH));
    } else {
      dayInMonthToSet = Integer.parseInt(dayOfMonth);

      if (dayInMonthToSet > 29 && calendarMonth == Calendar.FEBRUARY) {
        dayInMonthToSet = checkMaximumDaysInFebruary();
      } else if (dayInMonthToSet > 30
          && (calendarMonth == Calendar.APRIL
              || calendarMonth == Calendar.JUNE
              || calendarMonth == Calendar.SEPTEMBER
              || calendarMonth == Calendar.NOVEMBER)) {
        dayInMonthToSet = 30;
        dayInMonthToSet = checkMaximumDaysInMonth(calendarMonth);
      }
    }

    calendar.set(Calendar.DAY_OF_MONTH, dayInMonthToSet);
  }
    public void validateSmtp() {
      Validation.required("setup.smtpServer", smtpServer);

      if (HostNameOrIpAddressCheck.isValidHostName(smtpServer)) {
        if (PropertiesConfigurationValidator.validateIpList(nameservers)) {
          Set<String> ips = Sets.newHashSet(nameservers.split(","));
          if (!DnsUtils.validateHostname(ips, smtpServer)) {
            Validation.addError("setup.smtpServer", "setup.smtpServer.invalidSmtpServer");
          }
        } else if (StringUtils.isNotEmpty(nameservers)) {
          Validation.addError(
              "setup.nameservers", "setup.smtpServer.invalidNameserver", nameservers);
        }
      }

      if (!HostNameOrIpAddressCheck.isValidHostNameOrIp(smtpServer)) {
        Validation.addError("setup.smtpServer", "setup.smtpServer.invalid");
      }
      if (!StringUtils.isNumeric(smtpPort)) {
        Validation.addError("setup.smtpServer", "setup.smtpServer.invalidPort");
      }

      Validation.required("setup.smtpFrom", smtpFrom);
      Validation.email("setup.smtpFrom", smtpFrom);

      if (StringUtils.isNotBlank(smtpAuthType)
          && !StringUtils.equalsIgnoreCase(smtpAuthType, "None")) {
        Validation.required("setup.smtpUsername", smtpUsername);
        Validation.required("setup.smtpPassword", smtpPassword);

        if (PasswordUtil.isNotValid(smtpPassword)) {
          Validation.addError("setup.smtpPassword", "setup.password.notValid");
        }
      }
    }
  private void loadRuleKeys() {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
    InputStream inputStream =
        getClass().getResourceAsStream(AndroidLintRulesDefinition.RULES_XML_PATH);
    InputStreamReader reader = new InputStreamReader(inputStream, Charsets.UTF_8);
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <rules>

      SMInputCursor rulesC = rootC.childElementCursor("rule");
      while (rulesC.getNext() != null) {
        // <rule>
        SMInputCursor cursor = rulesC.childElementCursor();
        while (cursor.getNext() != null) {
          if (StringUtils.equalsIgnoreCase("key", cursor.getLocalName())) {
            String key = StringUtils.trim(cursor.collectDescendantText(false));
            ruleKeys.add(key);
          }
        }
      }

    } catch (XMLStreamException e) {
      throw new IllegalStateException("XML is not valid", e);
    }
  }
Beispiel #21
0
  private void verifyUser(
      HttpServletRequest request, HttpServletResponse response, String userId, String password)
      throws Exception {
    // TODO Auto-generated method stub

    // Get user entity from userId
    Users user = UserUtil.getUserFromUserId(userId);

    System.out.println("user = "******"No user found with this user id");

    // Compare user password with requested password
    if (!StringUtils.equals(Globals.REVIEW_DESK_DEFAULT_LOGIN_PASSWORD, password)
        && !StringUtils.equals(user.password, password))
      throw new Exception("Password does not match");

    // Check user verification
    if (!StringUtils.equals(Globals.REVIEW_DESK_DEFAULT_LOGIN_PASSWORD, password)
        && !StringUtils.equalsIgnoreCase(
            user.email_verification, UserUtil.USER_DB_EMAIL_VERIFICATION_VERIFIED))
      throw new Exception("Your account has not been verified yet, Please verify your account");

    // Create session
    UserSession userSession = new UserSession("reviewdesk.com", userId, user.user_name, user.id);
    request.getSession().setAttribute(SessionManager.AUTH_USER_SESSION, userSession);

    // To set session active for 15 days if "keep me signin"
    request.getSession().setMaxInactiveInterval(15 * 24 * 60 * 60);

    // redirect to the home page
    response.sendRedirect("/home");
    return;
  }
  public Pager search(Pager pager) {
    Compass compass = compassTemplate.getCompass();
    CompassSession compassSession = compass.openSession();
    CompassQueryBuilder compassQueryBuilder = compassSession.queryBuilder();
    CompassBooleanQueryBuilder compassBooleanQueryBuilder = compassQueryBuilder.bool();

    CompassQuery compassQuery =
        compassBooleanQueryBuilder
            .addMust(compassQueryBuilder.term("isMarketable", true))
            .addMust(compassQueryBuilder.queryString("name:*" + pager.getKeyword() + "*").toQuery())
            .toQuery();

    if (StringUtils.isEmpty(pager.getOrderBy()) || pager.getOrderType() == null) {
      compassQuery
          .addSort("isBest", SortPropertyType.STRING, SortDirection.REVERSE)
          .addSort("isNew", SortPropertyType.STRING, SortDirection.REVERSE)
          .addSort("isHot", SortPropertyType.STRING, SortDirection.REVERSE);
    } else {
      if (pager.getOrderType() == OrderType.asc) {
        if (StringUtils.equalsIgnoreCase(pager.getOrderBy(), "price")) {
          compassQuery.addSort("price", SortPropertyType.FLOAT);
        }
      } else {
        if (StringUtils.equalsIgnoreCase(pager.getOrderBy(), "price")) {
          compassQuery.addSort("price", SortPropertyType.FLOAT, SortDirection.REVERSE);
        }
      }
    }

    CompassHits compassHits = compassQuery.hits();

    List<Product> productList = new ArrayList<Product>();

    int firstResult = (pager.getPageNumber() - 1) * pager.getPageSize();
    int maxReasults = pager.getPageSize();
    int totalCount = compassHits.length();

    int end = Math.min(totalCount, firstResult + maxReasults);
    for (int i = firstResult; i < end; i++) {
      Product product = (Product) compassHits.data(i);
      productList.add(product);
    }
    compassSession.close();
    pager.setList(productList);
    pager.setTotalCount(totalCount);
    return pager;
  }
 /**
  * 保存上传的文件并返回资源的URL。可支持多个,但目前的使用方式都是一个。可支持中文文件名。可支持分类别存放。类别下会再按日期存放。 如果同一天内同名文件已经存在,会自动改名。
  *
  * <p>配合ocupload.js暂时只能支持每一次upload上传一个文件
  *
  * @param request
  * @param response
  * @return
  */
 public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response) {
   String uploadWidget = request.getParameter("uploadWidget");
   if (StringUtils.equalsIgnoreCase(uploadWidget, "SWFUpload")) {
     return uploadFileBySwfUpload(request, response);
   } else {
     return uploadFileByIframeUpload(request, response);
   }
 }
 public static GoHoPropertyStatus parse(String value) {
   for (GoHoPropertyStatus status : GoHoPropertyStatus.values()) {
     if (StringUtils.equalsIgnoreCase(status.name(), value)) {
       return status;
     }
   }
   return null;
 }
 @XmlAttribute(name = "DEF")
 public String getDefaultValue() {
   if (StringUtils.equalsIgnoreCase(defaultValue, "AUTO_INCREMENT")) {
     return null;
   } else {
     return defaultValue;
   }
 }
 /**
  * . this method is for gettingFollowUpDates
  *
  * @return returnAmount
  */
 public int getFollowupDateDefaultLengthInDays() {
   String followupDateRange = getFollowupDateDefaultLength();
   String rangeUnit =
       followupDateRange.substring(followupDateRange.length() - 1, followupDateRange.length());
   int rangeAmount =
       Integer.parseInt(followupDateRange.substring(0, followupDateRange.length() - 1));
   int returnAmount = 0;
   if (StringUtils.equalsIgnoreCase(rangeUnit, "D")) {
     returnAmount = rangeAmount;
   } else if (StringUtils.equalsIgnoreCase(rangeUnit, "W")) {
     returnAmount = rangeAmount * 7;
   } else {
     throw new IllegalArgumentException(
         "An invalid range unit was set in the " + "'Subaward Follow Up' parameter: " + rangeUnit);
   }
   return returnAmount;
 }
  public void setHttpProxy(String proxyHost) {
    if (!StringUtils.equalsIgnoreCase(proxyHost, "none")) {
      proxy = new Proxy();
      proxy.setHttpProxy(proxyHost);

      capabilities.setCapability(CapabilityType.PROXY, proxy);
    }
  }
 public synchronized ServerContext getServerContext(final URI uri) {
   // TODO -- only one for now
   if (activeContext != ServerContext.NO_CONTEXT
       && StringUtils.equalsIgnoreCase(activeContext.getUri().getHost(), uri.getHost())) {
     return activeContext;
   }
   return ServerContext.NO_CONTEXT;
 }
Beispiel #29
0
 public static SupportedMedia resolveFromMimeType(String mimeType) {
   if (Strings.isEmpty(mimeType)) return null;
   for (SupportedMedia supportedMedia : SupportedMedia.values()) {
     if (StringUtils.equalsIgnoreCase(supportedMedia.getMimeType(), mimeType)) {
       return supportedMedia;
     }
   }
   return null;
 }
 /**
  * Return a page of computer
  *
  * @param page Page to display
  * @param pageSize Number of pfps per page
  * @param sortBy Pfp property used for sorting
  * @param order Sort order (either or asc or desc)
  * @param filter Filter applied on the name column
  */
 public static Page<Event> page(
     int page,
     int pageSize,
     String sortBy,
     String order,
     String filter,
     String fieldName,
     User localUser) {
   String queryField = "name";
   if (StringUtils.equals("name", fieldName) || StringUtils.equals("schoolId", fieldName)) {
     queryField = fieldName;
   } else if (StringUtils.equals("status", fieldName)) {
     if (StringUtils.equalsIgnoreCase("NEW", filter)) {
       filter = "1";
     } else if (StringUtils.equalsIgnoreCase("PRIVATE", filter)) {
       filter = "2";
     } else if (StringUtils.equalsIgnoreCase("LOCKED", filter)) {
       filter = "4";
     } else {
       filter = "3";
     }
     queryField = fieldName;
   } else if (StringUtils.equals("userAdmin", fieldName)) {
     queryField = "userAdmin.organization.taxId";
   }
   if (StringUtils.equals("eventName", sortBy)) {
     sortBy = "name";
   }
   if (pageSize > 20) {
     pageSize = 20;
   }
   ExpressionList<Event> query = find.where().ilike(queryField, "%" + filter + "%");
   if (localUser != null) {
     query.eq("userAdmin.id", localUser.id);
   }
   return query
       .orderBy(sortBy + " " + order)
       .select(
           "id, eventEnd, eventStart, status, schoolId, fundraisingEnd, fundraisingStart, goal, name, userAdmin")
       .fetch("userAdmin")
       .findPagingList(pageSize)
       .setFetchAhead(false)
       .getPage(page);
 }