Example usage for org.apache.commons.lang3 StringUtils startsWithIgnoreCase

List of usage examples for org.apache.commons.lang3 StringUtils startsWithIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWithIgnoreCase.

Prototype

public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Case insensitive check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:org.pepstock.jem.ant.tasks.ValueParser.java

/**
 * Parses the value of variables into SCRIPT JCL and loads datasets into data descriptions
 * @param dd data description to load/*ww  w  .j  a  v a2 s. co m*/
 * @param valueParm value of property in metadata
 * @throws AntException if any error occurs
 */
public static final void loadDataDescription(DataDescription dd, String valueParm) throws AntException {
    // trim value
    String value = valueParm.trim();

    // init of variables to load dd
    String[] dsn = null;
    String disposition = null;
    String dataSource = null;
    boolean isSysout = false;
    // this boolean is set to true 
    // because if it's not able to parse the content,
    // the wjole string will be the content of dataset
    boolean isText = true;

    // parses using comma
    String[] stmtTokens = StringUtils.split(value, COMMAND_SEPARATOR);
    if (stmtTokens != null && stmtTokens.length > 0) {
        // scans all tokes
        for (int i = 0; i < stmtTokens.length; i++) {
            String token = stmtTokens[i].trim();
            // is datasetname?
            if (StringUtils.startsWithIgnoreCase(token, DSN_PREFIX)) {
                // gets all string after DSN and =
                String subToken = getValue(token, DSN_PREFIX);
                if (subToken != null) {
                    // sets that is not a text
                    isText = false;

                    String subValue = null;
                    // checks if the content is inside of brackets
                    if (subToken.startsWith("(") && subToken.endsWith(")")) {
                        // gets content inside brackets
                        subValue = StringUtils.removeEnd(StringUtils.removeStart(subToken, "("), ")");
                    } else {
                        // only 1 datasets
                        subValue = subToken;
                    }
                    // parses values
                    dsn = StringUtils.split(subValue, VALUE_SEPARATOR);
                }
            } else if (StringUtils.startsWithIgnoreCase(token, DISP_PREFIX)) {
                // sets that is not a text
                isText = false;
                // saves disposition
                disposition = getValue(token, DISP_PREFIX);
            } else if (StringUtils.startsWithIgnoreCase(token, DATASOURCE_PREFIX)) {
                // sets that is not a text
                isText = false;
                // saves data sourceinfo
                dataSource = getValue(token, DATASOURCE_PREFIX);
            } else if (StringUtils.startsWithIgnoreCase(token, SYSOUT)) {
                // sets that is not a text
                isText = false;
                // sets is a sysout
                isSysout = true;
            }
        }
    }
    // content of file
    if (isText) {
        dd.setDisposition(Disposition.SHR);
        DataSet ds = createDataSet(dd, null, valueParm);
        dd.addDataSet(ds);
    } else {
        // disposition DISP= is mandatory, always
        if (disposition == null) {
            throw new AntException(AntMessage.JEMA072E, dd.getName());
        }
        dd.setDisposition(disposition);

        // if sets SYSOUT but also DSN=, this is not allowed
        if (isSysout && dsn != null) {
            throw new AntException(AntMessage.JEMA073E, dd.getName());
        }
        // sets sysout
        dd.setSysout(isSysout);
        // if not sysout, loads datasets
        // datasource can be set ONLY with 1 dataset
        if (!isSysout && dsn != null) {
            if (dsn.length > 1 && dataSource != null) {
                throw new AntException(AntMessage.JEMA074E, dd.getName());
            }
            // loads all datasets and set datasource
            for (int k = 0; k < dsn.length; k++) {
                DataSet ds = createDataSet(dd, dsn[k], null);
                dd.addDataSet(ds);
                // doesn't check anything because
                // already done before
                if (dataSource != null) {
                    ds.setDatasource(dataSource);
                }
            }
        }
    }
}

From source file:org.pepstock.jem.node.DataPathsManager.java

