Example usage for java.util.regex Matcher end

List of usage examples for java.util.regex Matcher end

Introduction

In this page you can find the example usage for java.util.regex Matcher end.

Prototype

public int end() 

Source Link

Document

Returns the offset after the last character matched.

Usage

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

public void resolveKnownLicensesByText(LicenseFile licenseFile) {
    List<KnownLicense> foundLicenses = new ArrayList<>();
    String licenseText = licenseFile.getText();
    if (knownLicenses.getLicenses() == null) {
        return;/*  w  ww  . j ava2s .c om*/
    }
    SortedMap<TextVariant, KnownLicense> textVariantsBySize = new TreeMap<>(new Comparator<TextVariant>() {
        @Override
        public int compare(TextVariant o1, TextVariant o2) {
            return o2.getText().length() - o1.getText().length();
        }
    });
    for (KnownLicense knownLicense : knownLicenses.getLicenses().values()) {
        for (TextVariant textVariant : knownLicense.getTextVariants()) {
            textVariantsBySize.put(textVariant, knownLicense);
        }
    }
    for (SortedMap.Entry<TextVariant, KnownLicense> textVariantBySizeEntry : textVariantsBySize.entrySet()) {
        Matcher textVariantMatcher = textVariantBySizeEntry.getKey().getCompiledTextPattern()
                .matcher(licenseText);
        if (textVariantMatcher.find()) {
            foundLicenses.add(textVariantBySizeEntry.getValue());
            licenseText = licenseText.substring(textVariantMatcher.end());
            break;
        }
    }
    if (foundLicenses.size() == 0) {
        System.out.println("No known license found for license file " + licenseFile.getFileName());
    }
    licenseFile.setKnownLicenses(foundLicenses);
    if (StringUtils.isNotBlank(licenseText)) {
        licenseFile.setAdditionalLicenseText(licenseText);
    }
}

From source file:com.nttec.everychan.api.util.WakabaReader.java

/**
 *  ? ?   ,  HTML-?, ? ? &lt;span class="filesize"&gt;.
 * ?   ,     ?? {@link #currentAttachments}
 *  ??  {link {@link ThreadModel#attachmentsCount})  {@link #currentThread}.<br>
 *  ?    ??  /* ww  w .  jav a 2 s.c o m*/
 * (? , ??  ,   ,   ??,  ?, ? ?).
 */
protected void parseAttachment(String html) {
    AttachmentModel attachment = new AttachmentModel();
    attachment.size = -1;

    int startHref, endHref;
    if ((startHref = html.indexOf("href=\"")) != -1 && (endHref = html.indexOf('\"', startHref + 6)) != -1) {
        attachment.path = html.substring(startHref + 6, endHref);
        String pathLower = attachment.path.toLowerCase(Locale.US);
        if (pathLower.endsWith(".jpg") || pathLower.endsWith(".jpeg") || pathLower.endsWith(".png"))
            attachment.type = AttachmentModel.TYPE_IMAGE_STATIC;
        else if (pathLower.endsWith(".gif"))
            attachment.type = AttachmentModel.TYPE_IMAGE_GIF;
        else if (pathLower.endsWith(".svg") || pathLower.endsWith(".svgz"))
            attachment.type = AttachmentModel.TYPE_IMAGE_SVG;
        else if (pathLower.endsWith(".webm") || pathLower.endsWith(".mp4") || pathLower.endsWith(".ogv"))
            attachment.type = AttachmentModel.TYPE_VIDEO;
        else if (pathLower.endsWith(".mp3") || pathLower.endsWith(".ogg"))
            attachment.type = AttachmentModel.TYPE_AUDIO;
        else if (pathLower.startsWith("http") && (pathLower.contains("youtube.")))
            attachment.type = AttachmentModel.TYPE_OTHER_NOTFILE;
        else
            attachment.type = AttachmentModel.TYPE_OTHER_FILE;
    } else {
        return;
    }

    Matcher byteSizeMatcher = ATTACHMENT_SIZE_PATTERN.matcher(html);
    while (byteSizeMatcher.find()) {
        try {
            String digits = byteSizeMatcher.group(1).replace(',', '.');
            int multiplier = 1;
            String prefix = byteSizeMatcher.group(2);
            if (prefix != null) {
                if (prefix.equalsIgnoreCase("") || prefix.equalsIgnoreCase("k"))
                    multiplier = 1024;
                else if (prefix.equalsIgnoreCase("") || prefix.equalsIgnoreCase("m"))
                    multiplier = 1024 * 1024;
            }
            int value = Math.round(Float.parseFloat(digits) / 1024 * multiplier);
            attachment.size = value;

            char nextChar = ' ';
            int index = byteSizeMatcher.end();
            while (index < html.length() && nextChar <= ' ')
                nextChar = html.charAt(index++);
            if (nextChar == ',')
                break;
        } catch (NumberFormatException e) {
        }
    }

    Matcher pxSizeMatcher = ATTACHMENT_PX_SIZE_PATTERN.matcher(html);
    int indexEndPxSize = -1;
    while (pxSizeMatcher.find()) {
        try {
            int width = Integer.parseInt(pxSizeMatcher.group(1));
            int height = Integer.parseInt(pxSizeMatcher.group(2));
            attachment.width = width;
            attachment.height = height;
            indexEndPxSize = pxSizeMatcher.end();

            char nextChar = ' ';
            int index = pxSizeMatcher.end();
            while (index < html.length() && nextChar <= ' ')
                nextChar = html.charAt(index++);
            if (nextChar == ',')
                break;
        } catch (NumberFormatException e) {
        }
    }

    if (indexEndPxSize != -1) {
        Matcher originalNameMatcher = ATTACHMENT_ORIGINAL_NAME_PATTERN.matcher(html);
        if (originalNameMatcher.find(indexEndPxSize)) {
            String originalName = originalNameMatcher.group(1).trim();
            if (originalName != null && originalName.length() > 0) {
                attachment.originalName = StringEscapeUtils.unescapeHtml4(originalName);
            }
        }
    }

    ++currentThread.attachmentsCount;
    currentAttachments.add(attachment);
}

