Example usage for java.util.regex Matcher start

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

Introduction

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

Prototype

public int start() 

Source Link

Document

Returns the start index of the previous match.

Usage

From source file:com.untangle.app.branding_manager.BrandingManagerApp.java

/**
 * Using the non-branded version from uvm as a template base, modify
 * images and text to reflect branding.// www.j  a  va 2s  .  c  om
 */
private void createRootCaInstaller() {
    /*
     * Use the non-branded version as a template base.  Copy over.
     */
    UvmContextFactory.context().execManager().exec("rm -rf " + ROOT_CA_INSTALLER_DIRECTORY_NAME + "; cp -fa "
            + CertificateManager.ROOT_CA_INSTALLER_DIRECTORY_NAME + " " + ROOT_CA_INSTALLER_DIRECTORY_NAME);

    /*
     * Convert images to .bmp format
     */
    UvmContextFactory.context().execManager().exec("anytopnm " + BRANDING_LOGO + " | ppmtobmp > "
            + ROOT_CA_INSTALLER_DIRECTORY_NAME + "/images/modern-header.bmp");
    UvmContextFactory.context().execManager().exec("anytopnm " + BRANDING_LOGO + " | pnmrotate 90 | ppmtobmp > "
            + ROOT_CA_INSTALLER_DIRECTORY_NAME + "/images/modern-wizard.bmp");

    /*
     * Parse files replacing Untangle defaults
     */
    String companyName = settings.getCompanyName();
    String companyUrl = settings.getCompanyUrl();
    for (Map.Entry<FILE_PARSE_TYPE, String> filenameSet : ROOT_CA_INSTALLER_PARSE_FILE_NAMES.entrySet()) {
        String filename = filenameSet.getValue();
        File file = new File(filename);
        String name = file.getName();
        HashMap<REGEX_TYPE, Pattern> regexes = new HashMap<>();
        String quotedString = "";
        int flags = 0;
        if (filenameSet.getKey() == FILE_PARSE_TYPE.QUOTED) {
            quotedString = "\"";
        } else {
            flags = Pattern.CASE_INSENSITIVE;
        }

        /*
         * Build up regexes to find the first occurance of our current name.
         */
        regexes.put(REGEX_TYPE.COMPANY_NAME, Pattern.compile(
                "(" + quotedString + ".*?)" + DEFAULT_UNTANGLE_COMPANY_NAME + "(.*" + quotedString + ")",
                flags));
        regexes.put(REGEX_TYPE.COMPANY_URL, Pattern.compile(
                "(" + quotedString + ".*?)" + "http://.*.untangle.com(.*" + quotedString + ")", flags));

        StringBuilder parsed = new StringBuilder();
        Matcher match = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filename));
            for (String line = reader.readLine(); null != line; line = reader.readLine()) {
                /*
                 * When parsing the nsi file we only want to replace strings within quotes and
                 * for other files, everything.
                 */
                for (Map.Entry<REGEX_TYPE, Pattern> regex : regexes.entrySet()) {
                    match = regex.getValue().matcher(line);
                    int startPos = 0;
                    while (match.find(startPos)) {
                        switch (regex.getKey()) {
                        case COMPANY_NAME:
                            startPos = match.start() + match.group(1).length() + companyName.length();
                            line = match.replaceAll("$1" + companyName + "$2");
                            break;
                        case COMPANY_URL:
                            startPos = match.start() + match.group(1).length() + companyUrl.length();
                            line = match.replaceAll("$1" + companyUrl + "$2");
                            break;

                        default:
                            /* Shouldn'e be here...but if we are, make sure we exit the loop. */
                            startPos = line.length();
                        }
                        if (startPos >= line.length()) {
                            break;
                        }
                        match = regex.getValue().matcher(line);
                    }
                }
                parsed.append(line).append(EOL);
            }
        } catch (Exception x) {
            logger.warn("Unable to open installer configuration file: " + filename);
            return;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception x) {
                    logger.warn("Unable to close installer configuration file: " + filename);
                }
            }
        }

        FileOutputStream fos = null;
        File tmp = null;
        try {
            tmp = File.createTempFile(file.getName(), ".tmp");
            fos = new FileOutputStream(tmp);
            fos.write(parsed.toString().getBytes());
            fos.flush();
            fos.close();
            IOUtil.copyFile(tmp, new File(filename));
            tmp.delete();
        } catch (Exception ex) {
            IOUtil.close(fos);
            tmp.delete();
            logger.error("Unable to create installer file:" + filename + ":", ex);
        }
    }

    /*
     * Regenerate
     */
    UvmContextFactory.context().execManager().exec(CertificateManager.ROOT_CA_INSTALLER_SCRIPT);
}

