Java Code Examples for org.apache.commons.lang3.StringUtils.equals()

The following are Jave code examples for showing how to use equals() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: smarti   File: InMemoryStoreService.java   View Source Code Vote up 6 votes
@Override
protected Conversation doAppendMessage(Conversation conversation, Message message) {
    final Conversation cc = get(conversation.getId());
    int pos = 0;
    do {
        if (StringUtils.equals(cc.getMessages().get(pos).getId(), message.getId())) {
            break;
        }
        pos++;
    } while (pos < cc.getMessages().size());
    if (pos < cc.getMessages().size()) {
        cc.getMessages().remove(pos);
    }
    cc.getMessages().add(pos, message);
    cc.setLastModified(new Date());
    return cc;
}
 
Example 2
Project: Razor   File: RouteManager.java   View Source Code Vote up 6 votes
/**
 * Find route with request method and path
 *
 * @param path path to request
 * @param httpMethod http method
 * @return Router instance
 */
public Router findRoute(String path, String httpMethod) {

    Router router = routerMap.get(path.concat("::").concat(httpMethod));
    if (router != null) {
        return router;
    }

    router = routerMap.get(path.concat("::").concat(HttpMethod.ALL));
    if (router != null) {
        return router;
    }

    for (Router router1 : routerSet) {
        String routerHttpMethod = router1.getHttpMethod();
        if ((routerHttpMethod.equals(HttpMethod.ALL) || StringUtils.equals(routerHttpMethod, httpMethod)) && router1.match(path)) {
            return router1;
        }
    }

    return null;
}
 
Example 3
Project: YiDu-Novel   File: AjaxServiceAction.java   View Source Code Vote up 6 votes
/**
 * <p>
 * 修改密码
 * </p>
 */
private void dochangepass() {
    // TODO 输入检查
    TUser user = userService.getByNo(userno);
    if (StringUtils.equals(user.getPassword(), Utils.convert2MD5(password))) {
        dto.setCode(ReturnCode.FAILED);
        return;
    }

    if (StringUtils.isNotEmpty(password)) {
        user.setPassword(Utils.convert2MD5(password));
    }
    userService.save(user);
    dto.setCode(ReturnCode.SUCCESS);
    // TODO 文字检查和密码校对
}
 
Example 4
Project: bluegreen-manager   File: RdsSnapshotRestoreTask.java   View Source Code Vote up 6 votes
/**
 * Checks that mapped stage physical instnames are nonblank and are different from live physical instnames.
 * Returns silently if ok.
 */
private void checkDbMap()
{
  final String liveLogicalName = liveLogicalDatabase.getLogicalName();
  if (MapUtils.isEmpty(dbMap) || !dbMap.containsKey(liveLogicalName))
  {
    throw new IllegalArgumentException("Live logical database '" + liveLogicalName
        + "' is unmapped, don't know what stage physical instname to create");
  }
  final String stagePhysicalInstanceName = dbMap.get(liveLogicalName);
  if (StringUtils.isBlank(stagePhysicalInstanceName))
  {
    throw new IllegalArgumentException("You have mapped live logical database '" + liveLogicalName
        + "' to a blank string, we don't know what stage physical instname to create");
  }
  if (StringUtils.equals(stagePhysicalInstanceName, livePhysicalDatabase.getInstanceName()))
  {
    throw new IllegalArgumentException("You have mapped live logical database '" + liveLogicalName
        + "' to stage physical instname '" + stagePhysicalInstanceName
        + "', but live physical database is already using that instname");
  }
}
 
Example 5
Project: pingguopai   File: WebMvcConfigurer.java   View Source Code Vote up 6 votes
/**
 * 一个简单的签名认证,规则:
 * 1. 将请求参数按ascii码排序
 * 2. 拼接为a=value&b=value...这样的字符串(不包含sign)
 * 3. 混合密钥(secret)进行md5获得签名,与请求的签名进行比较
 */
private boolean validateSign(HttpServletRequest request) {
    String requestSign = request.getParameter("sign");//获得请求签名,如sign=19e907700db7ad91318424a97c54ed57
    if (StringUtils.isEmpty(requestSign)) {
        return false;
    }
    List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
    keys.remove("sign");//排除sign参数
    Collections.sort(keys);//排序

    StringBuilder sb = new StringBuilder();
    for (String key : keys) {
        sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
    }
    String linkString = sb.toString();
    linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'

    String secret = "Potato";//密钥,自己修改
    String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5

    return StringUtils.equals(sign, requestSign);//比较
}
 
