Java Examples for org.apache.commons.lang3.StringUtils

The following java examples will help you to understand the usage of org.apache.commons.lang3.StringUtils. These source code samples are taken from different open source projects.

Example 1
Project: lemon-master  File: StringUtils.java View source code
public static String trim(String text) {
    if (text == null) {
        return text;
    }
    // Unicode Character 'NO-BREAK SPACE' (U+00A0)
    text = text.replace("" + ((char) 160), " ");
    // Unicode Character 'ZERO WIDTH SPACE' (U+200B).
    text = text.replace("" + ((char) 8203), " ");
    text = org.apache.commons.lang3.StringUtils.trim(text);
    text = org.apache.commons.lang3.StringUtils.strip(text, " ");
    return text;
}
Example 2
Project: swagger-core-master  File: AllowableValuesUtils.java View source code
public static AllowableValues create(String values) {
    AllowableValues allowableValues = null;
    if (StringUtils.isNotEmpty(values)) {
        allowableValues = AllowableRangeValues.create(values);
        if (allowableValues == null) {
            allowableValues = AllowableEnumValues.create(values);
        }
    }
    return allowableValues;
}
Example 3
Project: java-sproc-wrapper-master  File: NameUtils.java View source code
public static String camelCaseToUnderscore(final String camelCase) {
    Preconditions.checkNotNull(camelCase, "camelCase");
    final String[] camelCaseParts = org.apache.commons.lang.StringUtils.splitByCharacterTypeCamelCase(camelCase);
    for (int i = 0; i < camelCaseParts.length; i++) {
        camelCaseParts[i] = camelCaseParts[i].toLowerCase(Locale.ENGLISH);
    }
    return org.apache.commons.lang.StringUtils.join(camelCaseParts, "_");
}
Example 4
Project: jrails-master  File: JavaScriptUtils.java View source code
public static String encodeURIComponent(String s, String ENCODING) {
    try {
        s = URLEncoder.encode(s, ENCODING);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Adjust for JavaScript specific annoyances
    s = org.apache.commons.lang.StringUtils.replace(s, "+", "%20");
    s = org.apache.commons.lang.StringUtils.replace(s, "%2B", "+");
    return s;
}
Example 5
Project: minuteProject-master  File: StringUtils.java View source code
public static boolean startsWithIgnoreCase(String valueToTest, String startsWith) {
    if (valueToTest == null)
        return false;
    if (startsWith == null)
        return false;
    valueToTest = org.apache.commons.lang.StringUtils.upperCase(valueToTest);
    startsWith = org.apache.commons.lang.StringUtils.upperCase(startsWith);
    return valueToTest.startsWith(startsWith);
}
Example 6
Project: ali-idea-plugin-master  File: PathUtils.java View source code
/**
     * Join path segments with separator.
     * <p>
     *
     * If path segment already contains separator on either side of the connecting point it is not duplicated.
     * <p>
     *
     * Examples:
     * pathJoin("/", "a", "b")  ... "a/b"
     * pathJoin("/", "a/", "/b")  ... "a/b"
     * pathJoin("/", "a/", "b/")  ... "a/b/"
     * pathJoin("/")  ... ""
     * pathJoin("/", "a")  ... "a"
     * pathJoin("/", "/a/")  ... "/a/"
     *
     * @param separator segment separator
     * @param parts path segments
     * @return resulting path
     */
public static String pathJoin(String separator, String... parts) {
    StringBuilder builder = new StringBuilder();
    if (parts.length == 0)
        return "";
    if (parts.length == 1)
        return parts[0];
    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        if (i == 0) {
            builder.append(org.apache.commons.lang.StringUtils.removeEnd(part, separator)).append(separator);
        } else if (i == parts.length - 1) {
            builder.append(org.apache.commons.lang.StringUtils.removeStart(part, separator));
        } else {
            builder.append(org.apache.commons.lang.StringUtils.removeStart(org.apache.commons.lang.StringUtils.removeEnd(part, separator), separator)).append(separator);
        }
    }
    return builder.toString();
}
Example 7
Project: aorra-master  File: VerticalAlignCssStyle.java View source code
@Override
public void style(Box box) {
    String align = getProperty().getValue();
    // currently only works with table cells
    if ((box instanceof TableCellBox) && !StringUtils.isBlank(align)) {
        TableCellBox tbox = (TableCellBox) box;
        VAlign a = VAlign.valueOf(align.toUpperCase());
        if (a != null) {
            tbox.setValign(a);
        } else {
            logger.warn("unknown vertical align " + align);
        }
    }
}
Example 8
Project: ChessCraft-master  File: HighlightStyle.java View source code
public static HighlightStyle getStyle(String style) {
    if (style == null) {
        return null;
    }
    style = style.trim().toUpperCase();
    for (HighlightStyle h : values()) {
        if (h.name().equals(style) || StringUtils.getLevenshteinDistance(h.name(), style) < 2) {
            return h;
        }
    }
    throw new ChessException("unknown highlight style: " + style);
}
Example 9
Project: dungeon-master  File: StringDistanceMetrics.java View source code
static int levenshteinDistance(final String a, final String b) {
    if (!CommandLimits.isWithinMaximumCommandLength(a)) {
        throw new IllegalArgumentException("input is too big.");
    }
    if (!CommandLimits.isWithinMaximumCommandLength(b)) {
        throw new IllegalArgumentException("input is too big.");
    }
    return StringUtils.getLevenshteinDistance(a, b);
}
Example 10
Project: fpcms-master  File: LayoutController.java View source code
@RequestMapping
public String layout(ModelMap model) throws Exception {
    model.put("nav", cmsChannelService.findChildsByChannelCode(getSite(), "nav"));
    CmsSite cmsSite = cmsSiteService.getById(getSite());
    String htmlLayout = cmsSite.getHtmlLayout();
    if (StringUtils.isBlank(htmlLayout)) {
        return "/layout";
    } else {
        return "/layout/" + htmlLayout;
    }
}
Example 11
Project: hq-master  File: AddressExtractorFactory.java View source code
/**
     * Returns default FQDN extractor for JDBC URL's
     *
     * @return {@code AddressExtractor}
     */
public static AddressExtractor getDatabaseServerFqdnExtractor() {
    return new AddressExtractor() {

        public String extractAddress(String containsAddress) {
            if (StringUtils.isBlank(containsAddress)) {
                return "localhost";
            }
            int beginIndex = containsAddress.indexOf("//") + "//".length();
            containsAddress = containsAddress.substring(beginIndex);
            return containsAddress.split(";")[0];
        }
    };
}
Example 12
Project: idea-php-symfony2-plugin-master  File: StringUtils.java View source code
public static String camelize(String input, boolean startWithLowerCase) {
    String[] strings = org.apache.commons.lang.StringUtils.split(input.toLowerCase(), "_");
    for (int i = startWithLowerCase ? 1 : 0; i < strings.length; i++) {
        strings[i] = org.apache.commons.lang.StringUtils.capitalize(strings[i]);
    }
    input = org.apache.commons.lang.StringUtils.join(strings);
    if (!startWithLowerCase) {
        return ucfirst(input);
    }
    return input;
}
Example 13
Project: JNetMan-master  File: InetAddressUtils.java View source code
public static short toPrefixLenght(String netmask) {
    short prefixLenght = 0;
    short thisNum;
    String thisBinaryNum;
    for (String num : StringUtils.split(netmask, '.')) {
        thisNum = Short.parseShort(num);
        thisBinaryNum = Integer.toBinaryString(thisNum);
        prefixLenght += StringUtils.countMatches(thisBinaryNum, "1");
    }
    return prefixLenght;
}
Example 14
Project: Mongrel-master  File: MongoDBTests.java View source code
@Override
protected String getDirectory() {
    ClassLoader loader = this.getClass().getClassLoader();
    String className = this.getClass().getCanonicalName().replaceAll("\\.", "\\/");
    String fullPath = loader.getResource(className + ".class").getFile();
    String directory = StringUtils.substringBeforeLast(fullPath, "/");
    return directory;
}
Example 15
Project: SCM-master  File: Command.java View source code
/**
     * Adds the server reference to the Arguments list.
     *
     * @param cmd    The accurev command line.
     * @param server The Accurev server details.
     */