/**
 * Returns the absolute data path or data path name using file name argument
 * @param fileName file name to use to get info
 * @param names if <code>true</code>, get data path name otherwise absolute data path  
 * @return if names is set to <code>true</code>, get data path name otherwise absolute data path 
 *//* ww  w .j a  va2s  .c  om*/
private String retrieveDataPath(String fileName, boolean name) {
    String file = FilenameUtils
            .normalize(fileName.endsWith(File.separator) ? fileName : fileName + File.separator, true);
    for (Path mp : dataPaths.getPaths()) {
        String pathToCheck = FilenameUtils.normalize(
                mp.getContent().endsWith(File.separator) ? mp.getContent() : mp.getContent() + File.separator,
                true);
        if (StringUtils.startsWithIgnoreCase(file, pathToCheck)) {
            return name ? mp.getName() : mp.getContent();
        }
    }
    return null;
}

From source file:org.phenotips.data.internal.controller.APGARController.java

/**
 * Checks if any relevant field names were selected.
 *
 * @return true if relevant fields were selected, false otherwise
 *///from   www  . j ava2s.  co  m
private boolean hasAnySelected(Collection<String> selectedFieldNames) {
    boolean hasAny = false;
    for (String selectedFieldName : selectedFieldNames) {
        if (StringUtils.startsWithIgnoreCase(selectedFieldName, this.getName())) {
            hasAny = true;
            break;
        }
    }
    return hasAny;
}

From source file:org.rm3l.ddwrt.tiles.status.wan.WANMonthlyTrafficTile.java

@Nullable
@Override/*  w  w  w  . j a v a 2s  .c om*/
protected Loader<NVRAMInfo> getLoader(int id, Bundle args) {

    if (nbRunsLoader <= 0 || mAutoRefreshToggle) {
        setLoadingViewVisibility(View.VISIBLE);
    }

    return new AsyncTaskLoader<NVRAMInfo>(this.mParentFragmentActivity) {

        @Nullable
        @Override
        public NVRAMInfo loadInBackground() {

            try {

                Log.d(LOG_TAG,
                        "Init background loader for " + WANMonthlyTrafficTile.class + ": routerInfo=" + mRouter
                                + " / this.mAutoRefreshToggle= " + mAutoRefreshToggle + " / nbRunsLoader="
                                + nbRunsLoader);

                if (nbRunsLoader > 0 && !mAutoRefreshToggle) {
                    //Skip run
                    Log.d(LOG_TAG, "Skip loader run");
                    throw new DDWRTTileAutoRefreshNotAllowedException();
                }
                nbRunsLoader++;

                @NotNull
                final NVRAMInfo nvramInfo = new NVRAMInfo();

                NVRAMInfo nvramInfoTmp = null;
                try {
                    //noinspection ConstantConditions
                    nvramInfoTmp = NVRAMParser.parseNVRAMOutput(SSHUtils.getManualProperty(mRouter,
                            mGlobalPreferences, "nvram show 2>/dev/null | grep traff[-_]"));
                } finally {
                    if (nvramInfoTmp != null) {
                        nvramInfo.putAll(nvramInfoTmp);
                    }

                }

                traffDataTableBuilder = ImmutableTable.builder();

                if (nvramInfo.isEmpty()) {
                    throw new DDWRTNoDataException("No Data!");
                }

                @SuppressWarnings("ConstantConditions")
                final Set<Map.Entry<Object, Object>> entries = nvramInfo.getData().entrySet();

                for (final Map.Entry<Object, Object> entry : entries) {
                    final Object key;
                    final Object value;
                    if (entry == null || (key = entry.getKey()) == null || (value = entry.getValue()) == null) {
                        continue;
                    }

                    if (!StringUtils.startsWithIgnoreCase(key.toString(), "traff-")) {
                        continue;
                    }

                    final String month = key.toString().replace("traff-", DDWRTCompanionConstants.EMPTY_STRING);

                    final String yearlyTraffData = value.toString();
                    final List<String> yearlyTraffDataList = MONTHLY_TRAFF_DATA_SPLITTER
                            .splitToList(yearlyTraffData);
                    if (yearlyTraffDataList == null || yearlyTraffDataList.isEmpty()) {
                        continue;
                    }

                    int dayNum = 1;
                    for (final String dailyInOutTraffData : yearlyTraffDataList) {
                        if (StringUtils.contains(dailyInOutTraffData, "[")) {
                            continue;
                        }
                        final List<String> dailyInOutTraffDataList = DAILY_TRAFF_DATA_SPLITTER
                                .splitToList(dailyInOutTraffData);
                        if (dailyInOutTraffDataList == null || dailyInOutTraffDataList.size() < 2) {
                            continue;
                        }
                        final String inTraff = dailyInOutTraffDataList.get(0);
                        final String outTraff = dailyInOutTraffDataList.get(1);

                        traffDataTableBuilder.put(month, dayNum++,
                                Lists.newArrayList(Double.parseDouble(inTraff), Double.parseDouble(outTraff)));

                    }
                }

                traffData = traffDataTableBuilder.build();

                return nvramInfo;

            } catch (@NotNull final Exception e) {
                e.printStackTrace();
                return new NVRAMInfo().setException(e);
            }

        }
    };
}