Example 6
Project: vind   File: SolrSearchServerTest.java   View Source Code Vote up 6 votes
public static <T> Matcher<SolrInputField> solrInputField(String fieldName, Matcher<T> valueMatcher) {
    return new TypeSafeMatcher<SolrInputField>() {
        @Override
        protected boolean matchesSafely(SolrInputField item) {
            return StringUtils.equals(fieldName, item.getName()) && valueMatcher.matches(item.getValue());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("SolrInputField(")
                    .appendValue(fieldName)
                    .appendText(" value matching ")
                    .appendDescriptionOf(valueMatcher)
                    .appendText(")");
        }
    };
}
 
Example 7
Project: telemarket-skittle-alley   File: UserMsgHandler.java   View Source Code Vote up 6 votes
@Override
public void apply(ApiRequest request, ApiResponse response, WebSocketSession session) {
    String msg = StringEscapeUtils.escapeHtml4(request.getMsg());
    if (StringUtils.isBlank(msg)) {
        return;
    }
    Map<String, Object> attributes = session.getAttributes();
    String id = session.getId();
    DrawPlayerInfo info = ((DrawPlayerInfo) attributes.get("info"));
    DrawGuessContext ctx = (DrawGuessContext) attributes.get("ctx");
    DrawGameStatus status = ctx.status();
    ArrayList<String> msgs = new ArrayList<>(2);
    if (status == DrawGameStatus.RUN) {
        if (StringUtils.equals(id, ctx.getCurrentUser())) {
            protectSecret(info, ctx, msg, msgs);
        } else {
            processGussPerson(info, ctx, msg, msgs);
        }
    } else {
        msgs.add("<b>" + info.getName() + "</b>: " + msg);
    }
    response.setCode(DrawCode.DRAW_MSG.getCode()).setData(msgs);
}
 
Example 8
Project: cyberduck   File: WorkdirPrefixer.java   View Source Code Vote up 5 votes
public String normalize(final String name) {
    if(StringUtils.equals(name, ".")) {
        return finder.find().getAbsolute();
    }
    if(StringUtils.equals(name, "..")) {
        return finder.find().getParent().getAbsolute();
    }
    if(!this.isAbsolute(name)) {
        return String.format("%s%s%s", finder.find().getAbsolute(), PreferencesFactory.get().getProperty("local.delimiter"), name);
    }
    return name;
}
 
Example 9
Project: sipsoup   File: OperatorEnv.java   View Source Code Vote up 5 votes
public static int judgePriority(String operatorName) {
    if (StringUtils.equals(operatorName, "#")) {
        // 这是一个特殊逻辑,运算栈需要有一个兜底判断的操作符,所以#是RPN默认的一个运算符,但是他不会表现在编译好的语法树里面
        return Integer.MIN_VALUE;
    }
    AlgorithmHolder holder = operatorMaps.get(operatorName);
    return holder.priority;
}
 
Example 10
Project: QiuQiu   File: XmlDataContext.java   View Source Code Vote up 5 votes
private RuleNode parseNode(Node item) throws Exception{

        // 节点非element节点 或 element节点name非rule, 则直接返回
        if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
            return null;
        }

        Element ruleNode = (Element) item;

        String table = ruleNode.getAttribute("table");
        String column = ruleNode.getAttribute("column");
        String javaType = ruleNode.getAttribute("javaType");
        KeyColumn keyColumn = new KeyColumn(table, column, javaType);

        String comparator = ruleNode.getAttribute("class");
        Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();

        RuleNode node = new RuleNode(keyColumn, comparatorClass);

        NodeList ruleChildren = item.getChildNodes();
        for (int i = 0; i < ruleChildren.getLength(); i++) {

            Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
                node.add(dataNode);
                dataNode.setRuleNode(node);
            });

        }

        return node;
    }
 
Example 11
Project: bluegreen-manager   File: ShellResult.java   View Source Code Vote up 5 votes
@Override
public boolean equals(Object obj)
{
  if (obj instanceof ShellResult)
  {
    ShellResult other = (ShellResult) obj;
    return StringUtils.equals(output, other.output) && exitValue == other.exitValue;
  }
  return false;
}
 
