List of usage examples for java.lang StringBuilder charAt
char charAt(int index);
From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java
/** * Updates a group assignment// w w w . jav a 2s . co m * * @param con a valid and open connection * @param group the FxGroupAssignment to be changed * @return returns true if changes were made to the group assignment * @throws FxApplicationException on errors */ private boolean updateGroupAssignment(Connection con, FxGroupAssignmentEdit group) throws FxApplicationException { if (group.isNew()) throw new FxInvalidParameterException("ex.structure.assignment.update.new", group.getXPath()); final StringBuilder sql = new StringBuilder(1000); boolean changes = false; boolean success = false; StringBuilder changesDesc = new StringBuilder(200); FxGroupAssignment org = (FxGroupAssignment) CacheAdmin.getEnvironment().getAssignment(group.getId()); PreparedStatement ps = null; try { sql.setLength(0); // enable / disable an assignment if (org.isEnabled() != group.isEnabled()) { if (changes) changesDesc.append(','); changesDesc.append("enabled=").append(group.isEnabled()); //apply for all child groups and properties as well! if (org.getAssignments().size() > 0) changesDesc.append(", ").append(group.isEnabled() ? "en" : "dis") .append("abled child assignments: "); for (FxAssignment as : org.getAssignments()) { changesDesc.append(as.getXPath()).append(','); } if (changesDesc.charAt(changesDesc.length() - 1) == ',') changesDesc.deleteCharAt(changesDesc.length() - 1); if (!group.isEnabled()) removeAssignment(org.getId(), true, false, true, false); else { StringBuilder affectedAssignment = new StringBuilder(500); affectedAssignment.append(org.getId()); for (FxAssignment as : org.getAllChildAssignments()) affectedAssignment.append(",").append(as.getId()); ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET ENABLED=? WHERE ID IN (" + affectedAssignment + ")"); ps.setBoolean(1, true); ps.executeUpdate(); ps.close(); } changes = true; } // set the assignment's position if (org.getPosition() != group.getPosition()) { int finalPos = setAssignmentPosition(con, group.getId(), group.getPosition()); if (changes) changesDesc.append(','); changesDesc.append("position=").append(finalPos); changes = true; } // change the assignment's default multiplicity (will be auto-adjusted to a valid value in FxGroupAssignmentEdit) if (org.getDefaultMultiplicity() != group.getDefaultMultiplicity()) { ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET DEFMULT=? WHERE ID=?"); ps.setInt(1, group.getDefaultMultiplicity()); ps.setLong(2, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("defaultMultiplicity=").append(group.getDefaultMultiplicity()); changes = true; } // change the assignment's multiplicity final boolean needMinChange = org.getMultiplicity().getMin() != group.getMultiplicity().getMin(); final boolean needMaxChange = org.getMultiplicity().getMax() != group.getMultiplicity().getMax(); if (needMinChange || needMaxChange) { if (org.getGroup().mayOverrideBaseMultiplicity()) { if (needMinChange) checkChangeGroupAssignmentMinMultiplicity(con, org, group); if (needMaxChange && getGroupInstanceMultiplicity(con, org.getGroup().getId(), false) > group .getMultiplicity().getMax()) throw new FxUpdateException("ex.structure.modification.contentExists", "maximumMultiplicity"); } else { throw new FxUpdateException("ex.structure.group.assignment.overrideBaseMultiplicityNotEnabled", org.getGroup().getId()); } ps = con.prepareStatement( "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET MINMULT=? ,MAXMULT=? WHERE ID=?"); ps.setInt(1, group.getMultiplicity().getMin()); ps.setInt(2, group.getMultiplicity().getMax()); ps.setLong(3, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("multiplicity=").append(group.getMultiplicity()); changes = true; } // set the assignment's position if (org.getPosition() != group.getPosition()) { int finalPos = setAssignmentPosition(con, group.getId(), group.getPosition()); if (changes) changesDesc.append(','); changesDesc.append("position=").append(finalPos); changes = true; } // set the XPath (and the alias) of a group assignment if (!org.getXPath().equals(group.getXPath()) || !org.getAlias().equals(group.getAlias())) { if (!XPathElement.isValidXPath(XPathElement.stripType(group.getXPath())) || group.getAlias() .equals(XPathElement.lastElement(XPathElement.stripType(org.getXPath())).getAlias())) throw new FxUpdateException("ex.structure.assignment.noXPath"); // generate correct XPATH if (!group.getXPath().startsWith(group.getAssignedType().getName())) group.setXPath(group.getAssignedType().getName() + group.getXPath()); //avoid duplicates if (org.getAssignedType().isXPathValid(group.getXPath(), true)) throw new FxUpdateException("ex.structure.assignment.exists", group.getXPath(), group.getAssignedType().getName()); // update db entries ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET XPATH=?, XALIAS=? WHERE ID=?"); ps.setString(1, group.getXPath()); ps.setString(2, group.getAlias()); ps.setLong(3, group.getId()); ps.executeUpdate(); ps.close(); // update the relevant content instances ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical); storage.updateXPath(con, group.getId(), XPathElement.stripType(org.getXPath()), XPathElement.stripType(group.getXPath())); //update all child assignments ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET XPATH=? WHERE ID=?"); for (FxAssignment child : org.getAllChildAssignments()) { ps.setString(1, group.getXPath() + child.getXPath().substring(org.getXPath().length())); ps.setLong(2, child.getId()); ps.executeUpdate(); storage.updateXPath(con, child.getId(), XPathElement.stripType(child.getXPath()), XPathElement .stripType(group.getXPath() + child.getXPath().substring(org.getXPath().length()))); } ps.close(); if (changes) changesDesc.append(','); changesDesc.append("xPath=").append(group.getXPath()).append(",alias=").append(group.getAlias()); changes = true; } // update label if (org.getLabel() != null && !org.getLabel().equals(group.getLabel()) || org.getLabel() == null && group.getLabel() != null || org.getHint() != null && !org.getHint().equals(group.getHint()) || org.getHint() == null && group.getHint() != null) { Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", group.getId()); if (changes) changesDesc.append(','); changesDesc.append("label=").append(group.getLabel()).append(','); changesDesc.append("hint=").append(group.getHint()).append(','); changes = true; } //update SystemInternal flag, this is a one way function, so it can only be set, but not reset!! if (!org.isSystemInternal() && group.isSystemInternal() && FxContext.getUserTicket().isGlobalSupervisor()) { ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET SYSINTERNAL=? WHERE ID=?"); ps.setBoolean(1, group.isSystemInternal()); ps.setLong(2, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("systemInternal=").append(group.isSystemInternal()); changes = true; } // change GroupMode // OneOf --> AnyOf always allowed, AnyOf --> OneOf not allowed if content exists if (org.getMode().getId() != group.getMode().getId()) { if (org.getMode().equals(GroupMode.AnyOf) && group.getMode().equals(GroupMode.OneOf)) { if (getGroupInstanceMultiplicity(con, org.getGroup().getId(), true) > 0) { throw new FxUpdateException(LOG, "ex.structure.group.assignment.modeChangeError"); } } ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET GROUPMODE=? WHERE ID=?"); ps.setLong(1, group.getMode().getId()); ps.setLong(2, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("groupMode=").append(group.getMode().getId()); changes = true; } // change the parentgroupassignment // TODO: change the parent group assignment & failure conditions // if (org.getParentGroupAssignment().getId() != group.getParentGroupAssignment().getId()) { // } // change the group assignment options if (updateGroupAssignmentOptions(con, group)) { changesDesc.append(",options:"); List<FxStructureOption> options = group.getOptions(); for (FxStructureOption option : options) { changesDesc.append(option.getKey()).append("=").append(option.getValue()) .append(" overridable=").append(option.isOverridable()).append(" isSet=") .append(option.isSet()).append(" isInherited=").append(option.getIsInherited()); } changes = true; } if (changes) htracker.track(group.getAssignedType(), "history.assignment.updateGroupAssignment", group.getXPath(), group.getAssignedType().getId(), group.getAssignedType().getName(), group.getGroup().getId(), group.getGroup().getName(), changesDesc.toString()); success = true; } catch (SQLException e) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e); EJBUtils.rollback(ctx); if (uniqueConstraintViolation) throw new FxEntryExistsException("ex.structure.assignment.group.exists", group.getAlias(), group.getXPath()); throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { Database.closeObjects(AssignmentEngineBean.class, null, ps); if (!success) { EJBUtils.rollback(ctx); } } return changes; }
From source file:gov.jgi.meta.hadoop.input.FastaLineReader.java
/** * Read one line from the InputStream into the given Text. A line * can be terminated by one of the following: '\n' (LF) , '\r' (CR), * or '\r\n' (CR+LF). EOF also terminates an otherwise unterminated * line.//w w w . j a v a2 s . c om * * @param str the object to store the given line (without newline) * @param maxLineLength the maximum number of bytes to store into str; * the rest of the line is silently discarded. * @param maxBytesToConsume the maximum number of bytes to consume * in this call. This is only a hint, because if the line cross * this threshold, we allow it to happen. It can overshoot * potentially by as much as one buffer length. * * @return the number of bytes read including the (longest) newline * found. * * @throws IOException if the underlying stream throws */ public int readLine(Text key, Text str, int maxLineLength, int maxBytesToConsume) throws IOException { int totalBytesRead = 0; int numRecordsRead = 0; Boolean eof = false; int startPosn; StringBuilder recordBlock = new StringBuilder(this.bufferSize); /* first thing to do is to move forward till you see a start character */ startPosn = bufferPosn; do { if (bufferPosn >= bufferLength) { totalBytesRead += bufferPosn - startPosn; bufferPosn = 0; bufferLength = in.read(buffer); if (bufferLength <= 0) { eof = true; break; // EOF } } } while (buffer[bufferPosn++] != '>'); /* if we hit the end of file already, then just return 0 bytes processed */ if (eof) return totalBytesRead; /* now bufferPosn should be at the start of a fasta record */ totalBytesRead += (bufferPosn - 1) - startPosn; startPosn = bufferPosn - 1; // startPosn guaranteed to be at a ">" /* find the next record start: first scan to end of the line */ eof = false; do { if (bufferPosn >= bufferLength) { /* copy the current buffer before refreshing the buffer */ int appendLength = bufferPosn - startPosn; for (int copyi = startPosn; copyi < startPosn + appendLength; copyi++) { recordBlock.append((char) buffer[copyi]); } //recordBlock.append(buffer, startPosn, appendLength); totalBytesRead += appendLength; startPosn = bufferPosn = 0; bufferLength = in.read(buffer); if (bufferLength <= 0) { eof = true; break; // EOF } } bufferPosn++; } while (buffer[bufferPosn - 1] != CR && buffer[bufferPosn - 1] != LF); /* find the next record start: scan till next ">" */ do { if (bufferPosn >= bufferLength) { /* copy the current buffer before refreshing the buffer */ int appendLength = bufferPosn - startPosn; for (int copyi = startPosn; copyi < startPosn + appendLength; copyi++) { recordBlock.append((char) buffer[copyi]); } //recordBlock.append(buffer, startPosn, appendLength); totalBytesRead += appendLength; startPosn = bufferPosn = 0; bufferLength = in.read(buffer); if (bufferLength <= 0) { eof = true; break; // EOF } } } while (buffer[bufferPosn++] != '>'); // only read one record at a time if (!eof) { bufferPosn--; // make sure we leave bufferPosn pointing to the next record int appendLength = bufferPosn - startPosn; for (int copyi = startPosn; copyi < startPosn + appendLength; copyi++) { recordBlock.append((char) buffer[copyi]); } //recordBlock.append(buffer, startPosn, appendLength); totalBytesRead += appendLength; } /* record block now has the byte array we want to process for reads */ int i = 1; // skip initial record seperator ">" int j = 1; do { key.clear(); str.clear(); /* first parse the key */ i = j; Boolean junkOnLine = false; while (j < recordBlock.length()) { int c = recordBlock.charAt(j++); if (c == CR || c == LF) { break; } //else if (c == ' ' || c == '\t') { // junkOnLine = true; // break; //} } if (j == i) { // then we didn't parse out a proper id LOG.error("Unable to parse entry: " + recordBlock); str.clear(); key.clear(); return totalBytesRead; } key.set(recordBlock.substring(i, j - 1)); /* in case there is additional metadata on the header line, ignore everything after the first word. */ if (junkOnLine) { while (j < recordBlock.length() && recordBlock.charAt(j) != CR && recordBlock.charAt(j) != LF) j++; } //LOG.info ("key = " + k.toString()); /* now skip the newlines */ while (j < recordBlock.length() && (recordBlock.charAt(j) == CR || recordBlock.charAt(j) == LF)) j++; /* now read the sequence */ StringBuilder sequenceTmp = new StringBuilder(recordBlock.length()); do { i = j; while (j < recordBlock.length()) { int c = recordBlock.charAt(j++); if (c == CR || c == LF) { break; } } //byte[] ba = recordBlock.getBytes(); //if (ba.length <= i || ba.length <= j - i - 1) { // LOG.fatal("hmm... ba.length = " + ba.length + " i = " + i + " j-i-1 = " + (j-i-1)); //} if (j == i) { // then we didn't parse out a proper id LOG.error("Unable to parse entry: " + recordBlock); str.clear(); key.clear(); return totalBytesRead; } for (int copyi = i; copyi < j - 1; copyi++) { sequenceTmp.append((char) recordBlock.charAt(copyi)); } while (j < recordBlock.length() && (recordBlock.charAt(j) == CR || recordBlock.charAt(j) == LF)) j++; } while (j < recordBlock.length() && recordBlock.charAt(j) != '>'); str.set(sequenceTmp.toString()); numRecordsRead++; /* now skip characters (newline or carige return most likely) till record start */ while (j < recordBlock.length() && recordBlock.charAt(j) != '>') { j++; } j++; // skip the ">" } while (j < recordBlock.length()); // LOG.info(""); // LOG.info("object key = " + key); byte[] strpacked = SequenceString.sequenceToByteArray(str.toString().toLowerCase()); str.clear(); str.append(strpacked, 0, strpacked.length); return totalBytesRead; }
From source file:com.wabacus.system.WabacusResponse.java
public String assembleResultsInfo(Throwable t) { String defaultErrorPrompt = null; if (t != null && !(t instanceof WabacusRuntimeTerminateException)) { defaultErrorPrompt = Config.getInstance().getResources().getString(rrequest, rrequest.getPagebean(), Consts.LOADERROR_MESS_KEY, false); if (Tools.isEmpty(defaultErrorPrompt)) { defaultErrorPrompt = "<strong>System is busy,Please try later</strong>"; } else {//from w w w . ja v a 2 s . com defaultErrorPrompt = rrequest.getI18NStringValue(defaultErrorPrompt.trim()); } } if (rrequest.getPagebean() == null) { log.error("?" + rrequest.getStringAttribute("PAGEID", "") + "??"); return "?" + rrequest.getStringAttribute("PAGEID", "") + "??"; } StringBuilder resultBuf = new StringBuilder(); resultBuf.append(showPageUrlSpan());//URL??onload? if (!rrequest.isLoadedByAjax() || (rrequest.getShowtype() != Consts.DISPLAY_ON_PAGE && rrequest.getShowtype() != Consts.DISPLAY_ON_PRINT)) { if (rrequest.getShowtype() == Consts.DISPLAY_ON_PAGE) { String promptmessages = this.messageCollector.promptMessageFirstTime(defaultErrorPrompt); if (!Tools.isEmpty(promptmessages)) { resultBuf.append("<span style='display:none'>templary</span>"); resultBuf.append("<script type=\"text/javascript\">"); resultBuf.append(promptmessages); resultBuf.append("</script>"); } } else { resultBuf.append(this.messageCollector.promptMessageInNonPage(defaultErrorPrompt)); } } else { String pageid = rrequest.getPagebean().getId(); resultBuf.append("<RESULTS_INFO-").append(pageid).append(">").append("{"); String confirmessage = this.messageCollector.getConfirmmessage(); if (confirmessage != null && !confirmessage.trim().equals("")) { resultBuf.append("confirmessage:\"").append(confirmessage).append("\""); resultBuf.append(",confirmkey:\"").append(this.messageCollector.getConfirmkey()).append("\""); resultBuf.append(",confirmurl:\"").append(this.messageCollector.getConfirmurl()).append("\""); } else { resultBuf.append("pageurl:\"").append(rrequest.getUrl()).append("\","); if (rrequest.getPagebean().isShouldProvideEncodePageUrl()) { resultBuf.append("pageEncodeUrl:\"") .append(Tools.convertBetweenStringAndAscii(rrequest.getUrl(), true)).append("\","); } if (dynamicRefreshComponentGuid != null && !dynamicRefreshComponentGuid.trim().equals("")) {//?ID resultBuf.append("dynamicRefreshComponentGuid:\"").append(dynamicRefreshComponentGuid) .append("\","); if (dynamicSlaveReportId != null && !dynamicSlaveReportId.trim().equals("")) { resultBuf.append("dynamicSlaveReportId:\"").append(dynamicSlaveReportId).append("\","); } } resultBuf.append("statecode:").append(this.statecode).append(","); resultBuf.append(this.messageCollector.promptMessageByRefreshJs(defaultErrorPrompt)); List<String[]> lstOnloadMethods = getLstRealOnloadMethods(); if (lstOnloadMethods != null && lstOnloadMethods.size() > 0) { resultBuf.append("onloadMethods:["); for (String[] methodTmp : lstOnloadMethods) { if (methodTmp == null || methodTmp.length != 2) continue; resultBuf.append("{methodname:").append(methodTmp[0]); if (methodTmp[1] != null && !methodTmp[1].trim().equals("")) { resultBuf.append(",methodparams:").append(methodTmp[1]); } resultBuf.append("},"); } if (resultBuf.charAt(resultBuf.length() - 1) == ',') { resultBuf.deleteCharAt(resultBuf.length() - 1); } resultBuf.append("],"); } if (lstUpdateReportGuids != null && lstUpdateReportGuids.size() > 0) {//GUID resultBuf.append("updateReportGuids:["); for (String rguidTmp : lstUpdateReportGuids) { resultBuf.append("{value:\"").append(rguidTmp).append("\"},"); } if (resultBuf.charAt(resultBuf.length() - 1) == ',') { resultBuf.deleteCharAt(resultBuf.length() - 1); } resultBuf.append("],"); } if (resultBuf.charAt(resultBuf.length() - 1) == ',') { resultBuf.deleteCharAt(resultBuf.length() - 1); } } resultBuf.append("}").append("</RESULTS_INFO-").append(pageid).append(">"); } return resultBuf.toString(); }
From source file:org.alfresco.solr.client.SOLRAPIClient.java
public Transactions getTransactions(Long fromCommitTime, Long minTxnId, Long toCommitTime, Long maxTxnId, int maxResults, ShardState shardState) throws AuthenticationException, IOException, JSONException, EncoderException { URLCodec encoder = new URLCodec(); StringBuilder url = new StringBuilder(GET_TRANSACTIONS_URL); StringBuilder args = new StringBuilder(); if (fromCommitTime != null) { args.append("?").append("fromCommitTime").append("=").append(fromCommitTime); }/*from w w w. java2 s .co m*/ if (minTxnId != null) { args.append(args.length() == 0 ? "?" : "&").append("minTxnId").append("=").append(minTxnId); } if (toCommitTime != null) { args.append(args.length() == 0 ? "?" : "&").append("toCommitTime").append("=").append(toCommitTime); } if (maxTxnId != null) { args.append(args.length() == 0 ? "?" : "&").append("maxTxnId").append("=").append(maxTxnId); } if (maxResults != 0 && maxResults != Integer.MAX_VALUE) { args.append(args.length() == 0 ? "?" : "&").append("maxResults").append("=").append(maxResults); } if (shardState != null) { args.append(args.length() == 0 ? "?" : "&"); args.append(encoder.encode("baseUrl")).append("=") .append(encoder.encode(shardState.getShardInstance().getBaseUrl())); args.append("&").append(encoder.encode("hostName")).append("=") .append(encoder.encode(shardState.getShardInstance().getHostName())); args.append("&").append(encoder.encode("template")).append("=") .append(encoder.encode(shardState.getShardInstance().getShard().getFloc().getTemplate())); for (String key : shardState.getShardInstance().getShard().getFloc().getPropertyBag().keySet()) { String value = shardState.getShardInstance().getShard().getFloc().getPropertyBag().get(key); if (value != null) { args.append("&").append(encoder.encode("floc.property." + key)).append("=") .append(encoder.encode(value)); } } for (String key : shardState.getPropertyBag().keySet()) { String value = shardState.getPropertyBag().get(key); if (value != null) { args.append("&").append(encoder.encode("state.property." + key)).append("=") .append(encoder.encode(value)); } } args.append("&").append(encoder.encode("instance")).append("=") .append(encoder.encode("" + shardState.getShardInstance().getShard().getInstance())); args.append("&").append(encoder.encode("numberOfShards")).append("=").append( encoder.encode("" + shardState.getShardInstance().getShard().getFloc().getNumberOfShards())); args.append("&").append(encoder.encode("port")).append("=") .append(encoder.encode("" + shardState.getShardInstance().getPort())); args.append("&").append(encoder.encode("stores")).append("="); for (StoreRef store : shardState.getShardInstance().getShard().getFloc().getStoreRefs()) { if (args.charAt(args.length() - 1) != '=') { args.append(encoder.encode(",")); } args.append(encoder.encode(store.toString())); } args.append("&").append(encoder.encode("isMaster")).append("=") .append(encoder.encode("" + shardState.isMaster())); args.append("&").append(encoder.encode("hasContent")).append("=") .append(encoder.encode("" + shardState.getShardInstance().getShard().getFloc().hasContent())); args.append("&").append(encoder.encode("shardMethod")).append("=").append( encoder.encode(shardState.getShardInstance().getShard().getFloc().getShardMethod().toString())); args.append("&").append(encoder.encode("lastUpdated")).append("=") .append(encoder.encode("" + shardState.getLastUpdated())); args.append("&").append(encoder.encode("lastIndexedChangeSetCommitTime")).append("=") .append(encoder.encode("" + shardState.getLastIndexedChangeSetCommitTime())); args.append("&").append(encoder.encode("lastIndexedChangeSetId")).append("=") .append(encoder.encode("" + shardState.getLastIndexedChangeSetId())); args.append("&").append(encoder.encode("lastIndexedTxCommitTime")).append("=") .append(encoder.encode("" + shardState.getLastIndexedTxCommitTime())); args.append("&").append(encoder.encode("lastIndexedTxId")).append("=") .append(encoder.encode("" + shardState.getLastIndexedTxId())); } url.append(args); GetRequest req = new GetRequest(url.toString()); Response response = null; List<Transaction> transactions = new ArrayList<Transaction>(); Long maxTxnCommitTime = null; Long maxTxnIdOnServer = null; try { response = repositoryHttpClient.sendRequest(req); if (response.getStatus() != HttpStatus.SC_OK) { throw new AlfrescoRuntimeException("GetTransactions return status is " + response.getStatus()); } Reader reader = new BufferedReader(new InputStreamReader(response.getContentAsStream(), "UTF-8")); JsonParser parser = jsonFactory.createJsonParser(reader); JsonToken token = parser.nextValue(); while (token != null) { if ("transactions".equals(parser.getCurrentName())) { token = parser.nextToken(); //START_ARRAY while (token == JsonToken.START_OBJECT) { token = parser.nextValue(); long id = parser.getLongValue(); token = parser.nextValue(); long commitTime = parser.getLongValue(); token = parser.nextValue(); long updates = parser.getLongValue(); token = parser.nextValue(); long deletes = parser.getLongValue(); Transaction txn = new Transaction(); txn.setCommitTimeMs(commitTime); txn.setDeletes(deletes); txn.setId(id); txn.setUpdates(updates); transactions.add(txn); token = parser.nextToken(); //END_OBJECT token = parser.nextToken(); // START_OBJECT or END_ARRAY; } } else if ("maxTxnCommitTime".equals(parser.getCurrentName())) { maxTxnCommitTime = parser.getLongValue(); } else if ("maxTxnId".equals(parser.getCurrentName())) { maxTxnIdOnServer = parser.getLongValue(); } token = parser.nextValue(); } parser.close(); reader.close(); } finally { if (response != null) { response.release(); } } return new Transactions(transactions, maxTxnCommitTime, maxTxnIdOnServer); }
From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleDeclaration.java
/** * Transforms the specified string from delimiter-separated (e.g. <tt>font-size</tt>) * to camel-cased (e.g. <tt>fontSize</tt>). * @param string the string to camelize/* ww w . j a v a2s . c o m*/ * @return the transformed string * @see com.gargoylesoftware.htmlunit.javascript.host.dom.DOMStringMap#decamelize(String) */ protected static String camelize(final String string) { if (string == null) { return null; } String result = CamelizeCache_.get(string); if (null != result) { return result; } // not found in CamelizeCache_; convert and store in cache final int pos = string.indexOf('-'); if (pos == -1 || pos == string.length() - 1) { // cache also this strings for performance CamelizeCache_.put(string, string); return string; } final StringBuilder buffer = new StringBuilder(string); buffer.deleteCharAt(pos); buffer.setCharAt(pos, Character.toUpperCase(buffer.charAt(pos))); int i = pos + 1; while (i < buffer.length() - 1) { if (buffer.charAt(i) == '-') { buffer.deleteCharAt(i); buffer.setCharAt(i, Character.toUpperCase(buffer.charAt(i))); } i++; } result = buffer.toString(); CamelizeCache_.put(string, result); return result; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMAppsBlock.java
@Override protected void renderData(Block html) { TBODY<TABLE<Hamlet>> tbody = html.table("#apps").thead().tr().th(".id", "ID").th(".user", "User") .th(".name", "Name").th(".type", "Application Type").th(".queue", "Queue") .th(".priority", "Application Priority").th(".starttime", "StartTime") .th(".finishtime", "FinishTime").th(".state", "State").th(".finalstatus", "FinalStatus") .th(".runningcontainer", "Running Containers").th(".allocatedCpu", "Allocated CPU VCores") .th(".allocatedMemory", "Allocated Memory MB").th(".allocatedGpu", "Allocated GPU") .th(".queuePercentage", "% of Queue").th(".clusterPercentage", "% of Cluster") .th(".progress", "Progress").th(".ui", "Tracking UI").th(".blacklisted", "Blacklisted Nodes")._() ._().tbody();/*from w ww. j a va2 s . c o m*/ StringBuilder appsTableData = new StringBuilder("[\n"); for (ApplicationReport appReport : appReports) { // TODO: remove the following condition. It is still here because // the history side implementation of ApplicationBaseProtocol // hasn't filtering capability (YARN-1819). if (!reqAppStates.isEmpty() && !reqAppStates.contains(appReport.getYarnApplicationState())) { continue; } AppInfo app = new AppInfo(appReport); ApplicationAttemptId appAttemptId = ApplicationAttemptId.fromString(app.getCurrentAppAttemptId()); String queuePercent = "N/A"; String clusterPercent = "N/A"; if (appReport.getApplicationResourceUsageReport() != null) { queuePercent = String.format("%.1f", appReport.getApplicationResourceUsageReport().getQueueUsagePercentage()); clusterPercent = String.format("%.1f", appReport.getApplicationResourceUsageReport().getClusterUsagePercentage()); } String blacklistedNodesCount = "N/A"; RMApp rmApp = rm.getRMContext().getRMApps().get(appAttemptId.getApplicationId()); if (rmApp != null) { RMAppAttempt appAttempt = rmApp.getRMAppAttempt(appAttemptId); Set<String> nodes = null == appAttempt ? null : appAttempt.getBlacklistedNodes(); if (nodes != null) { blacklistedNodesCount = String.valueOf(nodes.size()); } } String percent = StringUtils.format("%.1f", app.getProgress()); appsTableData.append("[\"<a href='").append(url("app", app.getAppId())).append("'>") .append(app.getAppId()).append("</a>\",\"") .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getUser()))) .append("\",\"") .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getName()))) .append("\",\"") .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getType()))) .append("\",\"") .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app.getQueue()))) .append("\",\"").append(String.valueOf(app.getPriority())).append("\",\"") .append(app.getStartedTime()).append("\",\"").append(app.getFinishedTime()).append("\",\"") .append(app.getAppState() == null ? UNAVAILABLE : app.getAppState()).append("\",\"") .append(app.getFinalAppStatus()).append("\",\"") .append(app.getRunningContainers() == -1 ? "N/A" : String.valueOf(app.getRunningContainers())) .append("\",\"") .append(app.getAllocatedCpuVcores() == -1 ? "N/A" : String.valueOf(app.getAllocatedCpuVcores())) .append("\",\"") .append(app.getAllocatedMemoryMB() == -1 ? "N/A" : String.valueOf(app.getAllocatedMemoryMB())) .append("\",\"") .append(app.getAllocatedGpu() == -1 ? "N/A" : String.valueOf(app.getAllocatedGpu())) .append("\",\"").append(queuePercent).append("\",\"").append(clusterPercent).append("\",\"") // Progress bar .append("<br title='").append(percent).append("'> <div class='").append(C_PROGRESSBAR) .append("' title='").append(join(percent, '%')).append("'> ").append("<div class='") .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", percent, '%')) .append("'> </div> </div>").append("\",\"<a "); String trackingURL = app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE) || app.getAppState() == YarnApplicationState.NEW ? null : app.getTrackingUrl(); String trackingUI = app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE) || app.getAppState() == YarnApplicationState.NEW ? "Unassigned" : app.getAppState() == YarnApplicationState.FINISHED || app.getAppState() == YarnApplicationState.FAILED || app.getAppState() == YarnApplicationState.KILLED ? "History" : "ApplicationMaster"; appsTableData.append(trackingURL == null ? "#" : "href='" + trackingURL).append("'>").append(trackingUI) .append("</a>\",").append("\"").append(blacklistedNodesCount).append("\"],\n"); } if (appsTableData.charAt(appsTableData.length() - 2) == ',') { appsTableData.delete(appsTableData.length() - 2, appsTableData.length() - 1); } appsTableData.append("]"); html.script().$type("text/javascript")._("var appsTableData=" + appsTableData)._(); tbody._()._(); }
From source file:com.arksoft.epamms.ZGlobal1_Operation.java
/** public String//from w w w .ja v a2 s .c om GetGeneralPath( View vSubtask, int lFlag, String stringFileType, String stringTarget ) { char stringReturn; char stringCLSID; int nRC = FALSE; stringReturn = ""; lFlag = 3; // set flag to 3 as that is all we currently support if ( lFlag == 3 ) //open for view { GetRegistryCLSID( stringCLSID, stringFileType ); // nRC = GetRegistryHTMLViewValue( "", stringCLSID, REG_SZ, stringReturn, sizeof( stringReturn ) ); nRC = GetRegistryGeneralValue( "", "rtffile", stringCLSID, REG_SZ, stringReturn, sizeof( stringReturn ) ); TraceLineS( "Flag 3 stringCLSID !", stringCLSID ) ; TraceLineS( "Flag 3 Return !", stringReturn ) ; if ( nRC == FALSE ) { // for win98 in case we are not in win2K nRC = GetRegistryGeneralValue( "", "rtffile", stringCLSID, REG_EXPAND_SZ, stringReturn, sizeof( stringReturn ) ); TraceLineS( "Flag 3C stringCLSID !", stringCLSID ) ; TraceLineS( "Flag 3C Return !", stringReturn ) ; } } TraceLineS( "RIGHT BEFORE STRCopy:", stringReturn ) ; stringTarget = zstrcpy( stringTarget, stringReturn ); TraceLineS( "RIGHT AFTER STRCopy", "" ) ; return stringTarget; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // Method Name: ConvertExternalValueOfAttribute // // Convert an external value for an attribute to its internal value. // //////////////////////////////////////////////////////////////////////////////////////////////////// public int ConvertExternalValueOfAttribute( String lpReturnedString, String srcString, View lpView, String entityName, String attributeName ) { zVIEW wXferO; zVIEW vDynamicT; zVIEW vQualObject; zVIEW zqFrameOrig; zVIEW zqFrame; LPVIEWENTITY lpEntityDef; LPVIEWATTRIB lpAttributeDef; LPDOMAIN lpDomain; String DataType; String Msg; String SavedTableName; String stringYearIndicator; int lInternalTableValue; int nLth; int nRC; GetViewByName( wXferO, "wXferO", lpView, zLEVEL_TASK ); lpReturnedString = ""; lpEntityDef = String MiGetEntityDefForView( lpView, entityName ); if ( lpEntityDef == 0 ) return -16; // Position on attribute. #ifdef VIEWENTITY_OD lpAttributeDef = String zGETPTR( lpEntityDef->hFirstOD_Attrib ); nRC = 1; while ( lpAttributeDef > 0 && nRC > 0 ) { if ( zstrcmp( lpAttributeDef->stringName, attributeName ) == 0 ) nRC = 0; if ( nRC > 0 ) lpAttributeDef = String zGETPTR( lpAttributeDef->hNextOD_Attrib ); } #else lpAttributeDef = String zGETPTR( lpEntityDef->hFirstAttributeDef ); nRC = 1; while ( lpAttributeDef > 0 && nRC > 0 ) { if ( zstrcmp( lpAttributeDef->stringName, attributeName ) == 0 ) nRC = 0; if ( nRC > 0 ) lpAttributeDef = String zGETPTR( lpAttributeDef->hNextAttributeDef ); } // #endif if ( nRC > 0 ) { MessageSend( lpView, "", "Data Conversion", "The attribute specified was not found.", zMSGQ_OBJECT_CONSTRAINT_ERROR, 0 ); return -1; } // If input is null, simply return because output has already been set to null. if ( *srcString == 0 ) return 0; nLth = zstrlen( srcString ); // Process depending on whether or not the Domain is a Table. lpDomain = (LPDOMAIN) zGETPTR( lpAttributeDef->hDomain ); if ( lpDomain->cDomainType == 'T' ) { if ( *(lpDomain->stringDomainOper) == 0 ) { // The domain is a static table so convert the value through the table interface. if ( lpDomain->cType == zTYPE_INTEGER ) { nRC = TableEntryExtToInt( &lInternalTableValue, lpView, lpDomain, 0, srcString ); zltoa( lInternalTableValue, lpReturnedString ); } else nRC = TableEntryExtToInt( lpReturnedString, lpView, lpDomain, 0, srcString ); // Internal value is STRING. if ( nRC < 0 ) { zstrcpy( Msg, "Invalid input value for attribute, " ); zstrcat( Msg, attributeName ); zstrcat( Msg, "." ); MessageSend( lpView, "", "Data Conversion", Msg, zMSGQ_OBJECT_CONSTRAINT_ERROR, 0 ); return -1; } } else { if ( zstrcmp( lpDomain->stringName, "FAISIR_DynamicTableSingle" ) == 0 ) { // Get Year Indicator value as GeneralParameter in zqFrame object. // If we get to this section of code, we must have come from zqFrame and the lpView is actually // the zqFrame view. // (This is very similar to the code in DomainC.) GetViewByName( zqFrameOrig, "zqFrame", lpView, zLEVEL_TASK ); CreateViewFromView( zqFrame, zqFrameOrig ); nRC = SetCursorFirstEntityByString( zqFrame, "GeneralParameter", "AttributeName", "YearIndicator", "" ); if ( nRC < zCURSOR_SET ) *stringYearIndicator = 0; else GetStringFromAttribute( stringYearIndicator, zqFrame, "GeneralParameter", "Value" ); if ( *stringYearIndicator == 0 ) { MessageSend( lpView, "", "Data Validation", "A YearIndicator value must be specified as a General Parameter in the Query.", zMSGQ_DOMAIN_ERROR, 0 ); return zCALL_ERROR; } zstrcpy( SavedTableName, "X_" ); zstrcat( SavedTableName, lpDomain->stringName ); zstrcat( SavedTableName, stringYearIndicator ); // Build the concatenated name. // Either get existing view or activate new one. nRC = GetViewByName( vDynamicT, SavedTableName, lpView, zLEVEL_TASK ); if ( nRC < 0 ) { // Set up Qualification object for YearIndicator. SfActivateSysEmptyOI( vQualObject, "KZDBHQUA", lpView, zMULTIPLE ); CreateEntity( vQualObject, "EntitySpec", zPOS_AFTER ); SetAttributeFromString( vQualObject, "EntitySpec", "EntityName", "FAISIRDomain" ); CreateEntity( vQualObject, "QualAttrib", zPOS_AFTER ); SetAttributeFromString( vQualObject, "QualAttrib", "EntityName", "FAISIRDomain" ); SetAttributeFromString( vQualObject, "QualAttrib", "AttributeName", "YearIndicator" ); SetAttributeFromString( vQualObject, "QualAttrib", "Value", stringYearIndicator ); SetAttributeFromString( vQualObject, "QualAttrib", "Oper", "=" ); // Activate the Domains for the YearIndicator. nRC = ActivateObjectInstance( vDynamicT, "mFAISIRD", zqFrame, vQualObject, zMULTIPLE ); DropView( vQualObject ); if ( nRC < 0 ) { MessageSend( lpView, "", "Data Validation", "A YearIndicator value must be specified as a General Parameter in the Query.", zMSGQ_DOMAIN_ERROR, 0 ); return zCALL_ERROR; } SetNameForView( vDynamicT, SavedTableName, 0, zLEVEL_APPLICATION ); CreateViewFromViewForTask( &vDynamicT, vDynamicT, 0 ); SetNameForView( vDynamicT, SavedTableName, lpView, zLEVEL_TASK ); } // Position on correct table entry. nRC = SetCursorFirstEntityByString( vDynamicT, "FAISIRDomain", "Name", attributeName, "" ); if ( nRC >= zCURSOR_SET ) nRC = SetCursorFirstEntityByString( vDynamicT, "FAISIRDomainValue", "ExternalDescription", srcString, "" ); if ( nRC < 0 ) { zstrcpy( Msg, "Invalid input value for attribute, " ); zstrcat( Msg, attributeName ); zstrcat( Msg, "." ); MessageSend( lpView, "", "Data Conversion", Msg, zMSGQ_OBJECT_CONSTRAINT_ERROR, 0 ); return -1; } GetStringFromAttribute( lpReturnedString, vDynamicT, "FAISIRDomainValue", "InternalStringValue" ); DropView( zqFrame ); } else { // The domain is a regular dynamic table so use the object in memory or activate it. zstrcpy( SavedTableName, "X_" ); zstrcat( SavedTableName, lpDomain->stringName ); nRC = GetViewByName( vDynamicT, SavedTableName, lpView, zLEVEL_TASK ); if ( nRC < 0 ) nRC = GetViewByName( vDynamicT, SavedTableName, lpView, zLEVEL_APPLICATION ); if ( nRC < 0 ) { // The table wasn't in memory, so call the dynamic table routine to load it. // Note that we will call the routine with an invalid request type, which will load // the table but not take action. SfActivateSysEmptyOI( &vQualObject, "KZDBHQUA", lpView, zMULTIPLE ); CreateEntity( vQualObject, "EntitySpec", zPOS_AFTER ); SetAttributeFromString( vQualObject, "EntitySpec", "EntityName", "Domain" ); CreateEntity( vQualObject, "QualAttrib", zPOS_AFTER ); SetAttributeFromString( vQualObject, "QualAttrib", "EntityName", "Domain" ); SetAttributeFromString( vQualObject, "QualAttrib", "AttributeName", "Name" ); SetAttributeFromString( vQualObject, "QualAttrib", "Value", lpDomain->stringName ); SetAttributeFromString( vQualObject, "QualAttrib", "Oper", "=" ); nRC = ActivateObjectInstance( &vDynamicT, "DOMAINT", lpView, vQualObject, zSINGLE | zLEVEL_APPLICATION ); SetNameForView( vDynamicT, SavedTableName, lpView, zLEVEL_APPLICATION ); } // Locate the entry in the table by external value and return the internal value. nRC = SetCursorFirstEntityByString( vDynamicT, "DomainValue", "ExternalDescription", srcString, 0 ); if ( nRC < 0 ) { zstrcpy( Msg, "Invalid input value for attribute, " ); zstrcat( Msg, attributeName ); zstrcat( Msg, "." ); MessageSend( lpView, "", "Data Conversion", Msg, zMSGQ_OBJECT_CONSTRAINT_ERROR, 0 ); return -1; } GetStringFromAttribute( lpReturnedString, vDynamicT, "DomainValue", "InternalStringValue" ); } } } else { // If Domain Type is not Table, use data type for conversion through wXferO attribute. DataType = lpDomain->cType; if ( DataType == 'L' ) { nRC = SetAttributeFromVariable( wXferO, "Root", "WorkInteger", srcString, zTYPE_STRING, nLth, 0, zUSE_DEFAULT_CONTEXT ); if ( nRC >= 0 ) GetStringFromAttribute( lpReturnedString, wXferO, "Root", "WorkInteger" ); else return -1; } else if ( DataType == 'T' ) { nRC = SetAttributeFromVariable( wXferO, "Root", "WorkDate", srcString, zTYPE_STRING, nLth, "M/D/YYYY", 0 ); if ( nRC >= 0 ) GetStringFromAttribute( lpReturnedString, wXferO, "Root", "WorkDate" ); else return -1; } else if ( DataType == 'D' ) { nRC = SetAttributeFromVariable( wXferO, "Root", "WorkDate", srcString, zTYPE_STRING, nLth, "M/D/YYYY", 0 ); if ( nRC >= 0 ) GetStringFromAttribute( lpReturnedString, wXferO, "Root", "WorkDate" ); else return -1; } else if ( DataType == 'M' ) { nRC = SetAttributeFromVariable( wXferO, "Root", "WorkDecimal", srcString, zTYPE_STRING, nLth, 0, zUSE_DEFAULT_CONTEXT ); if ( nRC >= 0 ) GetStringFromAttribute( lpReturnedString, wXferO, "Root", "WorkDecimal" ); else return -1; } else zstrcpy( lpReturnedString, srcString ); } return 0; } // ConvertExternalValueOfAttribute **/ //////////////////////////////////////////////////////////////////////////////////////////////////// // // Method Name: AddSpacesToString // // Insert spaces within a Zeidon string name where capital letters exist. // //////////////////////////////////////////////////////////////////////////////////////////////////// public String AddSpacesToString(String stringZeidonName) { StringBuilder sb = new StringBuilder(stringZeidonName); int k; for (k = 1; k < sb.length(); k++) { if (sb.charAt(k) >= 'A' && sb.charAt(k) <= 'Z') { sb.insert(k, ' '); k++; } } return sb.toString(); }
From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java
/** * Extract text and hyperlinks from an element * supposingly containing only text./*from w w w . j a va 2s .c om*/ * * @param textElement * The element to be processed. * @param rawStr * The StringBuffer to contain the raw text. * @param linkedStr * The StringBuffer to contain the text with hyperlinks. */ private void processTextElement(Element textElement, StringBuilder rawStr, StringBuilder linkedStr) { // we process each element contained in the specified text element for (Node node : textElement.childNodes()) { // element node if (node instanceof Element) { Element element = (Element) node; String eltName = element.tag().getName(); // section headers: same thing if (eltName.equals(XmlNames.ELT_H2) || eltName.equals(XmlNames.ELT_H3) || eltName.equals(XmlNames.ELT_H4) || eltName.equals(XmlNames.ELT_H5) || eltName.equals(XmlNames.ELT_H6)) { processParagraphElement(element, rawStr, linkedStr); } // paragraphs inside paragraphs are processed recursively else if (eltName.equals(XmlNames.ELT_P)) { processParagraphElement(element, rawStr, linkedStr); } // superscripts are to be avoided else if (eltName.equals(XmlNames.ELT_SUP)) { // they are either external references or WP inline notes // cf. http://en.wikipedia.org/wiki/Template%3ACitation_needed } // small caps are placed before phonetic transcriptions of names, which we avoid else if (eltName.equals(XmlNames.ELT_SMALL)) { // we don't need them, and they can mess up NER tools } // we ignore certain types of span (phonetic trancription, WP buttons...) else if (eltName.equals(XmlNames.ELT_SPAN)) { processSpanElement(element, rawStr, linkedStr); } // hyperlinks must be included in the linked string, provided they are not external else if (eltName.equals(XmlNames.ELT_A)) { processHyperlinkElement(element, rawStr, linkedStr); } // lists else if (eltName.equals(XmlNames.ELT_UL)) { processListElement(element, rawStr, linkedStr, false); } else if (eltName.equals(XmlNames.ELT_OL)) { processListElement(element, rawStr, linkedStr, true); } else if (eltName.equals(XmlNames.ELT_DL)) { processDescriptionListElement(element, rawStr, linkedStr); } // list item else if (eltName.equals(XmlNames.ELT_LI)) { processTextElement(element, rawStr, linkedStr); } // divisions are just processed recursively else if (eltName.equals(XmlNames.ELT_DIV)) { processDivisionElement(element, rawStr, linkedStr); } // quotes are just processed recursively else if (eltName.equals(XmlNames.ELT_BLOCKQUOTE)) { processQuoteElement(element, rawStr, linkedStr); } // citation else if (eltName.equals(XmlNames.ELT_CITE)) { processParagraphElement(element, rawStr, linkedStr); } // other elements are considered as simple text else { String text = element.text(); rawStr.append(text); linkedStr.append(text); } } // text node else if (node instanceof TextNode) { // get the text TextNode textNode = (TextNode) node; String text = textNode.text(); // if at the begining of a new line, or already preceeded by a space, remove leading spaces while (rawStr.length() > 0 && (rawStr.charAt(rawStr.length() - 1) == '\n' || rawStr.charAt(rawStr.length() - 1) == ' ') && text.startsWith(" ")) text = text.substring(1); // complete string buffers rawStr.append(text); linkedStr.append(text); } } }