下面列出了org.apache.commons.lang3.StringUtils#substringAfterLast ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Retrieve the extension that should be used for the output file. This is base don the template name.
* @param templateFilename The filename of the export template.
* @param isPdf Is this an export to a PDF file?
* @return The output filename extension.
*/
public static String getOutputExtension(String templateFilename, boolean isPdf)
{
if (isPdf)
{
return "pdf";
}
if (templateFilename.endsWith(".ftl"))
{
templateFilename = templateFilename.substring(0, templateFilename.length() - 4);
}
String extension = StringUtils.substringAfterLast(templateFilename, ".");
if (StringUtils.isEmpty(extension))
{
extension = StringUtils.substringAfterLast(templateFilename, "-");
}
return extension;
}
/**
* Generate new field,
* if the user did not set an output field path, use the input field name and the operation name
* if the user set an output field path, use the name of the last element in the path.
*
* @param originalField the field to copy
* @param operationProps the operation to execute
* @return
*/
public static Schema.Field genField(Schema.Field originalField, AggregateOperationProperties operationProps) {
Schema newFieldSchema =
AvroUtils.wrapAsNullable(genFieldType(originalField.schema(), operationProps.operation.getValue()));
String outputFieldPath = operationProps.outputFieldPath.getValue();
String newFieldName;
if (StringUtils.isEmpty(outputFieldPath)) {
newFieldName =
genOutputFieldNameByOpt(operationProps.fieldPath.getValue(), operationProps.operation.getValue());
} else {
newFieldName = outputFieldPath.contains(".") ? StringUtils.substringAfterLast(outputFieldPath, ".")
: outputFieldPath;
}
return new Schema.Field(newFieldName, newFieldSchema, originalField.doc(), originalField.defaultVal());
}
private String extractSnapshotLabel( String backupFilePath, String oldContainerName )
{
String label = null;
try
{
String s = StringUtils.substringBetween( backupFilePath, oldContainerName, ".tar.gz" );
label = StringUtils.substringAfterLast( s, "_" );
}
catch ( Exception e )
{
log.error( "Couldn't extract snapshot label from file '{}' and container '{}': {}", backupFilePath,
oldContainerName, e.getMessage() );
}
return label;
}
/**
* 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);
}
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
RestTemplate restTemplate = new RestTemplate();
// 自己拼接url
String clientId = parameters.getFirst("client_id");
String clientSecret = parameters.getFirst("client_secret");
String code = parameters.getFirst("code");
String url = String.format("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", clientId, clientSecret, code);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.build().encode().toUri();
String responseStr = restTemplate.getForObject(uri, String.class);
logger.info("获取accessToke的响应:" + responseStr);
String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
String accessToken = StringUtils.substringAfterLast(items[0], "=");
logger.info("获取Toke的响应:" + accessToken);
return new AccessGrant(accessToken, null, null, null);
}
private Map<String, Map<String, String>> extractCriterionDataFromParams(Map<String, String> params) {
Map<String, Map<String, String>> criterionDataMap = new HashMap<>();
for (Map.Entry<String, String> param : params.entrySet()) {
String possibleCriterionId = StringUtils.substringAfterLast(param.getKey(), "-");
String criterionDataLabel = StringUtils.substringBeforeLast(param.getKey(), "-");
if (StringUtils.isNumeric(possibleCriterionId)) {
if (!criterionDataMap.containsKey(possibleCriterionId)) {
criterionDataMap.put(possibleCriterionId, new HashMap<>());
}
criterionDataMap.get(possibleCriterionId).put(criterionDataLabel, param.getValue());
}
}
return criterionDataMap;
}
@Override
public Component render(String componentId) {
String fileName = getBlobPath();
if (fileName.contains("/"))
fileName = StringUtils.substringAfterLast(fileName, "/");
return new HighlightableLabel(componentId, fileName, match);
}
/**
* Send a file for download.
*
* @param filePath
*
*/
protected void sendDownload(String filePath, String mimeType) {
FacesContext fc = FacesContext.getCurrentInstance();
ServletOutputStream out = null;
FileInputStream in = null;
String filename = StringUtils.substringAfterLast(filePath, File.separator);
try {
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset();
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0");
response.setContentType(mimeType);
response.setHeader("Content-disposition", "attachment; filename=" + filename);
in = FileUtils.openInputStream(new File(filePath));
out = response.getOutputStream();
IOUtils.copy(in, out);
out.flush();
} catch (IOException ex) {
log.warn("Error generating file for download:" + ex.getMessage());
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
fc.responseComplete();
}
private OkrAttachmentFileInfo concreteAttachment(StorageMapping mapping, OkrWorkReportBaseInfo report, String name, EffectivePerson effectivePerson, String site) throws Exception {
OkrAttachmentFileInfo attachment = new OkrAttachmentFileInfo();
String fileName = UUID.randomUUID().toString();
String extension = FilenameUtils.getExtension( name );
if ( StringUtils.isNotEmpty(extension)) {
fileName = fileName + "." + extension;
}else{
throw new Exception("file extension is empty.");
}
if( name.indexOf( "\\" ) >0 ){
name = StringUtils.substringAfterLast( name, "\\");
}
if( name.indexOf( "/" ) >0 ){
name = StringUtils.substringAfterLast( name, "/");
}
attachment.setCreateTime( new Date() );
attachment.setLastUpdateTime( new Date() );
attachment.setExtension( extension );
attachment.setName( name );
attachment.setFileName( fileName );
attachment.setStorage( mapping.getName() );
attachment.setWorkInfoId( report.getWorkId() );
attachment.setCenterId( report.getCenterId() );
attachment.setStatus( "正常" );
attachment.setParentType( "中心工作" );
attachment.setCreatorUid( effectivePerson.getDistinguishedName() );
attachment.setSite( site );
attachment.setFileHost( "" );
attachment.setFilePath( "" );
attachment.setKey( report.getId() );
return attachment;
}
/**
* @return The last path component.
*/
@Override
public String getName() {
final char delimiter = this.getDelimiter();
if(String.valueOf(delimiter).equals(path)) {
return path;
}
if(!StringUtils.contains(path, delimiter)) {
return path;
}
return StringUtils.substringAfterLast(path, String.valueOf(delimiter));
}
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
// access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
String result = this.getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
log.info("responseToken: {}", result);
String[] params = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");
String accessToken = StringUtils.substringAfterLast(params[0], "=");
Long expiresIn = Long.valueOf(StringUtils.substringAfterLast(params[1], "="));
String refreshToken = StringUtils.substringAfterLast(params[2], "=");
return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
private OkrAttachmentFileInfo concreteAttachment(StorageMapping mapping, OkrWorkBaseInfo work, String name, EffectivePerson effectivePerson, String site) throws Exception {
OkrAttachmentFileInfo attachment = new OkrAttachmentFileInfo();
String fileName = UUID.randomUUID().toString();
String extension = FilenameUtils.getExtension( name );
if ( StringUtils.isNotEmpty(extension)) {
fileName = fileName + "." + extension;
}else{
throw new Exception("file extension is empty.");
}
if( name.indexOf( "\\" ) >0 ){
name = StringUtils.substringAfterLast( name, "\\");
}
if( name.indexOf( "/" ) >0 ){
name = StringUtils.substringAfterLast( name, "/");
}
attachment.setCreateTime( new Date() );
attachment.setLastUpdateTime( new Date() );
attachment.setExtension( extension );
attachment.setName( name );
attachment.setFileName( fileName );
attachment.setStorage( mapping.getName() );
attachment.setWorkInfoId( work.getId() );
attachment.setCenterId( work.getCenterId() );
attachment.setStatus( "正常" );
attachment.setParentType( "工作" );
attachment.setCreatorUid( effectivePerson.getDistinguishedName() );
attachment.setSite( site );
attachment.setFileHost( "" );
attachment.setFilePath( "" );
attachment.setKey( work.getId() );
return attachment;
}
/**
* @author lastwhisper
* @desc 生成路径以及文件名 例如://images/2019/04/28/15564277465972939.jpg
* @email [email protected]
*/
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
private String getArgumentName(ConstraintViolation<?> violation) {
String argumentIdentifier;
Object paramName = violation.getConstraintDescriptor().getAttributes().get(PARAMETER_NAME_ATTRIBUTE);
if (paramName instanceof String && paramName.toString().length() > 0) {
argumentIdentifier = (String) paramName;
} else {
argumentIdentifier = StringUtils.substringAfterLast(violation.getPropertyPath().toString(), ".");
}
return argumentIdentifier;
}
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;
}
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
log.info("【QQOAuth2Template】获取accessToke的响应:responseStr={}" , responseStr);
String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
//http://wiki.connect.qq.com/使用authorization_code获取access_token
//access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
String accessToken = StringUtils.substringAfterLast(items[0], "=");
Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
String refreshToken = StringUtils.substringAfterLast(items[2], "=");
return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
@Override
public String getQueueIdentifier(final String swapLocation) {
final String filename = swapLocation.contains("/") ? StringUtils.substringAfterLast(swapLocation, "/") : swapLocation;
final String[] splits = filename.split("-");
if (splits.length > 6) {
final String queueIdentifier = splits[1] + "-" + splits[2] + "-" + splits[3] + "-" + splits[4] + "-" + splits[5];
return queueIdentifier;
}
return null;
}
public static boolean supportImage(String name) {
String ext = StringUtils.substringAfterLast(name, ".");
if (StringUtils.isNotEmpty(ext)) {
ext = "." + StringUtils.lowerCase(ext);
return SUPPORT_IMAGE_TYPES.contains(ext);
}
return false;
}
/**
* Returns the name of this frame's source.
*
* @return the name of this frame's source
*/
private static String getSourceName(final Context cx) {
String source = (String) cx.getThreadLocal(KEY_LAST_SOURCE);
if (source == null) {
return "unknown";
}
// only the file name is interesting the rest of the url is mostly noise
source = StringUtils.substringAfterLast(source, "/");
// embedded scripts have something like "foo.html from (3, 10) to (10, 13)"
source = StringUtils.substringBefore(source, " ");
return source;
}
private void addClassFileMetadata(GraphRewrite event, EvaluationContext context, JavaClassFileModel javaClassFileModel)
{
try (FileInputStream fis = new FileInputStream(javaClassFileModel.getFilePath()))
{
final ClassParser parser = new ClassParser(fis, javaClassFileModel.getFilePath());
final JavaClass bcelJavaClass = parser.parse();
final String packageName = bcelJavaClass.getPackageName();
final String qualifiedName = bcelJavaClass.getClassName();
final JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
final JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
int majorVersion = bcelJavaClass.getMajor();
int minorVersion = bcelJavaClass.getMinor();
String simpleName = qualifiedName;
if (packageName != null && !packageName.isEmpty() && simpleName != null)
{
simpleName = StringUtils.substringAfterLast(simpleName, ".");
}
javaClassFileModel.setMajorVersion(majorVersion);
javaClassFileModel.setMinorVersion(minorVersion);
javaClassFileModel.setPackageName(packageName);
javaClassModel.setSimpleName(simpleName);
javaClassModel.setPackageName(packageName);
javaClassModel.setQualifiedName(qualifiedName);
javaClassModel.setClassFile(javaClassFileModel);
javaClassModel.setPublic(bcelJavaClass.isPublic());
javaClassModel.setInterface(bcelJavaClass.isInterface());
final String[] interfaceNames = bcelJavaClass.getInterfaceNames();
if (interfaceNames != null)
{
for (final String interfaceName : interfaceNames)
{
JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(interfaceName);
javaClassService.addInterface(javaClassModel, interfaceModel);
}
}
String superclassName = bcelJavaClass.getSuperclassName();
if (!bcelJavaClass.isInterface() && !StringUtils.isBlank(superclassName))
javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));
javaClassFileModel.setJavaClass(javaClassModel);
}
catch (Exception ex)
{
String nl = ex.getMessage() != null ? Util.NL + "\t" : " ";
final String message = "BCEL was unable to parse class file '" + javaClassFileModel.getFilePath() + "':" + nl + ex.toString();
LOG.log(Level.WARNING, message);
ClassificationService classificationService = new ClassificationService(event.getGraphContext());
classificationService.attachClassification(event, context, javaClassFileModel, UNPARSEABLE_CLASS_CLASSIFICATION, UNPARSEABLE_CLASS_DESCRIPTION);
javaClassFileModel.setParseError(message);
javaClassFileModel.setSkipDecompilation(true);
}
}