Example 12
Project: cyberduck   File: IRODSListService.java   View Source Code Vote up 5 votes
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
    try {
        final AttributedList<Path> children = new AttributedList<Path>();
        final IRODSFileSystemAO fs = session.getClient();
        final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(directory.getAbsolute());
        if(!f.exists()) {
            throw new NotfoundException(directory.getAbsolute());
        }
        for(File file : fs.getListInDirWithFileFilter(f, TrueFileFilter.TRUE)) {
            final String normalized = PathNormalizer.normalize(file.getAbsolutePath(), true);
            if(StringUtils.equals(normalized, directory.getAbsolute())) {
                continue;
            }
            final PathAttributes attributes = new PathAttributes();
            final ObjStat stats = fs.getObjStat(file.getAbsolutePath());
            attributes.setModificationDate(stats.getModifiedAt().getTime());
            attributes.setCreationDate(stats.getCreatedAt().getTime());
            attributes.setSize(stats.getObjSize());
            attributes.setChecksum(Checksum.parse(Hex.encodeHexString(Base64.decodeBase64(stats.getChecksum()))));
            attributes.setOwner(stats.getOwnerName());
            attributes.setGroup(stats.getOwnerZone());
            children.add(new Path(directory, PathNormalizer.name(normalized),
                    file.isDirectory() ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file),
                    attributes));
            listener.chunk(directory, children);
        }
        return children;
    }
    catch(JargonException e) {
        throw new IRODSExceptionMappingService().map("Listing directory {0} failed", e, directory);
    }
}
 
Example 13
Project: saluki   File: ScriptRouter.java   View Source Code Vote up 5 votes
public ScriptRouter(String type, String rule) {
  super(rule);
  engine = new ScriptEngineManager().getEngineByName(type);
  if (engine == null && StringUtils.equals(type, "javascript")) {
    engine = new ScriptEngineManager().getEngineByName("js");
  }
  if (engine == null) {
    throw new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule);
  }
}
 
Example 14
Project: YiDu-Novel   File: TArticle.java   View Source Code Vote up 5 votes
/**
 * 获得图片URL
 * 
 * @return 图片URL
 */
public String getImgUrl() {
    String fileName = "";
    if (getImgflag() == null) {
        fileName = "nocover.jpg";
    } else {
        switch (getImgflag()) {
        case 1:
            fileName = getArticleno() + "s.jpg";
            break;
        case 2:
            fileName = getArticleno() + "s.gif";
            break;
        case 3:
            fileName = getArticleno() + "s.png";
            break;
        case 10:
            fileName = getArticleno() + "l.jpg";
            break;
        default:
            fileName = "nocover.jpg";
            break;
        }
    }
    String imgUrl = YiDuConstants.yiduConf.getString(YiDuConfig.RELATIVE_IAMGE_PATH) + "/";
    if (StringUtils.equals("nocover.jpg", fileName)) {
        imgUrl = imgUrl + fileName;
    } else {
        if (YiDuConstants.yiduConf.getBoolean(YiDuConfig.ENABLE_CLEAN_IMAGE_URL, false)) {
            imgUrl = imgUrl + getArticleno() / YiDuConstants.SUB_DIR_ARTICLES + "-" + getArticleno() + "-"
                    + Utils.convert2MD5(imgUrl + fileName) + fileName;
        } else {
            imgUrl = imgUrl + getArticleno() / YiDuConstants.SUB_DIR_ARTICLES + "/" + getArticleno() + "/"
                    + fileName;
        }
    }
    return imgUrl;
}
 
Example 15
Project: scoold   File: QuestionController.java   View Source Code Vote up 5 votes
private void sendReplyNotifications(Post parentPost, Post reply) {
	// send email notification to author of post except when the reply is by the same person
	if (parentPost != null && reply != null && !StringUtils.equals(parentPost.getCreatorid(), reply.getCreatorid())) {
		Profile replyAuthor = reply.getAuthor(); // the current user - same as utils.getAuthUser(req)
		Map<String, Object> model = new HashMap<String, Object>();
		String name = replyAuthor.getName();
		String body = Utils.markdownToHtml(Utils.abbreviate(reply.getBody(), 500));
		String picture = Utils.formatMessage("<img src='{0}' width='25'>", replyAuthor.getPicture());
		String postURL = getServerURL() + parentPost.getPostLink(false, false);
		model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
		model.put("heading", Utils.formatMessage("New reply to <a href='{0}'>{1}</a>", postURL, parentPost.getTitle()));
		model.put("body", Utils.formatMessage("<h2>{0} {1}:</h2><div class='panel'>{2}</div>", picture, name, body));

		Profile authorProfile = pc.read(parentPost.getCreatorid());
		if (authorProfile != null) {
			User author = authorProfile.getUser();
			if (author != null) {
				if (authorProfile.getReplyEmailsEnabled()) {
					parentPost.addFollower(author);
				}
			}
		}
		if (parentPost.hasFollowers()) {
			emailer.sendEmail(new ArrayList<String>(parentPost.getFollowers().values()),
					name + " replied to '" + Utils.abbreviate(reply.getTitle(), 50) + "...'",
					Utils.compileMustache(model, utils.loadEmailTemplate("notify")));
		}
	}
}
 
