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

The following examples show how to use org.apache.commons.lang3.StringUtils#substringBeforeLast() . 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: FilesystemAsset.java    From archiva with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 2
Source File: PreparationService.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: UpgradeManageAction.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据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 "";
	
}
 
Example 4
Source File: ConsumerProxy.java    From ourea with Apache License 2.0 5 votes vote down vote up
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");
        }

    }
 
Example 5
Source File: NavBreadcrumbBuilderImpl.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: ValidatorService.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
        }
      }
    }
  }
}
 
Example 7
Source File: TimeBasedTokenSerializer.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 8
Source File: UrlProviderImpl.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: HtmlUnitRegExpProxy.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
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_);
    }
}
 
Example 10
Source File: StandardFileWrapper.java    From sdk-rest with MIT License 5 votes vote down vote up
private String getFileName() {
    String fileName = StringUtils.substringBeforeLast(this.name, ".");
    if (fileName == null || fileName.isEmpty()) {
        return name;
    }
    return fileName;
}
 
Example 11
Source File: DownloadController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: SyncopeOpenApiCustomizer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 13
Source File: DiscoverOrganizationByPackageStructureProvider.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: ContextURLParser.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 15
Source File: TempletesInterceptor.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 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;   
}
 
Example 16
Source File: GenericInvokeUtils.java    From saluki with Apache License 2.0 4 votes vote down vote up
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) };
}
 
Example 17
Source File: QuestionIndexManage.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 添加全部问题索引
 */
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();
}
 
Example 18
Source File: DefaultBrowseService.java    From archiva with Apache License 2.0 4 votes vote down vote up
@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 );
}
 
Example 19
Source File: Base.java    From crud-intellij-plugin with Apache License 2.0 4 votes vote down vote up
public String getPackage() {
    return StringUtils.substringBeforeLast(name, ".");
}
 
Example 20
Source File: PackageArch.java    From uyuni with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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");
}