From source file:com.miz.functions.MizLib.java

public static String getNameFromFilename(String input) {
    int lastIndex = 0;

    Pattern searchPattern = Pattern.compile(YEAR_PATTERN);
    Matcher searchMatcher = searchPattern.matcher(input);

    while (searchMatcher.find())
        lastIndex = searchMatcher.end();

    if (lastIndex > 0)
        try {//from  w ww. ja  v a  2s  . co  m
            return input.substring(0, lastIndex - 4);
        } catch (Exception e) {
        }

    return input;
}

From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java

/**
 * Retrieces the category of the article
 * from its content, and more particularly
 * from its first sentence, which generally
 * takes the following form in biographies:
 * "Firstname Lastname (19xx-19xx) was/is a politician/artist/etc."
 * //  w  w w  .ja  va  2s. co m
 * @param article
 *       Article to be processed.
 * @return
 *       The identified categories, possibly an empty list if none
 *       could be identified.
 */
public List<ArticleCategory> getArticleCategoriesFromContent(Article article) {
    logger.log("Using the article content to retrieve its categories");
    Set<ArticleCategory> categories = new TreeSet<ArticleCategory>();
    logger.increaseOffset();

    // get first sentence
    String text = article.getRawText();
    String firstSentence = null;
    Pattern pattern = Pattern.compile("[a-zA-Z0-9]{3,}\\. ");
    Matcher matcher = pattern.matcher(text);
    if (!matcher.find())
        logger.log("Could not find the first sentence of the article");
    else {
        int i = matcher.end();
        firstSentence = text.substring(0, i);
        logger.log("First sentence of the article: \"" + firstSentence + "\"");

        // identify state verb (to be)
        int index = firstSentence.length();
        String verb = null;
        for (String v : STATE_VERBS) {
            pattern = Pattern.compile("[^a-zA-Z0-9]" + v + "[^a-zA-Z0-9]");
            matcher = pattern.matcher(firstSentence);
            if (matcher.find()) {
                i = matcher.start();
                if (i > -1 && i < index) {
                    index = i;
                    verb = v;
                }
            }
        }
        if (verb == null)
            logger.log("WARNING: could not find any state verb in the first sentence");
        else {
            logger.log("State verb detected in the sentence: '" + verb + "'");

            // look for key words located in the second part of the sentence (after the verb)
            firstSentence = firstSentence.substring(index + verb.length());
            logger.log("Focusing on the end of the sentence: \"" + firstSentence + "\"");
            logger.increaseOffset();
            String temp[] = firstSentence.split("[^a-zA-Z0-9]");
            for (String key : temp) {
                if (!key.isEmpty()) {
                    ArticleCategory cat = CONTENT_CONVERSION_MAP.get(key);
                    if (cat == null) {
                        logger.log(key + ": no associated category");
                    } else {
                        categories.add(cat);
                        logger.log(key + ": category " + cat);
                    }
                }
            }
            logger.decreaseOffset();
        }
    }

    List<ArticleCategory> result = new ArrayList<ArticleCategory>(categories);
    Collections.sort(result);
    logger.decreaseOffset();
    logger.log("detected categories: " + result.toString());
    return result;
}

