public static void verifyCommand( String args[], @SuppressWarnings("unused") String help, Pattern[] patterns, int low, int high) { String message = ""; if (args.length > high) { message = "too many arguments"; } else if (args.length < low) { message = "too few arguments"; } else { for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) { if (patterns[i] != null) { Matcher m = patterns[i].matcher(args[i]); if (!m.matches()) message += String.format( "Argument %s (%s) does not match %s%n", i, args[i], patterns[i].pattern()); } } } if (message.length() != 0) { StringBuilder sb = new StringBuilder(); String del = "${"; for (String arg : args) { sb.append(del); sb.append(arg); del = ";"; } sb.append("}, is not understood. "); sb.append(message); throw new IllegalArgumentException(sb.toString()); } }
public String _range(String args[]) { verifyCommand(args, _rangeHelp, _rangePattern, 2, 3); Version version = null; if (args.length >= 3) version = new Version(args[2]); else { String v = domain.getProperty("@"); if (v == null) return null; version = new Version(v); } String spec = args[1]; Matcher m = RANGE_MASK.matcher(spec); m.matches(); String floor = m.group(1); String floorMask = m.group(2); String ceilingMask = m.group(3); String ceiling = m.group(4); String left = version(version, floorMask); String right = version(version, ceilingMask); StringBuilder sb = new StringBuilder(); sb.append(floor); sb.append(left); sb.append(","); sb.append(right); sb.append(ceiling); String s = sb.toString(); VersionRange vr = new VersionRange(s); if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) { domain.error( "${range} macro created an invalid range %s from %s and mask %s", s, version, spec); } return sb.toString(); }
public String getCoordinates(RevisionRef r) { StringBuilder sb = new StringBuilder(r.groupId).append(":").append(r.artifactId).append(":"); if (r.classifier != null) sb.append(r.classifier).append("@"); sb.append(r.version); return sb.toString(); }
private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException { S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)"); S_LOGGER.debug("Job name " + job.getName()); cli = getCLI(job); String deleteType = null; List<String> argList = new ArrayList<String>(); S_LOGGER.debug("job name " + job.getName()); S_LOGGER.debug("Builds " + builds); if (CollectionUtils.isEmpty(builds)) { // delete job S_LOGGER.debug("Job deletion started"); S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND); deleteType = DELETE_TYPE_JOB; argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND); argList.add(job.getName()); } else { // delete Build S_LOGGER.debug("Build deletion started"); deleteType = DELETE_TYPE_BUILD; argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND); argList.add(job.getName()); StringBuilder result = new StringBuilder(); for (String string : builds) { result.append(string); result.append(","); } String buildNos = result.substring(0, result.length() - 1); argList.add(buildNos); S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND); S_LOGGER.debug("Build numbers " + buildNos); } try { int status = cli.execute(argList); String message = deleteType + " deletion started in jenkins"; if (status == FrameworkConstants.JOB_STATUS_NOTOK) { deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1); message = "Error while deleting " + deleteType + " in jenkins"; } S_LOGGER.debug("Delete CI Status " + status); S_LOGGER.debug("Delete CI Message " + message); return new CIJobStatus(status, message); } finally { if (cli != null) { try { cli.close(); } catch (IOException e) { if (debugEnabled) { S_LOGGER.error( "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) " + e.getLocalizedMessage()); } } catch (InterruptedException e) { if (debugEnabled) { S_LOGGER.error( "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) " + e.getLocalizedMessage()); } } } } }
private static String convert(List<List<Particle>> lists) { StringBuilder sb = new StringBuilder(); for (List<Particle> list : lists) { if (list.isEmpty()) sb.append('.'); else sb.append('X'); } return sb.toString(); }
private String getCIJobPath(ApplicationInfo appInfo) { StringBuilder builder = new StringBuilder(Utility.getProjectHome()); builder.append(appInfo.getAppDirName()); builder.append(File.separator); builder.append(FOLDER_DOT_PHRESCO); builder.append(File.separator); builder.append(CI_JOB_INFO_NAME); return builder.toString(); }
public String valueToString(Object value) throws ParseException { if (!(value instanceof byte[])) throw new ParseException("Not a byte[]", 0); byte[] a = (byte[]) value; if (a.length != 4) throw new ParseException("Length != 4", 0); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 4; i++) { int b = a[i]; if (b < 0) b += 256; builder.append(String.valueOf(b)); if (i < 3) builder.append('.'); } return builder.toString(); }
/** * Joins array elements to string. * * @param arr Array. * @return String. */ @Nullable public static String compactArray(Object[] arr) { if (arr == null || arr.length == 0) return null; String sep = ", "; StringBuilder sb = new StringBuilder(); for (Object s : arr) sb.append(s).append(sep); if (sb.length() > 0) sb.setLength(sb.length() - sep.length()); return U.compact(sb.toString()); }
private String createPath(String filename) { StringBuilder sb = new StringBuilder(); int index = filename.indexOf("."); // sb.append("/Users/daniel/Documents/"); sb.append("C:\\Users\\Perica\\Documents\\PJ3 VVS Malmö AB\\GRAB\\"); sb.append(filename.substring(0, index)); sb.append("."); sb.append("txt"); return sb.toString(); }
protected void selected(CharPos start, CharPos end) { StringBuilder buf = new StringBuilder(); synchronized (msgs) { boolean sel = false; for (Message msg : msgs) { if (!(msg.text() instanceof RichText)) continue; RichText rt = (RichText) msg.text(); RichText.Part part = null; if (sel) { part = rt.parts; } else if (msg == start.msg) { sel = true; for (part = rt.parts; part != null; part = part.next) { if (part == start.part) break; } } if (sel) { for (; part != null; part = part.next) { if (!(part instanceof RichText.TextPart)) continue; RichText.TextPart tp = (RichText.TextPart) part; CharacterIterator iter = tp.ti(); int sch; if (tp == start.part) sch = tp.start + start.ch.getInsertionIndex(); else sch = tp.start; int ech; if (tp == end.part) ech = tp.start + end.ch.getInsertionIndex(); else ech = tp.end; for (int i = sch; i < ech; i++) buf.append(iter.setIndex(i)); if (part == end.part) { sel = false; break; } buf.append(' '); } if (sel) buf.append('\n'); } if (msg == end.msg) break; } } Clipboard cl; if ((cl = java.awt.Toolkit.getDefaultToolkit().getSystemSelection()) == null) cl = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); try { final CharPos ownsel = selstart; cl.setContents( new StringSelection(buf.toString()), new ClipboardOwner() { public void lostOwnership(Clipboard cl, Transferable tr) { if (selstart == ownsel) selstart = selend = null; } }); } catch (IllegalStateException e) { } }
@Override public String toString() { StringBuilder sb = new StringBuilder(); String del = "["; for (Link r = this; r != null; r = r.previous) { sb.append(del); sb.append(r.key); del = ","; } sb.append("]"); return sb.toString(); }
/** * Returns compact class host. * * @param obj Object to compact. * @return String. */ @Nullable public static Object compactObject(Object obj) { if (obj == null) return null; if (obj instanceof Enum) return obj.toString(); if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj; if (obj instanceof Collection) { Collection col = (Collection) obj; Object[] res = new Object[col.size()]; int i = 0; for (Object elm : col) res[i++] = compactObject(elm); return res; } if (obj.getClass().isArray()) { Class<?> arrType = obj.getClass().getComponentType(); if (arrType.isPrimitive()) { if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj); if (obj instanceof byte[]) return Arrays.toString((byte[]) obj); if (obj instanceof short[]) return Arrays.toString((short[]) obj); if (obj instanceof int[]) return Arrays.toString((int[]) obj); if (obj instanceof long[]) return Arrays.toString((long[]) obj); if (obj instanceof float[]) return Arrays.toString((float[]) obj); if (obj instanceof double[]) return Arrays.toString((double[]) obj); } Object[] arr = (Object[]) obj; int iMax = arr.length - 1; StringBuilder sb = new StringBuilder("["); for (int i = 0; i <= iMax; i++) { sb.append(compactObject(arr[i])); if (i != iMax) sb.append(", "); } sb.append("]"); return sb.toString(); } return U.compact(obj.getClass().getName()); }
protected String replace(String key, Link link) { if (link != null && link.contains(key)) return "${infinite:" + link.toString() + "}"; if (key != null) { key = key.trim(); if (key.length() > 0) { Processor source = domain; String value = null; if (key.indexOf(';') < 0) { Instruction ins = new Instruction(key); if (!ins.isLiteral()) { SortedList<String> sortedList = SortedList.fromIterator(domain.iterator()); StringBuilder sb = new StringBuilder(); String del = ""; for (String k : sortedList) { if (ins.matches(k)) { String v = replace(k, new Link(source, link, key)); if (v != null) { sb.append(del); del = ","; sb.append(v); } } } return sb.toString(); } } while (value == null && source != null) { value = source.getProperties().getProperty(key); source = source.getParent(); } if (value != null) return process(value, new Link(source, link, key)); value = doCommands(key, link); if (value != null) return process(value, new Link(source, link, key)); if (key != null && key.trim().length() > 0) { value = System.getProperty(key); if (value != null) return value; } if (!flattening && !key.equals("@")) domain.warning("No translation found for macro: " + key); } else { domain.warning("Found empty macro key"); } } else { domain.warning("Found null macro key"); } return "${" + key + "}"; }
/** * Converts a Date into a formatted string. * * @param date The Date to convert. * @return The formatted string. */ public static String format(Date date) { Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC")); StringBuilder sb = new StringBuilder(); c.setTime(date); sb.append(w4.format(c.get(Calendar.YEAR))); sb.append(w2.format(c.get(Calendar.MONTH) + 1)); sb.append(w2.format(c.get(Calendar.DAY_OF_MONTH))); sb.append(w2.format(c.get(Calendar.HOUR_OF_DAY))); sb.append(w2.format(c.get(Calendar.MINUTE))); sb.append(w2.format(c.get(Calendar.SECOND))); return sb.toString(); }
/** * Converts the given string to camel case. * * @param string string to convert * @return resulting string */ public static String camelCase(final String string) { final StringBuilder sb = new StringBuilder(string.length()); boolean dash = false; for (int p = 0; p < string.length(); p++) { final char ch = string.charAt(p); if (dash) { sb.append(Character.toUpperCase(ch)); dash = false; } else { dash = ch == '-'; if (!dash) sb.append(ch); } } return sb.toString(); }
public String toString() { StringBuilder out = new StringBuilder(); Formatter formatter = new Formatter(out, Locale.US); for (int topic = 0; topic < numTopics; topic++) { formatter.format("Topic %d", topic); for (TopicScores scores : diagnostics) { formatter.format("\t%s=%.4f", scores.name, scores.scores[topic]); } formatter.format("\n"); for (int position = 0; position < topicTopWords[topic].length; position++) { if (topicTopWords[topic][position] == null) { break; } formatter.format(" %s", topicTopWords[topic][position]); for (TopicScores scores : diagnostics) { if (scores.wordScoresDefined) { formatter.format("\t%s=%.4f", scores.name, scores.topicWordScores[topic][position]); } } out.append("\n"); } } return out.toString(); }
private void setSvnCredential(CIJob job) throws JDOMException, IOException { S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential"); try { String jenkinsTemplateDir = Utility.getJenkinsTemplateDir(); String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML; if (debugEnabled) { S_LOGGER.debug("credentialFilePath ... " + credentialFilePath); } File credentialFile = new File(credentialFilePath); SvnProcessor processor = new SvnProcessor(credentialFile); // DataInputStream in = new DataInputStream(new FileInputStream(credentialFile)); // while (in.available() != 0) { // System.out.println(in.readLine()); // } // in.close(); processor.changeNodeValue("credentials/entry//userName", job.getUserName()); processor.changeNodeValue("credentials/entry//password", job.getPassword()); processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName())); // jenkins home location String jenkinsJobHome = System.getenv(JENKINS_HOME); StringBuilder builder = new StringBuilder(jenkinsJobHome); builder.append(File.separator); processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML)); } catch (Exception e) { S_LOGGER.error( "Entered into the catch block of CIManagerImpl.setSvnCredential " + e.getLocalizedMessage()); } }
public static String getHex(byte[] raw) { if (raw == null) return null; final StringBuilder hex = new StringBuilder(2 * raw.length); for (final byte b : raw) hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))); return hex.toString(); }
String version(Version version, String mask) { if (version == null) { String v = domain.getProperty("@"); if (v == null) { domain.error( "No version specified for ${version} or ${range} and no implicit version ${@} either, mask=%s", mask); v = "0"; } version = new Version(v); } StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); String result = null; if (c != '~') { if (i == 3) { result = version.getQualifier(); } else if (Character.isDigit(c)) { // Handle masks like +00, =+0 result = String.valueOf(c); } else { int x = version.get(i); switch (c) { case '+': x++; break; case '-': x--; break; case '=': break; } result = Integer.toString(x); } if (result != null) { sb.append(del); del = "."; sb.append(result); } } } return sb.toString(); }
public String _basename(String args[]) { if (args.length < 2) { domain.warning("Need at least one file name for ${basename;...}"); return null; } String del = ""; StringBuilder sb = new StringBuilder(); for (int i = 1; i < args.length; i++) { File f = domain.getFile(args[i]); if (f.exists() && f.getParentFile().exists()) { sb.append(del); sb.append(f.getName()); del = ","; } } return sb.toString(); }
public String valueToString(Object value) throws ParseException { if (!(value instanceof byte[])) { throw new ParseException("该IP地址的值只能是字节数组", 0); } byte[] a = (byte[]) value; if (a.length != 4) { throw new ParseException("IP地址必须是四个整数", 0); } StringBuilder builder = new StringBuilder(); for (int i = 0; i < 4; i++) { int b = a[i]; if (b < 0) b += 256; builder.append(String.valueOf(b)); if (i < 3) builder.append('.'); } return builder.toString(); }
@Override public synchronized String format(LogRecord record) { StringBuilder sb = new StringBuilder(); sb.append(dateFormat.format(new Date(record.getMillis()))); sb.append(' '); sb.append(record.getLevel().getLocalizedName()); sb.append(": "); sb.append(formatMessage(record)); sb.append(LINE_SEPARATOR); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception e) { // ignore } } return sb.toString(); }
/** * Returns a string of the specified UTF8 token. * * @param token token * @param start start position * @param length length * @return string */ private static String utf8(final byte[] token, final int start, final int length) { // input is assumed to be correct UTF8. if input contains codepoints // larger than Character.MAX_CODE_POINT, results might be unexpected. final StringBuilder sb = new StringBuilder(length << 1); final int il = Math.min(start + length, token.length); for (int i = start; i < il; i += cl(token, i)) { final int cp = cp(token, i); if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) { sb.append((char) cp); } else { final int o = cp - Character.MIN_SUPPLEMENTARY_CODE_POINT; sb.append((char) ((o >>> 10) + Character.MIN_HIGH_SURROGATE)); sb.append((char) ((o & 0x3ff) + Character.MIN_LOW_SURROGATE)); } } return sb.toString(); }
public void write(long time, Instrument instrument1, Instrument instrument2) { double bid1 = instrument1.getBid(); double ask1 = instrument1.getAsk(); double bid2 = instrument2.getBid(); double ask2 = instrument2.getAsk(); if (bid1 > 0 && ask1 > 0 && bid2 > 0 && ask2 > 0) { StringBuilder sb = new StringBuilder(); sb.append(dateFormat.format(new Date(time))).append(","); sb.append(decimalFormat.format(bid1)).append(","); sb.append(decimalFormat.format(ask1)).append(","); sb.append(decimalFormat.format(bid2)).append(","); sb.append(decimalFormat.format(ask2)); writer.println(sb); writer.flush(); } }
/** * Return a string that describes the statistics for the top n entries, sorted by descending * order of total time spent dealing with the query. This will always include the totals entry * in the first position. * * @param n the desired number of entries to describe * @return a string describing the statistics for the top n entries */ public synchronized String toStringTop(int n) { StringBuilder out = new StringBuilder(); List<Entry> list = entries(); if (list.isEmpty()) return "<no queries executed>"; Collections.sort(list, TOTAL_TIME_DESCENDING); int maxCountLength = COUNT_FORMAT.format(list.get(0).numQueries).length(); double totalDuration = list.get(0).queryTime; for (Entry entry : list.subList(0, Math.min(n, list.size()))) out.append(entry.toString(maxCountLength, totalDuration)).append('\n'); return out.toString(); }
/** * replace ; <list> ; regex ; replace * * @param args * @return */ public String _replace(String args[]) { if (args.length != 4) { domain.warning("Invalid nr of arguments to replace " + Arrays.asList(args)); return null; } String list[] = args[1].split("\\s*,\\s*"); StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < list.length; i++) { String element = list[i].trim(); if (!element.equals("")) { sb.append(del); sb.append(element.replaceAll(args[2], args[3])); del = ", "; } } return sb.toString(); }
public StringBuilder listToCSVForUserView(List list) { StringBuilder csv = new StringBuilder(); csv.append( "Project,Iteration,Work Product,Name,State,Owner,Task Estimate,Task Remaining,Time Spent\n"); for (int i = 0; i < list.size(); i++) { Map map = (Map) list.get(i); String projectName = (String) map.get("projectName"); String iterationName = (String) map.get("iterationName"); String formattedId = (String) map.get("taskFormattedId"); String taskName = (String) map.get("taskName"); String taskState = (String) map.get("taskState"); String owner = (String) map.get("owner"); String taskEstimate = (String) map.get("taskEstimate"); String taskRemaining = (String) map.get("taskRemaining"); String taskTimeSpent = (String) map.get("hours"); if (taskEstimate == null) { taskEstimate = ""; } if (taskRemaining == null) { taskRemaining = ""; } csv.append("" + projectName + ","); csv.append("\"" + iterationName + "\","); csv.append(formattedId + ","); csv.append(taskName + ","); csv.append(taskState + ","); csv.append(owner + ","); csv.append(taskEstimate + ","); csv.append(taskRemaining + ","); csv.append(taskTimeSpent + "\n"); } return csv; }
public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int l = s.length(); Double sqrl = Math.sqrt(l); Double low = Math.floor(sqrl); Double high = Math.ceil(sqrl); int r = 0; int c = 0; if (low == high) { r = low.intValue(); c = low.intValue(); } else if (low * high >= l) { r = low.intValue(); c = high.intValue(); } else { r = high.intValue(); c = high.intValue(); } // System.out.println("Row: " + r); // System.out.println("Col: " + c); StringBuilder sb = new StringBuilder(); char en[] = s.toCharArray(); for (int i = 0; i < c; i++) { for (int j = 0; j < r; j++) { if (j * c + i < l) { sb.append(en[j * c + i]); } } sb.append(" "); } System.out.println(sb.toString()); }
private String generateOverviewText() throws InsufficientDataException { StringBuilder sb = new StringBuilder(); final String team = config.getTeam(); double total = checkTotal(); final String nl = System.getProperty("line.separator"); for (Entry<String, Row> entry : rows.entrySet()) { double hours = Double.parseDouble(entry.getValue().hoursTF.getText()); double fraction = hours / total; if (fraction < 0.004) continue; String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey(); sb.append(line + nl); } return sb.toString(); }
private void setMailCredential(CIJob job) { if (debugEnabled) { S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential"); } try { String jenkinsTemplateDir = Utility.getJenkinsTemplateDir(); String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML; if (debugEnabled) { S_LOGGER.debug("configFilePath ... " + mailFilePath); } File mailFile = new File(mailFilePath); SvnProcessor processor = new SvnProcessor(mailFile); // DataInputStream in = new DataInputStream(new FileInputStream(mailFile)); // while (in.available() != 0) { // System.out.println(in.readLine()); // } // in.close(); // Mail have to go with jenkins running email address InetAddress ownIP = InetAddress.getLocalHost(); processor.changeNodeValue( CI_HUDSONURL, HTTP_PROTOCOL + PROTOCOL_POSTFIX + ownIP.getHostAddress() + COLON + job.getJenkinsPort() + FORWARD_SLASH + CI + FORWARD_SLASH); processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId()); processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword()); processor.changeNodeValue("adminAddress", job.getSenderEmailId()); // jenkins home location String jenkinsJobHome = System.getenv(JENKINS_HOME); StringBuilder builder = new StringBuilder(jenkinsJobHome); builder.append(File.separator); processor.writeStream(new File(builder.toString() + CI_MAILER_XML)); } catch (Exception e) { S_LOGGER.error( "Entered into the catch block of CIManagerImpl.setMailCredential " + e.getLocalizedMessage()); } }