From source file:com.manydesigns.portofino.pageactions.text.TextAction.java

protected String processLocalUrls(String content) {
    List<String> hosts = new ArrayList<String>();
    hosts.add(context.getRequest().getLocalAddr());
    hosts.add(context.getRequest().getLocalName());
    hosts.addAll(portofinoConfiguration.getList(PortofinoProperties.HOSTNAMES));
    String patternString = BASE_USER_URL_PATTERN.replace("HOSTS", "(" + StringUtils.join(hosts, ")|(") + ")");
    Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(content);
    int lastEnd = 0;
    StringBuilder sb = new StringBuilder();
    String contextPath = context.getRequest().getContextPath();
    while (matcher.find()) {
        String attribute = matcher.group(1);
        String path = matcher.group(8 + hosts.size());
        assert path.startsWith("/");
        String queryString = matcher.group(10 + hosts.size());
        String hostAndPort = matcher.group(5);
        if (!StringUtils.isBlank(hostAndPort) && !path.startsWith(contextPath)) {
            logger.debug("Path refers to another web application on the same host, skipping: {}", path);
            continue;
        }//  ww w  . ja  v a 2  s . c o m

        sb.append(content.substring(lastEnd, matcher.start()));
        sb.append("portofino:hrefAttribute=\"").append(attribute).append("\"");

        if (path.startsWith(contextPath)) {
            path = path.substring(contextPath.length());
        }

        //path = convertPathToInternalLink(path);
        sb.append(" portofino:link=\"").append(path).append("\"");
        if (!StringUtils.isBlank(queryString)) {
            sb.append(" portofino:queryString=\"").append(queryString).append("\"");
        }

        lastEnd = matcher.end();
    }

    sb.append(content.substring(lastEnd));

    return sb.toString();
}

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

/**
 * Method runImpl.//w w w  .  j  a va2 s  .  c o  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:edu.northwestern.jcr.adapter.fedora.persistence.FedoraConnector.java

/**
 * Modifies or creates a Dublic Core field/value pair in the DC data stream.
 *
 * @param pid pid of the digital object//from   w w  w .  j  av a  2 s . c o  m
 * @param field Dublin Core field to be added or modified
 * @param value new value of the field
 */
public void modifyDCField(String pid, String field, String value) {
    String dcXML;
    byte[] b;
    String oldValue, newValue;
    Pattern pattern;
    Matcher matcher;
    int index;

    if (field.equals("identifier")) {
        // cannot change identifier
        log.error("attemp to change dc:identifier!");
        return;
    }

    b = getDataStream(pid, "DC");
    dcXML = new String(b);

    // DOT matches anything including newline characters
    pattern = Pattern.compile("<dc:" + field + ">.*</dc:" + field + ">", Pattern.DOTALL);
    matcher = pattern.matcher(dcXML);

    newValue = "<dc:" + field + ">" + value + "</dc:" + field + ">";

    if (matcher.find()) {
        // replace current value
        oldValue = matcher.group();
        index = matcher.start();
        dcXML = dcXML.substring(0, index) + newValue + dcXML.substring(index + oldValue.length());
    } else {
        // add to the end
        index = dcXML.indexOf("</oai_dc:dc>");
        dcXML = dcXML.substring(0, index) + newValue + "\n</oai_dc:dc>";
    }

    modifyDCDataStream(pid, dcXML.getBytes());
}

From source file:gtu.youtube.JavaYoutubeVideoUrlHandler.java

