List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java
@Override public ParserSchemaScim querySchemas(String providerName, String resourceEndPoint, ScimConnectorConfiguration conf) { List<String> excludedAttrs = new ArrayList<String>(); ServiceAccessManager accessManager = new ServiceAccessManager(conf); Header authHeader = accessManager.getAuthHeader(); String scimBaseUri = accessManager.getBaseUri(); if (authHeader == null || scimBaseUri.isEmpty()) { throw new ConnectorException( "The data needed for authorization of request to the provider was not found."); }//w w w. j a v a2 s .com HttpClient httpClient = initHttpClient(conf); String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).toString(); LOGGER.info("Qeury url: {0}", uri); HttpGet httpGet = buildHttpGet(uri, authHeader); try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); String responseString; if (entity != null) { responseString = EntityUtils.toString(entity); } else { responseString = ""; } int statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("Schema query status code: {0} ", statusCode); if (statusCode == 200) { if (!responseString.isEmpty()) { //LOGGER.warn("The returned response string for the \"schemas/\" endpoint"); JSONObject jsonObject = new JSONObject(responseString); ParserSchemaScim schemaParser = processSchemaResponse(jsonObject); excludedAttrs = excludeFromAssembly(excludedAttrs); for (String attr : excludedAttrs) { LOGGER.info("The attribute \"{0}\" will be omitted from the connId object build.", attr); } return schemaParser; } else { LOGGER.warn("Response string for the \"schemas/\" endpoint returned empty "); String resources[] = { USERS, GROUPS }; JSONObject responseObject = new JSONObject(); JSONArray responseArray = new JSONArray(); for (String resourceName : resources) { uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint) .append(resourceName).toString(); LOGGER.info("Additional query url: {0}", uri); httpGet = buildHttpGet(uri, authHeader); try (CloseableHttpResponse secondaryResponse = (CloseableHttpResponse) httpClient .execute(httpGet)) { statusCode = secondaryResponse.getStatusLine().getStatusCode(); responseString = EntityUtils.toString(secondaryResponse.getEntity()); if (statusCode == 200) { JSONObject jsonObject = new JSONObject(responseString); jsonObject = injectMissingSchemaAttributes(resourceName, jsonObject); responseArray.put(jsonObject); } else { LOGGER.warn( "No definition for provided shcemas was found, the connector will switch to default core schema configuration!"); return null; } } responseObject.put(RESOURCES, responseArray); } if (responseObject == JSONObject.NULL) { return null; } else { excludedAttrs = excludeFromAssembly(excludedAttrs); for (String attr : excludedAttrs) { LOGGER.info("The attribute \"{0}\" will be omitted from the connId object build.", attr); } return processSchemaResponse(responseObject); } } } else { handleInvalidStatus("while querying for schema. ", responseString, "schema", statusCode); } } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e); throw new ConnectorException( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification", e); } catch (IOException e) { StringBuilder errorBuilder = new StringBuilder( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object"); if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { errorBuilder.insert(0, "The connection timed out. "); throw new OperationTimeoutException(errorBuilder.toString(), e); } else { LOGGER.error( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object: {0}", e.getLocalizedMessage()); LOGGER.info( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object: {0}", e); throw new ConnectorIOException(errorBuilder.toString(), e); } } return null; }
From source file:ffx.potential.parsers.PDBFileMatcher.java
private void fixFile(FileFilePair currentPair, PDBFileReader filereader) throws IOException { File matchFile = currentPair.getMatchedFile(); Structure matchStructure = currentPair.getStructure(); if (matchStructure == null) { matchStructure = filereader.getStructure(matchFile); }/*from ww w .j a v a 2 s . c o m*/ File sourceFile = currentPair.getSourceFile(); if (sourceFile == null) { throw new IOException(String.format("No source file was matched to file %s", matchFile.toString())); } Structure sourceStructure = null; if (fixAtoms) { sourceStructure = filereader.getStructure(sourceFile); Atom[] matchAtoms = StructureTools.getAllAtomArray(matchStructure); for (Atom matchAtom : matchAtoms) { Atom sourceAtom = getMatchingAtom(matchAtom, sourceStructure, robustMatch); if (fixBFactors) { matchAtom.setTempFactor(sourceAtom.getTempFactor()); } } // Other methods can go here. } if (fixSSBonds) { if (sourceStructure == null) { sourceStructure = filereader.getStructure(sourceFile); } List<SSBond> sourceBonds = sourceStructure.getSSBonds(); List<SSBond> matchBonds = matchStructure.getSSBonds(); for (SSBond sourceBond : sourceBonds) { boolean isContained = false; for (SSBond matchBond : matchBonds) { if (compareSSBonds(matchBond, sourceBond)) { isContained = true; break; } } if (!isContained) { matchStructure.addSSBond(sourceBond.clone()); } } } if (fixCryst) { if (sourceStructure == null) { sourceStructure = filereader.getStructure(sourceFile); } PDBCrystallographicInfo crystalInfo = sourceStructure.getCrystallographicInfo(); try { PDBCrystallographicInfo duplicateInfo = cloneCrystalInfo(crystalInfo); matchStructure.setCrystallographicInfo(duplicateInfo); } catch (IllegalArgumentException ex) { logger.warning(String.format( " No crystal information for source structure " + "%s: nothing attached to file %s", sourceFile.toString(), matchFile.toString())); } } String pdb = matchStructure.toPDB(); if (headerLink) { StringBuilder pdbBuilder = new StringBuilder(pdb); int position = pdbBuilder.lastIndexOf("REMARK "); int remarkNumber = 4; if (position >= 0) { String nextLine = pdbBuilder.substring(position, position + 1000); int offset = nextLine.indexOf("%n"); if (offset < 0) { nextLine = pdbBuilder.substring(position); offset = nextLine.indexOf("%n"); } position += offset; String[] tok = nextLine.split(" +", 3); try { remarkNumber = Integer.parseInt(tok[1]) + 1; } catch (NumberFormatException ex) { // Silent. } } String toInsert = String.format("REMARK%4d SOURCE FILE: %s", remarkNumber, sourceFile.getName()); toInsert = toInsert .concat(String.format("REMARK%4d RMSD:%11.6f ANGSTROMS", remarkNumber, currentPair.getRMSD())); pdbBuilder.insert(position, toInsert); pdb = pdbBuilder.toString(); } File newFile = createVersionedCopy(matchFile); try (BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) { try { bw.write(pdb); } catch (IOException ex) { logger.warning(String.format(" Error writing to file %s", newFile.getName())); } } }
From source file:jenkins.branch.NameMangler.java
public static String apply(String name) { if (name.length() <= MAX_SAFE_LENGTH) { boolean unsafe = false; boolean first = true; for (char c : name.toCharArray()) { if (first) { if (c == '-') { // no leading dash unsafe = true;/*from w w w. j a va 2s.co m*/ break; } first = false; } if (!isSafe(c)) { unsafe = true; break; } } // See https://msdn.microsoft.com/en-us/library/aa365247 we need to consistently reserve names across all OS if (!unsafe) { // we know it is only US-ASCII if we got to here switch (name.toLowerCase(Locale.ENGLISH)) { case ".": case "..": case "con": case "prn": case "aux": case "nul": case "com1": case "com2": case "com3": case "com4": case "com5": case "com6": case "com7": case "com8": case "com9": case "lpt1": case "lpt2": case "lpt3": case "lpt4": case "lpt5": case "lpt6": case "lpt7": case "lpt8": case "lpt9": unsafe = true; break; default: if (name.endsWith(".")) { unsafe = true; } break; } } if (!unsafe) { return name; } } StringBuilder buf = new StringBuilder(name.length() + 16); for (char c : name.toCharArray()) { if (isSafe(c)) { buf.append(c); } else if (c == '/' || c == '\\' || c == ' ' || c == '.' || c == '_') { if (buf.length() == 0) { buf.append("0-"); } else { buf.append('-'); } } else if (c <= 0xff) { if (buf.length() == 0) { buf.append("0_"); } else { buf.append('_'); } buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0')); } else { if (buf.length() == 0) { buf.append("0_"); } else { buf.append('_'); } buf.append(StringUtils.leftPad(Integer.toHexString(((c & 0xffff) >> 8) & 0xff), 2, '0')); buf.append('_'); buf.append(StringUtils.leftPad(Integer.toHexString(c & 0xff), 2, '0')); } } // use the digest of the original name String digest; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] bytes = sha.digest(name.getBytes(StandardCharsets.UTF_8)); int bits = 0; int data = 0; StringBuffer dd = new StringBuffer(32); for (byte b : bytes) { while (bits >= 5) { dd.append(toDigit(data & 0x1f)); bits -= 5; data = data >> 5; } data = data | ((b & 0xff) << bits); bits += 8; } digest = dd.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA-1 not installed", e); // impossible } if (buf.length() <= MAX_SAFE_LENGTH - MIN_HASH_LENGTH - 1) { // we have room to add the min hash buf.append('.'); buf.append(StringUtils.right(digest, MIN_HASH_LENGTH)); return buf.toString(); } // buf now holds the mangled string, we will now try and rip the middle out to put in some of the digest int overage = buf.length() - MAX_SAFE_LENGTH; String hash; if (overage <= MIN_HASH_LENGTH) { hash = "." + StringUtils.right(digest, MIN_HASH_LENGTH) + "."; } else if (overage > MAX_HASH_LENGTH) { hash = "." + StringUtils.right(digest, MAX_HASH_LENGTH) + "."; } else { hash = "." + StringUtils.right(digest, overage) + "."; } int start = (MAX_SAFE_LENGTH - hash.length()) / 2; buf.delete(start, start + hash.length() + overage); buf.insert(start, hash); return buf.toString(); }
From source file:net.ontopia.persistence.query.sql.GenericSQLGenerator.java
protected String createStatement(SQLExpressionIF filter, List selects, boolean distinct, int offset, int limit, List orderby, boolean issetquery, BuildInfo info) { // Analyze query // WHERE and SELECT clauses must be created first. StringBuilder sql_select = createSelectClause(selects, distinct, info); if (issetquery) info.rtables.clear();// ww w. j a v a2 s . com StringBuilder sql_where = createWhereClause(filter, info); StringBuilder sql_group_by = createGroupByClause(info); StringBuilder sql_order_by = createOrderByClause(orderby, info); // FROM clause must be created at last. StringBuilder sql_from; if (issetquery) { sql_from = sql_where; sql_from.insert(0, '('); sql_from.append(')'); fromSubSelectAlias(sql_from, info); sql_where = null; } else sql_from = createFromClause(filter, info); StringBuilder sql_offset_limit = createOffsetLimitClause(offset, limit, info); // Construct the full statement. return createStatement(sql_select, sql_where, sql_from, sql_group_by, sql_order_by, sql_offset_limit, info); }
From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java
public final String portBindingCheck() { synchronized (this) { if (checkingPortBinding) { return lastPortCheckStatus; }//ww w .j a v a2 s . c om checkingPortBinding = true; } CheckerListener[] triggers = PluginVPNHelper.instance.getCheckerListeners(); for (CheckerListener l : triggers) { try { l.portCheckStart(); } catch (Exception e) { e.printStackTrace(); } } StringBuilder sReply = new StringBuilder(); try { int newStatusID = findBindingAddress(sReply); boolean doPortForwarding = config.getPluginBooleanParameter(PluginConstants.CONFIG_DO_PORT_FORWARDING); if (doPortForwarding) { boolean rpcCalled = false; if (newStatusID != STATUS_ID_BAD && vpnIP != null) { rpcCalled = callRPCforPort(vpnIP, sReply); } if (!rpcCalled) { if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; addReply(sReply, CHAR_WARN, "vpnhelper.port.forwarding.get.failed"); } } } if (newStatusID != -1) { currentStatusID = newStatusID; } String msgID = null; if (newStatusID == STATUS_ID_BAD) { msgID = "vpnhelper.topline.bad"; } else if (newStatusID == STATUS_ID_OK) { msgID = "vpnhelper.topline.ok"; } else if (newStatusID == STATUS_ID_WARN) { msgID = "vpnhelper.topline.warn"; } if (msgID != null) { sReply.insert(0, texts.getLocalisedMessageText(msgID) + "\n"); } } catch (Throwable t) { t.printStackTrace(); PluginVPNHelper.log(t.toString()); } lastPortCheckStatus = sReply.toString(); triggers = PluginVPNHelper.instance.getCheckerListeners(); for (CheckerListener l : triggers) { try { l.portCheckStatusChanged(lastPortCheckStatus); } catch (Exception e) { e.printStackTrace(); } } synchronized (this) { checkingPortBinding = false; } return lastPortCheckStatus; }
From source file:bogdanrechi.xmlo.Xmlo.java
/** * Perform XQuery operation./*from w w w . j av a 2 s .c o m*/ * * @param xqueryFile * XQuery file to perform by. */ private static void doXQuery(String xqueryFile) { Writer destinationFileStream = null; try { String xquery = Files.readTextFile(xqueryFile); _targetFolder = Files.getParent(_target); Format.println(GETTING_FILES); ArrayList<String> targets = new ArrayList<String>(); if (Files.browseFolder2(targets, _target, _recursive, _errorMessage)) { Format.println(PROCESSING); if (!_destinationIsTerminal && _destinationIsFile) destinationFileStream = new OutputStreamWriter(new FileOutputStream(_destination)); for (int i = 0; i < targets.size(); i++) { String target = targets.get(i); long timeStart = System.currentTimeMillis(); if (_verbose) Format.println(target); String outputFile = null; if (!_destinationIsTerminal && !_destinationIsFile) { outputFile = getDestinationFile(target, _extension == null ? EXTENSION_XQUERY_RESULT : _extension); if (_verbose) Format.print("Out: " + outputFile + "... "); } if (_verbose && _destinationIsFile && !_destinationIsTerminal) Format.print("... "); String output = null; Boolean error = false; Xml doc = new Xml(); if (!doc.load(new File(target))) { output = String.format("Error: %s", doc.getLastError()); if (_destinationIsTerminal) Format.print(output); error = true; } else if (!doc.applyXQuery(xquery, true, _errorMessage)) { output = String.format("Error: %s", doc.getLastError()); if (_destinationIsTerminal) Format.print(output); error = true; } Boolean hasResults = false; StringBuilder sb = new StringBuilder(); if (!error) if (hasResults = doc.hasXQueryResults()) { int j = 1; String firstItemText = ""; Property<String> itemTextProp = new Property<String>(); for (; doc.getNextXQueryResultItem(itemTextProp, _errorMessage); j++) { String itemText = itemTextProp.get(); if (!itemText.endsWith("\n")) itemText += "\n"; switch (j) { case 1: firstItemText = itemText; break; case 2: if (!_notNumbered) sb.append("\n-1-\n\n"); else sb.append("\n"); sb.append(firstItemText); default: if (!_notNumbered) sb.append(String.format("\n-%d-\n\n", j)); else sb.append("\n"); sb.append(itemText); break; } } if (!_errorMessage.isNull()) output = String.format("Error: %s", _errorMessage.get()); else { if (j == 1) sb.append("Empty selection"); else { if (j == 2) sb.append(firstItemText); if (!_notNumbered) sb.insert(0, String.format("%d node%s selected\n%s", j - 1, j == 2 ? "" : "s", j == 2 ? "\n" : "")); } output = sb.toString(); } if (_destinationIsTerminal) Format.print(output); } if (!_destinationIsTerminal) if (_destinationIsFile) { if (hasResults || !_resultsOnly) { if (_showDuration) destinationFileStream.write(String.format("--File: %s (in %s)\n\n", target, TimeMeasure.printDuration(timeStart))); else destinationFileStream.write(String.format("--File: %s\n\n", target)); if (output == null && !_resultsOnly) destinationFileStream.write(String.format("Error: %s\n\n", doc.getLastError())); else destinationFileStream.write(String.format("%s\n\n", output)); destinationFileStream.flush(); } } else if (hasResults || !_resultsOnly) { Files.createFolderForFile(outputFile); if (output == null && !_resultsOnly) Files.writeTextFile(String.format("Error: %s", doc.getLastError()), outputFile); else Files.writeTextFile(output, outputFile); } if (!_destinationIsTerminal && _verbose) if (_showDuration) Format.println(error ? "error!" : String.format("done in %s.", TimeMeasure.printDuration(timeStart))); else Format.println(error ? "error!" : "done."); } } else printErrorAndExit(_errorMessage.get()); } catch (Exception e) { printErrorAndExit(e.getMessage()); } finally { if (destinationFileStream != null) try { destinationFileStream.close(); if (_verbose) Format.println("Out: " + _destination + "... done."); } catch (IOException e) { printErrorAndExit("Unable to create results file!"); } } }
From source file:net.vexelon.mobileops.GLBClient.java
public String getCurrentBalance() throws HttpClientException { StringBuilder builder = new StringBuilder(100); HttpResponse resp;/* www . j a v a 2 s.c o m*/ long bytesCount = 0; try { String url = HTTP_MYTELENOR + GLBRequestType.GET_BALANCE.getPath(); url += '?'; url += new Date().getTime(); HttpGet httpGet = new HttpGet(url); // httpGet.setHeader("X-Requested-With", "XMLHttpRequest"); resp = httpClient.execute(httpGet, httpContext); } catch (Exception e) { throw new HttpClientException("Client protocol error!" + e.getMessage(), e); } StatusLine status = resp.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) throw new HttpClientException(status.getReasonPhrase(), status.getStatusCode()); try { HttpEntity entity = resp.getEntity(); // bytes downloaded bytesCount = entity.getContentLength() > 0 ? entity.getContentLength() : 0; Document doc = Jsoup.parse(entity.getContent(), RESPONSE_ENCODING, ""); Elements elements; // period bill elements = doc.select("#outstanding-amount"); if (elements.size() > 0) { Elements divs = elements.get(0).select("div"); for (Element el : divs) { String elClass = el.className(); if (elClass.contains("custme-select") || elClass.equalsIgnoreCase("history")) { builder.insert(0, el.html()); } } } // current bill elements = doc.select("#bars-wrapper .p-price"); if (elements.size() > 0) { Element el = elements.get(0); builder.insert(0, el.html()); } return builder.toString(); } catch (ClientProtocolException e) { throw new HttpClientException("Client protocol error!" + e.getMessage(), e); } catch (IOException e) { throw new HttpClientException("Client error!" + e.getMessage(), e); } finally { addDownloadedBytesCount(bytesCount); } }
From source file:eu.trentorise.opendata.jackan.CkanClient.java
/** * Search datasets according to the provided query. * * @param query/*from w w w .ja v a 2s .c o m*/ * The query object * @param limit * maximum results to return * @param offset * search begins from offset * @throws CkanException * on error */ public synchronized SearchResults<CkanDataset> searchDatasets(CkanQuery query, int limit, int offset) { checkNotNull(query, "Need a valid query!"); StringBuilder params = new StringBuilder(); params.append("rows=").append(limit).append("&start=").append(offset); if (query.getText().length() > 0) { params.append("&q="); params.append(urlEncode(query.getText())); } StringBuilder fq = new StringBuilder(); String fqPrefix = ""; fqPrefix = appendNamesList(fqPrefix, "groups", query.getGroupNames(), fq); fqPrefix = appendNamesList(fqPrefix, "organization", query.getOrganizationNames(), fq); fqPrefix = appendNamesList(fqPrefix, "tags", query.getTagNames(), fq); fqPrefix = appendNamesList(fqPrefix, "license_id", query.getLicenseIds(), fq); if (fq.length() > 0) { params.append("&fq=").append(urlEncode(fq.insert(0, "(").append(")").toString())); } DatasetSearchResponse dsr; dsr = getHttp(DatasetSearchResponse.class, "/api/3/action/package_search?" + params.toString()); for (CkanDataset ds : dsr.result.getResults()) { for (CkanResource cr : ds.getResources()) { cr.setPackageId(ds.getId()); } } return dsr.result; }
From source file:it.txt.access.capability.revocation.wizard.panel.PanelRevocationData.java
public void validateForm() throws PanelRevocationDataException { StringBuilder missingFields = new StringBuilder(); StringBuilder invalidFields = new StringBuilder(); isMissingTextField(textbox_rev_issuer, missingFields); isMissingTextField(textbox_rev_reason, missingFields); isMissingFormattedTextField(textbox_revoked_since_datetime, missingFields); isMissingFormattedTextField(textbox_revoked_since_time, missingFields); if (!isMissingTextField(textbox_notification_email, missingFields)) { if (!EmailValidator.getInstance().isValid(textbox_notification_email.getText())) { if (invalidFields.length() > 0) invalidFields.append(", " + textbox_notification_email.getName()); else/*from w w w . ja va2 s .co m*/ invalidFields.append(textbox_notification_email.getName()); } } isMissingTextField(textbox_revoked_aucap_issuer, missingFields); isMissingFormattedTextField(textbox_revoked_aucap_issue_datetime, missingFields); isMissingFormattedTextField(textbox_revoked_aucap_issue_time, missingFields); isMissingTextField(textbox_revoked_aucap_id, missingFields); isMissingTextField(textbox_revoked_aucap_version, missingFields); StringBuilder errorMessage = new StringBuilder(); if (missingFields.length() > 0) { missingFields.insert(0, "The following fields are empty:\n"); errorMessage.append(missingFields); } if (invalidFields.length() > 0) { invalidFields.insert(0, "The following fields are not valid:\n"); if (errorMessage.length() > 0) errorMessage.append("\n" + invalidFields); else errorMessage.append(invalidFields); } if (errorMessage.length() > 0) throw new PanelRevocationDataException(errorMessage.toString()); }
From source file:it.scoppelletti.mobilepower.app.AbstractActivity.java
/** * Costruisce il testo delle note di rilascio. * /* w ww .jav a 2s . c o m*/ * @param resId Identificatore del vettore di stringhe che rappresenta le * note di release. * @return Testo. Può essere {@code null}. */ private String buildReleaseNotes(int resId) { int n; int ver, lastVer; String note, pkgName; StringBuilder buf; PackageInfo pkgInfo; PackageManager pkgMgr; SharedPreferences prefs; SharedPreferences.Editor editor; String[] notes; try { notes = getResources().getStringArray(resId); } catch (Resources.NotFoundException ex) { myLogger.debug("Release notes {} not found.", resId); return null; } if (ArrayUtils.isEmpty(notes)) { myLogger.warn("Release notes {} is empty.", resId); onNextAsyncInitializer(); return null; } pkgName = getPackageName(); pkgMgr = getPackageManager(); try { pkgInfo = pkgMgr.getPackageInfo(pkgName, 0); } catch (PackageManager.NameNotFoundException ex) { myLogger.error("Failed to get PackageInfo.", ex); pkgInfo = null; } if (pkgInfo == null) { myLogger.debug("No PackagerInfo set."); return null; } ver = pkgInfo.versionCode; prefs = PreferenceManager.getDefaultSharedPreferences(this); lastVer = prefs.getInt(AppUtils.PREF_LASTVER, 1); myLogger.debug("Version code={}, Last version code={}", ver, lastVer); editor = prefs.edit(); editor.putInt(AppUtils.PREF_LASTVER, ver); editor.apply(); if (ver == 1 || ver <= lastVer) { return null; } ver -= 2; lastVer = (lastVer > 0) ? lastVer - 2 : -1; buf = new StringBuilder(); for (n = notes.length - 1; ver > lastVer; ver--) { if (ver > n) { continue; } note = notes[ver]; if (StringUtils.isBlank(note)) { continue; } buf.append(note); } if (buf.length() == 0) { return null; } buf.insert(0, "</h1>"); buf.insert(0, getString(R.string.lbl_releaseNotes)); buf.insert(0, "<h1>"); return buf.toString(); }