From source file:org.structr.web.maintenance.deploy.PageImportVisitor.java

private void createPage(final Path file, final String fileName) throws IOException, FrameworkException {

    final String name = StringUtils.substringBeforeLast(fileName, ".html");

    try (final Tx tx = app.tx(true, false, false)) {

        final PropertyMap properties = getPropertiesForPage(name);

        if (properties == null) {

            logger.info("Ignoring {} (not in pages.json)", fileName);
        } else {//  w w w . j a v  a  2s.  com

            final Page existingPage = getExistingPage(name);

            if (existingPage != null) {

                deletePage(app, name);
            }

            final String src = new String(Files.readAllBytes(file), Charset.forName("UTF-8"));
            final String contentType = get(properties, StructrApp.key(Page.class, "contentType"), "text/html");

            boolean visibleToPublic = get(properties, GraphObject.visibleToPublicUsers, false);
            boolean visibleToAuth = get(properties, GraphObject.visibleToAuthenticatedUsers, false);

            final Importer importer = new Importer(securityContext, src, null, name, visibleToPublic,
                    visibleToAuth, false);

            // enable literal import of href attributes
            importer.setIsDeployment(true);

            if (StringUtils.startsWithIgnoreCase(src, DoctypeString) && "text/html".equals(contentType)) {

                // Import document starts with <!DOCTYPE> definition, so we treat it as an HTML
                // document and use the Structr HTML importer.

                final boolean parseOk = importer.parse();
                if (parseOk) {

                    logger.info("Importing page {} from {}..", new Object[] { name, fileName });

                    // set comment handler that can parse and apply special Structr comments in HTML source files
                    importer.setCommentHandler(new DeploymentCommentHandler());

                    // parse page
                    final Page newPage = importer.readPage();

                    // remove duplicate elements
                    fixDocumentElements(newPage);

                    // store properties from pages.json
                    newPage.setProperties(securityContext, properties);
                }

            } else {

                // Import document does NOT start with a <!DOCTYPE> definition, so we assume a
                // template or shared component that we need to parse.

                final boolean parseOk = importer.parse(true);
                if (parseOk) {

                    logger.info("Importing page {} from {}..", new Object[] { name, fileName });

                    // set comment handler that can parse and apply special Structr comments in HTML source files
                    importer.setCommentHandler(new DeploymentCommentHandler());

                    // parse page
                    final Page newPage = app.create(Page.class, name);

                    // store properties from pages.json
                    newPage.setProperties(securityContext, properties);

                    // add children
                    importer.createChildNodes(newPage, newPage);
                }
            }
        }

        tx.success();
    }
}

From source file:org.symphonyoss.simplebot.Eliza.java

