Java Code Examples for org.apache.commons.lang.StringUtils.substring()

The following are Jave code examples for showing how to use substring() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: sql-first-mapper   File: SuffixParser.java   Source Code and License Vote up 6 votes
private Class<?> getType(String s) {
    String typeIdentifier = StringUtils.substring(s, s.length() - 1);
    Class<?> clazz;
    switch (typeIdentifier) {
        case "l":
            clazz = Long.class;
            break;
        case "s":
            clazz = String.class;
            break;
        case "d":
            clazz = Date.class;
            break;
        case "i":
            clazz = Integer.class;
            break;
        default:
            throw new RuntimeException("unknown type identifier: " + typeIdentifier);
    }
    return clazz;
}
 
Example 2
Project: wrdocletbase   File: RESTDocBuilder.java   Source Code and License Vote up 6 votes
@Override
protected int isAPIAuthNeeded(String url) {
	if (url != null && this.excludedUrls != null
			&& this.excludedUrls.size() != 0) {
		if (url.startsWith("{") && url.endsWith("}")) {
			url = StringUtils.substring(url, 1, url.length() - 1);
		}
		String[] urls = url.split(",");
		for (String u : urls) {
			for (String excludedUrl : this.excludedUrls) {
				if (matcher.match(excludedUrl, u)) {
					return 0;
				}
			}
			return 1;
		}
	}
	return -1;
}
 
Example 3
Project: wrdocletbase   File: AbstractDocBuilder.java   Source Code and License Vote up 6 votes
protected String getBriefFromCommentText(String commentText) {
	int index = StringUtils.indexOf(commentText, '\n');
	if (index != -1) {
		commentText = StringUtils.substring(commentText, 0, index);
	}
	index = StringUtils.indexOfAny(commentText, ".!?。!?…");
	if (index > 0) {
		commentText = StringUtils.substring(commentText, 0, index);
	}
	if (StringUtils.length(commentText) > 8) {
		commentText = StringUtils.substring(commentText, 0, 8) + "…";
	}
	return commentText;
}
 
Example 4
Project: Hydrograph   File: PreStartActivity.java   Source Code and License Vote up 6 votes
private void restartHydrograph() {
	logger.info("Starting New Hydrograph");
	String path = Platform.getInstallLocation().getURL().getPath();
	if ((StringUtils.isNotBlank(path)) && (StringUtils.startsWith(path, "/")) && (OSValidator.isWindows())) {
		path = StringUtils.substring(path, 1);
	}
	String command = path + HYDROGRAPH_EXE;
	Runtime runtime = Runtime.getRuntime();
	try {
		if (OSValidator.isWindows()) {
			String[] commandArray = { "cmd.exe", "/c", command };
			runtime.exec(commandArray);
		}
	} catch (IOException ioException) {
		logger.error("Exception occurred while starting hydrograph" + ioException);
	}
	System.exit(0);
}
 
Example 5
Project: ProjectAres   File: SidebarMatchModule.java   Source Code and License Vote up 5 votes
private void setRow(int maxScore, int row, @Nullable String text) {
    if(row < 0 || row >= MAX_ROWS) return;

    int score = text == null ? -1 : maxScore - row - 1;
    if(this.scores[row] != score) {
        this.scores[row] = score;

        if(score == -1) {
            this.scoreboard.resetScores(this.players[row]);
        } else {
            this.objective.getScore(this.players[row]).setScore(score);
        }
    }

    if(!Objects.equals(this.rows[row], text)) {
        this.rows[row] = text;

        if(text != null) {
            /*
             Split the row text into prefix and suffix, limited to 16 chars each. Because the player name
             is a color code, we have to restore the color at the split in the suffix. We also have to be
             careful not to split in the middle of a color code.
            */
            int split = MAX_PREFIX - 1; // Start by assuming there is a color code right on the split
            if(text.length() < MAX_PREFIX || text.charAt(split) != ChatColor.COLOR_CHAR) {
                // If there isn't, we can fit one more char in the prefix
                split++;
            }

            // Split and truncate the text, and restore the color in the suffix
            String prefix = StringUtils.substring(text, 0, split);
            String lastColors = org.bukkit.ChatColor.getLastColors(prefix);
            String suffix =  lastColors + StringUtils.substring(text, split, split + MAX_SUFFIX - lastColors.length());
            this.teams[row].setPrefix(prefix);
            this.teams[row].setSuffix(suffix);
        }
    }
}
 
