Java Code Examples for org.springframework.util.StringUtils#endsWithIgnoreCase()

The following examples show how to use org.springframework.util.StringUtils#endsWithIgnoreCase() . 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: ValidateCodeFilter.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    if (StrUtil.equals("/authentication/form", request.getRequestURI()) && StringUtils.endsWithIgnoreCase(request.getMethod(), "POST")) {
        try {
            validateCodeService.validate(new ServletWebRequest(request));
        } catch (ValidateCodeException exception) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
            return;
        }
    }

    chain.doFilter(request, response);

}
 
Example 2
Source File: ProtoFileResourceUtils.java    From raptor with Apache License 2.0 6 votes vote down vote up
public static ProtoFileInfo findProtoFile(String packageName, String fileName, ClassLoader classLoader) {
    fileName = StringUtils.endsWithIgnoreCase(fileName, ".proto") ? fileName : fileName + ".proto";
    String resource = packageName.replace(".", "/") + "/" + fileName;
    if (PROTO_FILE_CACHE.get(resource) != null) {
        return PROTO_FILE_CACHE.get(resource);
    }
    ProtoFileInfo protoFileInfo = new ProtoFileInfo();
    protoFileInfo.setFileName(fileName);
    protoFileInfo.setPackageName(packageName);

    if (classLoader == null) {
        classLoader = ProtoFileResourceUtils.class.getClassLoader();
    }
    try (InputStream in = classLoader.getResourceAsStream(resource)) {
        String content = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
        protoFileInfo.setContent(content);
        PROTO_FILE_CACHE.put(resource, protoFileInfo);
        return protoFileInfo;
    } catch (Exception e) {
        log.error("Read proto file [{}] error.", resource, e);
    }
    return null;
}
 
Example 3
Source File: FileStorageController.java    From oauth2-resource with MIT License 5 votes vote down vote up
private Map<String, Object> saveToDisk(MultipartFile multipartFile, String publicStorageLocation) {
    Map<String, Object> result = new HashMap<>(16);
    List<String> fileNames = new LinkedList<>();
    String fileType = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
    if (fileType == null || "".equals(fileType)) {
        String multipartFileContentType = multipartFile.getContentType();
        if (StringUtils.endsWithIgnoreCase("image/png", multipartFileContentType)) {
            fileType = "png";
        } else if (StringUtils.endsWithIgnoreCase("image/jpg", multipartFileContentType)) {
            fileType = "jpg";
        } else if (StringUtils.endsWithIgnoreCase("image/jpeg", multipartFileContentType)) {
            fileType = "jpg";
        } else if (StringUtils.endsWithIgnoreCase("application/pdf", multipartFileContentType)) {
            fileType = "pdf";
        } else if (StringUtils.endsWithIgnoreCase("application/msword", multipartFileContentType)) {
            fileType = "doc";
        }
    }
    if (whitelist.contains(StringUtils.trimAllWhitespace(fileType).toLowerCase())) {
        try {
            String newFileName = storageService.save(Paths.get(publicStorageLocation), multipartFile, fileType);
            fileNames.add(newFileName);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("上传文件异常", e);
            }
        }
    }
    if (fileNames.size() > 0) {
        result.put("status", 1);
    } else {
        result.put("status", 0);
    }
    result.put("files", fileNames);
    return result;
}
 
Example 4
Source File: BrowserSecurityController.java    From imooc-security with Apache License 2.0 5 votes vote down vote up
/**
 * 当需要身份认证时跳转到这个controller
 *
 * @param request
 * @param response
 * @return
 */
@RequestMapping("/authentication/require")
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        logger.info("引发跳转的请求是:"+targetUrl);
        if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
            redirectStrategy.sendRedirect(request,response,properties.getBrowser().getLoginPage());
        }
    }
    return new SimpleResponse("访问的服务器需要身份认证,请引导用户到登录页面");
}
 
Example 5
Source File: DataSourcePoolMetricsConfig.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get the name of a DataSource based on its {@code beanName}.
 *
 * @param beanName the name of the data source bean
 * @return a name for the given data source
 */
private String getDataSourceName( String beanName )
{
    if ( beanName.length() > DATASOURCE_SUFFIX.length()
        && StringUtils.endsWithIgnoreCase( beanName, DATASOURCE_SUFFIX ) )
    {
        return beanName.substring( 0, beanName.length() - DATASOURCE_SUFFIX.length() );
    }
    return beanName;
}
 
Example 6
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 7
Source File: GroovyBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Load bean definitions from the specified Groovy script or XML file.
 * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
 * of resources will be parsed as Groovy scripts.
 * @param encodedResource the resource descriptor for the Groovy script or XML file,
 * allowing specification of an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	// Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
	String filename = encodedResource.getResource().getFilename();
	if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
		return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
	}

	Closure beans = new Closure(this) {
		public Object call(Object[] args) {
			invokeBeanDefiningClosure((Closure) args[0]);
			return null;
		}
	};
	Binding binding = new Binding() {
		@Override
		public void setVariable(String name, Object value) {
			if (currentBeanDefinition != null) {
				applyPropertyToBeanDefinition(name, value);
			}
			else {
				super.setVariable(name, value);
			}
		}
	};
	binding.setVariable("beans", beans);

	int countBefore = getRegistry().getBeanDefinitionCount();
	try {
		GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding);
		shell.evaluate(encodedResource.getReader(), "beans");
	}
	catch (Throwable ex) {
		throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(),
				new Location(encodedResource.getResource()), null, ex));
	}
	return getRegistry().getBeanDefinitionCount() - countBefore;
}
 
