Exemple #1
0
 public List<SponsorDTO> getMatchingSponsors(SponsorCriteriaDto searchCriteria) {
   List<SponsorDTO> results = new ArrayList<SponsorDTO>();
   Collection<Sponsor> sponsors;
   if (ObjectUtils.isNull(searchCriteria)
       || (StringUtils.isEmpty(searchCriteria.getSponsorCode())
           && StringUtils.isEmpty(searchCriteria.getCustomerNumber()))) {
     sponsors = getBusinessObjectService().findAll(Sponsor.class);
   } else if (StringUtils.isNotEmpty(searchCriteria.getSponsorCode())) {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("sponsorCode", searchCriteria.getSponsorCode()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   } else {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("customerNumber", searchCriteria.getCustomerNumber()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   }
   if (sponsors != null && !sponsors.isEmpty()) {
     for (Sponsor sponsor : sponsors) {
       results.add(sponsorDtoService.buildDto(sponsor));
     }
   }
   return results;
 }
  @RequestMapping(value = "/reg", method = RequestMethod.POST)
  public ModelAndView register(
      @RequestParam("login") String login,
      @RequestParam("password") String password,
      @RequestParam("mail") String mail) {
    ModelAndView model = new ModelAndView();

    try {
      if (StringUtils.isEmpty(mail)
          || StringUtils.isEmpty(login)
          || StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException();
      }
      User user = new User(login, password, mail);
      model.addObject("title", "Access granted");
      model.addObject("message", "Enter in your mail for activate your account");
      model.setViewName("mail");
      model.addObject(user);
      userService.addUser(user);
    } catch (IllegalArgumentException ex) {
      model.addObject("title", "Registration failed");
      model.addObject("message", "Check your credentials");
      model.setViewName("error");
    } catch (Exception ex) {
      model.addObject("title", "Registration failed");
      model.addObject("message", "Login is already exists");
      model.setViewName("error");
    }
    return model;
  }
 /**
  *
  *
  * <ul>
  *   <li><b>IsEmpty/IsBlank</b> - checks if a String contains text
  *   <li><b>Equals</b> - compares two strings null-safe
  *   <li><b>startsWith</b> - check if a String starts with a prefix null-safe
  *   <li><b>endsWith</b> - check if a String ends with a suffix null-safe
  *   <li><b>IndexOf/LastIndexOf/Contains</b> - null-safe index-of checks
  *   <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b> - index-of any of a set
  *       of Strings
  *   <li><b>ContainsOnly/ContainsNone/ContainsAny</b> - does String contains only/none/any of
  *       these characters
  *   <li><b>Chomp/Chop</b> - removes the last part of a String
  *   <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b> - changes the case of a
  *       String
  *   <li><b>CountMatches</b> - counts the number of occurrences of one String in another
  *   <li><b>DefaultString</b> - protects against a null input String
  *   <li><b>Reverse/ReverseDelimited</b> - reverses a String
  *   <li><b>Abbreviate</b> - abbreviates a string using ellipsis
  *   <li><b>Difference</b> - compares Strings and reports on their differences
  *   <li><b>LevenshteinDistance</b> - the number of changes needed to change one String into
  *       another
  * </ul>
  */
 @Test
 public void testEmptyBlankStringUtils() {
   String[] array = new String[2];
   array[0] = StringUtils.repeat('*', 10) + strOne + StringUtils.repeat('*', 10);
   array[1] = StringUtils.repeat('~', 10) + strTwo + StringUtils.repeat('~', 10);
   System.out.println(StringUtils.join(array, ","));
   System.out.println("判断是否为空或者空格");
   System.out.println(
       "empty:"
           + StringUtils.isEmpty(strOne)
           + "\t"
           + StringUtils.isEmpty(null)
           + "\t"
           + StringUtils.isEmpty("")
           + "\t"
           + StringUtils.isEmpty(" "));
   System.out.println(
       "whitespace:"
           + StringUtils.isBlank(strOne)
           + "\t"
           + StringUtils.isBlank(null)
           + "\t"
           + StringUtils.isBlank("")
           + "\t"
           + StringUtils.isBlank(" "));
 }
Exemple #4
0
  public void doLogin() {
    errors.clear();
    currentProfile = EMPTY_PROFILE;

    if (StringUtils.isEmpty(login)) {
      errors.add("Пустой логин");
      return;
    }

    if (StringUtils.isEmpty(password)) {
      errors.add("Пустой пароль");
      return;
    }

    try {
      currentProfile = authBean.authenticate(login, password);
      FacesContext.getCurrentInstance().getExternalContext().redirect(initialRequest);
    } catch (SurvivalException e) {
      switch (e.getErrorType()) {
        case INVALID_LOGIN:
          errors.add("Неверный логин");
          break;
        case INVALID_PASSWORD:
          errors.add("Неверный пароль");
          break;
        default:
          errors.add("Внутренняя ошибка");
          break;
      }
    } catch (IOException e) {
      errors.add("Внутренняя ошибка");
    }
  }
 private UserUser getUsers(String userId) {
   if (StringUtils.isEmpty(userId)) {
     alert("无法获取到所必须的参数");
     return null;
   }
   UserUser targetUser = userUserProxy.getUserUserByUserNo(userId);
   if (null == targetUser || "N".equalsIgnoreCase(targetUser.getIsValid())) {
     alert("无法找到该用户或该用户已经无效,无需再次操作");
     return null;
   }
   if (!StringUtils.isEmpty(targetUser.getUserName())) {
     targetUser.setUserName(targetUser.getUserName() + "B");
   }
   if (!StringUtils.isEmpty(targetUser.getMobileNumber())) {
     targetUser.setMobileNumber(targetUser.getMobileNumber() + "B");
   }
   if (!StringUtils.isEmpty(targetUser.getEmail())) {
     targetUser.setEmail(targetUser.getEmail() + "B");
   }
   if (!StringUtils.isEmpty(targetUser.getMemberShipCard())) {
     targetUser.setMemberShipCard(targetUser.getMemberShipCard() + "B");
   }
   targetUser.setIsValid("N");
   targetUser.setUserPassword("****************");
   return targetUser;
 }
  @Override
  public AniServiceDto getByAniService(String aniServiceId, String clientSecret) throws Exception {
    if (StringUtils.isEmpty(aniServiceId) || StringUtils.isEmpty(clientSecret)) {
      throw new Exception("AniServiceId or ClientSecret is null.");
    }

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder
        .append(anicelMeta.getAniServiceBusUrl())
        .append(anicelMeta.getServiceBusGetByUrl())
        .append("/")
        .append(aniServiceId)
        .append("/")
        .append(clientSecret);

    UriComponentsBuilder uriComponentsBuilder =
        UriComponentsBuilder.fromHttpUrl(stringBuilder.toString());
    LOGGER.info(uriComponentsBuilder.toUriString());
    AniServiceHttpMessage result =
        restTemplateFactory
            .getRestTemplate(new Class[] {AniServiceDto.class})
            .getForObject(uriComponentsBuilder.toUriString(), AniServiceHttpMessage.class);

    if (result.getResultCode() == Message.ResultCode.SUCCESS) {
      return result.getReturnObj();
    } else {
      StringBuilder builder =
          new StringBuilder("message: ")
              .append(result.getMsg())
              .append(", error code:")
              .append(result.getResultCode());
      throw new Exception(builder.toString());
    }
  }
  @Override
  @Transactional
  public Collection create(CollectionDetailsInfo collectionDetailsInfo, UserAccount user)
      throws Exception {

    String filteredTrack = collectionDetailsInfo.getTrack();

    if (!StringUtils.isEmpty(filteredTrack)) {
      filteredTrack = getFilteredTrack(filteredTrack);

      if (StringUtils.isEmpty(filteredTrack)) {
        return null;
      }
    }

    Collection collection = adaptCollectionDetailsInfoToCollection(collectionDetailsInfo, user);
    collection.setTrack(filteredTrack);
    collection.setUsageType(UsageType.Production);
    try {
      collectionRepository.save(collection);
      collaboratorService.addCollaboratorToCollection(
          collectionDetailsInfo.getCode(), user.getId());
      return collection;
    } catch (Exception e) {

      logger.error("Error in creating collection.", e);
      return null;
    }
  }
  private boolean parseAuditLogForm(
      AuditLogForm auditLogForm,
      JEventCategory eventCategory,
      Model uiModel,
      Integer page,
      Integer size) {

    boolean hasParseErrors = false;
    String sDate = auditLogForm.getStartDateAsString();
    String eDate = auditLogForm.getEndDateAsString();
    try {

      if (!StringUtils.isEmpty(sDate)) {
        Date startDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(sDate));
        auditLogForm.setStartDate(startDate);
      }
      // Include endDate
      if (!StringUtils.isEmpty(eDate)) {
        Date endDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(eDate));
        if (endDate != null) {
          DateTime dateTime = new DateTime(endDate);
          dateTime = dateTime.plusDays(1);
          auditLogForm.setEndDate(dateTime.toDate());
        }
      }

    } catch (ParseException e) {
      logger.error(">>> Failed parsing date.", e);
      uiModel.addAttribute("error_msg", "Saisie invalide. Le format de date est incorrect.");
      populateAuditLog(new AuditLogForm(), eventCategory, uiModel, "auditconnections", page, size);
      hasParseErrors = true;
    }

    return hasParseErrors;
  }
  /**
   * Description:进行手机认证<br>
   *
   * @author hujianpan
   * @version 0.1 2014年8月30日
   * @param request
   * @param session
   * @param mobile 手机号
   * @param activeCode 验证码
   * @return String
   */
  @RequestMapping(value = "verificationMobailActiveCode")
  @ResponseBody
  public MessageBox verificationMobailActiveCode(HttpServletRequest request, HttpSession session) {
    String result = BusinessConstants.SUCCESS;
    Member member = currentMember();
    String userNameParam = "@@@@";
    String mobileParam = request.getParameter("mobile");
    String activeCodeParam = request.getParameter("activeCode");
    if (member != null) {
      userNameParam = member.getUsername();
      if (StringUtils.isEmpty(userNameParam)) {
        return new MessageBox("0", "用户名不能为空");
      }
    } else {
      return new MessageBox("0", "注册信息丢失,请重新登入或注册");
    }

    if (StringUtils.isEmpty(mobileParam)) {
      return new MessageBox("0", "用户手机号不能为空");
    }
    if (StringUtils.isEmpty(activeCodeParam)) {
      return new MessageBox("0", "手机验证码不能为空");
    }

    result =
        mobileApproService.verificationMobailActiveCode(
            request, member, mobileParam, activeCodeParam);
    if (!BusinessConstants.SUCCESS.equals(result)) {
      return new MessageBox("0", result);
    }

    return new MessageBox("1", "验证成功");
  }
  @Override
  public void restResource(
      final JavaType type, final boolean hide, final String path, final String rel) {

    final ClassOrInterfaceTypeDetails typeDetails = typeLocationService.getTypeDetails(type);
    Validate.notNull(typeDetails, "The repository specified, '" + type + "'doesn't exist");

    final AnnotationMetadataBuilder annotationBuilder =
        new AnnotationMetadataBuilder(REST_RESOURCE);
    if (hide) {
      annotationBuilder.addBooleanAttribute("exported", false);
    }
    if (!StringUtils.isEmpty(path)) {
      annotationBuilder.addStringAttribute("path", path);
    }
    if (!StringUtils.isEmpty(rel)) {
      annotationBuilder.addStringAttribute("rel", rel);
    }

    final ClassOrInterfaceTypeDetailsBuilder cidBuilder =
        new ClassOrInterfaceTypeDetailsBuilder(typeDetails);

    if (MemberFindingUtils.getAnnotationOfType(typeDetails.getAnnotations(), REST_RESOURCE)
        != null) {
      cidBuilder.removeAnnotation(REST_RESOURCE);
    }

    cidBuilder.addAnnotation(annotationBuilder);

    typeManagementService.createOrUpdateTypeOnDisk(cidBuilder.build());
  }
  private Requirement getRequirement(
      Class candidateClass,
      String packageName,
      int level,
      String requirementTitle,
      String requirementType,
      String narrativeText,
      String cardNumber,
      Optional<Narrative> narrative) {
    if (narrative.isPresent()) {
      requirementTitle = narrative.get().title();
      requirementType = narrative.get().type();
      narrativeText = Joiner.on("\n").join(narrative.get().text());
      cardNumber = narrative.get().cardNumber();
    }
    if (StringUtils.isEmpty(requirementType)) {
      requirementType = getRequirementType(level, candidateClass);
    }

    return Requirement.named(humanReadableVersionOf(packageName))
        .withOptionalCardNumber(cardNumber)
        .withOptionalDisplayName(
            StringUtils.isEmpty(requirementTitle)
                ? humanReadableVersionOf(packageName)
                : requirementTitle)
        .withType(requirementType)
        .withNarrativeText(narrativeText);
  }
  static Map<String, String> getDatabases() {
    Properties configuration = new Properties();
    try {
      configuration.load(
          MBTilesUtils.class.getClassLoader().getResourceAsStream("mbtiles4j.properties"));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    HashMap<String, String> result = new HashMap<String, String>();

    String dbs = configuration.getProperty("tile-dbs");
    if (StringUtils.isEmpty(dbs)) {
      return result;
    }

    String[] split = dbs.split(Pattern.quote(","));
    for (String entry : split) {
      String path = configuration.getProperty(entry + ".path");
      if (!StringUtils.isEmpty(path)) {
        result.put(entry, path);
      }
    }

    return result;
  }
  @RestMethod(method = HttpMethod.GET, template = "")
  public List<TestTeamPojo> getTeams(
      @QueryParameter(name = "teamType") @Description("Identifies the team type.") String teamType,
      @QueryParameter(name = "teamName") String teamName,
      @QueryParameter(name = "city") String cities[]) {

    List<TestTeamPojo> result = new ArrayList<TestTeamPojo>();
    for (TestTeamPojo team : teams) {
      boolean match = true;
      if (!StringUtils.isEmpty(teamType))
        if (!teamType.equals(team.getType().name())) match = false;
      if (!StringUtils.isEmpty(teamName)) if (!teamName.equals(team.getName())) match = false;

      if (cities.length > 0) {
        boolean found = false;
        for (String city : cities) {
          if (!StringUtils.isEmpty(city)) if (city.equals(team.getCity())) found = true;
        }
        if (!found) match = false;
      }
      if (match == true) result.add(team);
    }

    lastMethodCalled = "getTeams";
    lastHttpMethodCalled = "GET";

    return result;
  }
 @Override
 public final int compare(String[] o1, String[] o2) {
   String t1 = o1[this.index];
   String t2 = o2[this.index];
   if (StringUtils.isEmpty(t1) && StringUtils.isEmpty(t2)) {
     return 0;
   }
   if (StringUtils.isEmpty(t1)) {
     return 1;
   }
   if (StringUtils.isEmpty(t2)) {
     return -1;
   }
   if (StringUtils.isNumeric(t1) && StringUtils.isNumeric(t2)) {
     // 数値文字列の場合
     Long o1l = Long.valueOf(t1);
     Long o2l = Long.valueOf(t2);
     return this.compareTo(o1l, o2l, this.order);
   } else if (t1.matches("(?:\\d+日)?(?:\\d+時間)?(?:\\d+分)?(?:\\d+秒)?")) {
     try {
       // 時刻文字列の場合
       // SimpleDateFormatは24時間超えるような時刻でも正しく?パースしてくれる
       Date o1date = DateUtils.parseDate(t1, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       Date o2date = DateUtils.parseDate(t2, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       return this.compareTo(o1date, o2date, this.order);
     } catch (ParseException e) {
       e.printStackTrace();
     }
   }
   // 文字列の場合
   return this.compareTo(t1, t2, this.order);
 }
Exemple #15
0
 public void setProperties(Properties p) {
   dialect = p.getProperty("dialect");
   if (StringUtils.isEmpty(dialect)) {
     try {
       throw new PropertyException("dialect property is not found!");
     } catch (PropertyException e) {
       e.printStackTrace();
       logger.error("没有mybatis方言属性,拦截错误:", e);
     }
   }
   pageSqlId = p.getProperty("pageSqlId");
   if (StringUtils.isEmpty(pageSqlId)) {
     try {
       throw new PropertyException("pageSqlId property is not found!");
     } catch (PropertyException e) {
       e.printStackTrace();
       logger.error("没有mybatis分页拦截方法属性,拦截错误:", e);
     }
   }
   generateDialect();
   if (dialectObj == null) {
     logger.error("初始化分页插件方言错误!");
     throw new RuntimeException("初始化分页插件方言错误!");
   }
 }
Exemple #16
0
 public void send(String message, String username)
     throws PushNotInitializedException, UserNotFoundException, SqlInjectionException,
         InvalidRequestException, IOException, UnknownHostException {
   if (Logger.isDebugEnabled())
     Logger.debug("Try to send a message (" + message + ") to " + username);
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   ODocument userSystemProperties = user.field(UserDao.ATTRIBUTES_SYSTEM);
   if (Logger.isDebugEnabled()) Logger.debug("userSystemProperties: " + userSystemProperties);
   List<ODocument> loginInfos = userSystemProperties.field(UserDao.USER_LOGIN_INFO);
   if (Logger.isDebugEnabled()) Logger.debug("Sending to " + loginInfos.size() + " devices");
   for (ODocument loginInfo : loginInfos) {
     String pushToken = loginInfo.field(UserDao.USER_PUSH_TOKEN);
     String vendor = loginInfo.field(UserDao.USER_DEVICE_OS);
     if (Logger.isDebugEnabled()) Logger.debug("push token: " + pushToken);
     if (Logger.isDebugEnabled()) Logger.debug("vendor: " + vendor);
     if (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(pushToken)) {
       VendorOS vos = VendorOS.getVendorOs(vendor);
       if (Logger.isDebugEnabled()) Logger.debug("vos: " + vos);
       if (vos != null) {
         IPushServer pushServer = Factory.getIstance(vos);
         pushServer.setConfiguration(getPushParameters());
         pushServer.send(message, pushToken);
       } // vos!=null
     } // (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(deviceId)
   } // for (ODocument loginInfo : loginInfos)
 } // send
 @Override
 public MethodAction createActionIfPossible(String actionName) {
   // will resolve if both a class and method name can be parsed, and a valid class with that
   // method name can be loaded
   String methodName = MethodAction.methodNameForAction(actionName);
   String className = MethodAction.classNameForAction(actionName);
   if (StringUtils.isEmpty(methodName) || StringUtils.isEmpty(className)) {
     return null;
   }
   try {
     Class<?> clazz = Class.forName(className); // TODO - Restricted in GAE - why is this better?
     // ClassLoaderUtil.loadClass(className);
     Method method = ReflectUtil.findMethod(clazz, methodName);
     if (method == null) {
       return null;
     }
     MethodAction methodAction = new MethodAction(clazz, method, findInterceptors(method));
     // force instantiation of controller - this allows controllers to be injected into eachother
     // and also flushes out instantiation issues at startup
     Object controller = createController(methodAction);
     controllerInstances.put(methodAction.type(), controller);
     return methodAction;
   } catch (BaseException e) {
     throw e;
   } catch (Exception e) {
     return null;
   }
 }
  /**
   * Use resource key(Optional) and rest json entry as a template and fill in template using Avro as
   * a reference. e.g: Rest JSON entry HOCON template:
   * AccountId=${sf_account_id},Member_Id__c=${member_id} Avro:
   * {"sf_account_id":{"string":"0016000000UiCYHAA3"},"member_id":{"long":296458833}}
   *
   * <p>Converted Json: {"AccountId":"0016000000UiCYHAA3","Member_Id__c":296458833}
   *
   * <p>As it's template based approach, it can produce nested JSON structure even Avro is flat (or
   * vice versa).
   *
   * <p>e.g: Rest resource template: /sobject/account/memberId/${member_id} Avro:
   * {"sf_account_id":{"string":"0016000000UiCYHAA3"},"member_id":{"long":296458833}} Converted
   * resource: /sobject/account/memberId/296458833
   *
   * <p>Converted resource will be used to form end point.
   * http://www.server.com:9090/sobject/account/memberId/296458833
   *
   * <p>{@inheritDoc}
   *
   * @see gobblin.converter.Converter#convertRecord(java.lang.Object, java.lang.Object,
   *     gobblin.configuration.WorkUnitState)
   */
  @Override
  public Iterable<RestEntry<JsonObject>> convertRecord(
      Void outputSchema, GenericRecord inputRecord, WorkUnitState workUnit)
      throws DataConversionException {

    Config srcConfig =
        ConfigFactory.parseString(
            inputRecord.toString(), ConfigParseOptions.defaults().setSyntax(ConfigSyntax.JSON));

    String resourceKey = workUnit.getProp(CONVERTER_AVRO_REST_ENTRY_RESOURCE_KEY, "");
    if (!StringUtils.isEmpty(resourceKey)) {
      final String dummyKey = "DUMMY";
      Config tmpConfig =
          ConfigFactory.parseString(dummyKey + "=" + resourceKey).resolveWith(srcConfig);
      resourceKey = tmpConfig.getString(dummyKey);
    }

    String hoconInput = workUnit.getProp(CONVERTER_AVRO_REST_JSON_ENTRY_TEMPLATE);
    if (StringUtils.isEmpty(hoconInput)) {
      return new SingleRecordIterable<>(
          new RestEntry<>(resourceKey, parser.parse(inputRecord.toString()).getAsJsonObject()));
    }

    Config destConfig = ConfigFactory.parseString(hoconInput).resolveWith(srcConfig);
    JsonObject json =
        parser.parse(destConfig.root().render(ConfigRenderOptions.concise())).getAsJsonObject();
    return new SingleRecordIterable<>(new RestEntry<>(resourceKey, json));
  }
  /**
   * 创建权限类型实例<br>
   *
   * @param authType
   * @param name
   * @param description
   * @param isViewAble
   * @param isConfigAble
   * @return
   */
  public synchronized AuthTypeItem registeAuthTypeItem(
      String authType,
      String name,
      String description,
      boolean isViewAble,
      boolean isConfigAble,
      int orderIndex) {
    if (StringUtils.isEmpty(authType)) {
      throw new NullArgException("authType is empty");
    }

    AuthTypeItem res = null;
    if (authTypeItemMapping.containsKey(authType)) {
      res = authTypeItemMapping.get(authType);
      if (!StringUtils.isEmpty(name)) {
        res.setName(name);
      }
      if (!StringUtils.isEmpty(description)) {
        res.setDescription(description);
      }
      // 如果其中有一个与默认值不同,则认为不同的该值将生效
      // 如果其中有任意一个设置为不可见,则认为该类型可见
      if (!isViewAble) {
        res.setViewAble(isViewAble);
      }
      // 如果其中有任意一个设置为不可编辑,则认为不可编辑
      if (!isConfigAble) {
        res.setConfigAble(isConfigAble);
      }
    } else {
      res = new AuthTypeItem(authType, name, description, isViewAble, isConfigAble, orderIndex);
      authTypeItemMapping.put(authType, res);
    }
    return res;
  }
  /** 加载菜单 */
  @PostConstruct
  public void cacheMenus() throws Exception {
    try {
      List<MenuVo> menuList =
          DBUtils.jt()
              .query("select * from T_MENU order by displayOrder", createRowMapper(MenuVo.class));

      // 形成树状关系
      Map<String, MenuVo> menuMap = new HashMap<String, MenuVo>();
      for (MenuVo menu : menuList) {
        menuMap.put(menu.getMenuId(), menu);
      }
      for (MenuVo menu : menuList) {
        String pid = menu.getParentMenuId();
        if (!StringUtils.isEmpty(pid)) {
          MenuVo pMenu = menuMap.get(pid);
          pMenu.addSubMenu(menu);
        }
      }

      for (MenuVo menu : menuList) {
        if (!StringUtils.isEmpty(menu.getParentMenuId())) {
          menuMap.remove(menu.getMenuId());
        }
      }

      LocalCache.put(CACHE_KEY_MENU_MAP, Collections.unmodifiableMap(menuMap));
      logger.info("菜单缓存构建完毕。");
    } catch (Exception e) {
      logger.error("加载菜单出错", e);
      throw e;
    }
  }
  /**
   * 从类定义中解析表定义<br>
   * 仅解析传入类型:不对传入类型的接口,以及父类进行注解获取<br>
   * <功能详细描述>
   *
   * @param type
   * @return [参数说明]
   * @return JPAEntityTableDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityTableDef doAnalyzeTableDef(Class<?> type) {
    // 没有注解的时候默认使用类名当作表名
    String tableName = type.getSimpleName();
    String comment = "";
    // 如果存在javax注解中的Entity读取其Name
    // org.hibernate.annotations.Entity该类中不含有表名,不进行解析
    if (type.isAnnotationPresent(Entity.class)) {
      String entityName = type.getAnnotation(Entity.class).name();
      if (!StringUtils.isEmpty(entityName)) {
        tableName = entityName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableName = type.getAnnotation(Table.class).name();
      if (!StringUtils.isEmpty(annoTableName)) {
        tableName = annoTableName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(org.hibernate.annotations.Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableComment = type.getAnnotation(org.hibernate.annotations.Table.class).comment();
      if (!StringUtils.isEmpty(annoTableComment)) {
        comment = annoTableComment;
      }
    }

    JPAEntityTableDef tableDef = new JPAEntityTableDef();
    tableDef.setTableName(tableName);
    tableDef.setComment(comment);
    return tableDef;
  }
 /**
  * 更新用户登录登出记录
  *
  * @param userLog
  * @return
  */
 @Override
 public boolean updateUserLoginRecord(UserLoginRecord userLog) {
   if (StringUtils.isEmpty(userLog.getUname())) {
     return userLoginRecordDao.updateDeviceLogout(
         userLog.getSessionId(), userLog.getDeviceNo(), userLog.getSessionEndTime());
   } else {
     if (StringUtils.isEmpty(userLog.getSessionId())
         || StringUtils.isEmpty(userLog.getDeviceNo())) {
       return false;
     }
     UserLoginRecord dbLog =
         this.getUserLoginRecord(
             userLog.getSessionId(), userLog.getUname(), userLog.getDeviceNo());
     if (dbLog == null) {
       return userLoginRecordDao.updateDeviceLogout(
           userLog.getSessionId(), userLog.getDeviceNo(), userLog.getSessionEndTime());
     } else {
       dbLog.setLogoutTime(userLog.getLogoutTime());
       dbLog.setSessionEndTime(userLog.getSessionEndTime());
       dbLog.setLogoutType(userLog.getLogoutType());
       dbLog.setCreateTime(null);
       dbLog.setLoginTime(null);
       dbLog.setSessionStartTime(null);
       return userLoginRecordDao.updateUserLoginRecord(dbLog);
     }
   }
 }
  public MailConfiguration(XWiki xwiki) {
    this();

    String smtpServer = this.mailSenderConfiguration.getHost();
    if (!StringUtils.isBlank(smtpServer)) {
      setHost(smtpServer);
    }

    int port = this.mailSenderConfiguration.getPort();
    setPort(port);

    String from = this.mailSenderConfiguration.getFromAddress();
    if (!StringUtils.isBlank(from)) {
      setFrom(from);
    }

    String smtpServerUsername = this.mailSenderConfiguration.getUsername();
    String smtpServerPassword = this.mailSenderConfiguration.getPassword();
    if (!StringUtils.isEmpty(smtpServerUsername) && !StringUtils.isEmpty(smtpServerPassword)) {
      setSmtpUsername(smtpServerUsername);
      setSmtpPassword(smtpServerPassword);
    }

    Properties javaMailExtraProps = this.mailSenderConfiguration.getAdditionalProperties();
    if (!javaMailExtraProps.isEmpty()) {
      setExtraProperties(javaMailExtraProps);
    }
  }
 @Override
 public String getMainEntityName() {
   if (!StringUtils.isEmpty(getFirstName()) && !StringUtils.isEmpty(getLastName())) {
     return getFirstName() + " " + getLastName();
   }
   return String.valueOf(getId());
 }
Exemple #25
0
  public void inicializa() throws Exception {

    try {
      log.info("Inicializa el cliente MongoDB");
      String host = ApplicationConfiguration.getInstance().getProperty("mongo.host");
      if (StringUtils.isEmpty(host)) {
        throw new DocumentException("No está configurado el host");
      }
      String property = ApplicationConfiguration.getInstance().getProperty("mongo.port");
      if (StringUtils.isEmpty(property)) {
        throw new DocumentException("No está configurado el puerto");
      }
      int port = Integer.parseInt(property);
      String dbName = ApplicationConfiguration.getInstance().getProperty("mongo.data.base");
      if (StringUtils.isEmpty(dbName)) {
        throw new DocumentException("No está configurada la base de datos");
      }

      mongoClient = new MongoClient(host, port);
      dataBase = mongoClient.getDB(dbName);
    } catch (Exception e) {
      log.error("Error al iniciar el cliente: " + e.getMessage());
      e.printStackTrace();
      throw new DocumentException(e.getMessage());
    }
  }
  public String toStringUserFriendly() {
    StringBuffer sb = new StringBuffer();
    if (!StringUtils.isEmpty(name)) {
      sb.append("Név: ");
      sb.append(name);
      sb.append(", ");
    }
    if (!StringUtils.isEmpty(postCode)) {
      sb.append("Irányítószám");
      sb.append(postCode);
      sb.append(", ");
    }
    if (!StringUtils.isEmpty(address)) {
      sb.append("Cím:");
      sb.append(address);
      sb.append(", ");
    }
    if (!StringUtils.isEmpty(phoneNo)) {
      sb.append("Telefonszám: ");
      sb.append(phoneNo);
      sb.append(", ");
    }
    if (!StringUtils.isEmpty(email)) {
      sb.append("Email:");
      sb.append(email);
      sb.append(", ");
    }

    return sb.toString().substring(0, sb.length() - 2);
  }
  /**
   * 发送短信 aop流控,调整参数需要更改aop设置com.vdlm.sms.aop.SmsSendRateAop
   *
   * @param appId
   * @param mobile
   * @param content
   * @param ipAddress
   * @param clientIP
   * @return
   */
  public boolean doSend(
      String appId, String mobile, String content, String ipAddress, String clientIP) {
    String mandaoBatchId = "";
    if (StringUtils.isEmpty(ipAddress)) {
      logger.error("ipAddress is null, so send fail!");
      return false;
    }
    if (!WhiteListHelper.isLegalRequest(ipAddress, whitelist)) {
      logger.error("ipAddress is not in white list [" + whitelist + "], so send fail!");
      return false;
    }

    if (StringUtils.isEmpty(appId)) {
      logger.error("appid:" + appId + ", so send fail!");
      return false;
    }

    String smsSign = getSignByAppId(appId);
    if (StringUtils.isEmpty(smsSign)) {
      return false;
    }
    content += smsSign;
    try {
      Object bean = SpringContextUtil.getBean("smsServerSwitchListener");
      if (bean instanceof SmsServerSwitchListener) {
        SmsServerSwitchListener listener = (SmsServerSwitchListener) bean;
        serviceURL = listener.getServiceURL();
      }
      // String ext = "";
      String ext = "2"; // 默认用想去的ext
      if ("2".equals(appId)) {
        ext = "1";
      }
      if ("3".equals(appId)) {
        ext = "2";
      }
      if ("4".equals(appId)) {
        ext = "3";
      }
      if ("5".equals(appId)) {
        ext = "4";
      }
      if ("6".equals(appId)) {
        ext = "5";
      }
      mandaoBatchId =
          MandaoSmsHelper.sendSms(serviceURL, mandaoSmsSn, mandaoSmsPwd, mobile, content, ext);
    } catch (Exception e) {
      logger.error("fail send sms", e);
      mandaoBatchId = "";
    }

    insertSmsSendRecord(mobile, content, appId, mandaoBatchId);

    if (mandaoBatchId.equals("")) {
      return false;
    }

    return true;
  }
Exemple #28
0
  @Test
  public void test4() {
    mockStatic(StringUtils.class);
    when(StringUtils.isEmpty("abc")).thenReturn(Boolean.FALSE);
    assertTrue(StringUtils.isEmpty("abc"));

    PowerMockito.verifyStatic();
  }
  /**
   * Calculates the value by which we'd need to adjust the length of the given segment, by searching
   * for the nearest newline around it (before and after), and returning the distance to it (which
   * can be positive, if after, or negative, if before).
   *
   * @param segment The segment to do the calculation on.
   * @param stream The full stream used to figure out the adjustment
   * @param encoding The encoding to use to determine where the cutoffs are
   * @param delimiter The delimiter that determines how we adjust. If null then '\\r', \\n' and
   *     '\\r\\n' are used.
   * @return How much to adjust the segment length by.
   * @throws UploadFailedException Thrown if proper upload boundaries cannot be determined.
   * @throws IOException Thrown if the stream being used is invalid or inaccessible.
   */
  private int determineLengthAdjustment(
      UploadSegmentMetadata segment, RandomAccessFile stream, Charset encoding, String delimiter)
      throws UploadFailedException, IOException {
    long referenceFileOffset = segment.getOffset() + segment.getLength();
    byte[] buffer = new byte[maxAppendLength];

    // read 2MB before the segment boundary and 2MB after (for a total of 4MB = max append length)
    int bytesRead = readIntoBufferAroundReference(stream, buffer, referenceFileOffset);
    if (bytesRead > 0) {
      int middlePoint = bytesRead / 2;
      // search for newline in it
      int newLinePosBefore =
          StringExtensions.findNewline(
              buffer, middlePoint + 1, middlePoint + 1, true, encoding, delimiter);

      // in some cases, we may have a newline that is 2 characters long, and it occurrs exactly on
      // the midpoint, which means we won't be able to find its end.
      // see if that's the case, and then search for a new candidate before it.
      if ((delimiter == null || StringUtils.isEmpty(delimiter))
          && newLinePosBefore == middlePoint + 1
          && buffer[newLinePosBefore] == (byte) '\r') {
        int newNewLinePosBefore =
            StringExtensions.findNewline(
                buffer, middlePoint, middlePoint, true, encoding, delimiter);
        if (newNewLinePosBefore >= 0) {
          newLinePosBefore = newNewLinePosBefore;
        }
      }

      int newLinePosAfter =
          StringExtensions.findNewline(
              buffer, middlePoint, middlePoint, false, encoding, delimiter);
      if ((delimiter == null || StringUtils.isEmpty(delimiter))
          && newLinePosAfter == buffer.length - 1
          && buffer[newLinePosAfter] == (byte) '\r'
          && newLinePosBefore >= 0) {
        newLinePosAfter = -1;
      }

      int closestNewLinePos = findClosestToCenter(newLinePosBefore, newLinePosAfter, middlePoint);

      // middle point of the buffer corresponds to the reference file offset, so all we need to do
      // is return the difference between the closest newline and the center of the buffer
      if (closestNewLinePos >= 0) {
        return closestNewLinePos - middlePoint;
      }
    }

    // if we get this far, we were unable to find a record boundary within our limits => fail the
    // upload
    throw new UploadFailedException(
        MessageFormat.format(
            "Unable to locate a record boundary within {0}MB on either side of segment {1} (offset {2}). This means the record at that offset is larger than {0}MB.",
            maxAppendLength / 1024 / 1024 / 2,
            segment.getSegmentNumber(),
            segment.getOffset(),
            maxAppendLength / 1024 / 1024));
  }
 @RestMethod(method = HttpMethod.GET, template = "/queryAndTerminus")
 public void mixedTerminusArgs(
     @Terminus String terminus, @QueryParameter(name = "item1") String item1) {
   if (!StringUtils.isEmpty(item1) && StringUtils.isEmpty(terminus))
     throw new IllegalStateException(
         "Item1 is a query parameter but there seems to be no terminus.");
   lastMethodCalled = "mixedTerminusArgs";
   lastHttpMethodCalled = "GET";
 }