Example 6
Project: athena   File: DefaultInfluxDbMetricsRetriever.java   Source Code and License Vote up 5 votes
/**
 * Returns node id from full name.
 * The elements in full name is split by using '.';
 * We assume that the node id always comes before the last three '.'
 *
 * @param fullName full name
 * @return node id
 */
private String getNodeId(String fullName) {
    int index = StringUtils.lastOrdinalIndexOf(fullName,
            METRIC_DELIMITER, NUB_OF_DELIMITER);
    if (index != -1) {
        return StringUtils.substring(fullName, 0, index);
    } else {
        log.warn("Database {} contains malformed node id.", database);
        return null;
    }
}
 
Example 7
Project: atlas   File: CodeInjectByJavassist.java   Source Code and License Vote up 5 votes
/**
 * The injection of code for the specified jar package
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool,
                                  File inJar,
                                  File outJar,
                                  InjectParam injectParam) throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}
 
Example 8
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   Source Code and License Vote up 5 votes
/**
 * Method to process the KalturaMetadata object (and the XML it contains) into a list of field strings
 * @param metadata kaltura metadata object
 * @return List of field strings
 */
private List<String> convertKalturaMetadataToFieldsList(KalturaMetadata metadata) {
    List<String> fields = new ArrayList<String>();
    // if metadata exists for object
    if (metadata != null && StringUtils.isNotEmpty(metadata.xml)) {
        // check for malformed beginning of XML
        String metadataXml = metadata.xml;
        if (StringUtils.startsWithIgnoreCase(metadataXml, "xml=")){ 
            metadataXml = metadataXml.replaceAll("xml=", ""); 
        }

        // ensure XML begins with the <?xml tag
        int lastIndex = StringUtils.lastIndexOf(metadataXml, "<?xml");
        if(lastIndex > 0){
            metadataXml = StringUtils.substring(metadataXml, lastIndex);
        }

        // set the metadata's XML to the updated string
        metadata.xml = metadataXml;

        try {
            Document metadataDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(metadata.xml)));
            org.w3c.dom.Element root = metadataDoc.getDocumentElement();
            NodeList childNodes = root.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node instanceof org.w3c.dom.Element) {
                    fields.add(node.getTextContent());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error processing metadata fields for kaltura metadata object (" + metadata.objectId + ") :: " + e + ", xml="+metadata.xml, e);
        }
    }
    return fields;
}
 
Example 9
Project: QLExpress   File: CustBean.java   Source Code and License Vote up 5 votes
public static String firstToUpper(String value){
	if(StringUtils.isBlank(value))
		return "";
	value = StringUtils.trim(value);
	String f = StringUtils.substring(value,0,1);
	String s = "";
	if(value.length() > 1){
		s = StringUtils.substring(value,1);
	}
	return f.toUpperCase() + s;
}
 
Example 10
Project: dag-runner   File: DagRunner.java   Source Code and License Vote up 5 votes
public static String getDefaultJobName(Object obj) {
    String className;
    if (obj instanceof JobCommand) {
        return ((JobCommand) obj).getJobName();
    } else if (obj instanceof Class) {
        className = ((Class) obj).getSimpleName();
    } else if (obj instanceof String) {
        className = (String) obj;
    } else {
        className = obj.getClass().getSimpleName();
    }
    return StringUtils.lowerCase(StringUtils.substring(className, 0, 1))
            + StringUtils.substring(className, 1);
}
 
Example 11
Project: Hydrograph   File: ClassDetails.java   Source Code and License Vote up 5 votes
private String getJavaDoc(IClassFile classFile) throws JavaModelException {
	BinaryType binaryType=(BinaryType)classFile.getType();
	if(binaryType.getSource() !=null && binaryType.getJavadocRange()!=null){
	String javaDoc=Constants.EMPTY_STRING;
		javaDoc = StringUtils.substring(binaryType.getSource().toString(), 0, binaryType.getJavadocRange().getLength());
	javaDoc = StringUtils.replaceEachRepeatedly(javaDoc, new String[] { "/*", "*/", "*" }, new String[] {
			Constants.EMPTY_STRING, Constants.EMPTY_STRING, Constants.EMPTY_STRING });
	}
	return javaDoc;
}
 
