List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
private static void validateWsdl(String url) throws Exception { //If url is empty or null throw exception if (StringUtils.isEmpty(url)) { handleException("URL is not empty"); }/*from w ww . j a va 2 s . com*/ if (url.startsWith(APIConstants.WSDL_REGISTRY_LOCATION_PREFIX)) { url = APIUtil.getServerURL() + url; } URL wsdl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(wsdl.openStream(), Charset.defaultCharset())); String inputLine; boolean isWsdl2 = false; boolean isWsdl10 = false; StringBuilder urlContent = new StringBuilder(); try { while ((inputLine = in.readLine()) != null) { String wsdl2NameSpace = "http://www.w3.org/ns/wsdl"; String wsdl10NameSpace = "http://schemas.xmlsoap.org/wsdl/"; urlContent.append(inputLine); isWsdl2 = urlContent.indexOf(wsdl2NameSpace) > 0; isWsdl10 = urlContent.indexOf(wsdl10NameSpace) > 0; } } finally { in.close(); } if (isWsdl10) { javax.wsdl.xml.WSDLReader wsdlReader11 = javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader(); wsdlReader11.readWSDL(url); } else if (isWsdl2) { WSDLReader wsdlReader20 = WSDLFactory.newInstance().newWSDLReader(); wsdlReader20.readWSDL(url); } else { handleException("URL is not in format of wsdl1/wsdl2"); } }
From source file:org.brandroid.openmanager.activities.OpenExplorer.java
private void saveOpenedEditors() { StringBuilder editing = new StringBuilder(","); for (int i = 0; i < mViewPagerAdapter.getCount(); i++) { OpenFragment f = mViewPagerAdapter.getItem(i); if (f instanceof TextEditorFragment) { TextEditorFragment tf = (TextEditorFragment) f; if (!tf.isSalvagable()) continue; OpenPath path = tf.getPath(); if (editing.indexOf("," + path.getPath() + ",") == -1) editing.append(path + ","); }//from ww w . j a va 2 s.com } if (DEBUG && !editing.equals(",")) Logger.LogDebug("Saving [" + editing.toString() + "] as TextEditorFragments"); setSetting("editing", editing.toString()); }
From source file:org.apache.fineract.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java
@Transactional @Override//from w w w .j av a 2 s.co m public void updateDatatable(final String datatableName, final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final JsonElement element = this.fromJsonHelper.parse(command.json()); final JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element); final JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element); final JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element); final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); validateDatatableName(datatableName); final List<ResultsetColumnHeaderData> columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(datatableName); final Map<String, ResultsetColumnHeaderData> mapColumnNameDefinition = new HashMap<>(); for (final ResultsetColumnHeaderData columnHeader : columnHeaderData) { mapColumnNameDefinition.put(columnHeader.getColumnName(), columnHeader); } final boolean isConstraintApproach = this.configurationDomainService .isConstraintApproachEnabledForDatatables(); if (!StringUtils.isBlank(apptableName)) { validateAppTable(apptableName); final String oldApptableName = queryForApplicationTableName(datatableName); if (!StringUtils.equals(oldApptableName, apptableName)) { final String oldFKName = oldApptableName.substring(2) + "_id"; final String newFKName = apptableName.substring(2) + "_id"; final String actualAppTableName = mapToActualAppTable(apptableName); final String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + oldFKName; final String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + newFKName; StringBuilder sqlBuilder = new StringBuilder(); if (mapColumnNameDefinition.containsKey("id")) { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP KEY `fk_" + oldFKName + "`,") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD KEY `fk_" + newFKName + "` (`" + newFKName + "`),") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } else { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } this.jdbcTemplate.execute(sqlBuilder.toString()); deregisterDatatable(datatableName); registerDatatable(datatableName, apptableName); } } if (changeColumns == null && addColumns == null && dropColumns == null) { return; } if (dropColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final List<String> codeMappings = new ArrayList<>(); for (final JsonElement column : dropColumns) { parseDatatableColumnForDrop(column.getAsJsonObject(), sqlBuilder, datatableName, constrainBuilder, codeMappings); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(codeMappings); } if (addColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<>(); for (final JsonElement column : addColumns) { parseDatatableColumnForAdd(column.getAsJsonObject(), sqlBuilder, datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); registerColumnCodeMapping(codeMappings); } if (changeColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<>(); final List<String> removeMappings = new ArrayList<>(); for (final JsonElement column : changeColumns) { // remove NULL values from column where mandatory is true removeNullValuesFromStringColumn(datatableName, column.getAsJsonObject(), mapColumnNameDefinition); parseDatatableColumnForUpdate(column.getAsJsonObject(), mapColumnNameDefinition, sqlBuilder, datatableName, constrainBuilder, codeMappings, removeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); try { this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(removeMappings); registerColumnCodeMapping(codeMappings); } catch (final GenericJDBCException e) { if (e.getMessage().contains("Error on rename")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the column name modification not allowed"); } } catch (final Exception e) { // handle all other exceptions in here // check if exception message contains the // "invalid use of null value" SQL exception message // throw a 503 HTTP error - // PlatformServiceUnavailableException if (e.getMessage().toLowerCase().contains("invalid use of null value")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the data table columns contains null values"); } } } } catch (final SQLGrammarException e) { final Throwable realCause = e.getCause(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("datatable"); if (realCause.getMessage().toLowerCase().contains("unknown column")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("can't drop")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("duplicate column")) { baseDataValidator.reset().parameter("name").failWithCode("column.already.exists"); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } }
From source file:org.sakaiproject.message.impl.BaseMessageService.java
/** * Access the internal reference which can be used to access the message from within the system. * /* w ww . j a va2s. c o m*/ * @param channelRef * The channel reference. * @param id * The message id. * @return The the internal reference which can be used to access the message from within the system. */ public String messageReference(String channelRef, String id) { StringBuilder buf = new StringBuilder(); // start with the channel ref buf.append(channelRef); // swap channel for msg int pos = buf.indexOf(REF_TYPE_CHANNEL); buf.replace(pos, pos + REF_TYPE_CHANNEL.length(), REF_TYPE_MESSAGE); // add the id buf.append(Entity.SEPARATOR); buf.append(id); return buf.toString(); }
From source file:com.gst.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java
@Transactional @Override/*from w w w.ja v a 2 s.co m*/ public void updateDatatable(final String datatableName, final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final JsonElement element = this.fromJsonHelper.parse(command.json()); final JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element); final JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element); final JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element); final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); validateDatatableName(datatableName); final List<ResultsetColumnHeaderData> columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(datatableName); final Map<String, ResultsetColumnHeaderData> mapColumnNameDefinition = new HashMap<>(); for (final ResultsetColumnHeaderData columnHeader : columnHeaderData) { mapColumnNameDefinition.put(columnHeader.getColumnName(), columnHeader); } final boolean isConstraintApproach = this.configurationDomainService .isConstraintApproachEnabledForDatatables(); if (!StringUtils.isBlank(apptableName)) { validateAppTable(apptableName); final String oldApptableName = queryForApplicationTableName(datatableName); if (!StringUtils.equals(oldApptableName, apptableName)) { final String oldFKName = oldApptableName.substring(2) + "_id"; final String newFKName = apptableName.substring(2) + "_id"; final String actualAppTableName = mapToActualAppTable(apptableName); final String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + oldFKName; final String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + newFKName; StringBuilder sqlBuilder = new StringBuilder(); if (mapColumnNameDefinition.containsKey("id")) { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP KEY `fk_" + oldFKName + "`,") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD KEY `fk_" + newFKName + "` (`" + newFKName + "`),") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } else { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } this.jdbcTemplate.execute(sqlBuilder.toString()); deregisterDatatable(datatableName); registerDatatable(datatableName, apptableName); } } if (changeColumns == null && addColumns == null && dropColumns == null) { return; } if (dropColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final List<String> codeMappings = new ArrayList<>(); for (final JsonElement column : dropColumns) { parseDatatableColumnForDrop(column.getAsJsonObject(), sqlBuilder, datatableName, constrainBuilder, codeMappings); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(codeMappings); } if (addColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<>(); for (final JsonElement column : addColumns) { parseDatatableColumnForAdd(column.getAsJsonObject(), sqlBuilder, datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); registerColumnCodeMapping(codeMappings); } if (changeColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<>(); final List<String> removeMappings = new ArrayList<>(); for (final JsonElement column : changeColumns) { // remove NULL values from column where mandatory is true removeNullValuesFromStringColumn(datatableName, column.getAsJsonObject(), mapColumnNameDefinition); parseDatatableColumnForUpdate(column.getAsJsonObject(), mapColumnNameDefinition, sqlBuilder, datatableName, constrainBuilder, codeMappings, removeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); try { this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(removeMappings); registerColumnCodeMapping(codeMappings); } catch (final Exception e) { if (e.getMessage().contains("Error on rename")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the column name modification not allowed"); } // handle all other exceptions in here // check if exception message contains the // "invalid use of null value" SQL exception message // throw a 503 HTTP error - // PlatformServiceUnavailableException if (e.getMessage().toLowerCase().contains("invalid use of null value")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the data table columns contains null values"); } } } } catch (final DataIntegrityViolationException e) { final Throwable realCause = e.getCause(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("datatable"); if (realCause.getMessage().toLowerCase().contains("unknown column")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("can't drop")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("duplicate column")) { baseDataValidator.reset().parameter("name").failWithCode("column.already.exists"); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } catch (final PersistenceException ee) { Throwable realCause = ExceptionUtils.getRootCause(ee.getCause()); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("datatable"); if (realCause.getMessage().toLowerCase().contains("duplicate column name")) { baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name"); } else if (realCause.getMessage().contains("Table") && realCause.getMessage().contains("already exists")) { baseDataValidator.reset().parameter("datatableName").value(datatableName) .failWithCode("datatable.already.exists"); } else if (realCause.getMessage().contains("Column") && realCause.getMessage().contains("big")) { baseDataValidator.reset().parameter("column").failWithCode("length.too.big"); } else if (realCause.getMessage().contains("Row") && realCause.getMessage().contains("large")) { baseDataValidator.reset().parameter("row").failWithCode("size.too.large"); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
public static Map<String, Object> searchAPIsByURLPattern(Registry registry, String searchTerm, int start, int end) throws APIManagementException { SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator()); List<API> apiList = new ArrayList<API>(); final String searchValue = searchTerm.trim(); Map<String, Object> result = new HashMap<String, Object>(); int totalLength = 0; String criteria;/*from w ww .j a v a2 s . c o m*/ Map<String, List<String>> listMap = new HashMap<String, List<String>>(); GenericArtifact[] genericArtifacts = new GenericArtifact[0]; GenericArtifactManager artifactManager = null; try { artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY); PaginationContext.init(0, 10000, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE); if (artifactManager != null) { for (int i = 0; i < 20; i++) { //This need to fix in future.We don't have a way to get max value of // "url_template" entry stores in registry,unless we search in each API criteria = APIConstants.API_URI_PATTERN + i; listMap.put(criteria, new ArrayList<String>() { { add(searchValue); } }); genericArtifacts = (GenericArtifact[]) ArrayUtils.addAll(genericArtifacts, artifactManager.findGenericArtifacts(listMap)); } if (genericArtifacts == null || genericArtifacts.length == 0) { result.put("apis", apiSet); result.put("length", 0); return result; } totalLength = genericArtifacts.length; StringBuilder apiNames = new StringBuilder(); for (GenericArtifact artifact : genericArtifacts) { if (apiNames.indexOf(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME)) < 0) { String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS); if (isAllowDisplayAPIsWithMultipleStatus()) { if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) { API api = APIUtil.getAPI(artifact, registry); if (api != null) { apiList.add(api); apiNames.append(api.getId().getApiName()); } } } else { if (APIConstants.PUBLISHED.equals(status)) { API api = APIUtil.getAPI(artifact, registry); if (api != null) { apiList.add(api); apiNames.append(api.getId().getApiName()); } } } } totalLength = apiList.size(); } if (totalLength <= ((start + end) - 1)) { end = totalLength; } for (int i = start; i < end; i++) { apiSet.add(apiList.get(i)); } } } catch (APIManagementException e) { handleException("Failed to search APIs with input url-pattern", e); } catch (GovernanceException e) { handleException("Failed to search APIs with input url-pattern", e); } result.put("apis", apiSet); result.put("length", totalLength); return result; }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
/** * Given a URL, this method checks if the underlying document is a WSDL2 * * @param url// w w w . j ava 2 s . c o m * @return * @throws Exception */ public static boolean isWSDL2Document(String url) throws APIManagementException { URL wsdl = null; boolean isWsdl2 = false; try { wsdl = new URL(url); } catch (MalformedURLException e) { throw new APIManagementException("Malformed URL encountered", e); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(wsdl.openStream(), Charset.defaultCharset())); String inputLine; StringBuilder urlContent = new StringBuilder(); while ((inputLine = in.readLine()) != null) { String wsdl2NameSpace = "http://www.w3.org/ns/wsdl"; urlContent.append(inputLine); isWsdl2 = urlContent.indexOf(wsdl2NameSpace) > 0; } in.close(); if (isWsdl2) { WSDLReader wsdlReader20 = null; wsdlReader20 = WSDLFactory.newInstance().newWSDLReader(); wsdlReader20.readWSDL(url); } } catch (IOException e) { throw new APIManagementException("Error Reading Input from Stream from " + url, e); } catch (WSDLException e) { throw new APIManagementException("Error while reading WSDL Document from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("Error when closing input stream", e); } } } return isWsdl2; }
From source file:com.cohort.util.String2.java
/** * Returns the same StringBuilder, where all occurences of <tt>oldCh</tt> have * been replaced with <tt>newCh</tt>. * * @return the same StringBuilder, for convenience. *///w w w . j a v a 2 s. co m public static StringBuilder replaceAll(StringBuilder sb, char oldCh, char newCh) { String oldS = "" + oldCh; int po = sb.indexOf(oldS); while (po >= 0) { sb.setCharAt(po, newCh); po = sb.indexOf(oldS, po + 1); } return sb; }
From source file:com.cohort.util.String2.java
/** * This returns the string with just file-name-safe characters (0-9, A-Z, a-z, _, -, .). * This is different from String2.encodeFileNameSafe -- * this emphasizes readability, not avoiding losing information. * Non-safe characters are converted to '_'. * Adjacent '_' are collapsed into '_'./*from w w w . j a va 2 s. c om*/ * See posix fully portable file names at https://en.wikipedia.org/wiki/Filename . * See javadocs for java.net.URLEncoder, which describes valid characters * (but deals with encoding, whereas this method alters or removes). * The result may be shorter than s. * Note, this does not check for filenames that are too long * (Windows has a path+fileName max length of 255 chars). * * @param s If s is null, this returns "_null". * If s is "", this returns "_". * @return s with all of the non-fileNameSafe characters removed or changed */ public static String modifyToBeFileNameSafe(String s) { if (s == null) return "_null"; s = modifyToBeASCII(s); int n = s.length(); if (n == 0) return "_"; StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; i++) { char ch = s.charAt(i); sb.append(isFileNameSafe(ch) ? ch : '_'); } while (sb.indexOf("__") >= 0) replaceAll(sb, "__", "_"); return sb.toString(); }
From source file:com.cohort.util.String2.java
/** * Replaces all occurences of <tt>oldS</tt> in sb with <tt>newS</tt>. * If <tt>oldS</tt> occurs inside <tt>newS</tt>, it won't be replaced * recursively (obviously).//from w w w . j av a 2 s. c om * * @param sb the StringBuilder * @param oldS the string to be searched for * @param newS the string to replace oldS * @param ignoreCase If true, when searching sb for oldS, this ignores the case of sb and oldS. * @return the number of replacements made. */ public static int replaceAll(StringBuilder sb, String oldS, String newS, boolean ignoreCase) { int sbL = sb.length(); int oldSL = oldS.length(); if (oldSL == 0) return 0; int newSL = newS.length(); StringBuilder testSB = sb; String testOldS = oldS; if (ignoreCase) { testSB = new StringBuilder(sbL); for (int i = 0; i < sbL; i++) testSB.append(Character.toLowerCase(sb.charAt(i))); testOldS = oldS.toLowerCase(); } int po = testSB.indexOf(testOldS); //System.out.println("testSB=" + testSB.toString() + " testOldS=" + testOldS + " po=" + po); //not String2.log if (po < 0) return 0; StringBuilder sb2 = new StringBuilder(sbL / 5 * 6); //a little bigger int base = 0; int n = 0; while (po >= 0) { n++; sb2.append(sb.substring(base, po)); sb2.append(newS); base = po + oldSL; po = testSB.indexOf(testOldS, base); //System.out.println("testSB=" + testSB.toString() + " testOldS=" + testOldS + " po=" + po + // " sb2=" + sb2.toString()); //not String2.log } sb2.append(sb.substring(base)); sb.setLength(0); sb.append(sb2); return n; }