List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:org.rebioma.server.FileUploadServlet.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { FileItem uploadItem = null;/*from ww w . j a va2 s. com*/ File file = null; String fieldName, val, sessionId = null; String errorMsg = null; String successMsg = null; String csvUrl = null; String username = null; String password = null; boolean clearReview = false; traitement = new Traitement("Uploading file...", 100 * 1024, 0); traitement.addTraitementListener(listenerAdapteur); try { boolean isPublic = true, isVettable = false, showEmail = false; String collaboratorsCSV = ""; for (FileItem item : sessionFiles) { fieldName = item.getFieldName(); if (item.isFormField()) { val = item.getString(); if (fieldName.equals("sessionId")) { sessionId = val; } else if (fieldName.equals("show_email")) { showEmail = val.equalsIgnoreCase("on") ? true : false; } else if (fieldName.equals("clear_review")) { clearReview = val.equalsIgnoreCase("on") ? true : false; } else if (fieldName.equals("private_vetter")) { isPublic = val.equalsIgnoreCase("on") ? false : true; } else if (fieldName.equals("public_vetter")) { isPublic = val.equalsIgnoreCase("on") ? true : false; } else if (fieldName.equals("modeling")) { isVettable = val.equalsIgnoreCase("on") ? true : false; } else if (fieldName.equals("delimiter")) { delimiter = val; } else if (fieldName.equals("collaborators")) { collaboratorsCSV = val; } else if (fieldName.equals("csvUrl")) { csvUrl = val; } else if (fieldName.equals("username")) { username = val; } else if (fieldName.equals("password")) { password = val; } } else if (fieldName.startsWith("GWTU-")) { uploadItem = item; } } InputStream uploadInputStream = null; String fileName = null; User user = null; if (sessionId != null && !sessionId.trim().equals("")) { user = sessionService.getUserBySessionId(sessionId); if (user == null) { errorMsg = "{\"onFailure\": {\"Invalid\" : \"sessionId\"}}"; } } else if (username != null && password != null) { user = userDb.findByEmail(username); if (user == null || !BCrypt.checkpw(password, user.getPasswordHash())) { errorMsg = "{\"onFailure\": {\"Invalid\" : \"wrong username or password\"}}"; user = null; } } if (csvUrl != null) { try { uploadInputStream = getUrlInputStream(csvUrl); fileName = "occurrence"; } catch (IOException io) { errorMsg = "{\"onFailure\": {\"No File\" : \"" + io.getMessage() + "\"}}"; } } else { if (uploadItem == null) { errorMsg = "{\"onFailure\": {\"No File\" : \"\"}}"; } else if (uploadItem.getSize() == 0) { errorMsg = "{\"onFailure\": {\"Invalid file\": \"\"}}"; } else { fileName = uploadItem.getName(); uploadInputStream = uploadItem.getInputStream(); } } if (errorMsg == null) { // Handles a windows server: if (fileName.contains("\\")) { int endIndex = fileName.lastIndexOf("."); int beginIndex = fileName.lastIndexOf("\\") + 1; if (beginIndex >= endIndex) { endIndex = fileName.length(); } fileName = fileName.substring(beginIndex, endIndex); } // File.createTempFile requires a fileName at least 3 characters long: if (fileName.length() < 3) { fileName += "xx"; } file = /*new File("f:/"+fileName);//*/File.createTempFile(fileName, ".csv"); logger.info(file.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(uploadInputStream)); int lineNbr = 0; for (String line = reader.readLine(); line != null; line = reader.readLine()) { writer.write(line + "\n"); lineNbr++; } writer.close(); File _file = /*new File("f:/_"+fileName);//*/File.createTempFile("_" + fileName, ".csv"); logger.info(_file.getAbsolutePath()); List<String> missingHeaders = fileValidation.validateCsvInputStream(_file, new FileInputStream(file), delimiter.charAt(0), null, traitement, lineNbr); if (missingHeaders != null) { StringBuilder sb = new StringBuilder("["); for (String header : missingHeaders) { sb.append("\"" + header + "\","); } sb.replace(sb.length() - 1, sb.length(), "]"); errorMsg = "{\"onFailure\": {\"Missing Required Headers\": " + sb + "}}"; //fixing issue 394 //response.getWriter().write(errorMsg); } else { String out = fileValidation.proccessOccurrenceFile(file, user, showEmail, isPublic, isVettable, clearReview, delimiter.charAt(0), collaboratorsCSV, traitement); successMsg = "{\"onSuccess\": " + out + "}"; //response.getWriter().write("{\"onSuccess\": " + out + "}"); } //end issue 394 } else { //response.getWriter().write(errorMsg); } delimiter = DEFAULT_DELIMITER; // restore delimiter to default value. } catch (Exception e) { e.printStackTrace(); errorMsg = "{\"onFailure\": {\"Upload failed\": \"" + e.getLocalizedMessage() + "\"}}"; //response.getWriter().write(errorMsg); } traitement.removeListeners(listenerAdapteur); return successMsg != null ? successMsg : errorMsg; }
From source file:kr.wdream.storyshop.AndroidUtilities.java
public static SpannableStringBuilder replaceTags(String str, int flag) { try {/*from w ww . j a va 2 s. c o m*/ int start; int end; StringBuilder stringBuilder = new StringBuilder(str); if ((flag & FLAG_TAG_BR) != 0) { while ((start = stringBuilder.indexOf("<br>")) != -1) { stringBuilder.replace(start, start + 4, "\n"); } while ((start = stringBuilder.indexOf("<br/>")) != -1) { stringBuilder.replace(start, start + 5, "\n"); } } ArrayList<Integer> bolds = new ArrayList<>(); if ((flag & FLAG_TAG_BOLD) != 0) { while ((start = stringBuilder.indexOf("<b>")) != -1) { stringBuilder.replace(start, start + 3, ""); end = stringBuilder.indexOf("</b>"); if (end == -1) { end = stringBuilder.indexOf("<b>"); } stringBuilder.replace(end, end + 4, ""); bolds.add(start); bolds.add(end); } } ArrayList<Integer> colors = new ArrayList<>(); if ((flag & FLAG_TAG_COLOR) != 0) { while ((start = stringBuilder.indexOf("<c#")) != -1) { stringBuilder.replace(start, start + 2, ""); end = stringBuilder.indexOf(">", start); int color = Color.parseColor(stringBuilder.substring(start, end)); stringBuilder.replace(start, end + 1, ""); end = stringBuilder.indexOf("</c>"); stringBuilder.replace(end, end + 4, ""); colors.add(start); colors.add(end); colors.add(color); } } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder); for (int a = 0; a < bolds.size() / 2; a++) { spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } for (int a = 0; a < colors.size() / 3; a++) { spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3), colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannableStringBuilder; } catch (Exception e) { FileLog.e("tmessages", e); } return new SpannableStringBuilder(str); }
From source file:pt.webdetails.cfr.CfrApiTest.java
@Test public void testSetPermissionsNonAdmin() throws IOException, JSONException { List<String> nonAdminUserFiles = new ArrayList<String>(); boolean unsetPermissions = false; nonAdminUserFiles.add(fileStructure[0]); nonAdminUserFiles.add(dirStructure[0]); CfrApiForTests cfrApi = new CfrApiForTests(); cfrApi.setIsAdmin(false);// w w w .j a v a 2 s . c o m cfrApi.setNonAdminUserFiles(nonAdminUserFiles); String top = "{" + " \"status\": \"Operation finished. Check statusArray for details.\"," + " \"statusArray\": ["; String bot = " ]}"; String singleBot = "]}"; String setOnDirRecur; StringBuilder sbAllDir = new StringBuilder(); for (String dir : dirStructure) { if (nonAdminUserFiles.contains(dir)) { sbAllDir.append( " {\"status\": \"Added permission for path " + dir + " and user/role Authenticated\"},"); } else { unsetPermissions = true; } } setOnDirRecur = sbAllDir.toString(); if (!unsetPermissions) { setOnDirRecur = sbAllDir.replace(setOnDirRecur.lastIndexOf(","), setOnDirRecur.lastIndexOf(",") + 1, "") .toString(); } else { sbAllDir.append(" {\"status\": \"Some permissions could not be set\"}"); setOnDirRecur = sbAllDir.toString(); } String setOnDir = "{\"status\": \"Added permission for path " + dirStructure[0] + " and user/role Authenticated\"}"; String setOnFile = "{\"status\": \"Added permission for path " + fileStructure[0] + " and user/role Authenticated\"}"; String permissionsNotSet = "{\"status\": \"Some permissions could not be set\"}"; String path = "/"; List<String> ids = new ArrayList<String>(); ids.add("Authenticated"); List<String> permissions = new ArrayList<String>(); permissions.add("read"); permissions.add("write"); boolean recursive = true; List<String> files = new ArrayList<String>(); files.addAll(Arrays.asList(fileStructure)); files.addAll(Arrays.asList(dirStructure)); cfrApi.setFileNames(files); createCfrServiceMock(); cfrApi.setCfrService(cfrServiceMock); // setPermissions on a dir, with recursive = true String result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + setOnDirRecur + bot, result.replaceAll("\n", "")); //set permissions on a file, with recursive = true path = fileStructure[0]; files = new ArrayList<String>(); files.addAll(Arrays.asList(fileStructure[0])); cfrApi.setFileNames(files); result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + setOnFile + singleBot, result.replaceAll("\n", "")); // setPermissions on a dir, with recursive = false path = dirStructure[0]; recursive = false; result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + setOnDir + singleBot, result.replaceAll("\n", "")); //set permissions on a file, with recursive = false path = fileStructure[0]; result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + setOnFile + singleBot, result.replaceAll("\n", "")); //set permissions on a file not owned by non-admin user path = fileStructure[1]; result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + permissionsNotSet + singleBot, result.replaceAll("\n", "")); //set permissions on a dir not owned by non-admin user path = dirStructure[1]; result = cfrApi.setPermissions(path, ids, permissions, recursive); Assert.assertEquals(top + permissionsNotSet + singleBot, result.replaceAll("\n", "")); }
From source file:org.jumpmind.metl.core.runtime.component.Sorter.java
protected void appendSortColumns(StringBuilder sql, ModelEntity entity) { for (ComponentAttributeSetting componentAttribute : sortKeyAttributeIdList) { for (ModelAttribute attribute : entity.getModelAttributes()) { if (componentAttribute.getAttributeId().equals(attribute.getId())) { sql.append(attribute.getName()).append(","); break; }/* w ww. j av a2 s. co m*/ } } sql.replace(sql.length() - 1, sql.length(), ""); }
From source file:com.rvantwisk.gcodeparser.GCodeParser.java
private void parseLine() throws SimException { // Remove comments between () and all comments after ; final StringBuilder parsedLine = new StringBuilder( COMMENTS2.matcher(COMMENTS1.matcher(currentLine).replaceAll("")).replaceAll("")); // A map that holds all parsed codes Map<String, ParsedWord> block = new HashMap<>(10); // Hold's the current parsed word ParsedWord thisWord;/*from w w w . j av a 2s. co m*/ while ((thisWord = findWordInBlock(parsedLine)) != null) { final int pos = parsedLine.indexOf(thisWord.asRead); parsedLine.replace(pos, pos + thisWord.asRead.length(), ""); // We can have multiple G/M words within a block, so we move them to the 'key' String blockKey = thisWord.word; if (blockKey.equals("G") || blockKey.equals("M")) { blockKey = thisWord.parsed.replace('.', '_'); // Store gwords with a . as _ } if (block.containsKey(blockKey)) { throw new SimValidationException("Multiple " + thisWord.word + " words on one line."); } else { block.put(blockKey, thisWord); } } // First verify if the block itself is valid before we process it if (machineValidator != null) machineValidator.preVerify(block); // Copy to intermediate status to ensure our machine status is always valid intermediateStatus.copyFrom(machineStatus); // Notify the controller that we are about to start a new block, the block itself is valid, for example there we be no G1's and G0 on one line for (MachineController controller : this.machineController) { controller.startBlock(this, intermediateStatus, Collections.unmodifiableMap(block)); } intermediateStatus.startBlock(); // Copy the block to the machine intermediateStatus.setBlock(block); // Block en, no more data will come in for this block intermediateStatus.endBlock(); // Verify machine's state, for example if a R was found, do we also have a valid G to accompany with it? if (machineValidator != null) machineValidator.postVerify(intermediateStatus); // Notify the controller that everything was ok, now teh controller start 'running' the data for (MachineController controller : this.machineController) { controller.endBlock(this, intermediateStatus, Collections.unmodifiableMap(block)); } // setup new and valid machine status machineStatus.copyFrom(intermediateStatus); }
From source file:jp.go.nict.langrid.wrapper.ws_1_2.translation.AbstractTranslationService.java
private String toUpperCaseCharacterBehindDelimiter(String source) { StringBuilder sb = new StringBuilder(source); Pattern p = Pattern.compile("(\\Q*$%*\\E|\\Q*%$*\\E)\\. *[a-z]"); Matcher m = p.matcher(sb);/* ww w. java 2 s . co m*/ while (m.find()) { String sub = sb.substring(m.start(), m.end()); sb.replace(m.start(), m.end(), sub.toUpperCase()); } return sb.toString(); }
From source file:com.gargoylesoftware.htmlunit.WebConsole.java
/** * This method is used by all the public method to process the passed * parameters./*from w w w . ja v a 2 s .c o m*/ * * If the last parameter implements the Formatter interface, it will be * used to format the parameters and print the object. * @param objs the logging parameters * @return a String to be printed using the logger */ private String process(final Object[] objs) { if (objs == null) { return "null"; } final StringBuffer sb = new StringBuffer(); final LinkedList<Object> args = new LinkedList<>(Arrays.asList(objs)); final Formatter formatter = getFormatter(); if (args.size() > 1 && args.get(0) instanceof String) { final StringBuilder msg = new StringBuilder((String) args.remove(0)); int startPos = msg.indexOf("%"); while (startPos > -1 && startPos < msg.length() - 1 && args.size() > 0) { if (startPos != 0 && msg.charAt(startPos - 1) == '%') { // double % msg.replace(startPos, startPos + 1, ""); } else { final char type = msg.charAt(startPos + 1); String replacement = null; switch (type) { case 'o': case 's': replacement = formatter.parameterAsString(pop(args)); break; case 'd': case 'i': replacement = formatter.parameterAsInteger(pop(args)); break; case 'f': replacement = formatter.parameterAsFloat(pop(args)); break; default: break; } if (replacement != null) { msg.replace(startPos, startPos + 2, replacement); startPos = startPos + replacement.length(); } else { startPos++; } } startPos = msg.indexOf("%", startPos); } sb.append(msg); } for (final Object o : args) { if (sb.length() != 0) { sb.append(' '); } sb.append(formatter.printObject(o)); } return sb.toString(); }
From source file:gool.generator.common.CommonCodeGenerator.java
/** * <pre>/*from w w w . j ava 2s . c om*/ * Produce indented code in a manner similar to printf but with custom conversions. * %% a single "%" * %s Print an argument as a string, without indentation or newlines added. * Similar to the corresponding flag of <i>String.format</i>. * %<i>n</i> (where <i>n</i> is a digit) * Print an argument as a bloc indented <i>n</i> times from the current indentation level. * Newlines are inserted before and after the bloc. * %-<i>n</i> (where <i>n</i> is a digit) * <i>n</i> times the indentation string, does not consumes a argument. * %-0 becomes a empty string (it does nothing but is still parsed) * * @param format * the format string * @param arguments * the objects to format, each one corresponding to a % code * @return the formated string */ protected String formatIndented(String format, Object... arguments) { StringBuilder sb = new StringBuilder(format); int pos = sb.indexOf("%"); int arg = 0; while (pos != -1) { if (sb.charAt(pos + 1) == '%') { sb = sb.replace(pos, pos + 2, "%"); } else if (sb.charAt(pos + 1) == 's') { sb = sb.replace(pos, pos + 2, arguments[arg].toString()); pos += arguments[arg].toString().length() - 1; arg++; } else if (Character.isDigit(sb.charAt(pos + 1))) { String replacement = ("\n" + arguments[arg].toString().replaceFirst("\\s*\\z", "")).replace("\n", "\n" + StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 1), 10))) + "\n"; sb = sb.replace(pos, pos + 2, replacement); pos += replacement.length() - 1; arg++; } else if (sb.charAt(pos + 1) == '-' && Character.isDigit(sb.charAt(pos + 2))) { String replacement = StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 2), 10)); sb = sb.replace(pos, pos + 3, replacement); pos += replacement.length(); } pos = sb.indexOf("%", pos); } return sb.toString(); }
From source file:it.andreascarpino.ansible.inventory.type.AnsibleVariable.java
public String mapToString(Map<?, ?> map) { final StringBuilder buf = new StringBuilder(); buf.append("{"); if (!map.isEmpty()) { for (Entry<?, ?> o : map.entrySet()) { final Object v = o.getValue(); if (v != null) { buf.append("'" + o.getKey() + "': "); if (ClassUtils.isPrimitiveOrWrapper(v.getClass()) || v instanceof String) { buf.append("'" + v + "'"); } else { buf.append(valueToString(v)); }/*w w w. j av a 2 s . co m*/ buf.append(", "); } } buf.replace(buf.length() - 2, buf.length(), ""); } buf.append("}"); return buf.toString(); }
From source file:org.jumpmind.symmetric.db.derby.DerbyFunctions.java
public static String getPrimaryKeyWhereString(String[] pkColumnNames, ResultSet rs) throws SQLException { final String AND = " and "; ResultSetMetaData metaData = rs.getMetaData(); StringBuilder b = new StringBuilder(); for (int i = 0; i < pkColumnNames.length; i++) { String columnName = pkColumnNames[i]; int index = findColumnIndex(metaData, columnName); int type = metaData.getColumnType(index); if (type != Types.BINARY && type != Types.BLOB && type != Types.LONGVARBINARY && type != Types.VARBINARY) { b.append("\"").append(columnName).append("\"="); switch (type) { case Types.BIT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.FLOAT: case Types.REAL: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: case Types.BOOLEAN: b.append(rs.getObject(index)); break; case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: b.append("\"").append(rs.getString(index)).append("\""); break; case Types.DATE: case Types.TIMESTAMP: b.append("{ts '"); b.append(rs.getString(index)); b.append("'}"); break; }/*from w w w . ja v a 2 s. c o m*/ b.append(AND); } } b.replace(b.length() - AND.length(), b.length(), ""); return b.toString(); }