private List<DataFinal> findDataGroup(String baseUrlString) {
    List<DataFinal> rtnLst = new ArrayList<DataFinal>();
    List<DataConfig> lst = new ArrayList<DataConfig>();

    // parse Paramster
    for (Field f : DataFinal.class.getDeclaredFields()) {
        Pattern ptn = Pattern.compile(f.getName());
        Matcher mth = ptn.matcher(baseUrlString);
        while (mth.find()) {

            String paramStr = "";
            if (f.getName().equals("url")) {
                paramStr = this.getParamStr(baseUrlString, mth.end() + "=".length(), "\\,");
            } else if (f.getName().equals("quality")) {
                paramStr = this.getParamStr_forCatch(f.getName(), baseUrlString, mth.end() + "=".length(),
                        "\\w+");
            } else if (f.getName().equals("type")) {
                paramStr = this.getParamStr_forCatch(f.getName(), baseUrlString, mth.end() + "=".length(),
                        "video\\/\\w+\\;\\scodecs\\=\".*?\"");
            } else if (f.getName().equals("itag")) {
                paramStr = this.getParamStr_forCatch(f.getName(), baseUrlString, mth.end() + "=".length(),
                        "\\d+");
            }//www  . j a v  a2s .c  o  m

            DataConfig d = new DataConfig();
            d.paramStr = paramStr;
            d.name = f.getName();
            d.start = mth.start();
            d.end = mth.end() + ("=" + paramStr).length();

            lst.add(d);
        }
    }

    // URL
    for (int ii = 0; ii < lst.size(); ii++) {
        DataConfig d1 = lst.get(ii);

        if (d1.name.equals("url")) {
            // ? type
            d1.paramStr = d1.paramStr.replaceAll("type\\=video\\/\\w+\\;\\scodecs\\=\"[\\w\\.]+,?", "");
            d1.paramStr = d1.paramStr.replaceAll("type\\=video\\/\\w+\\;\\scodecs\\=\"[\\w\\.]+,\\s[\\w\\.]+\"",
                    "");

            // ? quality
            d1.paramStr = d1.paramStr.replaceAll("quality\\=\\w+", "");

            System.out.println("correct url = " + d1.paramStr);
        }
    }

    // Grouping
    List<DataConfig> urlLst = getMatchIndexDataConfig("url", lst);
    for (int ii = 0; ii < urlLst.size(); ii++) {
        DataConfig urlData = urlLst.get(ii);
        DataConfig qualityData = getIndex("quality", getMatchIndexDataConfig("quality", lst), ii);
        DataConfig typeData = getIndex("type", getMatchIndexDataConfig("type", lst), ii);

        DataFinal dd = new DataFinal();
        dd.url = urlData;
        dd.quality = qualityData;
        dd.type = typeData;
        dd.itag = getMockItag(urlData.paramStr);

        rtnLst.add(dd);
    }
    return rtnLst;
}

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);
            }/*w ww. j  a  va  2 s  .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:com.marand.thinkmed.medications.business.impl.TherapyDisplayProvider.java

public String getDecimalStringValue(final Double value, final Locale locale) throws ParseException {
    final boolean isDecimalNumber = value != null && value < 1 && value != 0;
    if (isDecimalNumber) {
        //if decimal, print until three nonzero numbers are visible
        final String[] numberSplittedByDecimalPoint = BigDecimal.valueOf(value).toPlainString().split("\\.");
        final Pattern pattern = Pattern.compile("[1-9]");
        final Matcher matcher = pattern.matcher(numberSplittedByDecimalPoint[1]);
        if (matcher.find()) {
            final int firstNonZeroNumberPosition = matcher.start();
            final String hashes = StringUtils.repeat("#", firstNonZeroNumberPosition + 3);
            return NumberFormatters.adjustableDoubleFormatter("0." + hashes, locale).valueToString(value);
        }/*from  w w w .  j  a  v  a  2s  .  c o  m*/
    }
    return NumberFormatters.doubleFormatter3(locale).valueToString(value);
}

From source file:com.g3net.tool.StringUtils.java

/**
 * src?regex??????? ?(handler)/*  w  ww. ja  va  2 s .  c o m*/
 * ?????
 * 
 * @param src
 * @param regex
 *            ??:&(\\d+;)([a-z)+)
 * @param handleGroupIndex
 *            ???
 * @param hander
 *            ?
 * @param reservesGroups
 *            ???,?hander?handleGroupIndex
 *            ?reservesGroups?hander?regex? 
 * @return
 */
