Example usage for java.lang StringBuffer replace

List of usage examples for java.lang StringBuffer replace

Introduction

In this page you can find the example usage for java.lang StringBuffer replace.

Prototype

@Override
public synchronized StringBuffer replace(int start, int end, String str) 

Source Link

Usage

From source file:org.tdod.ether.taimpl.commands.DoExits.java

/**
 * Executes the "exits" command./*from   ww w  .ja  v  a2s.  co  m*/
 *
 * @param entity The entity executing the command.
 * @param input The input string.
 *
 * @return true if the command can be executed, false otherwise.
 */
public final boolean execute(Entity entity, String input) {
    if (!entity.getEntityType().equals(EntityType.PLAYER)) {
        return false;
    }
    Player player = (Player) entity;

    Room room = player.getRoom();

    String[] split = input.split(" ");

    if (split.length > 1) {
        return false;
    }

    // TODO is the dark check before or after the param check?
    if (!room.isIlluminated()) {
        player.print(TaMessageManager.TOODRK.getMessage());
        return true;
    }

    ExitDirectionEnum[] exitOrder = { ExitDirectionEnum.NORTH, ExitDirectionEnum.NORTHEAST,
            ExitDirectionEnum.EAST, ExitDirectionEnum.SOUTHEAST, ExitDirectionEnum.SOUTH,
            ExitDirectionEnum.SOUTHWEST, ExitDirectionEnum.WEST, ExitDirectionEnum.NORTHWEST,
            ExitDirectionEnum.UP, ExitDirectionEnum.DOWN };

    StringBuffer buffer = new StringBuffer();
    buffer.append("Exits: ");
    for (ExitDirectionEnum exit : exitOrder) {
        if (room.getExit(exit) != null) {
            buffer.append(exit.getShortDescription() + ",");
        }
    }

    if (buffer.length() == 0) {
        _log.error("Well thats odd.  Room " + room.getRoomNumber() + " does not have any exits!");
        return false;
    }

    buffer.replace(buffer.length() - 1, buffer.length(), ".");
    player.println(buffer.toString());

    return true;
}

From source file:de.willuhn.jameica.hbci.passports.pintan.server.PassportHandleImpl.java

/**
 * @see de.willuhn.jameica.hbci.passport.PassportHandle#callback(org.kapott.hbci.passport.HBCIPassport, int, java.lang.String, int, java.lang.StringBuffer)
 *///from w  ww.  ja v a 2 s.  co m
public boolean callback(HBCIPassport passport, int reason, String msg, int datatype, StringBuffer retData)
        throws Exception {
    switch (reason) {
    case HBCICallback.NEED_PT_PIN: {
        retData.replace(0, retData.length(), DialogFactory.getPIN(passport));
        return true;
    }

    case HBCICallback.NEED_PT_PHOTOTAN: {
        Logger.debug("got phototan code, using phototan dialog");
        TANDialog dialog = new PhotoTANDialog(config, retData.toString());
        dialog.setContext(this.getContext(passport));
        dialog.setText(msg);
        retData.replace(0, retData.length(), (String) dialog.open());
        return true;
    }

    case HBCICallback.NEED_PT_TAN: {
        TANDialog dialog = null;

        String flicker = retData.toString();
        if (flicker != null && flicker.length() > 0) {
            Logger.debug("got flicker code " + flicker);
            // Wir haben einen Flicker-Code. Also zeigen wir den Flicker-Dialog statt
            // dem normalen TAN-Dialog an
            Logger.info("using chiptan OPTIC/USB");
            dialog = new ChipTANDialog(config, flicker);
        }

        // regulaerer TAN-Dialog
        if (dialog == null) {
            Logger.info("using chiptan MANUAL");
            Logger.debug("using regular tan dialog");
            dialog = new TANDialog(config);
        }

        dialog.setContext(this.getContext(passport));
        dialog.setText(msg);
        retData.replace(0, retData.length(), (String) dialog.open());
        return true;
    }

    // BUGZILLA 200
    case HBCICallback.NEED_PT_SECMECH: {
        if (config != null) {
            PtSecMech mech = config.getStoredSecMech();
            String type = mech != null ? StringUtils.trimToNull(mech.getId()) : null;
            if (type != null) {
                // Wir checken vorher noch, ob es das TAN-Verfahren ueberhaupt noch gibt
                PtSecMech m = PtSecMech.contains(retData.toString(), type);
                if (m != null) {
                    // Jepp, gibts noch
                    retData.replace(0, retData.length(), type);
                    return true;
                }
            }
        }

        PtSecMechDialog ptd = new PtSecMechDialog(config, retData.toString());
        retData.replace(0, retData.length(), (String) ptd.open());
        return true;
    }

    // BUGZILLA 827
    case HBCICallback.NEED_PT_TANMEDIA: {
        // Wenn wir eine Medienbezeichnung von HBCI4Java gekriegt haben und das genau
        // eine einzige ist. Dann uebernehmen wir diese ohne Rueckfrage. Der User
        // hat hier sonst eh keine andere Wahl.
        String media = retData.toString();
        if (media.length() > 0 && !media.contains("|")) {
            Logger.info("having exactly one TAN media name (provided by institute) - automatically using this: "
                    + media);
            retData.replace(0, retData.length(), media);
            return true;
        }

        // Falls wir eine PIN/TAN-Config haben, in der die Medienbezeichnung
        // hinterlegt ist, dann nehmen wir die.
        if (config != null) {
            media = config.getTanMedia();
            if (media != null && media.length() > 0) {
                Logger.info("having a stored TAN media name (provided by user) - automatically using this: "
                        + media);
                retData.replace(0, retData.length(), media);
                return true;
            }
        }

        Logger.info("asking user for TAN media (options provided by institute: " + media + ")");
        TanMediaDialog tmd = new TanMediaDialog(config, retData.toString());
        retData.replace(0, retData.length(), (String) tmd.open());
        return true;
    }
    }

    return false;
}