public static void addServer(ArgumentListBuilder cmd, AccurevServer server) {
    if (null != server && null != server.getHost() && StringUtils.isNotBlank(server.getHost())) {
        cmd.add("-H");
        if (server.getPort() != 0) {
            cmd.add(server.getHost() + ":" + server.getPort());
        } else {
            cmd.add(server.getHost());
        }
    }
}
Example 16
Project: shopizer-master  File: DynamicIndexNameUtil.java View source code
@SuppressWarnings("rawtypes")
public static String getIndexName(String name, Map indexData) {
    if (name.startsWith("%") && name.endsWith("%")) {
        String containedField = name.substring(1, name.length() - 1);
        String f = (String) indexData.get(containedField);
        if (StringUtils.isBlank(f)) {
            return name;
        }
        return f;
    }
    return name;
}
Example 17
Project: timey-master  File: AbstractInterceptor.java View source code
String flattenArgument(Object argument) {
    if (null == argument) {
        return "null";
    }
    if (argument instanceof Object[]) {
        if (ArrayUtils.isEmpty((Object[]) argument)) {
            return "no arguments";
        }
        return StringUtils.join((Object[]) argument, ", ");
    }
    return argument.toString();
}
Example 18
Project: uConomy-master  File: ItemUtils.java View source code
public static String toFriendlyName(Material material) {
    String materialName = material.name().toLowerCase();
    if (!materialName.contains("_")) {
        return StringUtils.capitalize(materialName);
    }
    List<String> words = new ArrayList<String>();
    for (String word : materialName.split("_")) {
        StringUtils.capitalize(word);
        words.add(word);
    }
    return StringUtils.join(words, " ");
}
Example 19
Project: mongo4idea-master  File: MongoUtils.java View source code
public static GeneralCommandLine buildCommandLine(String shellPath, ServerConfiguration serverConfiguration, MongoDatabase database) {
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(shellPath);
    commandLine.addParameter(buildMongoUrl(serverConfiguration, database));
    String username = serverConfiguration.getUsername();
    if (org.apache.commons.lang.StringUtils.isNotBlank(username)) {
        commandLine.addParameter("--username");
        commandLine.addParameter(username);
    }
    String password = serverConfiguration.getPassword();
    if (org.apache.commons.lang.StringUtils.isNotBlank(password)) {
        commandLine.addParameter("--password");
        commandLine.addParameter(password);
    }
    String authenticationDatabase = serverConfiguration.getAuthenticationDatabase();
    if (org.apache.commons.lang.StringUtils.isNotBlank(authenticationDatabase)) {
        commandLine.addParameter("--authenticationDatabase");
        commandLine.addParameter(authenticationDatabase);
    }
    AuthenticationMechanism authenticationMechanism = serverConfiguration.getAuthenticationMechanism();
    if (authenticationMechanism != null) {
        commandLine.addParameter("--authenticationMechanism");
        commandLine.addParameter(authenticationMechanism.getMechanismName());
    }
    String shellWorkingDir = serverConfiguration.getShellWorkingDir();
    if (org.apache.commons.lang.StringUtils.isNotBlank(shellWorkingDir)) {
        commandLine.setWorkDirectory(shellWorkingDir);
    }
    String shellArgumentsLine = serverConfiguration.getShellArgumentsLine();
    if (org.apache.commons.lang.StringUtils.isNotBlank(shellArgumentsLine)) {
        commandLine.addParameters(shellArgumentsLine.split(" "));
    }
    return commandLine;
}
Example 20
Project: owsi-core-parent-master  File: StringUtils.java View source code
private static String sanitizeString(String strToClean, Pattern cleanRegexpPattern) {
    if (strToClean == null) {
        return null;
    }
    String str = strToClean.trim();
    str = StringUtils.removeAccents(str);
    str = StringUtils.lowerCase(str);
    str = cleanRegexpPattern.matcher(str).replaceAll(DASH);
    str = CLEAN_DUPLICATE_DASHES_REGEXP_PATTERN.matcher(str).replaceAll(DASH);
    str = org.apache.commons.lang3.StringUtils.strip(str, DASH);
    return str;
}
Example 21
Project: jfairy-master  File: EmailProvider.java View source code
@Override
public String get() {
    String prefix = "";
    switch(baseProducer.randomBetween(1, 3)) {
        case 1:
            prefix = StringUtils.replace(firstName + lastName, " ", "");
            break;
        case 2:
            prefix = StringUtils.replace(firstName + "." + lastName, " ", ".");
            break;
        case 3:
            prefix = StringUtils.replace(lastName, " ", "");
            break;
    }
    return TextUtils.stripAccents(lowerCase(prefix + '@' + dataMaster.getRandomValue(PERSONAL_EMAIL)));
}
Example 22
Project: Leboncoin-master  File: FormatConsoleTable.java View source code
public void flush() {
    String formatString = "| %55s | %9s | %18s |";
    // Mind that all rows have the same sizes.
    for (int i = 0; i < rows.size(); i++) {
        Row row = rows.get(i);
        String strOut = String.format(formatString, row.adTitle, row.adPrice, row.status);
        // First or last row
        if (i == 0) {
            Logger.traceINFO(org.apache.commons.lang3.StringUtils.repeat("_", strOut.length()));
        }
        Logger.traceINFO(strOut);
        if (i == rows.size() - 1) {
            Logger.traceINFO(org.apache.commons.lang3.StringUtils.repeat("_", strOut.length()));
        }
    }
}
Example 23
Project: abmash-master  File: SubmittablePredicate.java View source code
@Override
public void buildCommands() {
    List<String> inputSelectors = Arrays.asList("form", "input", "textarea");
    if (text != null) {
        containsText("'" + StringUtils.join(inputSelectors, ',') + "'", text);
        containsAttribute("'" + StringUtils.join(inputSelectors, ',') + "'", "*", text);
    } else {
        add(JQueryFactory.select("'" + StringUtils.join(inputSelectors, ',') + "'", 50));
    }
}
Example 24
Project: ares-studio-master  File: LogicTextContentAssistant.java View source code
/* (non-Javadoc)
	 * @see org.eclipse.jface.text.contentassist.ContentAssistant#getContentAssistProcessor(java.lang.String)
	 */