From source file:com.miz.functions.MizLib.java

public static String decryptYear(String input) {
    String result = "";
    Pattern searchPattern = Pattern.compile(YEAR_PATTERN);
    Matcher searchMatcher = searchPattern.matcher(input);

    while (searchMatcher.find()) {
        try {//from www . ja v  a 2 s . c  o  m
            int lastIndex = searchMatcher.end();
            result = input.substring(lastIndex - 4, lastIndex);
        } catch (Exception e) {
        }
    }

    return result;
}

From source file:TimeSpan.java

/**
 * Creates a time span using the date string to specify the time units and
 * amounts.  Time units are specified using a single lower case letter of
 * the word for the time unit, e.g. {@code y} for year, {@code m} for month.
 *
 * @param timespan a string containing numbers each followed by a single
 *        character to denote the time unit
 *
 * @throws IllegalArgumentException if <ul> <li> any of the parameters are
 *         negative <li> if any of the time units are specified more than
 *         once</ul>/*from   w  w w .  j a v a2s.  c o m*/
 */
public TimeSpan(String timespan) {

    Matcher matcher = TIME_SPAN_PATTERN.matcher(timespan);

    // Keep track of which time units have been set so far using a bit flag
    // pattern.  Each of the 5 units is stored as a single bit in order of
    // length, with longest first.
    int unitBitFlags = 0;

    // Assign default values of 0 to all of the time ranges before hand,
    // then overwite those with what data the timespan string contains
    int y = 0;
    int m = 0;
    int w = 0;
    int d = 0;
    int h = 0;

    int prevEnd = 0;
    while (matcher.find()) {
        // check that the next time unit has a proper format by ensuring
        // that all the patterns occur with no character gaps, e.g. 30d is
        // valid but 30dd will cause an error from the extra 'd'.
        if (matcher.start() != prevEnd) {
            throw new IllegalArgumentException("invalid time unit format: " + timespan);
        }
        prevEnd = matcher.end();
        String lengthStr = timespan.substring(matcher.start(), matcher.end() - 1);
        int length = Integer.parseInt(lengthStr);
        checkDuration(length);
        char timeUnit = timespan.charAt(matcher.end() - 1);

        // Update the appropriate time based on the unit
        switch (timeUnit) {
        case 'y':
            checkSetTwice(unitBitFlags, 0, "years");
            unitBitFlags |= (1 << 0);
            y = length;
            break;
        case 'm':
            checkSetTwice(unitBitFlags, 1, "months");
            unitBitFlags |= (1 << 1);
            m = length;
            break;
        case 'w':
            checkSetTwice(unitBitFlags, 2, "weeks");
            unitBitFlags |= (1 << 2);
            w = length;
            break;
        case 'd':
            checkSetTwice(unitBitFlags, 3, "days");
            unitBitFlags |= (1 << 3);
            d = length;
            break;
        case 'h':
            checkSetTwice(unitBitFlags, 4, "hours");
            unitBitFlags |= (1 << 4);
            h = length;
            break;
        default:
            throw new IllegalArgumentException("Unknown time unit: " + timeUnit);
        }
    }

    // update the final variables;
    years = y;
    months = m;
    weeks = w;
    days = d;
    hours = h;
}

From source file:com.hurence.logisland.processor.mailer.MailerProcessor.java

/**
 * This parses the HTML template to//from   www .  j a  v  a 2s.  c o m
 * - get the list of needed parameters (${xxx} parameters in the template, so get the foo, bar etc variables)
 * - create a usable template using the MessageFormat system (have strings with ${0}, ${1} instead of ${foo}, ${bar})
 * @param htmlTemplate
 */