From source file:de.betterform.agent.betty.Betty.java

protected String replace(String string, String match, String replacement) {
    int start = string.indexOf(match);
    if (start > -1) {
        StringBuffer buffer = new StringBuffer(string);
        buffer.replace(start, start + match.length(), replacement);
        return buffer.toString();
    }//w w  w.j a  v a2 s . co  m

    return string;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }/*from  w  w w .  j a  v a 2s . co m*/

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

From source file:com.cloudmade.api.CMClient.java

/**
 * Find route between two points with given paramteres.
 * //  w w  w. j  a v  a 2  s.c o  m
 * @param start Starting point
 * @param end Ending point
 * @param routeType Type of route, e.g. car, foot, etc.
 * @param transitPoints List of points route must visit before
 *            reaching end. Points are visited in the same order they are
 *            specified in the sequence. Set it to <code>null</code> if you do not need it.
 * @param typeModifier Modifier of the route type, e.g. shortest
 * @param lang Language code in conference to `ISO 3166-1 alpha-2` standard
 * @param units Measure units for distance calculation (km/miles)
 * @return Route that was found
 * @throws OpenStreetMapRouteNotFoundException If no route found between points.
 */
public Route route(Point start, Point end, RouteType routeType, List<Point> transitPoints,
        RouteTypeModifier typeModifier, String lang, MeasureUnit units)
        throws OpenStreetMapRouteNotFoundException {
    byte[] response = {};

    try {
        StringBuffer tps = new StringBuffer("");
        if (transitPoints != null && transitPoints.size() > 0) {
            tps.append("[");
            for (Point transitPoint : transitPoints) {
                tps.append(transitPoint.toString()).append(",");
            }
            tps.replace(tps.length() - 1, tps.length(), "],");
        }
        String tms = "";
        if (typeModifier != null) {
            tms = "/" + typeModifier.name;
        }

        String uri = String.format(Locale.US, "/api/0.3/%s,%s%s/%s%s.js", start.toString(),
                URLEncoder.encode(tps.toString(), "utf-8"), end.toString(), routeType.name, tms);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("lang", lang));
        params.add(new NameValuePair("units", units.name));
        response = callService(uri, "routes", params.toArray(new NameValuePair[0]));
        JSONObject obj = new JSONObject(new String(response, "UTF-8"));

        return Utils.routeFromJson(obj);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openmrs.module.FacesRegister.web.controller.Faces361BRegisterManageController.java

private String dateFormat(String s) {
    /*/*from  www  .jav  a2s. c  om*/
     * this method formats the date string
     * it takes input in the format of dd/mm/yyyy and returns yyyy-mm-dd
     * This is done so that we can ensure correct sql date format
     */
    String temp = "";
    StringBuffer st = new StringBuffer(s);
    for (int i = st.length() - 1; i >= 0; i--) {
        if (st.charAt(i) == '/')
            st.replace(i, i + 1, "-"); //replace the slash "/" with the dash "-"
    }
    temp = st.substring(6, 10) + "-" + st.substring(3, 5) + "-" + st.substring(0, 2); // format date (yyyy-mm-dd)
    return temp;

}

From source file:org.apache.airavata.registry.tool.DBMigrator.java

private static void executeSQLScript(Connection conn, InputStream inputStream) throws Exception {
    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;
    try {/*from  www  .j av a  2 s  .  c o  m*/
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("//")) {
                continue;
            }
            if (line.startsWith("--")) {
                continue;
            }
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String token = st.nextToken();
                if ("REM".equalsIgnoreCase(token)) {
                    continue;
                }
            }
            sql.append(" ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                String sqlString = sql.substring(0, sql.length() - delimiter.length());
                executeSQL(sqlString, conn);
                sql.replace(0, sql.length(), "");
            }
        }
        System.out.println(sql.toString());
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString(), conn);
        }
    } catch (IOException e) {
        logger.error("Error occurred while executing SQL script for creating Airavata database", e);
        throw new Exception("Error occurred while executing SQL script for creating Airavata database", e);
    } finally {
        if (reader != null) {
            reader.close();
        }

    }
}