@Override
public IContentAssistProcessor getContentAssistProcessor(String contentType) {
    IContentAssistProcessor processor = null;
    processor = super.getContentAssistProcessor(contentType);
    if (!StringUtils.equalsIgnoreCase(contentType, IDocument.DEFAULT_CONTENT_TYPE) && processor == null) {
        processor = super.getContentAssistProcessor(IDocument.DEFAULT_CONTENT_TYPE);
    }
    return processor;
}
Example 25
Project: asta4d-master  File: AbstractString2Java8DateConvertor.java View source code
public T convert(String s) throws UnsupportedValueException {
    if (StringUtils.isEmpty(s)) {
        return null;
    }
    for (DateTimeFormatter formatter : availableFormatters()) {
        try {
            T tt = convert2Target(formatter, s);
            return tt;
        } catch (DateTimeParseException e) {
            System.out.println(formatter.toString());
            e.printStackTrace();
            continue;
        }
    }
    throw new UnsupportedValueException();
}
Example 26
Project: bamboo-artifactory-plugin-master  File: Utils.java View source code
public static <V> Map<String, V> filterMapKeysByPrefix(Map<String, V> map, String prefix) {
    Map<String, V> result = new HashedMap();
    if (map == null) {
        return result;
    }
    for (Map.Entry<String, V> entry : map.entrySet()) {
        if (StringUtils.startsWith(entry.getKey(), prefix)) {
            result.put(entry.getKey(), entry.getValue());
        }
    }
    return result;
}
Example 27
Project: beanfuse-master  File: SqlExecuteAction.java View source code
public String executeSql() {
    String sql = get("sql");
    if (StringUtils.isEmpty(sql)) {
        forward("result");
    }
    sql = sql.trim();
    if (sql.startsWith("select")) {
        SqlRowSet rowSet = sqlService.queryForRowSet(sql);
        SqlRowSetMetaData meta = rowSet.getMetaData();
        put("rowSet", rowSet);
        put("meta", meta);
    } else {
        sqlService.execute(sql);
    }
    return forward("result");
}
Example 28
Project: btpka3.github.com-master  File: LoginAction.java View source code
public String checkPassword(String userName, String password) {
    if (StringUtils.isBlank(userName)) {
        logger.debug("userName is empty.");
        return "error";
    }
    if (userName.trim().equals(password)) {
        logger.debug("password is correct.");
        return "success";
    }
    logger.debug("password is wrong.");
    return "error";
}
Example 29
Project: build-info-master  File: IssuesTrackerUtils.java View source code
public static Set<Issue> getAffectedIssuesSet(String affectedIssues) {
    Set<Issue> affectedIssuesSet = Sets.newHashSet();
    if (StringUtils.isNotBlank(affectedIssues)) {
        String[] issuePairs = affectedIssues.split(",");
        for (String pair : issuePairs) {
            String[] idAndUrl = pair.split(">>");
            if (idAndUrl.length == 3) {
                affectedIssuesSet.add(new Issue(idAndUrl[0], idAndUrl[1], idAndUrl[2]));
            }
        }
    }
    return affectedIssuesSet;
}
Example 30
Project: cassandra-unit-master  File: FileTmpHelper.java View source code
public static String copyClassPathDataSetToTmpDirectory(Class c, String initialClasspathDataSetLocation) throws IOException {
    InputStream dataSetInputStream = c.getResourceAsStream(initialClasspathDataSetLocation);
    String dataSetFileName = StringUtils.substringAfterLast(initialClasspathDataSetLocation, "/");
    String tmpPath = FileUtils.getTempDirectoryPath() + "/cassandra-unit/dataset/";
    String targetDataSetPathFileName = tmpPath + dataSetFileName;
    FileUtils.copyInputStreamToFile(dataSetInputStream, new File(targetDataSetPathFileName));
    return targetDataSetPathFileName;
}
Example 31
Project: constellio-master  File: ExtractDocumentTypeCodes.java View source code
public static void main(String[] args) {
    File file = new File("/Users/rodrigue/constellio-dev-2015-10-08/documentTypes.txt");
    assertThat(file).exists();
    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
        String line = "";
        while (StringUtils.isNotBlank(line = bufferedReader.readLine())) {
            String codePart = StringUtils.substringAfter(line, "code:");
            if (StringUtils.isNotBlank(codePart)) {
                if (StringUtils.split(codePart, ", ").length > 0) {
                    String code = StringUtils.split(codePart, ", ")[0];
                    System.out.println(code);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 32
Project: coprhd-controller-master  File: APIException.java View source code
public static String constructMessage(int statusCode, String statusText, String errorMessage) {
    StringBuilder sb = new StringBuilder();
    sb.append(statusCode);
    if (StringUtils.isNotBlank(statusText)) {
        sb.append(" : ").append(statusText);
    }
    if (StringUtils.isNotBlank(errorMessage)) {
        sb.append(" : ").append(errorMessage);
    }
    return sb.toString();
}
Example 33
Project: cruisecontrol-master  File: SingleQuoteTest.java View source code
public void testShouldEscapeSingleQuoteInProjectNameInDashboardPage() throws Exception {
    tester.beginAt("/tab/dashboard");
    String page = tester.getPageSource();
    assertTrue(StringUtils.contains(page, "new Tooltip('\\'_bar', 'tooltip_\\'')"));
    tester.beginAt("/forcebuild.ajax?projectName='");
    getJSONWithAjaxInvocation("getProjectBuildStatus.ajax");
    tester.beginAt("/tab/build/detail/'");
    page = tester.getPageSource();
    assertTrue(page, StringUtils.contains(page, "new BuildDetailObserver('\\'')"));
}
Example 34
Project: cts2-framework-master  File: DeleteHandler.java View source code
protected <I> void delete(I identifier, String changeSetUri, BaseMaintenanceService<?, ?, I> service) {
    if (StringUtils.isBlank(changeSetUri)) {
        UnknownChangeSet ex = new UnknownChangeSet();
        ex.setCts2Message(ModelUtils.createOpaqueData("A 'ChangeSetURI' is required to DELETE a Resource. Please supply one and retry your request."));
        throw ex;
    }
    service.deleteResource(identifier, changeSetUri);
}
Example 35
Project: Doris-master  File: ClientPutTask.java View source code
@Override
public void doRun(long index) {
    String key = kp + index;
    String value = vp + index;
    if (vl > 0) {
        value = StringUtils.repeat(vp, vl);
        value = vp + index + "_" + value;
    }
    if ("get".equals(operation)) {
        Object retVal = dataStore.get(key);
        if (isNeedPofiling() && !value.equals(retVal)) {
            System.err.println("value not got, ns=" + dataStore.getNamespace().getName() + ",id=" + dataStore.getNamespace().getId() + ",  key=" + key);
        }
    } else if ("put".equals(operation)) {
        dataStore.put(key, value);
    // System.err.println("put: key=" + key + ", value=" + value);
    } else if ("delete".equals(operation)) {
        dataStore.delete(key);
    } else {
        // get
        dataStore.get(key);
    }
}
Example 36
Project: ehour-master  File: DatabaseConfig.java View source code
@Override
public String toString() {
    return "DatabaseConfig{" + "database='" + (databaseType != null ? databaseType.name() : "") + '\'' + ", driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + (StringUtils.isBlank(username) ? "" : "*****") + '\'' + ", password='" + (StringUtils.isBlank(password) ? "" : "*****") + '\'' + '}';
}
Example 37
Project: entermedia-core-master  File: EmStringUtils.java View source code
public static List<String> split(String inText) {
    if (inText == null) {
        return null;
    }
    String text = inText.replace("\r", "");
    text = text.replace(",", "\n");
    //		String value = inText.replace(',', '\n').replace('\r', '\n').replace('\n', ' ');
    //
    //		String[] paths = org.apache.commons.lang.StringUtils.split(value,'\n');
    //		return Arrays.asList(paths);
    StrTokenizer str = new StrTokenizer(text, '\n');
    return str.getTokenList();
}
Example 38
Project: geowebcache-master  File: NullURLMangler.java View source code
public String buildURL(String baseURL, String contextPath, String path) {
    final String context = StringUtils.strip(contextPath, "/");
    // if context is root ("/") then don't append it to prevent double slashes ("//") in return URLs  
    if (context == null || context.isEmpty()) {
        return StringUtils.strip(baseURL, "/") + "/" + StringUtils.strip(path, "/");
    } else {
        return StringUtils.strip(baseURL, "/") + "/" + context + "/" + StringUtils.strip(path, "/");
    }
}
Example 39
Project: gluster-ovirt-poc-master  File: EngineConfigUtils.java View source code
/**
     * @param paths
     * @return The first file found from the list
     * @throws FileNotFoundException
     */
public static File locateFileInPaths(String... paths) throws FileNotFoundException {
    for (String path : paths) {
        if (path != null) {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        }
    }
    String msg = "Files " + StringUtils.join(paths, ",\n") + " does not exist";
    throw new FileNotFoundException(msg);
}
Example 40
Project: hadoop-book-master  File: ExtractMovieUDF.java View source code
public Text evaluate(final Text t) {
    if (t == null) {
        return null;
    }
    String s = t.toString();
    String[] parts = StringUtils.split(s, " ");
    if (parts.length != 3) {
        return null;
    }
    String path = parts[1];
    if (!path.startsWith("/movie/")) {
        return null;
    }
    result.set(path.substring(7));
    return result;
}
Example 41
Project: hiped2-master  File: ExtractMovie.java View source code
public Text evaluate(final Text t) {
    if (t == null) {
        return null;
    }
    String s = t.toString();
    String[] parts = StringUtils.split(s, " ");
    if (parts.length != 3) {
        return null;
    }
    String path = parts[1];
    if (!path.startsWith("/movie/")) {
        return null;
    }
    result.set(path.substring(7));
    return result;
}
Example 42
Project: invoicing-master  File: PurchaseReturnDetailQueryDTO.java View source code
public void setQueryCondition(Criteria queryCriteria) {
    if (this.getPurReturnId() != null && StringUtils.isNotBlank(this.getPurReturnId())) {
        queryCriteria.andPurReturnIdEqualTo(this.getPurReturnId());
    }
    if (this.getGoodsName() != null && StringUtils.isNotBlank(this.getGoodsName())) {
        queryCriteria.andGoodsNameLike("%" + this.getGoodsName() + "%");
    }
}
Example 43
Project: javardices-master  File: CategoryProcessor.java View source code
@Override
public void process(FeedChannel feed_channel, XMLStreamReader stax_xml_reader) {
    FeedEntry feed_entry = feed_channel.getLastFeedEntry();
    try {
        String atom_category = stax_xml_reader.getAttributeValue("", "term");
        String rss_category = stax_xml_reader.getElementText();
        String category = StringUtils.isBlank(atom_category) ? rss_category : atom_category;
        feed_entry.addCategory(StringUtils.trimToNull(category));
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}
Example 44
Project: jtwig-master  File: TestUtils.java View source code
public static String universalPath(String path) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(StringUtils.join(asList(path.split(Pattern.quote("/"))), File.separator));
        File file = new File(stringBuilder.toString());
        return new File(file.getParentFile(), file.getName()).getCanonicalPath();
    } catch (Exception e) {
        return path;
    }
}
Example 45
Project: Junit-DynamicSuite-master  File: IgnoreNonClassFilesTest.java View source code
@Test
public void onlyThisTestClassShouldBeFound() throws Exception {
    final String packagee = getClass().getPackage().getName();
    final String packageAsPath = StringUtils.replace(packagee, ".", "/");
    final String directory = "target/test-classes/" + packageAsPath;
    final DirectoryScanner scanner = new DirectoryScanner(new File(directory));
    assertThat(scanner.listClassNames().size(), is(1));
}
Example 46
Project: language-tools-bg-master  File: ParonymService.java View source code
public Set<String> findParonyms(String input) {
    Set<String> paronyms = Sets.newHashSet();
    int maxDistance = input.length() / 3;
    for (String word : Checker.formsDictionary.keySet()) {
        if (!word.startsWith(input) && StringUtils.getLevenshteinDistance(input, word, maxDistance) != -1) {
            paronyms.add(word);
        }
    }
    return paronyms;
}
Example 47
Project: marketcetera-master  File: StatelessClientContextTest.java View source code
@Test
public void all() {
    StatelessClientContext context = new StatelessClientContext();
    fillContext(context);
    StatelessClientContext copy = new StatelessClientContext();
    fillContext(copy);
    StatelessClientContext empty = new StatelessClientContext();
    single(context, copy, empty, StringUtils.EMPTY);
    assertEquals(empty, context);
}
Example 48
Project: muikku-master  File: TaskSrcQueryParams.java View source code
@Override
protected void cleanElement(Element e) {
    if (e.hasAttribute("src")) {
        String src = e.getAttribute("src");
        if (StringUtils.startsWith(src, "/workspace/")) {
            int i = StringUtils.indexOf(src, "?");
            if (i != -1) {
                e.setAttribute("src", StringUtils.substring(src, 0, i));
                markModified();
            }
        }
    }
}
Example 49
Project: ovirt-engine-master  File: EngineConfigUtils.java View source code
/**
     * @return The first file found from the list
     */
public static File locateFileInPaths(String... paths) throws FileNotFoundException {
    for (String path : paths) {
        if (path != null) {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        }
    }
    String msg = "Files " + StringUtils.join(paths, ",\n") + " does not exist";
    throw new FileNotFoundException(msg);
}
Example 50
Project: partake-master  File: RemoveCommentPermission.java View source code
public static boolean check(EventComment comment, Event event, UserEx user) {
    assert comment != null;
    assert event != null;
    if (user == null)
        return false;
    if (StringUtils.equals(comment.getUserId(), user.getId()))
        return true;
    if (StringUtils.equals(event.getOwnerId(), user.getId()))
        return true;
    if (event.isManager(user))
        return true;
    return false;
}
Example 51
Project: quhao-master  File: StringUtils.java View source code
public static String getLimitedWords(int max, String str) {
    if (StringUtils.isEmpty(str)) {
        return "";
    } else {
        String[] strArray = split(str, null);
        StringBuilder builder = new StringBuilder();
        int i = 0;
        for (String s : strArray) {
            builder.append(s);
            i++;
            if (i >= max) {
                builder.append("...");
                break;
            } else {
                builder.append(" ");
            }
        }
        return builder.toString().trim();
    }
}
Example 52
Project: rdap-server-sample-gtld-master  File: DomainStatusFieldParser.java View source code
@Override
public DomainStatus parse(String value) {
    // Strip of URL's (everything after a space)
    value = StringUtils.substringBefore(value, " ");
    // Replace the camelcase with underscores
    value = value.replaceAll("(.)(\\p{Upper})", "$1_$2");
    // and then uppercase it to find the status
    return DomainStatus.valueOf(StringUtils.upperCase(value));
}
Example 53
Project: shmuphiscores-master  File: ScoreDecorator.java View source code
public String replay() {
    if (score.replay != null && StringUtils.isNotBlank(score.replay)) {
        if (score.replay.contains("youtube")) {
            return "[youtube]" + score.replay.split("v=")[1] + "[/youtube]";
        } else {
            return "Replay : " + score.replay;
        }
    }
    return null;
}
Example 54
Project: smilonet-common-master  File: CheckEmptyValidator.java View source code
@Override
public void validate(ValidationContext ctx) {
    Boolean canBeEmpty = (Boolean) ctx.getBindContext().getValidatorArg("canBeEmpty");
    if (canBeEmpty == null) {
        canBeEmpty = true;
    }
    String checkedPropertyValue = (String) ctx.getProperty().getValue();
    String checkedPropertyName = (String) ctx.getProperty().getProperty();
    boolean isValid = true;
    if (!canBeEmpty && StringUtils.isEmpty(checkedPropertyValue)) {
        isValid = false;
    }
    if (isValid == false) {
        this.addInvalidMessage(ctx, checkedPropertyName, "�能为空");
    }
}
Example 55
Project: testcontainers-java-master  File: StringsTrait.java View source code
default SELF withFileFromString(String path, String content) {
    return ((SELF) this).withFileFromTransferable(path, new Transferable() {

        @Getter
        byte[] bytes = content.getBytes();

        @Override
        public long getSize() {
            return bytes.length;
        }

        @Override
        public String getDescription() {
            return "String: " + StringUtils.abbreviate(content, 100);
        }
    });
}
Example 56
Project: XCoLab-master  File: BaseController.java View source code
protected void setSeoTexts(HttpServletRequest request, String pageTitle, String pageSubtitle, String pageDescription) {
    //TODO: liferay internal - needs to be removed after transition
    if (StringUtils.isNotBlank(pageTitle)) {
    //  PortalUtil.setPageTitle(pageTitle, httpRequest);
    }
    if (StringUtils.isNotBlank(pageDescription)) {
    //PortalUtil.setPageDescription(pageDescription, httpRequest);
    }
    if (StringUtils.isNotBlank(pageSubtitle)) {
    //PortalUtil.setPageSubtitle(pageSubtitle, httpRequest);
    }
}
Example 57
Project: Activiti-master  File: DataStoreExport.java View source code
public static void writeDataStores(BpmnModel model, XMLStreamWriter xtw) throws Exception {
    for (DataStore dataStore : model.getDataStores().values()) {
        xtw.writeStartElement(ELEMENT_DATA_STORE);
        xtw.writeAttribute(ATTRIBUTE_ID, dataStore.getId());
        xtw.writeAttribute(ATTRIBUTE_NAME, dataStore.getName());
        if (StringUtils.isNotEmpty(dataStore.getItemSubjectRef())) {
            xtw.writeAttribute(ATTRIBUTE_ITEM_SUBJECT_REF, dataStore.getItemSubjectRef());
        }
        if (StringUtils.isNotEmpty(dataStore.getDataState())) {
            xtw.writeStartElement(ELEMENT_DATA_STATE);
            xtw.writeCharacters(dataStore.getDataState());
            xtw.writeEndElement();
        }
        xtw.writeEndElement();
    }
}
Example 58
Project: alien4cloud-master  File: ConnectStepToProcessor.java View source code
@Override
protected void processWorkflowOperation(ConnectStepToOperation operation, Workflow workflow) {
    Topology topology = EditionContextManager.getTopology();
    log.debug("connecting step <{}> to <{}> in the workflow <{}> from topology <{}>", operation.getFromStepId(), StringUtils.join(operation.getToStepIds(), ","), workflow.getName(), topology.getId());
    workflowBuilderService.connectStepTo(topology, workflow.getName(), operation.getFromStepId(), operation.getToStepIds());
}
Example 59
Project: AliView-master  File: MyStringUtils.java View source code
public static String replaceProblematicSequenceNameSymbols(String name) {
    if (name != null) {
        // replacing is done in two ways - with string regexp and StringUtilities (just for fun...)
        name = name.replaceAll("\\-", "_");
        name = StringUtils.replaceChars(name, ' ', '_');
        name = StringUtils.replace(name, "\"", "_");
        name = StringUtils.replace(name, "?", "");
        name = StringUtils.replace(name, ".", "");
        name = StringUtils.replace(name, "/", "_");
        name = StringUtils.replace(name, "|", "_");
    }
    return name;
}
Example 60
Project: analysis-core-plugin-master  File: CsharpNamespaceDetector.java View source code
/** {@inheritDoc}*/
@Override
public String detectPackageName(final InputStream stream) {
    try {
        LineIterator iterator = IOUtils.lineIterator(stream, "UTF-8");
        while (iterator.hasNext()) {
            String line = iterator.nextLine();
            if (line.matches("^namespace .*$")) {
                if (line.contains("{")) {
                    return StringUtils.substringBetween(line, " ", "{").trim();
                } else {
                    return StringUtils.substringAfter(line, " ").trim();
                }
            }
        }
    } catch (IOException exception) {
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return UNKNOWN_PACKAGE;
}
Example 61
Project: asperatus-master  File: Env.java View source code
public static String envOrProperty(final String name, final String def) {
    final String val = System.getProperty(name, System.getenv(name));
    if (StringUtils.isBlank(val)) {
        if (StringUtils.isBlank(def)) {
            throw new RuntimeException("Missing required property: " + name);
        }
        logger.log(Level.WARNING, String.format("Warning, missing property %s, using default of %s", name, def));
        return def;
    }
    return val;
}
Example 62
Project: barweb-master  File: KrysseTokenInterceptor.java View source code
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    boolean tokenHeaderMatches = StringUtils.equals(krysseToken, request.getHeader("KrysseToken"));
    if (!tokenHeaderMatches) {
        log.warn("tokenheader did not match kryssetoken");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    return tokenHeaderMatches;
}
Example 63
Project: bbs.newgxu.cn-master  File: HTMLEscapeFilter.java View source code
/**
	 * 因为�以支�直接写入html标签,也�以写入 ubb
	 * 现在��蔽了 javascript 标签
	 */
protected String convert(String s) {
    /*
		String str = StringUtils.replace(s, "<", "<");
		       str = StringUtils.replace(str, "javascript", "java_script");
		return StringUtils.replace(str, ">", ">");
		*/
    String str = StringUtils.replace(s, "<script>", "<script>");
    str = StringUtils.replace(str, "</script>", "</script>");
    str = StringUtils.replace(str, "<script language=\"javascript\">", "<script>");
    return str;
}
Example 64
Project: bean-query-master  File: DefaultNullValuePropertyValueGetter.java View source code
public static Object getProperty(Object from, String propertyName) {
    if (null == from || StringUtils.isBlank(propertyName)) {
        LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Object is null or the property [{}] is blank, returning null", propertyName);
        return null;
    }
    try {
        return PropertyUtils.getProperty(from, propertyName);
    } catch (Exception e) {
        LoggerFactory.getLogger(DefaultNullValuePropertyValueGetter.class).info("Exception [{}] when fetching property [{}] from object [{}], returning null as the value.", e.toString(), propertyName, from);
        return null;
    }
}
Example 65
Project: blueprints-arangodb-graph-master  File: ArangoGraphTest.java View source code
@Test
public void testCreateGraph() throws ArangoDBGraphException {
    ArangoDBGraph graph = new ArangoDBGraph(configuration, graphName, vertices, edges);
    assertTrue(hasGraph(graphName));
    String graphId = graph.getId();
    assertNotNull(StringUtils.isNotEmpty(graphId));
    graph.shutdown();
    graph = new ArangoDBGraph(configuration, graphName, vertices, edges);
    String x = graph.getId();
    assertNotNull(StringUtils.isNotEmpty(x));
    assertEquals(graphId, x);
    graph.shutdown();
}
Example 66
Project: cachecloud-master  File: RedisReadOnlyCommandEnum.java View source code
public static boolean contains(String command) {
    if (StringUtils.isBlank(command)) {
        return false;
    }
    for (RedisReadOnlyCommandEnum readEnum : RedisReadOnlyCommandEnum.values()) {
        String readCommand = readEnum.toString();
        command = StringUtils.trim(command);
        if (command.length() < readCommand.toString().length()) {
            continue;
        }
        String head = StringUtils.substring(command, 0, readCommand.length());
        if (readCommand.equalsIgnoreCase(head)) {
            return true;
        }
    }
    return false;
}
Example 67
Project: canal-master  File: SocketAddressEditor.java View source code
public void setAsText(String text) throws IllegalArgumentException {
    String[] addresses = StringUtils.split(text, ":");
    if (addresses.length > 0) {
        if (addresses.length != 2) {
            throw new RuntimeException("address[" + text + "] is illegal, eg.127.0.0.1:3306");
        } else {
            setValue(new InetSocketAddress(addresses[0], Integer.valueOf(addresses[1])));
        }
    } else {
        setValue(null);
    }
}
Example 68
Project: cas-master  File: CookieUtils.java View source code
/**
     * Gets ticket granting ticket from request.
     *
     * @param ticketGrantingTicketCookieGenerator the ticket granting ticket cookie generator
     * @param ticketRegistry                      the ticket registry
     * @param request                             the request
     * @return the ticket granting ticket from request
     */
public static TicketGrantingTicket getTicketGrantingTicketFromRequest(final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator, final TicketRegistry ticketRegistry, final HttpServletRequest request) {
    final String cookieValue = ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
    if (StringUtils.isNotBlank(cookieValue)) {
        final TicketGrantingTicket tgt = ticketRegistry.getTicket(cookieValue, TicketGrantingTicket.class);
        if (tgt != null && !tgt.isExpired()) {
            return tgt;
        }
    }
    return null;
}
Example 69
Project: cassandra-rest-master  File: QueryParser.java View source code
public static Query parse(String query) {
    String[] peaces;
    Query q = new Query();
    if (StringUtils.isBlank(query)) {
        return q;
    }
    if (StringUtils.indexOf(query, AND) > -1) {
        peaces = StringUtils.split(query, AND);
    } else {
        peaces = new String[] { query };
    }
    for (String peace : peaces) {
        if (peace != null && peace.indexOf(EQ_DELIM) > -1) {
            String[] kv = peace.split(EQ_DELIM);
            q.addEq(StringUtils.trim(kv[0]), StringUtils.trim(kv[1]));
        }
    }
    return q;
}
Example 70
Project: cattle-master  File: MacAddressGenerator.java View source code
@Override
protected String toString(long value) {
    String hex = StringUtils.leftPad(Long.toHexString(value), macLength, '0');
    StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < hex.length(); i++) {
        if (i > 0 && i % 2 == 0) {
            buffer.append(':');
        }
        buffer.append(hex.charAt(i));
    }
    return buffer.toString();
}
Example 71
Project: ccshop-master  File: PrivilegeChecker.java View source code
@Override
public Object exec(List arguments) throws TemplateModelException {
    if (arguments == null || arguments.size() == 0) {
        return true;
    }
    if (!(arguments.get(0) instanceof String)) {
        return true;
    }
    String res = (String) arguments.get(0);
    if (StringUtils.isBlank(res)) {
        return true;
    }
    HttpSession session = RequestHolder.getSession();
    System.out.println(String.format("check privilege ,res : {}, session id :{}", res, session == null ? null : session.getId()));
    return PrivilegeUtils.check(session, res);
}
Example 72
Project: cgeo-master  File: HtmlUtilsTest.java View source code
public static void testExtractText() {
    assertThat(HtmlUtils.extractText(null)).isEqualTo(StringUtils.EMPTY);
    assertThat(HtmlUtils.extractText(StringUtils.EMPTY)).isEqualTo(StringUtils.EMPTY);
    assertThat(HtmlUtils.extractText("   ")).isEqualTo(StringUtils.EMPTY);
    assertThat(HtmlUtils.extractText("<b>bold</b>")).isEqualTo("bold");
}
Example 73
Project: charaparser-unsupervised-master  File: IsAValue.java View source code
@Override
public boolean equals(Object obj) {
    if (obj == this) {
        return true;
    }
    if (obj == null || obj.getClass() != this.getClass()) {
        return false;
    }
    IsAValue myIsAValue = (IsAValue) obj;
    return ((StringUtils.equals(this.instance, myIsAValue.getInstance())) && (this.cls == myIsAValue.getCls()));
}
Example 74
Project: cloud-paulpredicts-master  File: ConfigDBAdapter.java View source code
@Override
public Properties getByGroup(String group) {
    Properties groupProperties = new Properties();
    List<Config> configs = ConfigDAO.getByGroup(group);
    for (Config config : configs) {
        if (StringUtils.isNotBlank(config.getParamKey()) && StringUtils.isNotBlank(config.getParamValue())) {
            groupProperties.put(config.getParamKey(), config.getParamValue());
        }
    }
    return groupProperties;
}
Example 75
Project: cloudsync-master  File: LogconsoleHandler.java View source code
@Override
public void publish(LogRecord record) {
    if (record.getParameters() == null) {
        if (keepCurrentLine) {
            keepCurrentLine = false;
            sizeCurrentLine = 0;
            System.out.print("\r");
        }
        System.out.println(LogfileFormatter.formatRecord(record, sdf));
    } else {
        int _sizeCurrentLine = record.getMessage().length();
        if (_sizeCurrentLine < sizeCurrentLine)
            System.out.print("\r" + StringUtils.repeat(' ', sizeCurrentLine));
        sizeCurrentLine = _sizeCurrentLine;
        keepCurrentLine = true;
        System.out.print(record.getMessage());
    }
}
Example 76
Project: codehaus-mojo-master  File: CCompilerClassicTest.java View source code
/**
     * Simple test, note: -o option has no space
     * @throws Exception
     */
public void testSimpleCompilation() throws Exception {
    CompilerConfiguration config = new CompilerConfiguration();
    CCompilerClassic compiler = new CCompilerClassic();
    Commandline cl = compiler.getCommandLine(new File("source.c"), new File("object.o"), config);
    assertTrue(StringUtils.contains(cl.toString(), "gcc -oobject.o -c source.c"));
}
Example 77
Project: codjo-data-process-master  File: ResultTabbedPane.java View source code
public void addResult(EventsBinder eventsBinder, StringBuffer resultString, String sql, WaitingPanel waitingPanel, int pageSize, SQLEditorTools sqlEditorTools) throws EventBinderException {
    ResultPaneLogic paneLogic = new ResultPaneLogic(eventsBinder, this, waitingPanel, pageSize, sqlEditorTools);
    ResultPaneGui paneGui = paneLogic.getResultPane();
    paneGui.init(sql, resultString, pageSize, paneLogic.getNavigationPanelLogic(), sqlEditorTools);
    add(StringUtils.abbreviate(sql, 30), paneGui);
    setSelectedIndex(getTabCount() - 1);
}
Example 78
Project: cointrader-master  File: AttachCommand.java View source code
@Override
public void run() {
    if (StringUtils.isBlank(args)) {
        out.println("You must supply a base class name for the module class");
        return;
    }
    try {
        context.attach(args);
    } catch (Exception e) {
        out.println(e.getMessage());
        log.warn("Could not load module \"" + args + "\"", e);
    }
}
Example 79
Project: commafeed-master  File: FeedEntryKeyword.java View source code
public static List<FeedEntryKeyword> fromQueryString(String keywords) {
    List<FeedEntryKeyword> list = new ArrayList<>();
    if (keywords != null) {
        for (String keyword : StringUtils.split(keywords)) {
            boolean not = false;
            if (keyword.startsWith("-") || keyword.startsWith("!")) {
                not = true;
                keyword = keyword.substring(1);
            }
            list.add(new FeedEntryKeyword(keyword, not ? Mode.EXCLUDE : Mode.INCLUDE));
        }
    }
    return list;
}
Example 80
Project: Composer-Eclipse-Plugin-master  File: LicenseContentAdapter.java View source code
@Override
public void setControlContents(Control control, String text, int cursorPosition) {
    String id = text.replaceAll(".+\\((.+)\\)$", "$1");
    String val = ((Text) control).getText();
    String[] chunks = val.split(",");
    chunks[chunks.length - 1] = id;
    val = StringUtils.join(chunks, ", ");
    cursorPosition = val.length();
    ((Text) control).setText(val);
    ((Text) control).setSelection(cursorPosition, cursorPosition);
}
Example 81
Project: copartner-master  File: IMUtils.java View source code
public static Long register(Long userId, String nick, String avatar) {
    Long imId = 0L;
    InRegister inregister = new InRegister();
    inregister.setParty_id(userId + "");
    inregister.setNick(nick);
    inregister.setPasswd(CommonConstant.IM_DEFAULT_PWD);
    inregister.setAvatar(avatar);
    String msg = JsonUtil.serialize(inregister);
    String returnMsg = IMSocketClient.sendMsg(msg);
    if (StringUtils.isNotEmpty(returnMsg)) {
        OutRegister obj = JsonUtil.deserialize(returnMsg, OutRegister.class);
        if (null != obj) {
            imId = obj.getMid();
        }
    }
    return imId;
}
Example 82
Project: CoreLib-master  File: SipCreatorUtilsTest.java View source code
@Test
public void testSipCreatorUtils() {
    String workingDir = StringUtils.endsWith(System.getProperty("user.dir"), "corelib") ? System.getProperty("user.dir") + "/corelib-solr-tools" : System.getProperty("user.dir");
    SipCreatorUtils sipCreatorUtils = new SipCreatorUtils();
    String repository = workingDir + "/src/test/resources/";
    sipCreatorUtils.setRepository(repository);
    assertEquals("europeana_isShownBy[0]", sipCreatorUtils.getHashField("9200103", "9200103_Ag_EU_TEL_Gallica_a0142"));
    PreSipCreatorUtils preSipCreatorUtils = new PreSipCreatorUtils();
    preSipCreatorUtils.setRepository(repository);
    assertEquals("europeana_isShownAt", preSipCreatorUtils.getHashField("00735", "00735_A_DE_Landesarchiv_ese_5_0000013080"));
}
Example 83
Project: cosmos-message-master  File: LessTag.java View source code
protected String getPrintString(String url) {
    StringBuffer content = new StringBuffer();
    content.append("<link rel=\"stylesheet/less\" type=\"text/css\" ");
    if (StringUtils.isNotEmpty(charset)) {
        content.append("charset=\"").append(charset).append("\" ");
    }
    content.append("href=\"").append(url).append("\"/>");
    return content.toString();
}
Example 84
Project: data-quality-master  File: ReplaceCharacterHelper.java View source code
static String replaceCharacters(String input, Random rnd) {
    if (StringUtils.isEmpty(input)) {
        return input;
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isUpperCase(ch)) {
                sb.append(Function.UPPER.charAt(rnd.nextInt(26)));
            } else if (Character.isLowerCase(ch)) {
                sb.append(Function.LOWER.charAt(rnd.nextInt(26)));
            } else if (Character.isDigit(ch)) {
                sb.append(rnd.nextInt(10));
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
Example 85
Project: dip-master  File: SparkHdfsWriter.java View source code
public static <T> void write(JavaDStream<T> javaDStream, AppArgs appArgs) {
    javaDStream.foreachRDD( rdd -> {
        rdd.map( record -> {
            StringBuilder recordBuilder = new StringBuilder();
            for (Object e : (Object[]) record) {
                recordBuilder.append(e);
                recordBuilder.append(appArgs.getProperty(DiPConfiguration.HDFS_OUTPUT_DELIMITER));
            }
            return StringUtils.removeEnd(recordBuilder.toString(), appArgs.getProperty(DiPConfiguration.HDFS_OUTPUT_DELIMITER));
        }).saveAsTextFile(appArgs.getProperty(DiPConfiguration.CLUSTER_FS_URL) + appArgs.getProperty(DiPConfiguration.HDFS_OUTPUT_PATH) + System.currentTimeMillis());
    });
}
Example 86
Project: disconf-master  File: DaoUtils.java View source code
/**
     * 将业务的Page转�Dao的Page
     *
     * @param page
     *
     * @return
     */
public static DaoPage daoPageAdapter(Page page) {
    DaoPage daoPage = new DaoPage();
    daoPage.setPageNo(page.getPageNo());
    daoPage.setPageSize(page.getPageSize());
    List<Order> orderList = new ArrayList<Order>();
    if (!StringUtils.isEmpty(page.getOrderBy())) {
        Order order = new Order(page.getOrderBy(), page.isAsc());
        orderList.add(order);
    }
    daoPage.setOrderList(orderList);
    return daoPage;
}
Example 87
Project: DisJob-master  File: CronController.java View source code
@RequestMapping("/transferFromCron")
@ResponseBody
public CronInfo transferFromCron(@RequestParam(value = "cronExpression", required = true) String cronExpression) {
    if (StringUtils.isEmpty(cronExpression)) {
        CronInfo cronInfo = new CronInfo();
        cronInfo.setChooseSpecial(true);
        cronInfo.setSpecial(CronUtils.defaultSpecial);
        return cronInfo;
    }
    CronInfo cronInfo = CronUtils.transferFromCronExpression(cronExpression);
    return cronInfo;
}
Example 88
Project: dk-master  File: SqlInfusion.java View source code
public static String FilteSqlInfusion(String input) {
    if ((input == null) || (input.trim() == "")) {
        return "";
    }
    if (!StringUtils.isNumeric(input)) {
        return input.replace("'", "’").replace("update", "u�d�te").replace("drop", "dr��").replace("delete", "delete").replace("exec", "exec").replace("create", "cre�te").replace("execute", "execute").replace("where", "where").replace("truncate", "trunc�te").replace("insert", "insert");
    } else {
        return input;
    }
}
Example 89
Project: dolphin-master  File: BlockCommentMerger.java View source code
@Override
public BlockComment doMerge(BlockComment first, BlockComment second) {
    if (StringUtils.isBlank(first.getContent()))
        return second;
    if (StringUtils.isBlank(second.getContent()))
        return first;
    BlockComment comment = new BlockComment();
    comment.setContent(first.getContent());
    copyPosition(first, comment);
    return comment;
}
Example 90
Project: eclipse-tapestry5-plugin-master  File: ServiceIntfMatcher.java View source code
@Override
public boolean matches(TapestryService service) {
    if (StringUtils.isEmpty(className)) {
        return false;
    }
    if (StringUtils.isEmpty(service.getDefinition().getIntfClass())) {
        return false;
    }
    return StringUtils.equals(className, service.getDefinition().getIntfClass()) || StringUtils.equals(getSimpleName(this.className), getSimpleName(service.getDefinition().getIntfClass()));
}
Example 91
Project: Eemory-master  File: StringEscapeUtil.java View source code
/**
     * <p>
     * Escapes the characters in a String using ENML entities.
     * </p>
     *
     * @param string
     *            the String to escape, may be null
     * @return a new escaped String, null if null string input
     */
public static String escapeEnml(final String string, final int tabWidth) {
    if (StringUtil.isNull(string)) {
        return string;
    }
    String escapedXml = StringEscapeUtils.escapeXml10(string);
    escapedXml = escapedXml.replaceAll(StringUtils.SPACE, Constants.HTML_NBSP);
    escapedXml = escapedXml.replaceAll(ConstantsUtil.TAB, StringUtils.repeat(Constants.HTML_NBSP, tabWidth));
    return escapedXml;
}
Example 92
Project: ef-orm-master  File: SpringBeansDataSourceLookup.java View source code
public DataSource getDataSource(String dataSourceName) {
    //忽略大�写
    if (isIgnorCase())
        dataSourceName = StringUtils.lowerCase(dataSourceName);
    if (cache != null) {
        DataSource datasource = cache.get(dataSourceName);
        if (datasource != null)
            return datasource;
    }
    cache = getCache();
    DataSource datasource = cache.get(dataSourceName);
    return datasource;
}
Example 93
Project: elasticsearch-maven-plugin-master  File: ValidateVersionStep.java View source code
@Override
public void execute(ClusterConfiguration config) {
    String version = config.getVersion();
    if (StringUtils.isBlank(version)) {
        throw new ElasticsearchSetupException(String.format("Please provide a valid Elasticsearch version."));
    }
    if (version.matches("[0-4]\\..*")) {
        throw new ElasticsearchSetupException(String.format("elasticsearch-maven-plugin supports only versions 5+ of Elasticsearch. You configured: %s.", version));
    }
}
Example 94
Project: excalibur-master  File: StrUtils.java View source code
public static String camelConvert(AvroScan avroScan, String name) {
    Validate.isTrue(StringUtils.isNotBlank(name), "Camel Convert Error , Params is Blank!");
    if (!avroScan.camelConvert()) {
        return name;
    }
    StringBuilder result = new StringBuilder();
    result.append(name.substring(0, 1).toLowerCase());
    boolean isUppering = false;
    for (int i = 1; i < name.length(); i++) {
        String s = name.substring(i, i + 1);
        if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
            if (!isUppering) {
                result.append("_");
                isUppering = true;
            }
        } else {
            isUppering = false;
        }
        result.append(s.toLowerCase());
    }
    return result.toString();
}
Example 95
Project: expenditures-master  File: MissionProcessProvider.java View source code
@Override
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
    final String currentValue = StringUtils.trim(value);
    final List<MissionProcess> result = new ArrayList<MissionProcess>();
    final MissionSystem missionSystem = MissionSystem.getInstance();
    for (final MissionProcess missionProcess : missionSystem.getMissionProcessesSet()) {
        String[] processIdParts = missionProcess.getProcessNumber().split("/M");
        if (missionProcess.getProcessIdentification().equals(currentValue) || processIdParts[processIdParts.length - 1].equals(currentValue)) {
            result.add(missionProcess);
        }
    }
    return result;
}
Example 96
Project: ForgeEssentials-master  File: FECrashCallable.java View source code
@Override
public String call() throws Exception {
    String modules = StringUtils.join(ModuleLauncher.getModuleList(), ", ");
    String n = System.getProperty("line.separator");
    String returned = //
    String.format(//
    "Running ForgeEssentials %s #%d (%s)", BuildInfo.VERSION, BuildInfo.getBuildNumber(), BuildInfo.getBuildHash());
    returned += ". Modules loaded: " + modules;
    if (Environment.hasCauldron) {
        returned = returned + n + "Cauldron detected - DO NOT REPORT THIS CRASH TO FE OR CAULDRON.";
    }
    return returned;
}
Example 97
Project: gazetteer-master  File: Static.java View source code
public void read(Request req, Response res) {
    String path = req.getPath();
    path = StringUtils.remove(path, "..");
    path = "static/" + StringUtils.remove(path, "/static");
    try {
        File file = new File(path);
        if (file.exists()) {
            String mime = Files.probeContentType(Paths.get(file.getPath()));
            res.setContentType(mime);
            res.setBody(ChannelBuffers.wrappedBuffer(IOUtils.toByteArray(new FileInputStream(file))));
        } else {
            res.setResponseCode(404);
        }
    } catch (Exception e) {
        res.setException(e);
    }
}
Example 98
Project: gecco-master  File: ProductListPipeline.java View source code
@Override
public void process(ProductList productList) {
    HttpRequest currRequest = productList.getRequest();
    //下一页继续抓�
    int currPage = productList.getCurrPage();
    int nextPage = currPage + 1;
    int totalPage = productList.getTotalPage();
    if (nextPage <= totalPage) {
        String nextUrl = "";
        String currUrl = currRequest.getUrl();
        if (currUrl.indexOf("page=") != -1) {
            nextUrl = StringUtils.replaceOnce(currUrl, "page=" + currPage, "page=" + nextPage);
        } else {
            nextUrl = currUrl + "&" + "page=" + nextPage;
        }
        SchedulerContext.into(currRequest.subRequest(nextUrl));
    }
}
Example 99
Project: gsan-master  File: ValidadorTipoLogradouroCommand.java View source code
@Override
public void execute() throws Exception {
    String tipoLogradouro = linha.get("idTipoLogradouroImovel");
    if (StringUtils.isEmpty(tipoLogradouro)) {
        cadastroImovel.addMensagemErro("Tipo do logradouro do imóvel inválido");
    } else {
        LogradouroTipo tipo = repositorioImovel.pesquisarTipoLogradouro(Integer.valueOf(tipoLogradouro));
        if (tipo == null) {
            cadastroImovel.addMensagemErro("Tipo do logradouro do imóvel inexistente");
        }
    }
}
Example 100
Project: hercules-master  File: TestJsonKeyExtractor.java View source code
@Override
public Iterable<String> extractKeys(EntityWithCollection team) {
    String users = StringUtils.isEmpty(team.getJsonCollection()) ? "{}" : team.getJsonCollection();
    users = users.substring(1, users.length() - 1);
    String[] keys = users.split(",");
    List<String> resultKeys = new ArrayList<String>(keys.length);
    for (String k : keys) {
        resultKeys.add(k.trim());
    }
    return resultKeys;
}
Example 101
Project: HexScape-master  File: GameService.java View source code
public static void removeUnseeableHiddenMarkersInfos(Game game, String userId) {
    for (Player player : game.getPlayers()) {
        if (player != null && player.getArmy() != null) {
            for (CardInstance card : player.getArmy().getCards()) {
                for (MarkerInstance marker : card.getMarkers()) {
                    if (marker instanceof UnknownTypeMarkerInstance) {
                        if (!StringUtils.equals(userId, player.getUserId())) {
                            ((UnknownTypeMarkerInstance) marker).setHiddenMarkerTypeId(null);
                        }
                    }
                }
            }
        }
    }
}