private void prepareTemplateAndParameters(String htmlTemplate) {
    Pattern pattern = Pattern.compile("\\$\\{(.+?)}"); // Detect ${...} sequences
    Matcher matcher = pattern.matcher(htmlTemplate);

    // To construct a new template with ${0}, ${1} fields ..
    StringBuilder buffer = new StringBuilder();
    int previousStart = 0;
    int currentParameterIndex = 0;

    // Loop through the parameters in the template
    while (matcher.find()) {
        String parameter = matcher.group(1);

        String stringBeforeCurrentParam = htmlTemplate.substring(previousStart, matcher.start());

        // Add string before parameter
        buffer.append(stringBeforeCurrentParam);
        // Replace parameter with parameter index
        buffer.append("{" + currentParameterIndex + "}");

        // Save current parameter name in the list
        parameterNames.add(parameter);

        previousStart = matcher.end();
        currentParameterIndex++;
    }

    // Add string after the last parameter
    String stringAfterLastParam = htmlTemplate.substring(previousStart);
    buffer.append(stringAfterLastParam);

    // Create the HTML form
    htmlForm = new MessageFormat(buffer.toString());
}

From source file:com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.java

private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args,
        final int actionType) {
    // in a first time just improve replacement with a String (not a function)
    if (RA_REPLACE == actionType && args.length == 2 && (args[1] instanceof String)) {
        final String thisString = Context.toString(thisObj);
        String replacement = (String) args[1];
        final Object arg0 = args[0];
        if (arg0 instanceof String) {
            replacement = REPLACE_PATTERN.matcher(replacement).replaceAll("\\$");
            // arg0 should *not* be interpreted as a RegExp
            return StringUtils.replaceOnce(thisString, (String) arg0, replacement);
        } else if (arg0 instanceof NativeRegExp) {
            try {
                final NativeRegExp regexp = (NativeRegExp) arg0;
                final RegExpData reData = new RegExpData(regexp);
                final String regex = reData.getJavaPattern();
                final int flags = reData.getJavaFlags();
                final Pattern pattern = Pattern.compile(regex, flags);
                final Matcher matcher = pattern.matcher(thisString);
                return doReplacement(thisString, replacement, matcher, reData.hasFlag('g'));
            } catch (final PatternSyntaxException e) {
                LOG.warn(e.getMessage(), e);
            }/*ww  w  .  j  a  v a  2s. c o  m*/
        }
    } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
        if (args.length == 0) {
            return null;
        }
        final Object arg0 = args[0];
        final String thisString = Context.toString(thisObj);
        final RegExpData reData;
        if (arg0 instanceof NativeRegExp) {
            reData = new RegExpData((NativeRegExp) arg0);
        } else {
            reData = new RegExpData(Context.toString(arg0));
        }

        final Pattern pattern = Pattern.compile(reData.getJavaPattern(), reData.getJavaFlags());
        final Matcher matcher = pattern.matcher(thisString);

        final boolean found = matcher.find();
        if (RA_SEARCH == actionType) {
            if (found) {
                setProperties(matcher, thisString, matcher.start(), matcher.end());
                return matcher.start();
            }
            return -1;
        }

        if (!found) {
            return null;
        }
        final int index = matcher.start(0);
        final List<Object> groups = new ArrayList<>();
        if (reData.hasFlag('g')) { // has flag g
            groups.add(matcher.group(0));
            setProperties(matcher, thisString, matcher.start(0), matcher.end(0));

            while (matcher.find()) {
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
            }
        } else {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                Object group = matcher.group(i);
                if (group == null) {
                    group = Context.getUndefinedValue();
                }
                groups.add(group);
            }

            setProperties(matcher, thisString, matcher.start(), matcher.end());
        }
        final Scriptable response = cx.newArray(scope, groups.toArray());
        // the additional properties (cf ECMA script reference 15.10.6.2 13)
        response.put("index", response, Integer.valueOf(index));
        response.put("input", response, thisString);
        return response;
    }

    return wrappedAction(cx, scope, thisObj, args, actionType);
}

From source file:lineage2.gameserver.network.clientpackets.Say2C.java