From source file:org.nuxeo.connect.packages.dependencies.DependencyResolution.java

private StringBuffer append(StringBuffer sb, List<String> pkgList, String title) {
    if (!pkgList.isEmpty()) {
        append(sb, title, pkgList.size());
        for (String pkg : pkgList) {
            sb.append(pkg + "/");
        }/*from   w w w .jav a  2 s . co  m*/
        sb.replace(sb.length() - 1, sb.length(), "\n");
    }
    return sb;
}

From source file:org.sakaiproject.imagegallery.springutil.SqlScriptParser.java

/**
 * Parse the SQL script to produce an array of database statements.
 * @param sqlScriptReader A reader that reads the SQL script text.
 * @return An array of strings, each containing a single statement.
 * @throws RuntimeException-wrapped IOException if the script cannot be read.
 * @throws RuntimeException-wrapped ParseException if the script cannot be parsed.
 *//*from   www  .jav  a2 s .c  o  m*/
public static String[] parse(Reader sqlScriptReader) {
    char statementDelimiter = ';';
    List<String> statements = new ArrayList<String>();

    StringBuffer sql = new StringBuffer(1024);
    String line = "";
    BufferedReader in = new BufferedReader(sqlScriptReader);
    int lineNumber = 0;

    // Read each line and build up statements.
    try {
        while ((line = in.readLine()) != null) {
            lineNumber++;
            // Trim
            line = cleanLine(line);

            // Check for statement delimiter change.
            Character newDelimiter = parseForNewStatementDelimiter(line);
            if (newDelimiter != null) {
                statementDelimiter = newDelimiter.charValue();
                continue;
            }

            // Validate and strip comments
            parseLine(line, sql, lineNumber, statementDelimiter);
            if (sql.length() > 0) {
                if (sql.charAt(sql.length() - 1) == statementDelimiter) {
                    // This line terminates the statement.
                    // Lose the delimiter.
                    String statement = sql.toString().substring(0, sql.length() - 1).trim();
                    if (statement.length() > 0) {
                        statements.add(statement);
                        s_log.debug("Found statement: " + statement);
                    }
                    // Clear buffer for the next statement.
                    sql.replace(0, sql.length(), "");
                } else {
                    // This line does not terminate the statement. Add a
                    // space and go on to the next one.
                    sql.append(" ");
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Catch any statements not followed by delimiter.
    String orphanStatement = sql.toString().trim();
    if (orphanStatement.length() > 0) {
        statements.add(orphanStatement);
        s_log.debug("Found statement: " + orphanStatement);
    }

    String[] result = new String[statements.size()];
    statements.toArray(result);
    return result;
}

From source file:org.apache.struts.config.ActionConfigMatcher.java

/**
 * <p> Inserts into a value wildcard-matched strings where specified.
 * </p>/*from  w w  w  .j  a v  a2 s.com*/
 *
 * @param val  The value to convert
 * @param vars A Map of wildcard-matched strings
 * @return The new value
 */
protected String convertParam(String val, Map vars) {
    if (val == null) {
        return null;
    } else if (val.indexOf("{") == -1) {
        return val;
    }

    Map.Entry entry;
    StringBuffer key = new StringBuffer("{0}");
    StringBuffer ret = new StringBuffer(val);
    String keyTmp;
    int x;

    for (Iterator i = vars.entrySet().iterator(); i.hasNext();) {
        entry = (Map.Entry) i.next();
        key.setCharAt(1, ((String) entry.getKey()).charAt(0));
        keyTmp = key.toString();

        // Replace all instances of the placeholder
        while ((x = ret.toString().indexOf(keyTmp)) > -1) {
            ret.replace(x, x + 3, (String) entry.getValue());
        }
    }

    return ret.toString();
}