Example 8
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 9
Source File: BrowserSecurityController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SavedRequest savedRequest = requestCache.getRequest(request, response);
    if (savedRequest != null) {
        String targetUrl = savedRequest.getRedirectUrl();
        if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
            redirectStrategy.sendRedirect(request, response, "/login.html");
    }
    return "访问的资源需要身份认证!";
}
 
Example 10
Source File: SwaggerHeaderFilter.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (!StringUtils.endsWithIgnoreCase(path, GatewaySwaggerProvider.SWAGGER2URL)) {
            return chain.filter(exchange);
        }
        String basePath = path.substring(0, path.lastIndexOf(GatewaySwaggerProvider.SWAGGER2URL));
        ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    };
}
 
Example 11
Source File: GroovyBeanDefinitionReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load bean definitions from the specified Groovy script or XML file.
 * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
 * of resources will be parsed as Groovy scripts.
 * @param encodedResource the resource descriptor for the Groovy script or XML file,
 * allowing specification of an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	// Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
	String filename = encodedResource.getResource().getFilename();
	if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
		return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
	}

	Closure beans = new Closure(this) {
		public Object call(Object[] args) {
			invokeBeanDefiningClosure((Closure) args[0]);
			return null;
		}
	};
	Binding binding = new Binding() {
		@Override
		public void setVariable(String name, Object value) {
			if (currentBeanDefinition != null) {
				applyPropertyToBeanDefinition(name, value);
			}
			else {
				super.setVariable(name, value);
			}
		}
	};
	binding.setVariable("beans", beans);

	int countBefore = getRegistry().getBeanDefinitionCount();
	try {
		GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding);
		shell.evaluate(encodedResource.getReader(), "beans");
	}
	catch (Throwable ex) {
		throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(),
				new Location(encodedResource.getResource()), null, ex));
	}
	return getRegistry().getBeanDefinitionCount() - countBefore;
}
 
Example 12
Source File: ConsulPropertySource.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the properties in key value style i.e., values are expected to be either a
 * sub key or a constant.
 * @param values values to parse
 */
protected void parsePropertiesInKeyValueFormat(List<GetValue> values) {
	if (values == null) {
		return;
	}

	for (GetValue getValue : values) {
		String key = getValue.getKey();
		if (!StringUtils.endsWithIgnoreCase(key, "/")) {
			key = key.replace(this.context, "").replace('/', '.');
			String value = getValue.getDecodedValue();
			this.properties.put(key, value);
		}
	}
}
 
Example 13
Source File: FebsDocGatewayHeaderFilter.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (!StringUtils.endsWithIgnoreCase(path, URI)) {
            return chain.filter(exchange);
        }
        String basePath = path.substring(0, path.lastIndexOf(URI));
        ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    };
}
 
Example 14
Source File: GwSwaggerHeaderFilter.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (!StringUtils.endsWithIgnoreCase(path, GatewaySwaggerProvider.API_URI)) {
            return chain.filter(exchange);
        }
        String basePath = path.substring(0, path.lastIndexOf(GatewaySwaggerProvider.API_URI));
        ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    };
}
 
Example 15
Source File: GroovyBeanDefinitionReader.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Load bean definitions from the specified Groovy script or XML file.
 * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds
 * of resources will be parsed as Groovy scripts.
 * @param encodedResource the resource descriptor for the Groovy script or XML file,
 * allowing specification of an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	// Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
	String filename = encodedResource.getResource().getFilename();
	if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
		return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("Loading Groovy bean definitions from " + encodedResource);
	}

	Closure beans = new Closure(this) {
		@Override
		public Object call(Object[] args) {
			invokeBeanDefiningClosure((Closure) args[0]);
			return null;
		}
	};
	Binding binding = new Binding() {
		@Override
		public void setVariable(String name, Object value) {
			if (currentBeanDefinition != null) {
				applyPropertyToBeanDefinition(name, value);
			}
			else {
				super.setVariable(name, value);
			}
		}
	};
	binding.setVariable("beans", beans);

	int countBefore = getRegistry().getBeanDefinitionCount();
	try {
		GroovyShell shell = new GroovyShell(getBeanClassLoader(), binding);
		shell.evaluate(encodedResource.getReader(), "beans");
	}
	catch (Throwable ex) {
		throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(),
				new Location(encodedResource.getResource()), null, ex));
	}

	int count = getRegistry().getBeanDefinitionCount() - countBefore;
	if (logger.isDebugEnabled()) {
		logger.debug("Loaded " + count + " bean definitions from " + encodedResource);
	}
	return count;
}
 
