下面列出了org.apache.commons.lang3.StringUtils#substringBeforeLast ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public StorageAsset getParent( )
{
Path parentPath;
if (basePath!=null && assetPath.equals( basePath )) {
parentPath=null;
} else
{
parentPath = assetPath.getParent( );
}
String relativeParent = StringUtils.substringBeforeLast( relativePath,"/");
if (parentPath!=null) {
return new FilesystemAsset(storage, relativeParent, parentPath, basePath, true, setPermissionsForNew );
} else {
return null;
}
}
/**
* List all preparation details.
*
* @param name of the preparation.
* @param folderPath filter on the preparation path.
* @param path preparation full path in the form folder_path/preparation_name. Overrides folderPath and name if
* present.
* @param sort how to sort the preparations.
* @param order how to order the sort.
* @return the preparation details.
*/
public Stream<PreparationDTO> listAll(String name, String folderPath, String path, Sort sort, Order order) {
if (path != null) {
// Transform path argument into folder path + preparation name
if (path.contains(PATH_SEPARATOR.toString())) {
// Special case the path should start with /
if (!path.startsWith(PATH_SEPARATOR.toString())) {
path = PATH_SEPARATOR.toString().concat(path);
}
folderPath = StringUtils.substringBeforeLast(path, PATH_SEPARATOR.toString());
// Special case if the preparation is in the root folder
if (org.apache.commons.lang3.StringUtils.isEmpty(folderPath)) {
folderPath = PATH_SEPARATOR.toString();
}
name = StringUtils.substringAfterLast(path, PATH_SEPARATOR.toString());
} else {
// the preparation is in the root folder
folderPath = PATH_SEPARATOR.toString();
name = path;
LOGGER.warn("Using path argument without '{}'. {} filter has been transformed into {}{}.",
PATH_SEPARATOR, path, PATH_SEPARATOR, name);
}
}
return listAll(filterPreparation().byName(name).withNameExactMatch(true).byFolderPath(folderPath), sort, order);
}
/**
* 根据Id查询升级
*/
@RequestMapping(params="method=queryUpgrade",method=RequestMethod.GET)
@ResponseBody//方式来做ajax,直接返回字符串
public String queryUpgrade(ModelMap model,String upgradeSystemId,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UpgradeSystem upgradeSystem = upgradeService.findUpgradeSystemById(upgradeSystemId);
if(upgradeSystem != null){
//删除最后一个逗号
String _upgradeLog = StringUtils.substringBeforeLast(upgradeSystem.getUpgradeLog(), ",");//从右往左截取到相等的字符,保留左边的
List<UpgradeLog> upgradeLogList = JsonUtils.toGenericObject(_upgradeLog+"]", new TypeReference< List<UpgradeLog> >(){});
upgradeSystem.setUpgradeLogList(upgradeLogList);
if(upgradeSystem != null){
return JsonUtils.toJSONString(upgradeSystem);
}
}
return "";
}
protected String extractBreadcrumbUrl(String url, String root) {
String indexFileName = SiteProperties.getIndexFileName();
String breadcrumbUrl = StringUtils.substringBeforeLast(StringUtils.substringAfter(url, root), indexFileName);
if (!breadcrumbUrl.startsWith("/")) {
breadcrumbUrl = "/" + breadcrumbUrl;
}
return breadcrumbUrl;
}
private void validateImportRequiredField(
int line,
Class<?> model,
String fieldName,
FileField fileField,
List<String> relationalFieldList)
throws IOException, ClassNotFoundException {
Mapper mapper = advancedImportService.getMapper(model.getName());
String field = getField(fileField);
Integer rowNum = fileField.getIsMatchWithFile() ? line : null;
int importType = fileField.getImportType();
for (Property prop : mapper.getProperties()) {
if (prop.isRequired()) {
if (prop.getName().equals(fieldName)
&& importType == FileFieldRepository.IMPORT_TYPE_IGNORE_EMPTY) {
logService.addLog(IExceptionMessage.ADVANCED_IMPORT_LOG_5, field, rowNum);
} else if ((importType == FileFieldRepository.IMPORT_TYPE_FIND_NEW
|| importType == FileFieldRepository.IMPORT_TYPE_NEW)
&& field.contains(".")
&& !fileField.getTargetType().equals("MetaFile")) {
String newField = StringUtils.substringBeforeLast(field, ".");
newField = newField + "." + prop.getName();
if (!relationalFieldList.contains(newField)) {
logService.addLog(IExceptionMessage.ADVANCED_IMPORT_LOG_3, newField, null);
}
}
}
}
}
@Override
public String deserialize(final String token) throws InvalidTokenException {
validateTimestamp(token);
String decodedToken = StringUtils.substringBeforeLast(token, TIMESTAMP_DEMILITER);
if (StringUtils.isBlank(decodedToken)) {
throw new InvalidTokenException("The token is blank.");
}
return decodedToken;
}
private String toUrl(SlingHttpServletRequest request, Page page, Map<String, String> params, String template, String selectorFilter) {
if (page != null && params.containsKey(selectorFilter)) {
Resource pageResource = page.adaptTo(Resource.class);
boolean deepLink = !WCMMode.DISABLED.equals(WCMMode.fromRequest(request));
if (deepLink) {
Resource subPageResource = toSpecificPage(pageResource, params.get(selectorFilter));
if (subPageResource != null) {
pageResource = subPageResource;
}
}
params.put(PAGE_PARAM, pageResource.getPath());
}
String prefix = "${", suffix = "}"; // variables have the format ${var}
if (template.contains("{{")) {
prefix = "{{";
suffix = "}}"; // variables have the format {{var}}
}
StringSubstitutor sub = new StringSubstitutor(params, prefix, suffix);
String url = sub.replace(template);
url = StringUtils.substringBeforeLast(url, "#" + prefix); // remove anchor if it hasn't been substituted
if (url.contains(prefix)) {
LOGGER.warn("Missing params for URL substitution. Resulted URL: {}", url);
}
return url;
}
RegExpData(final NativeRegExp re) {
final String str = re.toString(); // the form is /regex/flags
final String jsSource = StringUtils.substringBeforeLast(str.substring(1), "/");
final String jsFlags = StringUtils.substringAfterLast(str, "/");
global_ = jsFlags.indexOf('g') != -1;
pattern_ = PATTENS.get(str);
if (pattern_ == null) {
pattern_ = Pattern.compile(jsRegExpToJavaRegExp(jsSource), getJavaFlags(jsFlags));
PATTENS.put(str, pattern_);
}
}
/**
* Parse URL path to extract package info.
* Only public for unit tests.
* @param path url path
* @return name, epoch, vesion, release, arch of package
*/
public static PkgInfo parsePackageFileName(String path) {
List<String> parts = Arrays.asList(path.split("/"));
String extension = FilenameUtils.getExtension(path);
String basename = FilenameUtils.getBaseName(path);
String arch = StringUtils.substringAfterLast(basename, ".");
String rest = StringUtils.substringBeforeLast(basename, ".");
String release = "";
String name = "";
String version = "";
String epoch = "";
// Debian packages names need spacial handling
if ("deb".equalsIgnoreCase(extension) || "udeb".equalsIgnoreCase(extension)) {
name = StringUtils.substringBeforeLast(rest, "_");
rest = StringUtils.substringAfterLast(rest, "_");
PackageEvr pkgEv = PackageUtils.parseDebianEvr(rest);
epoch = pkgEv.getEpoch();
version = pkgEv.getVersion();
release = pkgEv.getRelease();
}
else {
release = StringUtils.substringAfterLast(rest, "-");
rest = StringUtils.substringBeforeLast(rest, "-");
version = StringUtils.substringAfterLast(rest, "-");
name = StringUtils.substringBeforeLast(rest, "-");
epoch = null;
}
PkgInfo p = new PkgInfo(name, epoch, version, release, arch);
// path is getPackage/<org>/<checksum>/filename
if (parts.size() == 9 && parts.get(5).equals("getPackage")) {
p.setOrgId(parts.get(6));
p.setChecksum(parts.get(7));
}
return p;
}
@Override
public OpenAPIConfiguration customize(final OpenAPIConfiguration configuration) {
init();
super.customize(configuration);
MessageContext ctx = JAXRSUtils.createContextValue(
JAXRSUtils.getCurrentMessage(), null, MessageContext.class);
String url = StringUtils.substringBeforeLast(ctx.getUriInfo().getRequestUri().getRawPath(), "/");
configuration.getOpenAPI().setServers(List.of(new Server().url(url)));
return configuration;
}
private String findPackage(final ArchiveModel payload, String entryName) {
String packageName = StringUtils.removeEnd(entryName, ".class");
packageName = StringUtils.replace(packageName, "/", ".");
packageName = StringUtils.substringBeforeLast(packageName, ".");
if(StringUtils.endsWith(payload.getArchiveName(), ".war")) {
packageName = StringUtils.substringAfterLast(packageName, "WEB-INF.classes.");
}
else if(StringUtils.endsWith(payload.getArchiveName(), ".par")) {
packageName = StringUtils.removeStart(packageName, "classes.");
}
return packageName;
}
private String getFileName() {
String fileName = StringUtils.substringBeforeLast(this.name, ".");
if (fileName == null || fileName.isEmpty()) {
return name;
}
return fileName;
}
private Constructor<TServiceClient> getClientConstructorClazz() {
String parentClazzName = StringUtils.substringBeforeLast(serviceInfo.getInterfaceClazz().getCanonicalName(),
".Iface");
String clientClazzName = parentClazzName + "$Client";
try {
return ((Class<TServiceClient>) Class.forName(clientClazzName)).getConstructor(TProtocol.class);
} catch (Exception e) {
//
LOGGER.error("get thrift client class constructor fail.e:", e);
throw new IllegalArgumentException("invalid iface implement");
}
}
public String getPackage() {
return StringUtils.substringBeforeLast(name, ".");
}
public static ContextURL parse(final URI contextURL) {
if (contextURL == null) {
return null;
}
final ContextURL.Builder contextUrl = ContextURL.with();
String contextURLasString = contextURL.toASCIIString();
boolean isEntity = false;
if (contextURLasString.endsWith("/$entity") || contextURLasString.endsWith("/@Element")) {
isEntity = true;
contextUrl.suffix(Suffix.ENTITY);
contextURLasString = contextURLasString.replace("/$entity", StringUtils.EMPTY).
replace("/@Element", StringUtils.EMPTY);
} else if (contextURLasString.endsWith("/$ref")) {
contextUrl.suffix(Suffix.REFERENCE);
contextURLasString = contextURLasString.replace("/$ref", StringUtils.EMPTY);
} else if (contextURLasString.endsWith("/$delta")) {
contextUrl.suffix(Suffix.DELTA);
contextURLasString = contextURLasString.replace("/$delta", StringUtils.EMPTY);
} else if (contextURLasString.endsWith("/$deletedEntity")) {
contextUrl.suffix(Suffix.DELTA_DELETED_ENTITY);
contextURLasString = contextURLasString.replace("/$deletedEntity", StringUtils.EMPTY);
} else if (contextURLasString.endsWith("/$link")) {
contextUrl.suffix(Suffix.DELTA_LINK);
contextURLasString = contextURLasString.replace("/$link", StringUtils.EMPTY);
} else if (contextURLasString.endsWith("/$deletedLink")) {
contextUrl.suffix(Suffix.DELTA_DELETED_LINK);
contextURLasString = contextURLasString.replace("/$deletedLink", StringUtils.EMPTY);
}
contextUrl.serviceRoot(URI.create(StringUtils.substringBefore(contextURLasString, Constants.METADATA)));
final String rest = StringUtils.substringAfter(contextURLasString, Constants.METADATA + "#");
String firstToken;
String entitySetOrSingletonOrType;
if (rest.startsWith("Collection(")) {
firstToken = rest.substring(0, rest.indexOf(')') + 1);
entitySetOrSingletonOrType = firstToken;
} else {
final int openParIdx = rest.indexOf('(');
if (openParIdx == -1) {
firstToken = StringUtils.substringBeforeLast(rest, "/");
entitySetOrSingletonOrType = firstToken;
} else {
firstToken = isEntity ? rest : StringUtils.substringBeforeLast(rest, ")") + ")";
final List<String> parts = new ArrayList<>();
for (String split : firstToken.split("\\)/")) {
parts.add(split.replaceAll("\\(.*", ""));
}
entitySetOrSingletonOrType = StringUtils.join(parts, '/');
final int commaIdx = firstToken.indexOf(',');
if (commaIdx != -1) {
contextUrl.selectList(firstToken.substring(openParIdx + 1, firstToken.length() - 1));
}
}
}
contextUrl.entitySetOrSingletonOrType(entitySetOrSingletonOrType);
final int slashIdx = entitySetOrSingletonOrType.lastIndexOf('/');
if (slashIdx != -1 && entitySetOrSingletonOrType.substring(slashIdx + 1).indexOf('.') != -1) {
contextUrl.entitySetOrSingletonOrType(entitySetOrSingletonOrType.substring(0, slashIdx));
contextUrl.derivedEntity(entitySetOrSingletonOrType.substring(slashIdx + 1));
}
if (!firstToken.equals(rest)) {
final String[] pathElems = StringUtils.substringAfter(rest, "/").split("/");
if (pathElems.length > 0 && pathElems[0].length() > 0) {
if (pathElems[0].indexOf('.') == -1) {
contextUrl.navOrPropertyPath(pathElems[0]);
} else {
contextUrl.derivedEntity(pathElems[0]);
}
if (pathElems.length > 1) {
contextUrl.navOrPropertyPath(pathElems[1]);
}
}
}
return contextUrl.build();
}
@Override
public AvailabilityStatus artifactAvailable( String groupId, String artifactId, String version, String classifier,
String repositoryId )
throws ArchivaRestServiceException
{
List<String> selectedRepos = getSelectedRepos( repositoryId );
boolean snapshot = VersionUtil.isSnapshot( version );
try
{
for ( String repoId : selectedRepos )
{
org.apache.archiva.repository.ManagedRepository managedRepo = repositoryRegistry.getManagedRepository(repoId);
if (!proxyRegistry.hasHandler(managedRepo.getType())) {
throw new RepositoryException( "No proxy handler found for repository type "+managedRepo.getType());
}
RepositoryProxyHandler proxyHandler = proxyRegistry.getHandler(managedRepo.getType()).get(0);
if ( ( snapshot && !managedRepo.getActiveReleaseSchemes().contains(ReleaseScheme.SNAPSHOT) ) || ( !snapshot
&& managedRepo.getActiveReleaseSchemes().contains(ReleaseScheme.SNAPSHOT) ) )
{
continue;
}
ManagedRepositoryContent managedRepositoryContent = getManagedRepositoryContent( repoId );
// FIXME default to jar which can be wrong for war zip etc....
ArchivaItemSelector itemSelector = ArchivaItemSelector.builder( ).withNamespace( groupId )
.withProjectId( artifactId ).withVersion( version ).withClassifier( StringUtils.isEmpty( classifier )
? ""
: classifier )
.withType( "jar" )
.withArtifactId( artifactId ).build();
org.apache.archiva.repository.content.Artifact archivaArtifact = managedRepositoryContent.getItem( itemSelector ).adapt( org.apache.archiva.repository.content.Artifact.class );
StorageAsset file = archivaArtifact.getAsset( );
if ( file != null && file.exists() )
{
return new AvailabilityStatus( true );
}
// in case of SNAPSHOT we can have timestamped version locally !
if ( StringUtils.endsWith( version, VersionUtil.SNAPSHOT ) )
{
StorageAsset metadataFile = file.getStorage().getAsset(file.getParent().getPath()+"/"+MetadataTools.MAVEN_METADATA );
if ( metadataFile.exists() )
{
MetadataReader metadataReader = repositoryRegistry.getMetadataReader( managedRepositoryContent.getRepository( ).getType( ) );
ArchivaRepositoryMetadata archivaRepositoryMetadata =
metadataReader.read( metadataFile );
int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
// rebuild file name with timestamped version and build number
String timeStampFileName = new StringBuilder( artifactId ).append( '-' ) //
.append( StringUtils.remove( version, "-" + VersionUtil.SNAPSHOT ) ) //
.append( '-' ).append( timeStamp ) //
.append( '-' ).append( Integer.toString( buildNumber ) ) //
.append( ( StringUtils.isEmpty( classifier ) ? "" : "-" + classifier ) ) //
.append( ".jar" ).toString();
StorageAsset timeStampFile = file.getStorage().getAsset(file.getParent().getPath() + "/" + timeStampFileName );
log.debug( "try to find timestamped snapshot version file: {}", timeStampFile.getPath() );
if ( timeStampFile.exists() )
{
return new AvailabilityStatus( true );
}
}
}
String path = managedRepositoryContent.toPath( archivaArtifact );
file = proxyHandler.fetchFromProxies( managedRepositoryContent.getRepository(), path );
if ( file != null && file.exists() )
{
// download pom now
String pomPath = StringUtils.substringBeforeLast( path, ".jar" ) + ".pom";
proxyHandler.fetchFromProxies( managedRepositoryContent.getRepository(), pomPath );
return new AvailabilityStatus( true );
}
}
} catch ( RepositoryException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(),
Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
}
return new AvailabilityStatus( false );
}
/**
* 添加全部问题索引
*/
public void addAllQuestionIndex(){
long count = 0;
int page = 1;//分页 当前页
int maxresult = 200;// 每页显示记录数
questionIndexManage.taskRunMark_delete();
questionIndexManage.taskRunMark_add(count);
boolean allow = QuestionLuceneInit.INSTANCE.allowCreateIndexWriter();//是否允许创建IndexWriter
if(allow){
//删除所有问题索引变化标记
questionIndexService.deleteAllIndex();
try {
QuestionLuceneInit.INSTANCE.createIndexWriter();//创建IndexWriter
questionLuceneManage.deleteAllIndex();//删除所有索引
while(true){
count++;
questionIndexManage.taskRunMark_delete();
questionIndexManage.taskRunMark_add(count);
//当前页
int firstindex = (page-1)*maxresult;
//查询问题
List<Question> questionList = questionService.findQuestionByPage(firstindex, maxresult);
if(questionList == null || questionList.size() == 0){
break;
}
List<QuestionTag> questionTagList = questionTagService.findAllQuestionTag();
if(questionTagList != null && questionTagList.size() >0){
for(Question question : questionList){
//删除最后一个逗号
String _appendContent = StringUtils.substringBeforeLast(question.getAppendContent(), ",");//从右往左截取到相等的字符,保留左边的
List<AppendQuestionItem> appendQuestionItemList = JsonUtils.toGenericObject(_appendContent+"]", new TypeReference< List<AppendQuestionItem> >(){});
question.setAppendQuestionItemList(appendQuestionItemList);
List<QuestionTagAssociation> questionTagAssociationList = questionService.findQuestionTagAssociationByQuestionId(question.getId());
if(questionTagAssociationList != null && questionTagAssociationList.size() >0){
for(QuestionTag questionTag : questionTagList){
for(QuestionTagAssociation questionTagAssociation : questionTagAssociationList){
if(questionTagAssociation.getQuestionTagId().equals(questionTag.getId())){
questionTagAssociation.setQuestionTagName(questionTag.getName());
question.addQuestionTagAssociation(questionTagAssociation);
break;
}
}
}
}
}
}
//写入索引
questionLuceneManage.addIndex(questionList);
page++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
if (logger.isErrorEnabled()) {
logger.error("添加全部问题索引",e);
}
}finally {
QuestionLuceneInit.INSTANCE.closeIndexWriter();//关闭IndexWriter
}
}
questionIndexManage.taskRunMark_delete();
}
private static Object generateArrayType(ServiceDefinition def, String type, MetadataType metadataType,
Set<String> resolvedTypes) {
type = StringUtils.substringBeforeLast(type, "[]");
return new Object[] { generateType(def, type, metadataType, resolvedTypes) };
}
/**
* preHandle()方法在业务处理器处理请求之前被调用
*/
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,
Object handler) throws Exception {
//System.out.println(request.getRequestURI()+" -- "+request.getQueryString()+" -- "+request.getMethod());
//拦截用户角色处理 注解参考: @RoleAnnotation(resourceCode=ResourceEnum._2001000)
if(handler instanceof HandlerMethod){
HandlerMethod handlerMethod= (HandlerMethod) handler;
Method method=handlerMethod.getMethod();
RoleAnnotation roleAnnotation = method.getAnnotation(RoleAnnotation.class);
if(roleAnnotation != null){
boolean flag = userRoleManage.checkPermission(roleAnnotation.resourceCode(),null);
if(!flag){
return false;
}
}
}
//设置自定义标签的URL
if(request != null){
if(Configuration.getPath() == null || "".equals(Configuration.getPath())){
Configuration.setPath(request.getContextPath());
}
//添加sessionId
TemplateThreadLocal.addRuntimeParameter("sessionId", request.getSession().getId());
//Cookies
TemplateThreadLocal.addRuntimeParameter("cookies", request.getCookies());
//URI
TemplateThreadLocal.addRuntimeParameter("requestURI", request.getRequestURI());
//URL参数
TemplateThreadLocal.addRuntimeParameter("queryString", request.getQueryString());
//IP
TemplateThreadLocal.addRuntimeParameter("ip", IpAddress.getClientIpAddress(request));
//获取登录用户(user/开头的URL才有值)
AccessUser accessUser = AccessUserThreadLocal.get();
if(accessUser != null){
TemplateThreadLocal.addRuntimeParameter("accessUser", accessUser);
}else{
//获取登录用户
AccessUser _accessUser = oAuthManage.getUserName(request);
if(_accessUser != null){
UserState userState = userManage.query_userState(_accessUser.getUserName().trim());//用户状态
if(userState != null && userState.getSecurityDigest().equals(_accessUser.getSecurityDigest())){//验证安全摘要
TemplateThreadLocal.addRuntimeParameter("accessUser", _accessUser );
AccessUserThreadLocal.set(_accessUser);
}
}
}
}
//设置令牌
csrfTokenManage.setToken(request,response);
SystemSetting systemSetting = settingService.findSystemSetting_cache();
if(systemSetting.getCloseSite().equals(3)){//3.全站关闭
boolean backstage_flag = false;
//后台URL
for (AntPathRequestMatcher rm : backstage_filterMatchers) {
if (rm.matches(request)) {
backstage_flag = true;
}
}
if(backstage_flag == false){
String baseURI = Configuration.baseURI(request.getRequestURI(), request.getContextPath());
//删除后缀
baseURI = StringUtils.substringBeforeLast(baseURI, ".");
if(!baseURI.equalsIgnoreCase("message")){
response.sendRedirect(Configuration.getUrl(request)+"message");
return false;
}
}
}
return true;
}
/**
* Returns the channel architecture as a universal arch string, practically
* stripping away any arch type suffixes (e.g. "-deb"). The universal string is
* meant to be recognized in the whole linux ecosystem.
*
* @return a package architecture string
*/
public String toUniversalArchString() {
return StringUtils.substringBeforeLast(getLabel(), "-deb");
}