public static String replaceAll(String src, String regex, int handleGroupIndex, GroupHandler hander,
        int[] reservesGroups) {

    if (src == null || src.trim().length() == 0) {
        return "";
    }
    Matcher m = Pattern.compile(regex).matcher(src);

    StringBuffer sbuf = new StringBuffer();
    String replacementFirst = "";
    String replacementTail = "";
    if (reservesGroups != null && reservesGroups.length > 0) {
        Arrays.sort(reservesGroups);
        for (int i = 0; i < reservesGroups.length; i++) {
            if (reservesGroups[i] < handleGroupIndex) {
                replacementFirst = replacementFirst + "$" + reservesGroups[i];
            } else {
                replacementTail = replacementTail + "$" + reservesGroups[i];
            }
        }
    }

    // perform the replacements:
    while (m.find()) {
        String value = m.group(handleGroupIndex);

        String group = m.group();

        String handledStr = hander.handler(value);
        String replacement = "";
        if (reservesGroups == null) {
            int start0 = m.start();
            int end0 = m.end();
            int start = m.start(handleGroupIndex);
            int end = m.end(handleGroupIndex);
            int relativeStart = start - start0;
            int relativeEnd = end - start0;
            StringBuilder sbgroup = new StringBuilder(group);
            sbgroup = sbgroup.replace(relativeStart, relativeEnd, handledStr);
            replacement = sbgroup.toString();
        } else {
            replacement = replacementFirst + handledStr + replacementTail;
        }

        m.appendReplacement(sbuf, replacement);

    }
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    return sbuf.toString();
    // return null;
}

From source file:com.android.email.activity.MessageView.java

/**
 * Reload the body from the provider cursor.  This must only be called from the UI thread.
 *
 * @param bodyText text part//  w  w w  .jav a 2  s.c  o m
 * @param bodyHtml html part
 *
 * TODO deal with html vs text and many other issues
 */
private void reloadUiFromBody(String bodyText, String bodyHtml) {
    String text = null;
    mHtmlTextRaw = null;
    boolean hasImages = false;

    if (bodyHtml == null) {
        text = bodyText;
        /*
         * Convert the plain text to HTML
         */
        StringBuffer sb = new StringBuffer("<html><body>");
        if (text != null) {
            // Escape any inadvertent HTML in the text message
            text = EmailHtmlUtil.escapeCharacterToDisplay(text);
            // Find any embedded URL's and linkify
            Matcher m = Patterns.WEB_URL.matcher(text);
            while (m.find()) {
                int start = m.start();
                /*
                 * WEB_URL_PATTERN may match domain part of email address. To detect
                 * this false match, the character just before the matched string
                 * should not be '@'.
                 */
                if (start == 0 || text.charAt(start - 1) != '@') {
                    String url = m.group();
                    Matcher proto = WEB_URL_PROTOCOL.matcher(url);
                    String link;
                    if (proto.find()) {
                        // This is work around to force URL protocol part be lower case,
                        // because WebView could follow only lower case protocol link.
                        link = proto.group().toLowerCase() + url.substring(proto.end());
                    } else {
                        // Patterns.WEB_URL matches URL without protocol part,
                        // so added default protocol to link.
                        link = "http://" + url;
                    }
                    String href = String.format("<a href=\"%s\">%s</a>", link, url);
                    m.appendReplacement(sb, href);
                } else {
                    m.appendReplacement(sb, "$0");
                }
            }
            m.appendTail(sb);
        }
        sb.append("</body></html>");
        text = sb.toString();
    } else {
        text = bodyHtml;
        mHtmlTextRaw = bodyHtml;
        hasImages = IMG_TAG_START_REGEX.matcher(text).find();
    }

    mShowPicturesSection.setVisibility(hasImages ? View.VISIBLE : View.GONE);
    if (mMessageContentView != null) {
        mMessageContentView.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null);
    }

    // Ask for attachments after body
    mLoadAttachmentsTask = new LoadAttachmentsTask();
    mLoadAttachmentsTask.execute(mMessage.mId);
}