Example 12
Project: Hydrograph   File: ClassDetails.java   Source Code and License Vote up 5 votes
private String getJavaDoc(SourceType javaClassFile) throws JavaModelException {
	StringBuffer source = new StringBuffer(javaClassFile.getSource());
	try {
		String javaDoc = StringUtils.substring(source.toString(), 0, javaClassFile.getJavadocRange().getLength());
		javaDoc = StringUtils.replaceEachRepeatedly(javaDoc, new String[] { "/*", "*/", "*" },
				new String[] { Constants.EMPTY_STRING, Constants.EMPTY_STRING, Constants.EMPTY_STRING });
	} catch (Exception exception) {
		LOGGER.warn("Failed to build java-doc for :{}", javaClassFile);
	}
	return javaDoc;
}
 
Example 13
Project: Hydrograph   File: MethodDetails.java   Source Code and License Vote up 5 votes
private String createFormattedJavaDoc(IMethod iMethod) throws JavaModelException {
	String source = iMethod.getSource();
	if (iMethod.getJavadocRange() != null) {
		javaDoc = StringUtils.substring(source, 0, iMethod.getJavadocRange().getLength());
		javaDoc = StringUtils.replaceEachRepeatedly(javaDoc, new String[] { "/*", "*/", "*" }, new String[] {
				Constants.EMPTY_STRING, Constants.EMPTY_STRING, Constants.EMPTY_STRING });
	}
	return javaDoc;
}
 
Example 14
Project: Hydrograph   File: ApplicationWorkbenchWindowAdvisor.java   Source Code and License Vote up 5 votes
private static String getInstallationConfigPath()  {
	String path = Platform.getInstallLocation().getURL().getPath();
	if(StringUtils.isNotBlank(path) && StringUtils.startsWith(path, "/") && OSValidator.isWindows()){
		path = StringUtils.substring(path, 1);
	}
	
	return path + "config/service/config" ;
}
 
Example 15
Project: YiDu-Novel   File: GenerateHtmlFileInterceptor.java   Source Code and License Vote up 4 votes
public static String getVarNameFromMethodName(String methodName) {
    String varName = StringUtils.substringAfter(methodName, "get");
    String firstChar = StringUtils.substring(varName, 0, 1);
    varName = varName.replaceFirst(firstChar, firstChar.toLowerCase());
    return varName;
}
 
Example 16
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   Source Code and License Vote up 4 votes
/**
 * Decodes the permissions string into a map of values.
 * Keys: containerType, containerId, Owner, Hidden, Reusable, Remixable
 * 
 * @param permissionString the string representation of the permissions
 *      ("site:<siteId>::{<ownerId>}h,S,r" OR "playlist:<playlistId>::{<ownerId>}h,S,r")
 * @param failIfInvalid if true then this will throw an exception if the input string is invalid, otherwise it will return defaults
 * @return Map of permission data OR defaults if input string is invalid
 * @throws IllegalArgumentException if the string decoding fails
 */