Example 16
Project: fat-lining   File: ValidationUtils.java   View Source Code Vote up 5 votes
/**
 * Validate passwords input
 * <ul>
 *  <li>password is not empty</li>
 *  <li>password has appropriate length</li>
 *  <li>password and repeated password match</li>
 * </ul>
 * @param password to validate
 * @param repeatedPassword to validate
 * @param errors resulting to validation
 */
public void validatePasswords(String password, String repeatedPassword, Errors errors) {
	String cleanPassword = StringUtils.trimToEmpty(password);
	if (StringUtils.isBlank(cleanPassword)) {
		errors.rejectValue("password", "validation.error.password.blank");
	} else if (StringUtils.length(cleanPassword) < config.getPasswordLength()) {
		errors.rejectValue("password", "validation.error.password.tooShort", new Object[]{config.getPasswordLength()}, StringUtils.EMPTY);
	} else {
		String cleanRepeatedPassword = StringUtils.trimToEmpty(repeatedPassword);
		if (!StringUtils.equals(cleanPassword, cleanRepeatedPassword)) {
			errors.rejectValue("repeatedPassword", "validation.error.password.noMatch");
		}
	}
	
}
 
Example 17
Project: YiDu-Novel   File: SingleBookFilter.java   View Source Code Vote up 4 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    YiDuConstants.singleBookFlag.set(false);
    HttpServletRequest req = (HttpServletRequest) request;
    String uri = req.getRequestURI();
    if (StringUtils.endsWithAny(uri, "css", "js", "jpg", "png", "gif")) {
        // 静态资源直接跳过
        logger.debug("ignore static resource." + uri);
        chain.doFilter(request, response);
    } else {
        // 非静态资源时,根据具体的信息去做判别,时候需要标识单本
        String rootDomian = YiDuConstants.yiduConf.getString(YiDuConfig.ROOT_DOMAIN);
        String aname = StringUtils.substringBeforeLast(req.getServerName(), "." + rootDomian);
        logger.debug("aname : " + aname);
        if (StringUtils.isNotBlank(aname)) {
            int articleno = SingleBookManager.getArticleno(aname);
            if (articleno != 0) {
                // TODO 即便找到对应的小说,也只做首页和阅读页,其他全部404吧
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(uri);
                boolean matchFlag = false;
                String newURI = "";
                if (m.find()) {
                    // 阅读页
                    newURI = ReaderAction.URL + "?chapterno="
                            + StringUtils.substringBeforeLast(m.group(1), ".html");
                    matchFlag = true;
                } else if (StringUtils.equals(uri, "/") || StringUtils.isEmpty(uri)) {
                    // 首页
                    newURI = InfoAction.URL + "?articleno=" + articleno;
                    matchFlag = true;
                } else {
                    // 返回404
                    YiDuConstants.singleBookFlag.set(true);
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                logger.debug("newURI str: " + newURI);
                if (matchFlag) {
                    YiDuConstants.singleBookFlag.set(true);
                    YiDuConstants.singleBookServerName.set(req.getServerName());
                    req.getRequestDispatcher(newURI).forward(request, response);
                }
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
 
Example 18
Project: unitstack   File: CopyObjectResponder.java   View Source Code Vote up 4 votes
private boolean hasS3ObjectKey(S3Object s3Object, Matcher sourceMatcher) {
  return sourceMatcher.groupCount() > 1
      && StringUtils.equals(s3Object.getKey(), sourceMatcher.group(2));
}
 
Example 19
Project: ServerObserver   File: ConfigBase.java   View Source Code Vote up 4 votes
public void onConfigChanged(final @Nonnull String modid) {
	if (StringUtils.equals(modid, Reference.MODID)) {
		save();
		reload();
	}
}
 
Example 20
Project: configcenter   File: DefaultConfigProperties.java   View Source Code Vote up 2 votes
/**
 * 转换为原始value
 *
 * @param savableValue 可存储的value
 * @return 原始value
 */
public static String toRawValue(String savableValue) {
    return StringUtils.equals(savableValue, NULL_VALUE) ? null : savableValue;
}