Java Code Examples for org.apache.commons.lang3.StringUtils#length()
The following examples show how to use
org.apache.commons.lang3.StringUtils#length() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WordSimilarity.java From Algorithms with Apache License 2.0 | 6 votes |
/** * 计算N的值,N表示所在分支层分支数,如:人 Aa01A01= 和 少儿 Ab04B01=,以A开头的子分支只有14个 * 这一点在论文中说的非常不清晰,所以以国人的文章进行编码真是痛苦 * * @param encodeHead 输入两个字符串的公共开头 * @return 经过计算之后得到N的值 */ protected static int getN(String encodeHead) { int length = StringUtils.length(encodeHead); switch (length) { case 1: return getCount(encodeHead, 2); case 2: return getCount(encodeHead, 4); case 4: return getCount(encodeHead, 5); case 5: return getCount(encodeHead, 7); default: return 0; } }
Example 2
Source File: InstagramEditProfileRequest.java From instagram4j with Apache License 2.0 | 6 votes |
@Builder private InstagramEditProfileRequest(String biography, String fullName, String phone, String website, String username, String email, InstagramUserGenderEnum gender) { if (StringUtils.length(biography) > 150) { throw new IllegalArgumentException("biography cannot be longer than 150 chars."); } if (StringUtils.isEmpty(username)) { throw new IllegalArgumentException("username cannot be empty."); } this.biography = biography; this.fullName = fullName; this.phone = phone; this.website = website; this.username = username; this.email = email; this.gender = gender; }
Example 3
Source File: SDSTouchFeature.java From cyberduck with GNU General Public License v3.0 | 6 votes |
/** * Validate node name convention */ public boolean validate(final String filename) { // Empty argument if not known in validation if(StringUtils.isNotBlank(filename)) { if(StringUtils.length(filename) > 150) { // Node (room, folder, file) names are limited to 150 characters. return false; } // '\\', '<','>', ':', '\"', '|', '?', '*', '/', leading '-', trailing '.' if(StringUtils.containsAny(filename, '\\', '<', '>', ':', '"', '|', '?', '*', '/')) { return false; } if(StringUtils.startsWith(filename, "-")) { return false; } if(StringUtils.endsWith(filename, ".")) { return false; } } return true; }
Example 4
Source File: WorkflowReminder.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
public WorkflowReminder build() { WorkflowReminder reminder = new WorkflowReminder(recipients, senderAdminId, type, message, date); if (CollectionUtils.isEmpty(reminder.recipients)) { throw new IllegalStateException("Missing required recipients"); } if (reminder.senderAdminId <= 0) { throw new IllegalStateException("Missing required sender"); } if (reminder.type == null) { throw new IllegalStateException("Missing required type"); } if (StringUtils.length(reminder.message) > MAX_MESSAGE_LENGTH) { throw new IllegalStateException("Message is too long"); } if (reminder.date == null) { throw new IllegalStateException("Missing required date"); } return reminder; }
Example 5
Source File: ParaClient.java From para with Apache License 2.0 | 6 votes |
/** * Default constructor. * @param accessKey app access key * @param secretKey app secret key */ public ParaClient(String accessKey, String secretKey) { this.accessKey = accessKey; this.secretKey = secretKey; if (StringUtils.length(secretKey) < 6) { logger.warn("Secret key appears to be invalid. Make sure you call 'signIn()' first."); } this.throwExceptionOnHTTPError = false; ObjectMapper mapper = ParaObjectUtils.getJsonMapper(); mapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS); ClientConfig clientConfig = new ClientConfig(); clientConfig.register(GenericExceptionMapper.class); clientConfig.register(new JacksonJsonProvider(mapper)); clientConfig.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); SSLContext sslContext = SslConfigurator.newInstance().createSSLContext(); apiClient = ClientBuilder.newBuilder(). sslContext(sslContext). withConfig(clientConfig).build(); }
Example 6
Source File: TTable.java From dubbo-2.6.5 with Apache License 2.0 | 6 votes |
private String getDataFormat(ColumnDefine columnDefine, int width, String data) { switch (columnDefine.align) { case MIDDLE: { final int length = StringUtils.length(data); final int diff = width - length; final int left = diff / 2; return repeat(" ", diff - left) + "%s" + repeat(" ", left); } case RIGHT: { return "%" + width + "s"; } case LEFT: default: { return "%-" + width + "s"; } } }
Example 7
Source File: UserGroupController.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
private boolean isValid(ComAdmin admin, UserGroupForm form, Popups popups) { int userGroupId = form.getId(); if(!admin.permissionAllowed(Permission.ROLE_CHANGE)) { throw new PermissionDeniedDataAccessException("Missing permission to change rights", null); } String shortname = form.getShortname(); if (StringUtils.isBlank(shortname)) { popups.field("shortname", "error.name.is.empty"); return false; } if (StringUtils.length(shortname) < 3) { popups.field("shortname", "error.name.too.short"); return false; } if (StringUtils.length(shortname) > 100) { popups.field("shortname", "error.username.tooLong"); return false; } if(!userGroupService.isShortnameUnique(shortname, userGroupId, form.getCompanyId())) { popups.field("shortname", "error.usergroup.duplicate"); return false; } return true; }
Example 8
Source File: PetController.java From testing-java-junit5 with Apache License 2.0 | 5 votes |
public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) { if (StringUtils.length(pet.getName()) > 0 && pet.isNew() && owner.getPet(pet.getName(), true) != null){ result.rejectValue("name", "duplicate", "already exists"); } owner.getPets().add(pet); if (result.hasErrors()) { model.put("pet", pet); return VIEWS_PETS_CREATE_OR_UPDATE_FORM; } else { petService.save(pet); return "redirect:/owners/" + owner.getId(); } }
Example 9
Source File: DefaultPasswordStrategy.java From cola with MIT License | 5 votes |
/** * 检查密码强度 * * @param password 密码 */ @Override public void check(String password) { if (StringUtils.isEmpty(password)) { throw new InvalidPasswordException(messages.getMessage("PasswordIsNull", "Password must not be null")); } if (StringUtils.length(password) < properties.getMinLength()) { throw new InvalidPasswordException(messages.getMessage("PasswordIsTooShort", "The length of password is too short")); } if (StringUtils.length(password) > properties.getMinLength()) { throw new InvalidPasswordException(messages.getMessage("PasswordIsTooLong", "The length of password is too long")); } }
Example 10
Source File: XPathExpressionEngine.java From commons-configuration with Apache License 2.0 | 5 votes |
@Override public String attributeKey(final String parentKey, final String attributeName) { final StringBuilder buf = new StringBuilder(StringUtils.length(parentKey) + StringUtils.length(attributeName) + PATH_DELIMITER.length() + ATTR_DELIMITER.length()); if (StringUtils.isNotEmpty(parentKey)) { buf.append(parentKey).append(PATH_DELIMITER); } buf.append(ATTR_DELIMITER).append(attributeName); return buf.toString(); }
Example 11
Source File: BounceFilterFormValidator.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
private boolean validateShortName(final BounceFilterForm form, final Popups popups) { final String shortName = form.getShortName(); if(StringUtils.isBlank(shortName)) { popups.field("shortName", "error.name.is.empty"); return false; } if(StringUtils.length(shortName) < 3) { popups.field("shortName", "error.name.too.short"); return false; } return true; }
Example 12
Source File: SensitiveInfoUtils.java From Resource with GNU General Public License v3.0 | 5 votes |
public static String idCard(String id) { if (StringUtils.isBlank(id)) { return ""; } int length = StringUtils.length(id); if (length < 8) { return StringUtils.left(id, 4).concat(StringUtils.leftPad(StringUtils.right(id, 4), length, "*")); } String num = StringUtils.right(id, 4); return StringUtils.left(id, 4).concat(StringUtils.leftPad(num, StringUtils.length(id) - 4, "*")); }
Example 13
Source File: InfoController.java From cyberduck with GNU General Public License v3.0 | 5 votes |
/** * Permission value from input field. * * @return Null if invalid string has been entered entered, */ private Permission getPermissionFromOctalField() { if(StringUtils.isNotBlank(octalField.stringValue())) { if(StringUtils.length(octalField.stringValue()) >= 3) { if(StringUtils.isNumeric(octalField.stringValue())) { return new Permission(Integer.valueOf(octalField.stringValue()).intValue()); } } } log.warn(String.format("Invalid octal field input %s", octalField.stringValue())); return null; }
Example 14
Source File: WorkflowController.java From openemm with GNU Affero General Public License v3.0 | 4 votes |
@PostMapping("/save.action") public String save(ComAdmin admin, @ModelAttribute("workflowForm") WorkflowForm workflowForm, @RequestParam(value = "forwardName", required = false) String forwardName, @RequestParam(value = "forwardParams", required = false) String forwardParams, @RequestParam(value = "forwardTargetItemId", required = false) String forwardTargetItemId, RedirectAttributes redirectModel, HttpSession session, Popups popups) throws Exception { List<Message> errors = new ArrayList<>(); List<Message> warnings = new ArrayList<>(); Workflow newWorkflow = getWorkflow(workflowForm, admin); Workflow existingWorkflow = workflowService.getWorkflow(newWorkflow.getWorkflowId(), newWorkflow.getCompanyId()); Workflow.WorkflowStatus existingStatus = existingWorkflow != null ? existingWorkflow.getStatus() : Workflow.WorkflowStatus.STATUS_NONE; Workflow.WorkflowStatus newStatus = newWorkflow.getStatus() != Workflow.WorkflowStatus.STATUS_NONE ? newWorkflow.getStatus() : Workflow.WorkflowStatus.STATUS_OPEN; boolean isActiveOrTesting = newStatus == Workflow.WorkflowStatus.STATUS_ACTIVE || newStatus == Workflow.WorkflowStatus.STATUS_TESTING; if (StringUtils.isNotEmpty(forwardName) && StringUtils.length(newWorkflow.getShortname()) < 3) { newWorkflow.setShortname(INCOMPLETE_WORKFLOW_NAME); } // Running or complete campaign should never be saved. if (existingStatus.isChangeable()) { // Set OPEN_STATUS until validation passed and workflow is activated. newWorkflow.setStatus(Workflow.WorkflowStatus.STATUS_OPEN); workflowService.saveWorkflow(admin, newWorkflow, getIcons(workflowForm)); newWorkflow.setStatus(newStatus); if (existingWorkflow == null) { writeUserActivityLog(admin, "create campaign", getWorkflowDescription(newWorkflow)); } else { writeWorkflowChangeLog(admin, existingWorkflow, newWorkflow); } List<WorkflowIcon> icons = newWorkflow.getWorkflowIcons(); if (StringUtils.isNotEmpty(forwardName)) { return getForward(forwardName, forwardParams, forwardTargetItemId, newWorkflow.getWorkflowId(), icons, redirectModel); } errors.addAll(validateWorkflow(admin, icons, newWorkflow.getWorkflowId(), newStatus)); checkAndSetDuplicateMailing(admin, redirectModel, icons, isActiveOrTesting); boolean isValid = errors.isEmpty() && !redirectModel.containsAttribute("affectedMailings"); setStatus(admin, newWorkflow, existingWorkflow, errors, warnings, isValid); if (errors.isEmpty()) { popups.success("default.changes_saved"); } workflowForm.setWorkflowId(newWorkflow.getWorkflowId()); } else { assert (existingWorkflow != null); if (existingWorkflow == null) { throw new Exception("Unexpected empty existingWorkflow"); } if (StringUtils.isNotEmpty(forwardName)) { return getForward(forwardName, forwardParams, forwardTargetItemId, existingWorkflow.getWorkflowId(), existingWorkflow.getWorkflowIcons(), redirectModel); } if (validateStatusTransition(existingStatus, newStatus, errors)) { final ChangingWorkflowStatusResult changingResult = workflowService.changeWorkflowStatus(existingWorkflow.getWorkflowId(), existingWorkflow.getCompanyId(), newStatus); writeWorkflowStatusChangeLog(newWorkflow, existingWorkflow, admin); if(changingResult.isAnyMailingDeactivated()) { writeUserActivityLog(admin, "do deactivate containing mailings", getWorkflowDescription(newWorkflow)); } } } if (isActiveOrTesting) { errors.forEach(popups::alert); } else { errors.forEach(popups::warning); } warnings.forEach(popups::warning); updateForwardParameters(session, forwardTargetItemId, workflowForm.getWorkflowId(), forwardParams); return String.format("redirect:/workflow/%d/view.action", workflowForm.getWorkflowId()); }
Example 15
Source File: ParaServer.java From para with Apache License 2.0 | 4 votes |
/** * @return Jetty config bean */ @Bean public ServletWebServerFactory jettyConfigBean() { JettyServletWebServerFactory jef = new JettyServletWebServerFactory(); jef.addServerCustomizers((JettyServerCustomizer) (Server server) -> { if (Config.getConfigBoolean("access_log_enabled", true)) { // enable access log via Logback HandlerCollection handlers = new HandlerCollection(); for (Handler handler : server.getHandlers()) { handlers.addHandler(handler); } RequestLogHandler reqLogs = new RequestLogHandler(); reqLogs.setServer(server); RequestLogImpl rli = new RequestLogImpl(); rli.setResource("/logback-access.xml"); rli.setQuiet(true); rli.start(); reqLogs.setRequestLog(rli); handlers.addHandler(reqLogs); server.setHandler(handlers); } for (Connector y : server.getConnectors()) { for (ConnectionFactory cf : y.getConnectionFactories()) { if (cf instanceof HttpConnectionFactory) { HttpConnectionFactory dcf = (HttpConnectionFactory) cf; // support for X-Forwarded-Proto // redirect back to https if original request uses it if (Config.IN_PRODUCTION) { ForwardedRequestCustomizer frc = new ForwardedRequestCustomizer() { public void customize(Connector connector, HttpConfiguration config, Request request) { super.customize(connector, config, request); String cfProto = request.getHeader("CloudFront-Forwarded-Proto"); if (StringUtils.equalsIgnoreCase(cfProto, config.getSecureScheme())) { request.setScheme(cfProto); request.setSecure(true); } } }; HttpConfiguration httpConfiguration = dcf.getHttpConfiguration(); httpConfiguration.addCustomizer(frc); } // Disable Jetty version header dcf.getHttpConfiguration().setSendServerVersion(false); // Increase idle timeout dcf.getHttpConfiguration().setIdleTimeout(TimeUnit.MINUTES.toMillis(5)); } } } }); String contextPath = Config.getConfigParam("context_path", ""); if (StringUtils.length(contextPath) > 1 && contextPath.charAt(0) == '/') { jef.setContextPath(contextPath); } jef.setPort(getServerPort()); logger.info("Listening on port {}...", jef.getPort()); return jef; }
Example 16
Source File: AdlsGen2CloudStorageParametersValidator.java From cloudbreak with Apache License 2.0 | 4 votes |
private boolean isLengthMatches(String text) { return StringUtils.length(text) >= MIN_ACCOUNT_NAME_LENGTH && StringUtils.length(text) <= MAX_ACCOUNT_NAME_LENGTH; }
Example 17
Source File: CalendarEventEntityProvider.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Build a {@link TimeRange} from the supplied request parameters. If the parameters are supplied but invalid, an * {@link IllegalArgumentException} will be thrown. * * @param params the request params * @return {@link TimeRange} if valid or null if not */ @SuppressWarnings("deprecation") private TimeRange buildTimeRangeFromRequest(final Map<String, Object> params) { // OPTIONAL params String firstDate = null; String lastDate = null; if (params.containsKey("firstDate")) { firstDate = (String) params.get("firstDate"); } if (params.containsKey("lastDate")) { lastDate = (String) params.get("lastDate"); } // check date params are correct (length is ok) if (StringUtils.isNotBlank(firstDate) && StringUtils.length(firstDate) != 10) { throw new IllegalArgumentException( "firstDate must be in the format yyyy-MM-dd"); } if (StringUtils.isNotBlank(lastDate) && StringUtils.length(lastDate) != 10) { throw new IllegalArgumentException( "lastDate must be in the format yyyy-MM-dd"); } // if we have dates, create a range for filtering // these need to be converted to Time and then a TimeRange created. This is what the CalendarService uses to filter :( // note that our firstDate is always the beginning of the day and the lastDate is always the end // this is to ensure we get full days TimeRange range = null; if (StringUtils.isNotBlank(firstDate) && StringUtils.isNotBlank(lastDate)) { final Time start = this.timeService.newTimeLocal( Integer.valueOf(StringUtils.substring(firstDate, 0, 4)), Integer.valueOf(StringUtils.substring(firstDate, 5, 7)), Integer.valueOf(StringUtils.substring(firstDate, 8, 10)), 0, 0, 0, 0); final Time end = this.timeService.newTimeLocal( Integer.valueOf(StringUtils.substring(lastDate, 0, 4)), Integer.valueOf(StringUtils.substring(lastDate, 5, 7)), Integer.valueOf(StringUtils.substring(lastDate, 8, 10)), 23, 59, 59, 999); range = this.timeService.newTimeRange(start, end, true, true); } return range; }
Example 18
Source File: AdminControllerUtil.java From attic-rave with Apache License 2.0 | 4 votes |
public static void checkTokens(String sessionToken, String token, SessionStatus status) { if (StringUtils.length(sessionToken) != TOKEN_LENGTH || !(sessionToken.equals(token))) { status.setComplete(); throw new SecurityException("Token does not match"); } }
Example 19
Source File: MtaMetadataCriteriaValidator.java From multiapps-controller with Apache License 2.0 | 4 votes |
private static void validateMaxLength(String value, String valueName, int maxLength) { int valueLength = StringUtils.length(value); if (valueLength > maxLength) { throw new IllegalArgumentException(MessageFormat.format(SHOULD_NOT_BE_LONGER_THAN, valueName, maxLength, valueLength, value)); } }
Example 20
Source File: WasbCloudStorageParametersValidator.java From cloudbreak with Apache License 2.0 | 4 votes |
private boolean isLengthMatches(String text) { return StringUtils.length(text) >= MIN_ACCOUNT_NAME_LENGTH && StringUtils.length(text) <= MAX_ACCOUNT_NAME_LENGTH; }