/**
 * Method runImpl./* w ww .j a  v  a2s. co m*/
 */
@Override
protected void runImpl() {
    Player activeChar = getClient().getActiveChar();
    if (activeChar == null) {
        return;
    }
    if ((_type == null) || (_text == null) || (_text.length() == 0)) {
        activeChar.sendActionFailed();
        return;
    }
    _text = _text.replaceAll("\\\\n", "\n");
    if (_text.contains("\n")) {
        String[] lines = _text.split("\n");
        _text = StringUtils.EMPTY;
        for (int i = 0; i < lines.length; i++) {
            lines[i] = lines[i].trim();
            if (lines[i].length() == 0) {
                continue;
            }
            if (_text.length() > 0) {
                _text += "\n  >";
            }
            _text += lines[i];
        }
    }
    if (_text.length() == 0) {
        activeChar.sendActionFailed();
        return;
    }
    if ((_text.length() > 0) && (_text.charAt(0) == '.')) {
        String fullcmd = _text.substring(1).trim();
        String command = fullcmd.split("\\s+")[0];
        String args = fullcmd.substring(command.length()).trim();
        if (command.length() > 0) {
            IVoicedCommandHandler vch = VoicedCommandHandler.getInstance().getVoicedCommandHandler(command);
            if (vch != null) {
                vch.useVoicedCommand(command, activeChar, args);
                return;
            }
        }
        activeChar.sendMessage(new CustomMessage("common.command404", activeChar));
        return;
    } else if (_text.startsWith("==")) {
        String expression = _text.substring(2);
        Expression expr = null;
        if (!expression.isEmpty()) {
            try {
                expr = ExpressionTree.parse(expression);
            } catch (ExpressionParseException ignored) {
            }
            if (expr != null) {
                double result;
                try {
                    VarMap vm = new VarMap();
                    vm.setValue("adena", activeChar.getAdena());
                    result = expr.eval(vm, null);
                    activeChar.sendMessage(expression);
                    activeChar.sendMessage("=" + Util.formatDouble(result, "NaN", false));
                } catch (Exception ignored) {
                }
            }
        }
        return;
    }
    if ((Config.CHATFILTER_MIN_LEVEL > 0) && ArrayUtils.contains(Config.CHATFILTER_CHANNELS, _type.ordinal())
            && (activeChar.getLevel() < Config.CHATFILTER_MIN_LEVEL)) {
        if (Config.CHATFILTER_WORK_TYPE == 1) {
            _type = ChatType.ALL;
        } else if (Config.CHATFILTER_WORK_TYPE == 2) {
            activeChar.sendMessage(new CustomMessage("chat.NotHavePermission", activeChar)
                    .addNumber(Config.CHATFILTER_MIN_LEVEL));
            return;
        }
    }
    boolean globalchat = (_type != ChatType.ALLIANCE) && (_type != ChatType.CLAN) && (_type != ChatType.PARTY);
    if ((globalchat || ArrayUtils.contains(Config.BAN_CHANNEL_LIST, _type.ordinal()))
            && (activeChar.getNoChannel() != 0)) {
        if ((activeChar.getNoChannelRemained() > 0) || (activeChar.getNoChannel() < 0)) {
            if (activeChar.getNoChannel() > 0) {
                int timeRemained = Math.round(activeChar.getNoChannelRemained() / 60000);
                activeChar.sendMessage(
                        new CustomMessage("common.ChatBanned", activeChar).addNumber(timeRemained));
            } else {
                activeChar.sendMessage(new CustomMessage("common.ChatBannedPermanently", activeChar));
            }
            activeChar.sendActionFailed();
            return;
        }
        activeChar.updateNoChannel(0);
    }
    if (globalchat) {
        if (Config.ABUSEWORD_REPLACE) {
            if (Config.containsAbuseWord(_text)) {
                _text = Config.ABUSEWORD_REPLACE_STRING;
                activeChar.sendActionFailed();
            }
        } else if (Config.ABUSEWORD_BANCHAT && Config.containsAbuseWord(_text)) {
            activeChar.sendMessage(new CustomMessage("common.ChatBanned", activeChar)
                    .addNumber(Config.ABUSEWORD_BANTIME * 60));
            Log.add(activeChar + ": " + _text, "abuse");
            activeChar.updateNoChannel(Config.ABUSEWORD_BANTIME * 60000);
            activeChar.sendActionFailed();
            return;
        }
    }
    Matcher m = EX_ITEM_LINK_PATTERN.matcher(_text);
    ItemInstance item;
    int objectId;
    while (m.find()) {
        objectId = Integer.parseInt(m.group(1));
        item = activeChar.getInventory().getItemByObjectId(objectId);
        if (item == null) {
            activeChar.sendActionFailed();
            break;
        }
        ItemInfoCache.getInstance().put(item);
    }
    String translit = activeChar.getVar("translit");
    if (translit != null) {
        m = SKIP_ITEM_LINK_PATTERN.matcher(_text);
        StringBuilder sb = new StringBuilder();
        int end = 0;
        while (m.find()) {
            sb.append(
                    Strings.fromTranslit(_text.substring(end, end = m.start()), translit.equals("tl") ? 1 : 2));
            sb.append(_text.substring(end, end = m.end()));
        }
        _text = sb.append(
                Strings.fromTranslit(_text.substring(end, _text.length()), translit.equals("tl") ? 1 : 2))
                .toString();
    }
    Log.LogChat(_type.name(), activeChar.getName(), _target, _text);
    Say2 cs = new Say2(activeChar.getObjectId(), _type, activeChar.getName(), _text);
    switch (_type) {
    case TELL:
        Player receiver = World.getPlayer(_target);
        if ((receiver == null) && Config.ALLOW_FAKE_PLAYERS
                && FakePlayersTable.getActiveFakePlayers().contains(_target)) {
            cs = new Say2(activeChar.getObjectId(), _type, "->" + _target, _text);
            activeChar.sendPacket(cs);
            return;
        } else if ((receiver != null) && receiver.isInOfflineMode()) {
            activeChar.sendMessage("The person is in offline trade mode.");
            activeChar.sendActionFailed();
        } else if ((receiver != null) && !receiver.isInBlockList(activeChar) && !receiver.isBlockAll()) {
            if (!receiver.getMessageRefusal()) {
                if (activeChar.antiFlood.canTell(receiver.getObjectId(), _text)) {
                    receiver.sendPacket(cs);
                }
                cs = new Say2(activeChar.getObjectId(), _type, "->" + receiver.getName(), _text);
                activeChar.sendPacket(cs);
            } else {
                activeChar.sendPacket(Msg.THE_PERSON_IS_IN_A_MESSAGE_REFUSAL_MODE);
            }
        } else if (receiver == null) {
            activeChar.sendPacket(
                    new SystemMessage(SystemMessage.S1_IS_NOT_CURRENTLY_LOGGED_IN).addString(_target),
                    ActionFail.STATIC);
        } else {
            activeChar.sendPacket(Msg.YOU_HAVE_BEEN_BLOCKED_FROM_THE_CONTACT_YOU_SELECTED, ActionFail.STATIC);
        }
        break;
    case SHOUT:
        if (activeChar.isCursedWeaponEquipped()) {
            activeChar.sendPacket(Msg.SHOUT_AND_TRADE_CHATING_CANNOT_BE_USED_SHILE_POSSESSING_A_CURSED_WEAPON);
            return;
        }
        if (activeChar.isInObserverMode()) {
            activeChar.sendPacket(Msg.YOU_CANNOT_CHAT_LOCALLY_WHILE_OBSERVING);
            return;
        }
        if (!activeChar.isGM() && !activeChar.antiFlood.canShout(_text)) {
            activeChar.sendMessage("Shout chat is allowed once per 5 seconds.");
            return;
        }
        if (Config.GLOBAL_SHOUT) {
            announce(activeChar, cs);
        } else {
            shout(activeChar, cs);
        }
        activeChar.sendPacket(cs);
        break;
    case TRADE:
        if (activeChar.isCursedWeaponEquipped()) {
            activeChar.sendPacket(Msg.SHOUT_AND_TRADE_CHATING_CANNOT_BE_USED_SHILE_POSSESSING_A_CURSED_WEAPON);
            return;
        }
        if (activeChar.isInObserverMode()) {
            activeChar.sendPacket(Msg.YOU_CANNOT_CHAT_LOCALLY_WHILE_OBSERVING);
            return;
        }
        if (!activeChar.isGM() && !activeChar.antiFlood.canTrade(_text)) {
            activeChar.sendMessage("Trade chat is allowed once per 5 seconds.");
            return;
        }
        if (Config.GLOBAL_TRADE_CHAT) {
            announce(activeChar, cs);
        } else {
            shout(activeChar, cs);
        }
        activeChar.sendPacket(cs);
        break;
    case ALL:
        if (activeChar.isCursedWeaponEquipped()) {
            cs = new Say2(activeChar.getObjectId(), _type, activeChar.getTransformationName(), _text);
        }
        List<Player> list = null;
        if (activeChar.isInObserverMode() && (activeChar.getObserverRegion() != null)
                && (activeChar.getOlympiadObserveGame() != null)) {
            OlympiadGame game = activeChar.getOlympiadObserveGame();
            if (game != null) {
                list = game.getAllPlayers();
            }
        } else if (activeChar.isInOlympiadMode()) {
            OlympiadGame game = activeChar.getOlympiadGame();
            if (game != null) {
                list = game.getAllPlayers();
            }
        } else {
            list = World.getAroundPlayers(activeChar);
        }
        if (list != null) {
            for (Player player : list) {
                if ((player == activeChar) || (player.getReflection() != activeChar.getReflection())
                        || player.isBlockAll() || player.isInBlockList(activeChar)) {
                    continue;
                }
                player.sendPacket(cs);
            }
        }
        activeChar.sendPacket(cs);
        break;
    case CLAN:
        if (activeChar.getClan() != null) {
            activeChar.getClan().broadcastToOnlineMembers(cs);
        }
        break;
    case ALLIANCE:
        if ((activeChar.getClan() != null) && (activeChar.getClan().getAlliance() != null)) {
            activeChar.getClan().getAlliance().broadcastToOnlineMembers(cs);
        }
        break;
    case PARTY:
        if (activeChar.isInParty()) {
            activeChar.getParty().broadCast(cs);
        }
        break;
    case PARTY_ROOM:
        MatchingRoom r = activeChar.getMatchingRoom();
        if ((r != null) && (r.getType() == MatchingRoom.PARTY_MATCHING)) {
            r.broadCast(cs);
        }
        break;
    case COMMANDCHANNEL_ALL:
        if (!activeChar.isInParty() || !activeChar.getParty().isInCommandChannel()) {
            activeChar.sendPacket(Msg.YOU_DO_NOT_HAVE_AUTHORITY_TO_USE_THE_COMMAND_CHANNEL);
            return;
        }
        if (activeChar.getParty().getCommandChannel().getChannelLeader() == activeChar) {
            activeChar.getParty().getCommandChannel().broadCast(cs);
        } else {
            activeChar.sendPacket(Msg.ONLY_CHANNEL_OPENER_CAN_GIVE_ALL_COMMAND);
        }
        break;
    case COMMANDCHANNEL_COMMANDER:
        if (!activeChar.isInParty() || !activeChar.getParty().isInCommandChannel()) {
            activeChar.sendPacket(Msg.YOU_DO_NOT_HAVE_AUTHORITY_TO_USE_THE_COMMAND_CHANNEL);
            return;
        }
        if (activeChar.getParty().isLeader(activeChar)) {
            activeChar.getParty().getCommandChannel().broadcastToChannelPartyLeaders(cs);
        } else {
            activeChar.sendPacket(Msg.ONLY_A_PARTY_LEADER_CAN_ACCESS_THE_COMMAND_CHANNEL);
        }
        break;
    case HERO_VOICE:
        boolean PremiumHeroChat = false;
        if (Config.PREMIUM_HEROCHAT && (activeChar.getNetConnection().getBonus() > 1)) {
            long endtime = activeChar.getNetConnection().getBonusExpire();
            if (endtime >= 0) {
                PremiumHeroChat = true;
            }
        }
        if (activeChar.isHero() || activeChar.getPlayerAccess().CanAnnounce || PremiumHeroChat) {
            if (!activeChar.getPlayerAccess().CanAnnounce) {
                if (!activeChar.antiFlood.canHero(_text)) {
                    activeChar.sendMessage("Hero chat is allowed once per 10 seconds.");
                    return;
                }
            }
            for (Player player : GameObjectsStorage.getAllPlayersForIterate()) {
                if (!player.isInBlockList(activeChar) && !player.isBlockAll()) {
                    player.sendPacket(cs);
                }
            }
        }
        break;
    case PETITION_PLAYER:
    case PETITION_GM:
        if (!PetitionManager.getInstance().isPlayerInConsultation(activeChar)) {
            activeChar.sendPacket(new SystemMessage(SystemMessage.YOU_ARE_CURRENTLY_NOT_IN_A_PETITION_CHAT));
            return;
        }
        PetitionManager.getInstance().sendActivePetitionMessage(activeChar, _text);
        break;
    case BATTLEFIELD:
        if (activeChar.getBattlefieldChatId() == 0) {
            return;
        }
        for (Player player : GameObjectsStorage.getAllPlayersForIterate()) {
            if (!player.isInBlockList(activeChar) && !player.isBlockAll()
                    && (player.getBattlefieldChatId() == activeChar.getBattlefieldChatId())) {
                player.sendPacket(cs);
            }
        }
        break;
    case MPCC_ROOM:
        MatchingRoom r2 = activeChar.getMatchingRoom();
        if ((r2 != null) && (r2.getType() == MatchingRoom.CC_MATCHING)) {
            r2.broadCast(cs);
        }
        break;
    default:
        _log.warn("Character " + activeChar.getName() + " used unknown chat type: " + _type.ordinal() + ".");
    }
}

