List of usage examples for java.lang StringBuilder replace
@Override public StringBuilder replace(int start, int end, String str)
From source file:it.unibas.spicy.model.algebra.query.operators.xquery.GenerateXQueryForSourceToTargetExchange.java
private String materializeResultOfExchange(MappingTask mappingTask, List<FORule> tgds) { if (logger.isTraceEnabled()) logger.trace("Materializing Result of S-T Exchange..."); StringBuilder result = new StringBuilder(); result.append("\n(:----------------------- RESULT OF EXCHANGE ---------------------------:)\n\n"); List<SetAlias> targetVariables = mappingTask.getTargetProxy().getMappingData().getVariables(); for (int i = 0; i < targetVariables.size(); i++) { SetAlias targetVariable = targetVariables.get(i); List<FORule> relevantTGDs = findRelevantTGDs(targetVariable, mappingTask.getMappingData().getRewrittenRules()); if (!relevantTGDs.isEmpty()) { String viewName = XQNames.finalXQueryNameSTExchange(targetVariable); /// TODO: check GenerateXQuery.materializedViews.put("" + targetVariable.getId(), viewName); result.append(generateBlockForShredding(targetVariable, mappingTask, relevantTGDs, viewName)); result.append(",\n"); }//from w ww.j a v a 2 s. co m } result.replace(result.length() - 2, result.length(), "\n"); return result.toString(); }
From source file:org.apache.directory.server.core.schema.SchemaInterceptor.java
/** * Checks to see the presence of all required attributes within an entry. *///w w w .j a v a 2 s . c o m private void assertRequiredAttributesPresent(Dn dn, Entry entry, Set<String> must) throws LdapException { for (Attribute attribute : entry) { must.remove(attribute.getAttributeType().getOid()); } if (!must.isEmpty()) { // include AT names for better error reporting StringBuilder sb = new StringBuilder(); sb.append('['); for (String oid : must) { String name = schemaManager.getAttributeType(oid).getName(); sb.append(name).append('(').append(oid).append("), "); } int end = sb.length(); sb.replace(end - 2, end, ""); // remove the trailing ', ' sb.append(']'); throw new LdapSchemaViolationException(ResultCodeEnum.OBJECT_CLASS_VIOLATION, I18n.err(I18n.ERR_279, sb, dn.getName())); } }
From source file:pl.epodreczniki.service.MetadataService.java
private ContentProviderOperation toInsertOperation(JSONBook book) { if (book == null) { return null; }//from w ww . j a va 2 s . c om int longerEdge = Util.getLongerEdge(this); StringBuilder authorsStringBuilder = new StringBuilder(); String mainAuthor = null; if (book.getMdAuthors() != null) { final JSONAuthor.JSONAuthorComparator cmp = new JSONAuthor.JSONAuthorComparator(); Map<String, List<JSONAuthor>> byRoles = authorsByRoles(book.getMdAuthors()); for (Map.Entry<String, List<JSONAuthor>> entry : byRoles.entrySet()) { final String roleName = entry.getKey(); if (!roleName.equals(KEY_ROLELESS)) { authorsStringBuilder.append("<b>").append(roleName).append("</b><br />"); } else { authorsStringBuilder.append("<b>").append("Autorzy").append("</b><br />"); } Collections.sort(entry.getValue(), cmp); for (JSONAuthor auth : entry.getValue()) { final String fullName = TextUtils.isEmpty(auth.getMdFullName()) ? auth.getFullName() : auth.getMdFullName(); if (!TextUtils.isEmpty(fullName)) { authorsStringBuilder.append(fullName); authorsStringBuilder.append(", "); if (mainAuthor == null) { mainAuthor = fullName; } } } if (authorsStringBuilder.toString().endsWith(", ")) { authorsStringBuilder.replace(authorsStringBuilder.length() - 2, authorsStringBuilder.length(), "<br />"); } } } String educationLevel = null; Integer epClass = null; if (book.getMdSchool() != null) { educationLevel = book.getMdSchool().getMdEducationLevel(); epClass = book.getMdSchool().getEpClass(); } String subject = null; if (book.getMdSubject() != null) { subject = book.getMdSubject().getMdName(); } String zip = null; Long extractedSize = null; if (book.getFormats() != null) { Map<Integer, UrlAndSize> resolutions = new TreeMap<Integer, UrlAndSize>(); for (JSONFormat format : book.getFormats()) { final String formatStr = format.getFormat(); if (!TextUtils.isEmpty(formatStr)) { if (formatStr.matches(Constants.RE_ZIP)) { final int resolution = Integer.parseInt(formatStr.split("-")[1]); final String url = format.getUrl(); final Long size = format.getSize(); resolutions.put(resolution, new UrlAndSize(url, size)); } } } int chosen = 0; for (Map.Entry<Integer, UrlAndSize> entry : resolutions.entrySet()) { chosen = chosen == 0 ? entry.getKey() : (entry.getKey() <= longerEdge ? entry.getKey() : chosen); } final UrlAndSize choice = resolutions.get(chosen); zip = choice.url; extractedSize = choice.size; } String cover = null; if (book.getCovers() != null) { Map<Integer, String> resolutions = new TreeMap<Integer, String>(); for (JSONFormat cvr : book.getCovers()) { final String formatStr = cvr.getFormat(); if (!TextUtils.isEmpty(formatStr)) { if (formatStr.matches(Constants.RE_COVER)) { final int resolution = Integer.parseInt(formatStr.split("-")[1]); final String url = cvr.getUrl(); resolutions.put(resolution, url); } } } int chosen = 0; for (Map.Entry<Integer, String> entry : resolutions.entrySet()) { chosen = chosen == 0 ? entry.getKey() : (entry.getKey() <= longerEdge ? entry.getKey() : chosen); } Log.e("MDS", "chosen cover resolution: " + chosen); cover = resolutions.get(chosen); } ContentProviderOperation.Builder res = ContentProviderOperation.newInsert(BooksProvider.BOOKS_URI) .withValue(BooksTable.C_MD_CONTENT_ID, book.getMdContentId()) .withValue(BooksTable.C_MD_TITLE, book.getMdTitle()) .withValue(BooksTable.C_MD_ABSTRACT, book.getMdAbstract()) .withValue(BooksTable.C_MD_PUBLISHED, book.getMdPublished() == null ? 0 : book.getMdPublished() ? 1 : 0) .withValue(BooksTable.C_MD_VERSION, book.getMdVersion()) .withValue(BooksTable.C_MD_LANGUAGE, book.getMdLanguage()) .withValue(BooksTable.C_MD_LICENSE, book.getMdLicense()) .withValue(BooksTable.C_MD_CREATED, book.getMdCreated()) .withValue(BooksTable.C_MD_REVISED, book.getMdRevised()).withValue(BooksTable.C_COVER, cover) .withValue(BooksTable.C_LINK, book.getLink()) .withValue(BooksTable.C_MD_SUBTITLE, book.getMdSubtitle()) .withValue(BooksTable.C_AUTHORS, authorsStringBuilder.toString()) .withValue(BooksTable.C_MAIN_AUTHOR, mainAuthor) .withValue(BooksTable.C_EDUCATION_LEVEL, educationLevel).withValue(BooksTable.C_CLASS, epClass) .withValue(BooksTable.C_SUBJECT, subject).withValue(BooksTable.C_ZIP, zip) .withValue(BooksTable.C_EXTRACTED_SIZE, extractedSize); if (book.getAppVersion() != null) { return res.withValue(BooksTable.C_APP_VERSION, book.getAppVersion()).build(); } else { return res.build(); } }
From source file:org.sakaiproject.nakamura.http.i18n.I18nFilter.java
/** * Filter <code>output</code> of any message keys by replacing them with the matching * message from the language bundle associated to the user. * * @param srequest/*from w w w . j av a2s. c om*/ * @param response * @param output * @throws IOException */ private void writeFilteredResponse(SlingHttpServletRequest srequest, ServletResponse response, String output) throws IOException { StringBuilder sb = new StringBuilder(output); try { Session session = srequest.getResourceResolver().adaptTo(Session.class); Node bundlesNode = session.getNode(bundlesPath); // load the language bundle Locale locale = getLocale(srequest); Properties bndLang = getLangBundle(bundlesNode, locale.toString()); // load the default bundle Properties bndLangDefault = getLangBundle(bundlesNode, "default"); // check for message keys and replace them with the appropriate message Matcher m = messageKeyPattern.matcher(output); ArrayList<String> matchedKeys = new ArrayList<String>(); while (m.find()) { String msgKey = m.group(0); String key = m.group(1); if (!matchedKeys.contains(key)) { String message = ""; if (bndLang.containsKey(key)) { message = bndLang.getProperty(key); } else if (bndLangDefault.containsKey(key)) { message = bndLangDefault.getProperty(key); } else { String msg = "[MESSAGE KEY NOT FOUND '" + key + "']"; logger.warn(msg); if (showMissingKeys) { message = msg; } } // replace all instances of msgKey with the actual message int keyStart = sb.indexOf(msgKey); while (keyStart >= 0) { sb.replace(keyStart, keyStart + msgKey.length(), message); keyStart = sb.indexOf(msgKey, keyStart); } // track the group so we don't try to replace it again matchedKeys.add(key); } } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } response.setContentLength(sb.length()); // send the output to the actual response try { response.getWriter().write(sb.toString()); } catch (IllegalStateException e) { response.getOutputStream().write(sb.toString().getBytes("UTF-8")); } }
From source file:meff.Function.java
private Map<String, String> compile() { class Compiler { private Map<String, StringBuilder> functions; private String currentFunctionName; private StringBuilder currentFunction; Compiler(String functionName) { functions = new HashMap<>(); currentFunctionName = functionName; currentFunction = new StringBuilder(); functions.put(currentFunctionName, currentFunction); }/*from ww w . ja v a 2s .c o m*/ void compileLine(StringBuilder line) { // Manage score value features { Matcher m = Pattern.compile("(score_\\w+)(>=|>|<=|<|==)(-?\\d+)").matcher(line); while (m.find()) { int offset = m.start(); String beginning = m.group(1); String operator = m.group(2); String end = m.group(3); StringBuilder newScore = new StringBuilder(); switch (operator) { case ">=": newScore.append(beginning).append("_min=").append(end); break; case ">": newScore.append(beginning).append("_min=").append(Integer.parseInt(end) + 1); break; case "<=": newScore.append(beginning).append("=").append(end); break; case "<": newScore.append(beginning).append("=").append(Integer.parseInt(end) - 1); break; case "==": newScore.append(beginning).append("_min=").append(end).append(",").append(beginning) .append("=").append(end); break; } line.replace(offset, offset + m.group().length(), newScore.toString()); m.reset(); // Need to reset the matcher, so it updates the length of the text } } currentFunction.append(line).append("\n"); } Map<String, String> getOutput() { Map<String, String> outputMap = new HashMap<>(functions.size()); for (Map.Entry<String, StringBuilder> entry : functions.entrySet()) { outputMap.put(entry.getKey() + ".mcfunction", entry.getValue().toString()); } return outputMap; } } Compiler compiler = new Compiler(getName()); boolean comment = false; StringBuilder sb = new StringBuilder(); for (String line : data.lines) { line = line.trim(); if (line.startsWith("#") || line.startsWith("//")) { continue; } if (line.isEmpty()) { continue; } int si = 0; // start index int bci = -1; // block comment index int bcei = -1; // block comment end index int prevBci = -1; int prevBcei = -1; while ((!comment && (bci = line.indexOf("/*", si)) > -1) || (comment && (bcei = line.indexOf("*/", si)) > -1)) { if (comment) { if (line.charAt(bcei - 1) == '\\') { si = bcei + 2; bcei = prevBcei; continue; } comment = false; si = bcei + 2; } else { if (line.charAt(bci - 1) == '\\') { sb.append(line.substring(si, bci - 1)).append("/*"); si = bci + 2; bci = prevBci; continue; } sb.append(line.substring(si, bci)); comment = true; si = bci + 2; } prevBci = bci; prevBcei = bcei; } if (comment) { continue; } if (line.endsWith("\\")) { line = line.substring(si, line.length() - 1); sb.append(line); } else { sb.append(line.substring(si)); compiler.compileLine(sb); sb.delete(0, sb.length()); } } return compiler.getOutput(); }
From source file:com.cloopen.rest.sdk.CCPRestSDK.java
/** * ???// ww w .j a v a 2s .co m * * @param to * ? ??????????100 * @param templateId * ? ?Id * @param datas * ?? ???{??} * @return */ public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId))) throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "") + (isEmpty(templateId) ? " ?Id " : "") + ""); CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { e1.printStackTrace(); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("to", to); json.addProperty("templateId", templateId); if (datas != null) { StringBuilder sb = new StringBuilder("["); for (String s : datas) { sb.append("\"" + s + "\"" + ","); } sb.replace(sb.length() - 1, sb.length(), "]"); JsonParser parser = new JsonParser(); JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray(); json.add("datas", Jarray); } requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>") .append("<templateId>").append(templateId).append("</templateId>"); if (datas != null) { sb.append("<datas>"); for (String s : datas) { sb.append("<data>").append(s).append("</data>"); } sb.append("</datas>"); } sb.append("</TemplateSMS>").toString(); requsetbody = sb.toString(); } //? System.out.println("" + requsetbody); LoggerUtil.info("sendTemplateSMS Request body = " + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); //??? status = response.getStatusLine().getStatusCode(); System.out.println("Https??" + status); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172001", "" + "Https?" + status); } catch (Exception e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } LoggerUtil.info("sendTemplateSMS response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }
From source file:org.apache.oozie.command.coord.CoordCommandUtils.java
/** * @param eAction the actionXml related element * @param actionBean the coordinator action bean * @return//from ww w.j a v a 2 s . co m * @throws Exception */ static String dryRunCoord(Element eAction, CoordinatorActionBean actionBean) throws Exception { String action = XmlUtils.prettyPrint(eAction).toString(); StringBuilder actionXml = new StringBuilder(action); Configuration actionConf = new XConfiguration(new StringReader(actionBean.getRunConf())); actionBean.setActionXml(action); if (CoordUtils.isInputLogicSpecified(eAction)) { new CoordInputLogicEvaluatorUtil(actionBean).validateInputLogic(); } boolean isPushDepAvailable = true; String pushMissingDependencies = actionBean.getPushInputDependencies().getMissingDependencies(); if (pushMissingDependencies != null) { ActionDependency actionDependencies = DependencyChecker.checkForAvailability(pushMissingDependencies, actionConf, true); if (actionDependencies.getMissingDependencies().size() != 0) { isPushDepAvailable = false; } } boolean isPullDepAvailable = true; CoordActionInputCheckXCommand coordActionInput = new CoordActionInputCheckXCommand(actionBean.getId(), actionBean.getJobId()); if (actionBean.getMissingDependencies() != null) { StringBuilder existList = new StringBuilder(); StringBuilder nonExistList = new StringBuilder(); StringBuilder nonResolvedList = new StringBuilder(); getResolvedList(actionBean.getPullInputDependencies().getMissingDependencies(), nonExistList, nonResolvedList); isPullDepAvailable = actionBean.getPullInputDependencies().checkPullMissingDependencies(actionBean, existList, nonExistList); } if (isPullDepAvailable && isPushDepAvailable) { // Check for latest/future boolean isLatestFutureDepAvailable = coordActionInput.checkUnResolvedInput(actionBean, actionXml, actionConf); if (isLatestFutureDepAvailable) { String newActionXml = CoordActionInputCheckXCommand.resolveCoordConfiguration(actionXml, actionConf, actionBean.getId()); actionXml.replace(0, actionXml.length(), newActionXml); } } return actionXml.toString(); }
From source file:org.betaconceptframework.astroboa.model.impl.BinaryChannelImpl.java
public String buildResourceApiURL(Integer width, Integer height, Double aspectRatio, CropPolicy cropPolicy, ContentDispositionType contentDispositionType, boolean friendlyUrl, boolean relative) { if (StringUtils.isBlank(contentObjectId) || StringUtils.isBlank(binaryPropertyPermanentPath)) { return ""; }/* w w w . ja v a 2s . c om*/ // Astroboa RESTful API URL pattern for accessing the value of content object properties // http://server/resource-api/ // <reposiotry-id>/objects/<contentObjectId>/<binaryChannelPropertyValuePath> // ?contentDispositionType=<contentDispositionType>&width=<width>&height=<height> StringBuilder resourceApiURLBuilder = new StringBuilder(); if (!relative) { String serverURL = getServerURL(); if (serverURL != null) { resourceApiURLBuilder.append(serverURL); } } resourceApiURLBuilder.append(getRestfulApiBasePath()).append(CmsConstants.FORWARD_SLASH); resourceApiURLBuilder.append((StringUtils.isBlank(repositoryId) ? "no-repository" : repositoryId)); resourceApiURLBuilder.append(CmsConstants.RESOURCE_API_OBJECTS_COLLECTION_URI_PATH); if (friendlyUrl) { resourceApiURLBuilder.append(CmsConstants.FORWARD_SLASH).append(contentObjectSystemName); } else { resourceApiURLBuilder.append(CmsConstants.FORWARD_SLASH).append(contentObjectId); } resourceApiURLBuilder.append(CmsConstants.FORWARD_SLASH).append(binaryPropertyPermanentPath); if (binaryPropertyIsMultiValued) { resourceApiURLBuilder.append(CmsConstants.LEFT_BRACKET).append(getId()) .append(CmsConstants.RIGHT_BRACKET); } StringBuilder urlParametersBuilder = new StringBuilder(); if (contentDispositionType != null) { urlParametersBuilder.append(CmsConstants.AMPERSAND).append("contentDispositionType") .append(CmsConstants.EQUALS_SIGN).append(contentDispositionType.toString().toLowerCase()); } if (isJPGorPNGorGIFImage()) { if (width != null && width > 0) { urlParametersBuilder.append(CmsConstants.AMPERSAND).append("width").append(CmsConstants.EQUALS_SIGN) .append(width); } if (height != null && height > 0) { urlParametersBuilder.append(CmsConstants.AMPERSAND).append("height") .append(CmsConstants.EQUALS_SIGN).append(height); } // we accept to set a new aspect ratio only if if (aspectRatio != null && (width == null || height == null)) { urlParametersBuilder.append(CmsConstants.AMPERSAND).append("aspectRatio") .append(CmsConstants.EQUALS_SIGN).append(aspectRatio); if (cropPolicy != null) { urlParametersBuilder.append(CmsConstants.AMPERSAND).append("cropPolicy") .append(CmsConstants.EQUALS_SIGN).append(cropPolicy.toString()); } } } if (urlParametersBuilder.length() > 0) { urlParametersBuilder.replace(0, 1, CmsConstants.QUESTION_MARK); } return resourceApiURLBuilder.append(urlParametersBuilder).toString(); }
From source file:gov.nih.nci.nbia.customserieslist.FileGenerator.java
/** * generate comma separate string from the series instance uid list * @param seriesItems/*from www .ja v a2 s.c om*/ */ public String generateImageMetadata(List<BasketSeriesItemBean> seriesItems) { String[] csvHeaders = new String[] { "Collection", "Patient Id", "Study Date", "Study Description", "Modality", "Series Description", "Manufacturer", "Manufacturer Model", "Software Version", "Series UID" }; StringBuilder sb = new StringBuilder(); for (String csvHeader : csvHeaders) { sb.append(csvHeader); sb.append(","); } sb.append("\n"); int size = seriesItems.size(); List<Integer> seriesPKIdLst = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { BasketSeriesItemBean bsib = seriesItems.get(i); seriesPKIdLst.add(bsib.getSeriesPkId()); } StudyDAO studyDAO = (StudyDAO) SpringApplicationContext.getBean("studyDAO"); List<StudyDTO> studies = studyDAO.findStudiesBySeriesIdDBSorted(seriesPKIdLst); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); for (StudyDTO study : studies) { List<SeriesDTO> seriesLst = study.getSeriesList(); for (SeriesDTO series : seriesLst) { sb.append(series.getProject()); sb.append(","); sb.append(series.getPatientId()); sb.append(","); sb.append(df.format(study.getDate())); sb.append(","); sb.append(StringEscapeUtils.escapeCsv(study.getDescription())); sb.append(","); sb.append(series.getModality()); sb.append(","); sb.append(StringEscapeUtils.escapeCsv(series.getDescription())); sb.append(","); sb.append(StringEscapeUtils.escapeCsv(series.getManufacturer())); sb.append(","); sb.append(StringEscapeUtils.escapeCsv(series.getManufacturerModelName())); sb.append(","); sb.append(StringEscapeUtils.escapeCsv(series.getSoftwareVersion())); sb.append(","); sb.append(series.getSeriesId()); sb.append(","); sb.append("\n"); } } int lastComma = sb.lastIndexOf(","); sb.replace(lastComma, lastComma, ""); sb.trimToSize(); return sb.toString(); }
From source file:net.sourceforge.fenixedu.domain.Degree.java
public String getFilteredName(final ExecutionYear executionYear, final Locale locale) { final StringBuilder res = new StringBuilder(getNameFor(executionYear).getContent(locale)); for (final Space campus : Space.getAllCampus()) { String toRemove = " - " + campus.getName(); if (res.toString().contains(toRemove)) { res.replace(res.indexOf(toRemove), res.indexOf(toRemove) + toRemove.length(), StringUtils.EMPTY); }/* ww w .j ava 2 s . c o m*/ } return res.toString(); }