Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:net.douglasthrift.bigscreenbot.BigScreenBot.java

private void doCommandFromMessage(String channel, String sender, String login, String hostname,
        String message) {/*from  w w  w  .j a v  a  2 s. co m*/
    boolean admin = matchNickMasks(sender, login, hostname, admins);

    synchronized (bans) {
        if (!admin && (matchNickMasks(sender, login, hostname, bans.values()) || !isNickInChannels(sender)))
            return;
    }

    message = Colors.removeFormattingAndColors(message);

    String[] arguments = StringUtils.split(message, null, 2);
    String argument = "";
    Command command = null;

    if (arguments.length != 0) {
        if (channel == null) {
            if (isValidURL(arguments[0])) {
                fling(channel, sender, admin, arguments);

                return;
            }
        } else if (arguments.length == 2
                && Pattern.compile("^" + Pattern.quote(getNick()) + ":?$", Pattern.CASE_INSENSITIVE)
                        .matcher(arguments[0]).matches()
                && isValidURL(StringUtils.split(arguments[1], null, 2)[0])) {
            fling(channel, sender, admin, Arrays.copyOfRange(arguments, 1, arguments.length));

            return;
        }

        argument = arguments[0].toLowerCase();

        if (argument.startsWith("!"))
            argument = argument.substring(1);

        command = commands.get(argument);
    }

    if (channel != null) {
        if (command == null)
            return;

        if (!admin && command.isAdmin())
            return;

        if (!command.isChannel())
            return;
    } else {
        if (command == null) {
            sendMessage(channel, sender, String.format("unknown command (\"%1$s\"); try \"help\"", argument));

            return;
        }

        if (!admin && command.isAdmin()) {
            sendMessage(channel, sender, String.format("unauthorized command (\"%1$s\")", argument));

            return;
        }

        if (!command.isPrivate()) {
            sendMessage(channel, sender, String.format("inappropriate command (\"%1$s\")", argument));

            return;
        }
    }

    command.execute(channel, sender, admin, arguments.length == 2 ? arguments[1] : "");
}

From source file:com.hichinaschool.flashcards.libanki.Models.java