protected Map<String, String> decodeMetadataPermissions(String permissionString, boolean failIfInvalid) {
    Map<String, String> decodedPermissions = new HashMap<String, String>(6);
    // check if permissions string is a valid format
    if (StringUtils.isNotEmpty(permissionString) 
            && StringUtils.contains(permissionString, "::{") 
            && (StringUtils.startsWith(permissionString, "site:") || StringUtils.startsWith(permissionString, "playlist:"))) {
        // first find the last "}" in the string (first from the right)
        int braceRight = StringUtils.lastIndexOf(permissionString, '}');
        if (braceRight == -1) {
            throw new IllegalArgumentException("Invalid format- no '}' (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // find the last "::{" from the right of the brace
        int braceLeft = StringUtils.lastIndexOf(permissionString, "::{", braceRight);
        if (braceLeft == -1) {
            throw new IllegalArgumentException("Invalid format - no '::{' (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // chop the string into the 3 parts dropping the braces and :: separators
        String containerStr = StringUtils.substring(permissionString, 0, braceLeft);
        braceLeft += 2; // shift over to the actual brace
        String ownerId = StringUtils.substring(permissionString, braceLeft+1, braceRight);
        if (StringUtils.isEmpty(ownerId)) {
            throw new IllegalArgumentException("Invalid format - no ownerId (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        decodedPermissions.put(METADATA_OWNER, ownerId);
        // get the containerId from the first piece
        if (StringUtils.startsWith(containerStr, "site:")) {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "site");
            decodedPermissions.put(METADATA_CONTAINER_ID, StringUtils.substring(containerStr, 5));
        } else if (StringUtils.startsWith(containerStr, "playlist:")) {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "playlist");
            decodedPermissions.put(METADATA_CONTAINER_ID, StringUtils.substring(containerStr, 9));
        } else {
            // should never really happen
            throw new IllegalArgumentException("Invalid format - bad prefix (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        if (StringUtils.isEmpty(decodedPermissions.get(METADATA_CONTAINER_ID))) {
            throw new IllegalArgumentException("Invalid format - no containerId (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // split the permissions
        String perms = StringUtils.substring(permissionString, braceRight+1);
        if (StringUtils.isEmpty(perms)) {
            throw new IllegalArgumentException("Invalid format - no perms (e.g. 'site:<site_library_id>::{<ownerId>}h,S,r') for permissions string: "+permissionString);
        }
        // get the permissions ([0] = hidden, [1] = reusable, [2] = remixable)
        String[] permissions = StringUtils.split(perms, ',');
        decodedPermissions.put(METADATA_HIDDEN, permissions[0]);
        decodedPermissions.put(METADATA_REUSABLE, permissions[1]);
        decodedPermissions.put(METADATA_REMIXABLE, permissions[2]);

    } else { // load default metadata
        if (failIfInvalid) {
            throw new IllegalArgumentException("Invalid string format - fails to match basic rules (e.g. not empty, contains '::{' and starts with 'site' or 'playlist') for permissions string: "+permissionString);
        } else {
            decodedPermissions.put(METADATA_CONTAINER_TYPE, "");
            decodedPermissions.put(METADATA_CONTAINER_ID, "");
            decodedPermissions.put(METADATA_OWNER, null);
            decodedPermissions.put(METADATA_HIDDEN, DEFAULT_METADATA_HIDDEN);
            decodedPermissions.put(METADATA_REUSABLE, DEFAULT_METADATA_REUSABLE);
            decodedPermissions.put(METADATA_REMIXABLE, DEFAULT_METADATA_REMIXABLE);
        }
    }
    return decodedPermissions;
}
 
Example 17
Project: sql-first-mapper   File: DaoWriter.java   Source Code and License Vote up 4 votes
private void createDaoClass(DaoDesc daoDesc, SqlFirstApcConfig sqlFirstApcConfig) {
    String queryExecutorClassName = sqlFirstApcConfig.queryExecutorClassName();
    
    String baseDaoClassName = StringUtils.isBlank(daoDesc.getBaseDaoClassName()) ? sqlFirstApcConfig.baseDaoClassName() : daoDesc.getBaseDaoClassName();
    
    List<QueryDesc> queryDescList = daoDesc.getQueryDescList();
    QueryDesc firstElement = queryDescList.iterator().next();
    
    VelocityContext context = new VelocityContext();
    String className = firstElement.getClassName();
    String packageName = firstElement.getPackageName();
    String daoClassName = className + "Dao";
    
    
    try {
        context.put("hasDtoClasses", queryDescList.stream().anyMatch(queryDesc -> queryDesc.hasRequest() || queryDesc.hasRequest()));
        context.put("queryDescList", queryDescList);
        String implementClassName = daoDesc.getImplementClassName();//implementMap.get(packageName + "." + className);
        
        Set<String> implementsSet = new HashSet<>();
        implementsSet.add(SqlSourceDao.class.getName());
        if (StringUtils.isNotBlank(implementClassName)) {
            implementsSet.add(implementClassName);
        }
        
        context.put("baseClassFullName", baseDaoClassName);
        context.put("baseClassSimpleName", MiscUtils.getLastWordAfterDot(baseDaoClassName));
        
        context.put("queryExecutorClassFullName", queryExecutorClassName);
        context.put("queryExecutorClassName", MiscUtils.getLastWordAfterDot(queryExecutorClassName));

        String templateFileName;
        DaoType daoType = daoDesc.getDaoType();
        if (daoType == null || daoType == DaoType.USE_DEFAULT) {
            daoType = sqlFirstApcConfig.daoType();
        }
        switch (daoType) {
            case PLAIN_SQL:
                templateFileName = "dao-class-plain-template.vm";
                break;
            case SPRING_REPOSITORY:
                templateFileName = "dao-class-spring-template.vm";
                String targetClassName = daoDesc.getTargetClassName();
                if (StringUtils.isNotBlank(targetClassName)) {
                    daoClassName = MiscUtils.getLastWordAfterDot(targetClassName);
                    packageName = StringUtils.substring(targetClassName, 0, -daoClassName.length() - 1);
                } else if (daoClassName.endsWith("CustomDao")) {
                    daoClassName = StringUtils.substring(daoClassName, 0, -9) + "Impl";
                }
                implementsSet.add(daoDesc.getSourceClassName());
                break;
            default:
                throw new RuntimeException("Not supported DaoType " + daoType);
        }
        
        processImplementsList(context, implementsSet);
        context.put("daoClassName", daoClassName);
        context.put("classPackage", packageName);
        JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(packageName + "." + daoClassName);
        
        try (PrintWriter writer = new PrintWriter(builderFile.openWriter())) {
            Template template = Velocity.getTemplate(templateFileName, MiscUtils.UTF_8);
            template.merge(context, writer);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 18
Project: lams   File: ImportService.java   Source Code and License Vote up 4 votes
private Organisation parseGroup(HSSFRow row, int rowIndex) {
Organisation org = new Organisation();
String[] args = new String[1];

String name = StringUtils.substring(parseStringCell(row.getCell(ImportService.NAME)), 0, 240);

//validate organisation name
if (StringUtils.isBlank(name)) {
    rowResult.add(messageService.getMessage("error.name.required"));
    hasError = true;
    return null;

} else if (!ValidationUtil.isOrgNameValid(name)) {
    rowResult.add(messageService.getMessage("error.name.invalid.characters"));
    hasError = true;
    return null;
}

org.setName(name);
org.setCode(parseStringCell(row.getCell(ImportService.CODE)));
org.setDescription(parseStringCell(row.getCell(ImportService.DESCRIPTION)));

String localeId = parseStringCell(row.getCell(ImportService.LOCALE_ID));
SupportedLocale locale = getLocale(localeId);
if (locale == null) {
    args[0] = "(" + localeId + ")";
    rowResult.add(messageService.getMessage("error.locale.invalid", args));
    hasError = true;
} else {
    org.setLocale(locale);
}

String orgStateText = parseStringCell(row.getCell(ImportService.ORGANISATION_STATE));
OrganisationState orgState = getOrganisationState(orgStateText);
org.setOrganisationState(orgState);

org.setOrganisationType((OrganisationType) service.findById(OrganisationType.class,
	parentOrg.getOrganisationType().getOrganisationTypeId().equals(OrganisationType.ROOT_TYPE)
		? OrganisationType.COURSE_TYPE : OrganisationType.CLASS_TYPE));

org.setParentOrganisation(parentOrg);
org.setCourseAdminCanAddNewUsers(parseBooleanCell(row.getCell(ImportService.ADMIN_ADD_NEW_USERS)));
org.setCourseAdminCanBrowseAllUsers(parseBooleanCell(row.getCell(ImportService.ADMIN_BROWSE_ALL_USERS)));
org.setCourseAdminCanChangeStatusOfCourse(parseBooleanCell(row.getCell(ImportService.ADMIN_CHANGE_STATUS)));

return (hasError ? null : org);
   }
 
Example 19
Project: morf   File: OracleDialect.java   Source Code and License Vote up 4 votes
/**
 * Truncate table names to 27 characters, then add a 3 character suffix since 30 is the maximum supported by Oracle.
 */
private String truncatedTableNameWithSuffix(String tableName, String suffix) {
  return StringUtils.substring(tableName, 0, 27) + StringUtils.substring(suffix, 0, 3);
}
 
Example 20
Project: Yidu   File: GenerateHtmlFileInterceptor.java   Source Code and License Vote up 4 votes
public static String getVarNameFromMethodName(String methodName) {
    String varName = StringUtils.substringAfter(methodName, "get");
    String firstChar = StringUtils.substring(varName, 0, 1);
    varName = varName.replaceFirst(firstChar, firstChar.toLowerCase());
    return varName;
}