private void processMessage(Message message) {
    String messageString = message.getMessage();
    if (StringUtils.isNotEmpty(messageString) && StringUtils.isNotBlank(messageString)) {
        MlMessageParser messageParser = new MlMessageParser();
        try {//from www . ja va2s  . com
            messageParser.parseMessage(messageString);
            String text = messageParser.getText();
            if (StringUtils.startsWithIgnoreCase(text, "eliza")) {
                ElizaCommand cmd = getElizaCommand(text);
                switch (cmd) {
                case SAD:
                    sendMLMessage(formatURLText("https://www.youtube.com/watch?v=mLLO2mFy4MU"));
                    break;
                case HUNGRY:
                    sendMessage("Auh? Get some food", MessageSubmission.FormatEnum.TEXT);
                    break;
                case UNKNOWN:
                    break;
                case HAPPY_BD:
                    sendMLMessage(formatURLText("https://www.youtube.com/watch?v=_z-1fTlSDF0"));
                    break;
                case FACT:
                    sendFact();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.symphonyoss.simplebot.LunchBoxBot.java

private void processMessage(Message message) {
    username = message.getFromUserId().toString();
    String messageString = message.getMessage();
    if (StringUtils.isNotEmpty(messageString) && StringUtils.isNotBlank(messageString)) {
        MlMessageParser messageParser = new MlMessageParser();
        try {/*w  w  w . j a  v  a  2s  . c o  m*/
            messageParser.parseMessage(messageString);
            String text = messageParser.getText();
            if (isFeedback == true) {
                processFeedback(text);
                isFeedback = false;
            }

            if (StringUtils.startsWithIgnoreCase(text, "/lunchbox")) {
                LunchBotCommand cmd = getLunchBotCommand(text);

                switch (cmd) {
                case MENU:
                    HashMap lunch = parseLunchMenu(todayDateString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FEEDBACK:
                    isFeedback = true;
                    break;
                case TOMORROW:
                    LocalDate tomorrowDate = LocalDate.from(todayDate.toInstant().atZone(ZoneId.of("UTC")))
                            .plusDays(1);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy,MM,dd");
                    String tomorrowString = tomorrowDate.format(formatter);
                    lunch = parseLunchMenu(tomorrowString);
                    sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body"));
                    break;
                case FORMAT:
                    sendMessage(
                            "- For feedback on individual items on the menu, <item number> -> <number of stars (out of 5)>\n- For feedback on lunch as a whole, <overall> -> <number of stars (out of 5)>, comments (optional)\n\n\nP.S: Please provide complete feedback in a single message with each section separated by a comma");
                    break;
                case OPTIONS:
                    sendMessage(
                            "For today's menu:  '/lunchbox menu' OR '/lunchbox today's menu'\nFor tomorrow's menu: '/lunchbox tomorrow' OR '/lunchbox tomorrow's menu'\nFor tips on format for feedback: '/lunchbox format'\nFor feedback: '/lunchbox feedback' <hit enter and then provide feedback all in one message>\nFor options: '/lunchbox help'\n\n\nP.S: All commands should be typed without quotes");
                    break;
                case UNKNOWN:
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.talend.dataprofiler.core.pattern.PatternLanguageType.java

public static String findLanguageByName(String name) {
    if (name.equalsIgnoreCase(SupportDBUrlType.REDSHIFT.getDBKey())) {
        return SupportDBUrlType.REDSHIFT.getLanguage();
    }/*w ww  . j a va2  s. c o  m*/
    if (name.equalsIgnoreCase(SupportDBUrlType.EXASOL.getDBKey())) {
        return SupportDBUrlType.EXASOL.getLanguage();
    }
    for (PatternLanguageType oneType : values()) {
        // we should consider the name like "Hive | Impala"
        if (name != null && StringUtils.startsWithIgnoreCase(name, oneType.getName())) {
            return oneType.getLiteral();
        }
    }
    // When the type is not supported officially, return the database name.
    return name;
}

From source file:org.talend.dataquality.semantic.api.LocalDictionaryCache.java

private Set<String> doSuggestValues(String categoryName, String input, int num, boolean isPrefixSearch) {
    String jointInput = DictionarySearcher.getJointTokens(input);
    String queryString = isPrefixSearch ? jointInput + "*" : "*" + jointInput + "*";

    final BooleanQuery booleanQuery = new BooleanQuery();
    final Query catQuery = new TermQuery(new Term(DictionarySearcher.F_WORD, categoryName));
    booleanQuery.add(catQuery, BooleanClause.Occur.MUST);
    final Query wildcardQuery = new WildcardQuery(new Term(DictionarySearcher.F_SYNTERM, queryString));
    booleanQuery.add(wildcardQuery, BooleanClause.Occur.MUST);

    Set<String> results = new TreeSet<String>();

    try {//from   w  w  w.j a  v a  2  s.  c  om
        mgr.maybeRefresh();
        IndexSearcher searcher = mgr.acquire();
        IndexReader reader = searcher.getIndexReader();
        TopDocs topDocs = searcher.search(booleanQuery, num);
        mgr.release(searcher);
        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            Document doc = reader.document(topDocs.scoreDocs[i].doc);
            IndexableField[] fields = doc.getFields(DictionarySearcher.F_RAW);
            for (IndexableField f : fields) {
                final String str = f.stringValue();
                if (isPrefixSearch) {
                    if (StringUtils.startsWithIgnoreCase(str, input) || StringUtils
                            .startsWithIgnoreCase(DictionarySearcher.getJointTokens(str), jointInput)) {
                        results.add(str);
                    }
                } else {// infix search
                    if (StringUtils.containsIgnoreCase(str, input) || StringUtils
                            .containsIgnoreCase(DictionarySearcher.getJointTokens(str), jointInput)) {
                        results.add(str);
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.trace(e.getMessage(), e);
    }
    return results;
}

From source file:org.tdwg.dwca.wikipedia.taxonbox.TaxonInfoBase.java

public void postprocess(WikiArticle page, Language lang) {
    // set classification and scientific name from flexible rank names
    for (Name n : names) {
        if (n != null) {
            setNameIfLowest(n);/*from www  .ja  v a 2 s.c  o m*/
            if (n.getRank() != null && n.getScientific() != null) {
                if (n.getRank() == Rank.Kingdom) {
                    setKingdom(n.getScientific());
                } else if (n.getRank() == Rank.Phylum) {
                    setPhylum(n.getScientific());
                } else if (n.getRank() == Rank.Class) {
                    setClazz(n.getScientific());
                } else if (n.getRank() == Rank.Order) {
                    setOrder(n.getScientific());
                } else if (n.getRank() == Rank.Family) {
                    setFamily(n.getScientific());
                } else if (n.getRank() == Rank.Genus) {
                    setGenus(n.getScientific());
                } else if (n.getRank() == Rank.Subgenus) {
                    setSubgenus(n.getScientific());
                }
            }
        }
    }

    // replace genus abbreviation in names?
    setScientificName(expandName(getScientificName()));
    List<String> syns = Lists.newArrayList();

    // expand synonyms
    for (String syn : getSynonyms()) {
        syns.add(expandName(syn));
    }
    getSynonyms().clear();
    getSynonyms().addAll(syns);

    // make sure we dont have wrong kingdom pages - we keep the known pages
    if (getScientificName() != null) {
        Kingdom kingdom = null;
        for (Kingdom k : Kingdom.values()) {
            if (StringUtils.startsWithIgnoreCase(getScientificName(), k.name())) {
                kingdom = k;
                break;
            }
        }
        // try virus separately
        if (StringUtils.startsWithIgnoreCase(getScientificName(), "virus")) {
            kingdom = Kingdom.VIRUSES;
        }

        if (kingdom != null) {
            // seems we got a kingdom page - make sure its the real one!
            if (!page.getTitle().equalsIgnoreCase(knownPageTitle(kingdom, lang))) {
                log.warn("Wrong kingdom page {} found. Ignore");
                setScientificName(null);
                setRank(null);
            }
        }
    }
}