From source file:hudson.plugins.emailext.plugins.content.BuildLogMultilineRegexContent.java

private String getContent(BufferedReader reader) throws IOException {
    final Pattern pattern = Pattern.compile(regex);
    final boolean asHtml = matchedSegmentHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;//from  www .  j a  v a 2 s . c  o  m

    StringBuilder line = new StringBuilder();
    StringBuilder fullLog = new StringBuilder();
    int ch;
    // Buffer log contents including line terminators, and remove console notes
    while ((ch = reader.read()) != -1) {
        if (ch == '\r' || ch == '\n') {
            if (line.length() > 0) {
                // Remove console notes (JENKINS-7402)
                fullLog.append(ConsoleNote.removeNotes(line.toString()));
                line.setLength(0);
            }
            fullLog.append((char) ch);
        } else {
            line.append((char) ch);
        }
    }
    // Buffer the final log line if it has no line terminator
    if (line.length() > 0) {
        // Remove console notes (JENKINS-7402)
        fullLog.append(ConsoleNote.removeNotes(line.toString()));
    }
    StringBuilder content = new StringBuilder();
    int numMatches = 0;
    boolean insidePre = false;
    int lastMatchEnd = 0;
    final Matcher matcher = pattern.matcher(fullLog);
    while (matcher.find()) {
        if (maxMatches != 0 && ++numMatches > maxMatches) {
            break;
        }
        if (showTruncatedLines) {
            if (matcher.start() > lastMatchEnd) {
                // Append information about truncated lines.
                int numLinesTruncated = countLineTerminators(
                        fullLog.subSequence(lastMatchEnd, matcher.start()));
                if (numLinesTruncated > 0) {
                    insidePre = stopPre(content, insidePre);
                    appendLinesTruncated(content, numLinesTruncated, asHtml);
                }
            }
        }
        if (asHtml) {
            insidePre = startPre(content, insidePre);
        }
        if (substText != null) {
            final StringBuffer substBuf = new StringBuffer();
            matcher.appendReplacement(substBuf, substText);
            // Remove prepended text between matches
            final String segment = substBuf.substring(matcher.start() - lastMatchEnd);
            appendMatchedSegment(content, segment, escapeHtml, matchedSegmentHtmlStyle);
        } else {
            appendMatchedSegment(content, matcher.group(), escapeHtml, matchedSegmentHtmlStyle);
        }
        lastMatchEnd = matcher.end();
    }
    if (showTruncatedLines) {
        if (fullLog.length() > lastMatchEnd) {
            // Append information about truncated lines.
            int numLinesTruncated = countLineTerminators(fullLog.subSequence(lastMatchEnd, fullLog.length()));
            if (numLinesTruncated > 0) {
                insidePre = stopPre(content, insidePre);
                appendLinesTruncated(content, numLinesTruncated, asHtml);
            }
        }
    }
    stopPre(content, insidePre);
    return content.toString();
}