public void renameField(JSONObject m, JSONObject field, String newName) {
    mCol.modSchema();//  ww  w.  j av  a2s .c o m
    try {
        String pat = String.format("\\{\\{([:#^/]|[^:#/^}][^:}]*?:|)%s\\}\\}",
                Pattern.quote(field.getString("name")));
        if (newName == null) {
            newName = "";
        }
        String repl = "{{$1" + newName + "}}";

        JSONArray tmpls = m.getJSONArray("tmpls");
        for (int i = 0; i < tmpls.length(); ++i) {
            JSONObject t = tmpls.getJSONObject(i);
            for (String fmt : new String[] { "qfmt", "afmt" }) {
                if (!newName.equals("")) {
                    t.put(fmt, t.getString(fmt).replaceAll(pat, repl));
                } else {
                    t.put(fmt, t.getString(fmt).replaceAll(pat, ""));
                }
            }
        }
        field.put("name", newName);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    save(m);
}

From source file:org.terasoluna.gfw.web.pagination.PaginationTagTest.java

/**
 * customized case 5./*  w  ww  . ja va  2 s.c o  m*/
 * 
 * <pre>
 * -innerElement is span
 * </pre>
 */
@Test
public void testDoStartTagInternal15() throws Exception {

    Page<String> page = mock(Page.class);
    // set mock behavior
    when(page.getNumber()).thenReturn(20);
    when(page.getSize()).thenReturn(10);
    when(page.getTotalPages()).thenReturn(100);
    when(page.getTotalElements()).thenReturn(1000L);

    tag.setPage(page);

    // customize
    tag.setOuterElement("p");
    tag.setInnerElement("span");

    int ret = tag.doStartTagInternal();

    System.out.println(getOutput().replaceAll(Pattern.quote("\""), "\\\\\""));

    assertThat(ret, is(TagSupport.EVAL_BODY_INCLUDE));
    String expected = "<p><span><a href=\"?page=0&size=10\">&lt;&lt;</a></span><span><a href=\"?page=19&size=10\">&lt;</a></span><span><a href=\"?page=15&size=10\">16</a></span><span><a href=\"?page=16&size=10\">17</a></span><span><a href=\"?page=17&size=10\">18</a></span><span><a href=\"?page=18&size=10\">19</a></span><span><a href=\"?page=19&size=10\">20</a></span><span class=\"active\"><a href=\"javascript:void(0)\">21</a></span><span><a href=\"?page=21&size=10\">22</a></span><span><a href=\"?page=22&size=10\">23</a></span><span><a href=\"?page=23&size=10\">24</a></span><span><a href=\"?page=24&size=10\">25</a></span><span><a href=\"?page=21&size=10\">&gt;</a></span><span><a href=\"?page=99&size=10\">&gt;&gt;</a></span></p>";
    assertThat(getOutput(), is(expected));
}

From source file:com.csipsimple.utils.PreferencesWrapper.java

public String[] getCodecList() {
    return TextUtils.split(prefs.getString(CODECS_LIST, ""), Pattern.quote(CODECS_SEPARATOR));
}

From source file:com.ichi2.libanki.test.SchedTestCase.java

@MediumTest
public void test_finished() {
    Collection d = Shared.getEmptyDeck(getInstrumentation().getContext());
    assertNotNull(d);//from w w  w . j av a2  s.  c  om
    // nothing due
    String finishedMsg = d.getSched().finishedMsg(getInstrumentation().getTargetContext()).toString();
    MoreAsserts.assertContainsRegex(Pattern.quote("Congratulations"), finishedMsg);
    MoreAsserts.assertNotContainsRegex(Pattern.quote("limit"), finishedMsg);
    Note f = d.newNote();
    f.setitem("Front", "one");
    f.setitem("Back", "two");
    d.addNote(f);
    // have a new card
    finishedMsg = d.getSched().finishedMsg(getInstrumentation().getTargetContext()).toString();
    MoreAsserts.assertContainsRegex(Pattern.quote("new cards available"), finishedMsg);
    // turn it into a review
    d.reset();
    Card c = f.cards().get(0);
    c.startTimer();
    d.getSched().answerCard(c, 3);
    // nothing should be due tomorrow, as it's due in a week
    finishedMsg = d.getSched().finishedMsg(getInstrumentation().getTargetContext()).toString();
    MoreAsserts.assertContainsRegex(Pattern.quote("Congratulations"), finishedMsg);
    MoreAsserts.assertNotContainsRegex(Pattern.quote("limit"), finishedMsg);
}

From source file:com.hp.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchListItems(String logicalListName, String term, long workspaceId, boolean multiValue,
        boolean extensible) {
    int defaultSize = 10;
    JSONObject ret = new JSONObject();

    MqmRestClient client;//from www .j  a v a 2s  . c  o m
    try {
        client = createClient();
    } catch (ClientException e) {
        logger.warn(PRODUCT_NAME + " connection failed", e);
        return error(e.getMessage(), e.getLink());
    }
    try {

        PagedList<ListItem> listItemPagedList = client.queryListItems(logicalListName, term, workspaceId, 0,
                defaultSize);
        List<ListItem> listItems = listItemPagedList.getItems();
        boolean moreResults = listItemPagedList.getTotalCount() > listItems.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        if (!multiValue) {
            String quotedTerm = Pattern.quote(term.toLowerCase());
            if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
                JSONObject notSpecifiedItemJson = new JSONObject();
                notSpecifiedItemJson.put("id", -1);
                notSpecifiedItemJson.put("text", NOT_SPECIFIED);
                retArray.add(notSpecifiedItemJson);
            }
        }

        for (ListItem item : listItems) {
            if (!toBeFiltered(item)) {
                JSONObject itemJson = new JSONObject();
                itemJson.put("id", item.getId());
                itemJson.put("text", item.getName());
                retArray.add(itemJson);
            }

        }
        // we shall use "if (extensible){}" on following line, but we do not have UI ready for the case: multiValue = true & extensible = true
        if (extensible && !multiValue) {
            //if exactly one item matches, we do not want to bother user with "new value" item
            if ((listItems.size() != 1)
                    || (!listItems.get(0).getName().toLowerCase().equals(term.toLowerCase()))) {
                retArray.add(createNewValueJson("0"));
            }
        }

        ret.put("results", retArray);
    } catch (RequestException e) {
        logger.warn("Failed to retrieve list items", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:com.ichi2.libanki.Models.java

public void renameField(JSONObject m, JSONObject field, String newName) throws ConfirmModSchemaException {
    mCol.modSchema(true);//from w ww  . ja v a  2s. com
    try {
        String pat = String.format("\\{\\{([^{}]*)([:#^/]|[^:#/^}][^:}]*?:|)%s\\}\\}",
                Pattern.quote(field.getString("name")));
        if (newName == null) {
            newName = "";
        }
        String repl = "{{$1$2" + newName + "}}";

        JSONArray tmpls = m.getJSONArray("tmpls");
        for (int i = 0; i < tmpls.length(); ++i) {
            JSONObject t = tmpls.getJSONObject(i);
            for (String fmt : new String[] { "qfmt", "afmt" }) {
                if (!newName.equals("")) {
                    t.put(fmt, t.getString(fmt).replaceAll(pat, repl));
                } else {
                    t.put(fmt, t.getString(fmt).replaceAll(pat, ""));
                }
            }
        }
        field.put("name", newName);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    save(m);
}

From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java

/**
 * Check if a value is in the given keyword(s)
 * If no keyword(s) given must return true
 *
 * @param value String/*  ww w .  j ava2  s.c  om*/
 * @param keywords String[]
 * @param caseSensitive boolean
 * @return boolean
 */
static boolean matchKeyword(String value, String[] keywords, boolean caseSensitive) {
    if (keywords != null) {
        String regexpStart = null;
        if (caseSensitive)
            regexpStart = REGEXP_SENSITIVE_START;
        else
            regexpStart = REGEXP_INSENSITIVE_START;

        for (int i = 0; i < keywords.length; i++) {
            if (!value.matches(regexpStart + Pattern.quote(keywords[i]) + REGEXP_END))
                return false;
        }

        // all keywords match return true
        return true;
    }

    // if no keyword or keywords given
    // we must not filter this record so will return true
    return true;
}

From source file:de.iteratec.iteraplan.businesslogic.service.SearchServiceImpl.java

/**
 * Adds the information where the search string was found to the SearchRowDTO.
 * /*from w  w w  . ja v a2 s.  c  o m*/
 * @param container
 * @param line
 * @param highlighter
 *          A match highlighter that places markers at the matched words in the object
 */
private void setFoundIn(SearchRowDTO container, Object[] line, Highlighter highlighter) {
    // retrieve the locale of the user
    Locale locale = UserContext.getCurrentLocale();
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);

    List<String> foundIn = new ArrayList<String>();
    for (int m = 2; m < line.length; m++) {

        if (line[m] != null) {
            String text = line[m].toString();

            if (!StringUtils.isEmpty(text)) {
                if (m != 2) {
                    String foundInHighlighted = getFoundInHighlightedString(highlighter, analyzer, text);
                    if (foundInHighlighted != null && foundInHighlighted.compareTo("") != 0) {
                        foundIn.add(MessageAccess.getStringOrNull(LINE_INDEX_TO_MSG_KEY.get(Integer.valueOf(m)),
                                locale) + ": " + foundInHighlighted);
                    }
                } // If found in attributeString
                else {
                    String[] splittedText = text.split(Pattern.quote("^^^"));
                    for (int n = 0; n < splittedText.length; n++) {
                        String foundInHighlighted = getFoundInHighlightedString(highlighter, analyzer,
                                splittedText[n]);
                        if (foundInHighlighted != null && foundInHighlighted.compareTo("") != 0) {
                            foundIn.add(foundInHighlighted);
                        }
                    }
                }
            }
            container.setFoundIn(foundIn);
        }
    }
}

From source file:adalid.commons.util.StrUtils.java

public static String getIdentifier(String string, String separator) {
    if (string == null) {
        return null;
    }//  ww  w . j a va  2 s  .com
    String sep = separator == null ? DEFAULT_SEPARATOR
            : separator.replaceAll(INVALID_SEPARATOR, DEFAULT_SEPARATOR);
    String invalidCharactersRegex = "[^a-zA-Z0-9]";
    String severalSeparatorsRegex = sep.length() == 0 ? null : Pattern.quote(sep) + "+";
    String dhxless = dhxless(string, sep, invalidCharactersRegex, severalSeparatorsRegex);
    return dhxless;
}