Example 16
Source File: ConsulPropertySource.java    From spring-cloud-formula with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the properties in key value style i.e., values are expected to be either a
 * sub key or a constant.
 *
 * @param values values to parse
 */
protected void parsePropertiesInKeyValueFormat(List<GetValue> values) {
    if (values == null) {
        return;
    }
    Map<String, Map<String, String>> groups = new HashMap<>();
    for (GetValue getValue : values) {
        String key = getValue.getKey();
        // skip all the path which end with /, only process those real keys
        if (!StringUtils.endsWithIgnoreCase(key, "/")) {
            key = key.replace(this.context, "");
            // until now, key = groupId/status/realKey
            String value = getValue.getDecodedValue();
            logger.debug("context:" + this.context + " key is " + key + ", value is " + value);
            if (!StringUtils.isEmpty(key)) {
                kvGrouping(groups, key, value);
            }
        }
    }
    // process all effective keys
    for (Map.Entry<String, Map<String, String>> entry : groups.entrySet()) {
        String prefix = "full/";
        // check if this group contains grayRelease and if this instance matches
        if (entry.getValue().containsKey("instance/list")) {
            String list = entry.getValue().get("instance/list");
            List idList = Arrays.asList(list.split(SPLITTER));
            String id = System.getenv("EM_INSTANCE_ID");
            if (idList.contains(id)) {
                prefix = "gray/";
            }
        }

        // based on the status/matching, filter out those keys with the same prefix
        for (Map.Entry<String, String> subGroups : entry.getValue().entrySet()) {
            if (subGroups.getKey().equals(prefix + "kvs")) {
                String kvs = subGroups.getValue();
                if (null == kvs) {
                    logger.warn("Null value is ignored for kvs!");
                    return;
                }
                // decode kv pairs from this value
                decodeKVs(kvs);
            }
        }
    }

}
 
Example 17
Source File: ConfigurationClassBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private void loadBeanDefinitionsFromImportedResources(
		Map<String, Class<? extends BeanDefinitionReader>> importedResources) {

	Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>();

	for (Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) {
		String resource = entry.getKey();
		Class<? extends BeanDefinitionReader> readerClass = entry.getValue();

		// Default reader selection necessary?
		if (BeanDefinitionReader.class == readerClass) {
			if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) {
				// When clearly asking for Groovy, that's what they'll get...
				readerClass = GroovyBeanDefinitionReader.class;
			}
			else {
				// Primarily ".xml" files but for any other extension as well
				readerClass = XmlBeanDefinitionReader.class;
			}
		}

		BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
		if (reader == null) {
			try {
				// Instantiate the specified BeanDefinitionReader
				reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
				// Delegate the current ResourceLoader to it if possible
				if (reader instanceof AbstractBeanDefinitionReader) {
					AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
					abdr.setResourceLoader(this.resourceLoader);
					abdr.setEnvironment(this.environment);
				}
				readerInstanceCache.put(readerClass, reader);
			}
			catch (Exception ex) {
				throw new IllegalStateException(
						"Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]");
			}
		}

		// TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations
		reader.loadBeanDefinitions(resource);
	}
}
 
Example 18
Source File: ConfigurationClassBeanDefinitionReader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void loadBeanDefinitionsFromImportedResources(
		Map<String, Class<? extends BeanDefinitionReader>> importedResources) {

	Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>();

	for (Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) {
		String resource = entry.getKey();
		Class<? extends BeanDefinitionReader> readerClass = entry.getValue();

		// Default reader selection necessary?
		if (BeanDefinitionReader.class == readerClass) {
			if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) {
				// When clearly asking for Groovy, that's what they'll get...
				readerClass = GroovyBeanDefinitionReader.class;
			}
			else {
				// Primarily ".xml" files but for any other extension as well
				readerClass = XmlBeanDefinitionReader.class;
			}
		}

		BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
		if (reader == null) {
			try {
				// Instantiate the specified BeanDefinitionReader
				reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
				// Delegate the current ResourceLoader to it if possible
				if (reader instanceof AbstractBeanDefinitionReader) {
					AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
					abdr.setResourceLoader(this.resourceLoader);
					abdr.setEnvironment(this.environment);
				}
				readerInstanceCache.put(readerClass, reader);
			}
			catch (Throwable ex) {
				throw new IllegalStateException(
						"Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]");
			}
		}

		// TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations
		reader.loadBeanDefinitions(resource);
	}
}
 
Example 19
Source File: LockableSelect.java    From tx-lcn with Apache License 2.0 4 votes vote down vote up
public boolean isxLock() {
    return StringUtils.endsWithIgnoreCase(StringUtils.trimAllWhitespace(this.select.toString()),
            StringUtils.trimAllWhitespace(SqlUtils.FOR_UPDATE));
}
 
Example 20
Source File: LockableSelect.java    From tx-lcn with Apache License 2.0 4 votes vote down vote up
public boolean issLock() {
    return StringUtils.endsWithIgnoreCase(StringUtils.trimAllWhitespace(this.select.toString()),
            StringUtils.trimAllWhitespace(SqlUtils.LOCK_IN_SHARE_MODE));
}