List of usage examples for org.apache.commons.lang3 StringUtils startsWith
public static boolean startsWith(final CharSequence str, final CharSequence prefix)
Check if a CharSequence starts with a specified prefix.
null s are handled without exceptions.
From source file:org.phenotips.ontology.internal.solr.MendelianInheritanceInMan.java
@Override public OntologyTerm getTerm(String id) { OntologyTerm result = super.getTerm(id); if (result == null) { String optionalPrefix = STANDARD_NAME + ":"; if (StringUtils.startsWith(id, optionalPrefix)) { result = getTerm(StringUtils.substringAfter(id, optionalPrefix)); }//from ww w . j ava 2s . c om } return result; }
From source file:org.phenotips.vocabulary.internal.solr.AbstractOWLSolrVocabulary.java
/** * If the {@code id} stats with the optional prefix, removes the prefix and performs the search again. * * @param id the ID of the term of interest * @return the {@link VocabularyTerm} corresponding with the given ID, null if no such {@link VocabularyTerm} exists */// w w w . j a v a2 s. c o m private VocabularyTerm searchTermWithoutPrefix(@Nonnull final String id) { final String optPrefix = this.getTermPrefix() + SEPARATOR; return StringUtils.startsWith(id.toUpperCase(), optPrefix.toUpperCase()) ? getTerm(StringUtils.substringAfter(id, SEPARATOR)) : null; }
From source file:org.phenotips.vocabulary.internal.solr.MendelianInheritanceInMan.java
@Override public VocabularyTerm getTerm(String id) { VocabularyTerm result = super.getTerm(id); if (result == null) { String optionalPrefix = STANDARD_NAME + ":"; if (StringUtils.startsWith(id, optionalPrefix)) { result = getTerm(StringUtils.substringAfter(id, optionalPrefix)); }//from w w w .ja va 2 s. co m } return result; }
From source file:org.pircbotx.ReplayServer.java
public static void replay(Configuration.Builder config, InputStream input, String title) throws Exception { log.info("---Replaying {}---", title); StopWatch timer = new StopWatch(); timer.start();//from w w w. j a v a 2 s. c om //Wrap listener manager with ours that siphons off events final Queue<Event> eventQueue = Lists.newLinkedList(); WrapperListenerManager newManager = new WrapperListenerManager(config.getListenerManager(), eventQueue); config.setListenerManager(newManager); config.addListener(new ReplayListener()); final LinkedList<String> outputQueue = Lists.newLinkedList(); ReplayPircBotX bot = new ReplayPircBotX(config.buildConfiguration(), outputQueue); BufferedReader fileInput = new BufferedReader(new InputStreamReader(input)); boolean skippedHeader = false; while (true) { String lineRaw = fileInput.readLine(); if (bot.isClosed() && StringUtils.isNotBlank(lineRaw)) { throw new RuntimeException("bot is closed but file still has line " + lineRaw); } else if (!bot.isClosed() && StringUtils.isBlank(lineRaw)) { throw new RuntimeException("bot is not closed but file doesn't have any more lines"); } else if (bot.isClosed() && StringUtils.isBlank(lineRaw)) { log.debug("(done) Bot is closed and file doesn't have any more lines"); break; } log.debug("(line) " + lineRaw); String[] lineParts = StringUtils.split(lineRaw, " ", 2); String command = lineParts[0]; String line = lineParts[1]; //For now skip the info lines PircBotX is supposed to send on connect //They are only sent when connect() is called which requires multithreading if (!skippedHeader) { if (command.equals("pircbotx.output")) continue; else if (command.equals("pircbotx.input")) { log.debug("Finished skipping header"); skippedHeader = true; } else throw new RuntimeException("Unknown line " + lineRaw); } if (command.equals("pircbotx.input")) { bot.getInputParser().handleLine(line); } else if (command.equals("pircbotx.output")) { String lastOutput = outputQueue.isEmpty() ? null : outputQueue.pop(); if (StringUtils.startsWith(line, "JOIN")) { log.debug("Skipping JOIN output, server should send its own JOIN"); } else if (StringUtils.startsWith(line, "QUIT")) { log.debug("Skipping QUIT output, server should send its own QUIT"); } else if (!line.equals(lastOutput)) { log.error("Expected last output: " + line); log.error("Given last output: " + lastOutput); for (String curOutput : outputQueue) { log.error("Queued output: " + curOutput); } throw new RuntimeException("Failed to verify output (see log)"); } } else { throw new RuntimeException("Unknown line " + lineRaw); } for (Event curEvent : Iterables.consumingIterable(eventQueue)) log.debug("(events) " + curEvent); log.debug(""); } timer.stop(); log.debug("---Replay successful in {}---", DurationFormatUtils.formatDuration(timer.getTime(), "mm'min'ss'sec'SSS'ms'")); }
From source file:org.sakaiproject.assignment.api.AssignmentReferenceReckoner.java
/** * This is a builder for an AssignmentReference * * @param container//from www . j a v a 2 s. co m * @param context * @param id * @param reference * @param subtype * @return */ @Builder(builderMethodName = "reckoner", buildMethodName = "reckon") public static AssignmentReference newAssignmentReferenceReckoner(Assignment assignment, AssignmentSubmission submission, String container, String context, String id, String reference, String subtype) { if (StringUtils.startsWith(reference, REFERENCE_ROOT)) { // we will get null, assignment, [a|c|s|grades|submissions], context, [auid], id String[] parts = StringUtils.splitPreserveAllTokens(reference, Entity.SEPARATOR); if (parts.length > 2) { if (subtype == null) subtype = parts[2]; if (parts.length > 3) { // context is the container if (context == null) context = parts[3]; // submissions have the assignment unique id as a container if ("s".equals(subtype) && parts.length > 5) { if (container == null) container = parts[4]; if (id == null) id = parts[5]; } else { // others don't if (parts.length > 4) { if (id == null) id = parts[4]; } } } } } else if (assignment != null) { context = assignment.getContext(); id = assignment.getId(); subtype = "a"; } else if (submission != null) { Assignment submissionAssignment = submission.getAssignment(); if (submissionAssignment != null) { context = submission.getAssignment().getContext(); container = submission.getAssignment().getId(); id = submission.getId(); subtype = "s"; } else { log.warn("no assignment while constructing submission reference"); } } return new AssignmentReference((container == null) ? "" : container, (context == null) ? "" : context, (id == null) ? "" : id, (reference == null) ? "" : reference, (subtype == null) ? "" : subtype); }
From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java
@Override public boolean parseEntityReference(String stringReference, Reference reference) { if (StringUtils.startsWith(stringReference, REFERENCE_ROOT)) { AssignmentReferenceReckoner.AssignmentReference reckoner = AssignmentReferenceReckoner.reckoner() .reference(stringReference).reckon(); reference.set(SAKAI_ASSIGNMENT, reckoner.getSubtype(), reckoner.getId(), reckoner.getContainer(), reckoner.getContext());//from w ww .j a va 2 s . co m return true; } return false; }
From source file:org.sakaiproject.webservices.interceptor.RemoteHostMatcher.java
/** * Is this HTTP request allowed based on the remote host and the configured allows/denied properties. * @param request The HTTP request./* w w w . j a v a2 s .c om*/ * @return <code>true</code> if we should allow access. */ public boolean isAllowed(HttpServletRequest request) { String host = request.getRemoteHost(); String addr = request.getRemoteAddr(); // Check requests that are always allowed ... String uri = request.getRequestURI(); for (String allowedUri : allowRequests) { if (StringUtils.startsWith(uri, allowedUri)) { if (logAllowed) log.info("Access granted for request ({}): {}/{}", uri, host, addr); return true; } } // Check if explicit denied ... for (Pattern pattern : denyPattern) { if (pattern.matcher(host).matches() || pattern.matcher(addr).matches()) { if (logDenied) log.info("Access denied ({}): {}/{}", pattern.pattern(), host, addr); return false; } } // Check if explicitly allowed ... for (Pattern pattern : allowPattern) { if (pattern.matcher(host).matches() || pattern.matcher(addr).matches()) { if (logAllowed) log.info("Access granted ({}): {}/{}", pattern.pattern(), host, addr); return true; } } // Allow if allows is null, but denied is not if ((!denyPattern.isEmpty()) && (allowPattern.isEmpty())) { if (logAllowed) log.info("Access granted (implicit): {}/{}", host, addr); return true; } // Deny this request if (logDenied) log.info("Access denied (implicit): {}/{}", host, addr); return false; }
From source file:org.sejda.cli.SejdaConsole.java
/** * throws an exception if there are duplicate option:value pairs specified, that would override each other silently otherwise * /*from w ww .j a v a2s . c om*/ */ private void validateNoDuplicateCommandArguments() { Map<String, Object> uniqueArguments = new HashMap<>(); for (final String eachArgument : arguments.getCommandArguments()) { if (uniqueArguments.containsKey(eachArgument) && StringUtils.startsWith(eachArgument, "-")) { throw new ArgumentValidationException("Option '" + eachArgument + "' is specified twice. Please note that the correct way to specify a list of values for an option is to repeat the values after the option, without re-stating the option name. Example: --files /tmp/file1.pdf /tmp/files2.pdf"); } uniqueArguments.put(eachArgument, eachArgument); } }
From source file:org.squashtest.tm.web.internal.interceptor.SecurityExpressionResolverExposerInterceptor.java
/** * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) *//* ww w .j a va 2 s . c o m*/ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView != null && modelAndView.hasView() && !StringUtils.startsWith(modelAndView.getViewName(), "redirect:")) { FilterInvocation filterInvocation = new FilterInvocation(request, response, DUMMY_CHAIN); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { LOGGER.debug( "No authentication available for '{}{}'. Thymeleaf won't have access to '#sec' in view '{}'", request.getServletPath(), request.getPathInfo(), modelAndView.getViewName()); return; } WebSecurityExpressionRoot expressionRoot = new WebSecurityExpressionRoot(authentication, filterInvocation); expressionRoot.setTrustResolver(trustResolver); expressionRoot.setPermissionEvaluator(permissionEvaluator); modelAndView.addObject("sec", expressionRoot); } }
From source file:org.structr.core.property.Property.java
protected void determineSearchType(final SecurityContext securityContext, final String requestParameter, final Query query) throws FrameworkException { if (StringUtils.startsWith(requestParameter, "[") && StringUtils.endsWith(requestParameter, "]")) { // check for existance of range query string Matcher matcher = rangeQueryPattern.matcher(requestParameter); if (matcher.matches()) { if (matcher.groupCount() == 2) { String rangeStart = matcher.group(1); String rangeEnd = matcher.group(2); PropertyConverter inputConverter = inputConverter(securityContext); Object rangeStartConverted = rangeStart; Object rangeEndConverted = rangeEnd; if (inputConverter != null) { rangeStartConverted = inputConverter.convert(rangeStartConverted); rangeEndConverted = inputConverter.convert(rangeEndConverted); }//from w w w .j a v a 2s . c om query.andRange(this, rangeStartConverted, rangeEndConverted); return; } logger.log(Level.WARNING, "Unable to determine range query bounds for {0}", requestParameter); } else { if ("[]".equals(requestParameter)) { if (isIndexedWhenEmpty()) { // requestParameter contains only [], // which we use as a "not-blank" selector query.notBlank(this); return; } else { throw new FrameworkException(400, "PropertyKey " + jsonName() + " must be indexedWhenEmpty() to be used in not-blank search query."); } } else { throw new FrameworkException(422, "Invalid range pattern."); } } } if (requestParameter.contains(",") && requestParameter.contains(";")) { throw new FrameworkException(422, "Mixing of AND and OR not allowed in request parameters"); } if (requestParameter.contains(";")) { if (multiValueSplitAllowed()) { // descend into a new group query.and(); for (final String part : requestParameter.split("[;]+")) { query.or(this, convertSearchValue(securityContext, part)); } // ascend to the last group query.parent(); } else { query.or(this, convertSearchValue(securityContext, requestParameter)); } } else { query.and(this, convertSearchValue(securityContext, requestParameter)); } }