You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IpLogGenerator.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.iplog;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileReader;
  47. import java.io.IOException;
  48. import java.io.OutputStream;
  49. import java.text.MessageFormat;
  50. import java.text.ParseException;
  51. import java.text.SimpleDateFormat;
  52. import java.util.ArrayList;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.Comparator;
  56. import java.util.Date;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.Set;
  62. import java.util.TreeMap;
  63. import java.util.TreeSet;
  64. import javax.xml.parsers.DocumentBuilderFactory;
  65. import javax.xml.parsers.ParserConfigurationException;
  66. import javax.xml.transform.OutputKeys;
  67. import javax.xml.transform.Transformer;
  68. import javax.xml.transform.TransformerConfigurationException;
  69. import javax.xml.transform.TransformerException;
  70. import javax.xml.transform.TransformerFactory;
  71. import javax.xml.transform.dom.DOMSource;
  72. import javax.xml.transform.stream.StreamResult;
  73. import org.eclipse.jgit.diff.Edit;
  74. import org.eclipse.jgit.diff.EditList;
  75. import org.eclipse.jgit.diff.MyersDiff;
  76. import org.eclipse.jgit.diff.RawText;
  77. import org.eclipse.jgit.errors.ConfigInvalidException;
  78. import org.eclipse.jgit.errors.MissingObjectException;
  79. import org.eclipse.jgit.iplog.Committer.ActiveRange;
  80. import org.eclipse.jgit.lib.BlobBasedConfig;
  81. import org.eclipse.jgit.lib.Constants;
  82. import org.eclipse.jgit.lib.MutableObjectId;
  83. import org.eclipse.jgit.lib.ObjectLoader;
  84. import org.eclipse.jgit.lib.PersonIdent;
  85. import org.eclipse.jgit.lib.Repository;
  86. import org.eclipse.jgit.lib.WindowCursor;
  87. import org.eclipse.jgit.revwalk.FooterKey;
  88. import org.eclipse.jgit.revwalk.RevCommit;
  89. import org.eclipse.jgit.revwalk.RevTree;
  90. import org.eclipse.jgit.revwalk.RevWalk;
  91. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  92. import org.eclipse.jgit.treewalk.TreeWalk;
  93. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  94. import org.eclipse.jgit.util.RawParseUtils;
  95. import org.w3c.dom.Document;
  96. import org.w3c.dom.Element;
  97. /**
  98. * Creates an Eclipse IP log in XML format.
  99. *
  100. * @see <a href="http://www.eclipse.org/projects/xml/iplog.xsd">IP log XSD</a>
  101. */
  102. public class IpLogGenerator {
  103. private static final String IPLOG_NS = "http://www.eclipse.org/projects/xml/iplog";
  104. private static final String IPLOG_PFX = "iplog:";
  105. private static final String INDENT = "{http://xml.apache.org/xslt}indent-amount";
  106. private static final FooterKey BUG = new FooterKey("Bug");
  107. /** Projects indexed by their ID string, e.g. {@code technology.jgit}. */
  108. private final Map<String, Project> projects = new TreeMap<String, Project>();
  109. /** Projects indexed by their ID string, e.g. {@code technology.jgit}. */
  110. private final Map<String, Project> consumedProjects = new TreeMap<String, Project>();
  111. /** Known committers, indexed by their foundation ID. */
  112. private final Map<String, Committer> committersById = new HashMap<String, Committer>();
  113. /** Known committers, indexed by their email address. */
  114. private final Map<String, Committer> committersByEmail = new HashMap<String, Committer>();
  115. /** Discovered contributors. */
  116. private final Map<String, Contributor> contributorsByName = new HashMap<String, Contributor>();
  117. /** All known CQs matching the projects we care about. */
  118. private final Set<CQ> cqs = new HashSet<CQ>();
  119. /** Root commits which were scanned to gather project data. */
  120. private final Set<RevCommit> commits = new HashSet<RevCommit>();
  121. /** The meta file we loaded to bootstrap our definitions. */
  122. private IpLogMeta meta;
  123. private String characterEncoding = "UTF-8";
  124. private Repository db;
  125. private RevWalk rw;
  126. private NameConflictTreeWalk tw;
  127. private final WindowCursor curs = new WindowCursor();
  128. private final MutableObjectId idbuf = new MutableObjectId();
  129. private Document doc;
  130. /** Create an empty generator. */
  131. public IpLogGenerator() {
  132. // Do nothing.
  133. }
  134. /**
  135. * Set the character encoding used to write the output file.
  136. *
  137. * @param encodingName
  138. * the character set encoding name.
  139. */
  140. public void setCharacterEncoding(String encodingName) {
  141. characterEncoding = encodingName;
  142. }
  143. /**
  144. * Scan a Git repository's history to compute the changes within it.
  145. *
  146. * @param repo
  147. * the repository to scan.
  148. * @param startCommit
  149. * commit the IP log is needed for.
  150. * @param version
  151. * symbolic label for the version.
  152. * @throws IOException
  153. * the repository cannot be read.
  154. * @throws ConfigInvalidException
  155. * the {@code .eclipse_iplog} file present at the top level of
  156. * {@code startId} is not a valid configuration file.
  157. */
  158. public void scan(Repository repo, RevCommit startCommit, String version)
  159. throws IOException, ConfigInvalidException {
  160. try {
  161. db = repo;
  162. rw = new RevWalk(db);
  163. tw = new NameConflictTreeWalk(db);
  164. RevCommit c = rw.parseCommit(startCommit);
  165. loadEclipseIpLog(version, c);
  166. loadCommitters(repo);
  167. scanProjectCommits(meta.getProjects().get(0), c);
  168. commits.add(c);
  169. } finally {
  170. WindowCursor.release(curs);
  171. db = null;
  172. rw = null;
  173. tw = null;
  174. }
  175. }
  176. private void loadEclipseIpLog(String version, RevCommit commit)
  177. throws IOException, ConfigInvalidException {
  178. TreeWalk log = TreeWalk.forPath(db, IpLogMeta.IPLOG_CONFIG_FILE, commit
  179. .getTree());
  180. if (log == null)
  181. return;
  182. meta = new IpLogMeta();
  183. try {
  184. meta.loadFrom(new BlobBasedConfig(null, db, log.getObjectId(0)));
  185. } catch (ConfigInvalidException e) {
  186. throw new ConfigInvalidException(MessageFormat.format(IpLogText.get().configurationFileInCommitIsInvalid
  187. , log.getPathString(), commit.name()), e);
  188. }
  189. if (meta.getProjects().isEmpty()) {
  190. throw new ConfigInvalidException(MessageFormat.format(IpLogText.get().configurationFileInCommitHasNoProjectsDeclared
  191. , log.getPathString(), commit.name()));
  192. }
  193. for (Project p : meta.getProjects()) {
  194. p.setVersion(version);
  195. projects.put(p.getName(), p);
  196. }
  197. for (Project p : meta.getConsumedProjects()) {
  198. consumedProjects.put(p.getName(), p);
  199. }
  200. cqs.addAll(meta.getCQs());
  201. }
  202. private void loadCommitters(Repository repo) throws IOException {
  203. SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  204. File list = new File(repo.getDirectory(), "gerrit_committers");
  205. BufferedReader br = new BufferedReader(new FileReader(list));
  206. String line;
  207. while ((line = br.readLine()) != null) {
  208. String[] field = line.trim().split(" *\\| *");
  209. String user = field[1];
  210. String name = field[2];
  211. String email = field[3];
  212. Date begin = parseDate(dt, field[4]);
  213. Date end = parseDate(dt, field[5]);
  214. if (user.startsWith("username:"))
  215. user = user.substring("username:".length());
  216. Committer who = committersById.get(user);
  217. if (who == null) {
  218. who = new Committer(user);
  219. int sp = name.indexOf(' ');
  220. if (0 < sp) {
  221. who.setFirstName(name.substring(0, sp).trim());
  222. who.setLastName(name.substring(sp + 1).trim());
  223. } else {
  224. who.setFirstName(name);
  225. who.setLastName(null);
  226. }
  227. committersById.put(who.getID(), who);
  228. }
  229. who.addEmailAddress(email);
  230. who.addActiveRange(new ActiveRange(begin, end));
  231. committersByEmail.put(email, who);
  232. }
  233. }
  234. private Date parseDate(SimpleDateFormat dt, String value)
  235. throws IOException {
  236. if ("NULL".equals(value) || "".equals(value) || value == null)
  237. return null;
  238. int dot = value.indexOf('.');
  239. if (0 < dot)
  240. value = value.substring(0, dot);
  241. try {
  242. return dt.parse(value);
  243. } catch (ParseException e) {
  244. IOException err = new IOException(MessageFormat.format(IpLogText.get().invalidDate, value));
  245. err.initCause(e);
  246. throw err;
  247. }
  248. }
  249. private void scanProjectCommits(Project proj, RevCommit start)
  250. throws IOException {
  251. rw.reset();
  252. rw.markStart(start);
  253. RevCommit commit;
  254. while ((commit = rw.next()) != null) {
  255. if (proj.isSkippedCommit(commit)) {
  256. continue;
  257. }
  258. final PersonIdent author = commit.getAuthorIdent();
  259. final Date when = author.getWhen();
  260. Committer who = committersByEmail.get(author.getEmailAddress());
  261. if (who != null && who.inRange(when)) {
  262. // Commit was written by the committer while they were
  263. // an active committer on the project.
  264. //
  265. who.setHasCommits(true);
  266. continue;
  267. }
  268. // Commit from a non-committer contributor.
  269. //
  270. final int cnt = commit.getParentCount();
  271. if (2 <= cnt) {
  272. // Avoid a pointless merge attributed to a non-committer.
  273. // Skip this commit if every file matches at least one
  274. // of the parent commits exactly, if so then the blame
  275. // for code in that file can be fully passed onto that
  276. // parent and this non-committer isn't responsible.
  277. //
  278. tw.setFilter(TreeFilter.ANY_DIFF);
  279. tw.setRecursive(true);
  280. RevTree[] trees = new RevTree[1 + cnt];
  281. trees[0] = commit.getTree();
  282. for (int i = 0; i < cnt; i++)
  283. trees[i + 1] = commit.getParent(i).getTree();
  284. tw.reset(trees);
  285. boolean matchAll = true;
  286. while (tw.next()) {
  287. boolean matchOne = false;
  288. for (int i = 1; i <= cnt; i++) {
  289. if (tw.getRawMode(0) == tw.getRawMode(i)
  290. && tw.idEqual(0, i)) {
  291. matchOne = true;
  292. break;
  293. }
  294. }
  295. if (!matchOne) {
  296. matchAll = false;
  297. break;
  298. }
  299. }
  300. if (matchAll)
  301. continue;
  302. }
  303. Contributor contributor = contributorsByName.get(author.getName());
  304. if (contributor == null) {
  305. String id = author.getEmailAddress();
  306. String name = author.getName();
  307. contributor = new Contributor(id, name);
  308. contributorsByName.put(name, contributor);
  309. }
  310. String id = commit.name();
  311. String subj = commit.getShortMessage();
  312. SingleContribution item = new SingleContribution(id, when, subj);
  313. List<String> bugs = commit.getFooterLines(BUG);
  314. if (1 == bugs.size()) {
  315. item.setBugID(bugs.get(0));
  316. } else if (2 <= bugs.size()) {
  317. StringBuilder tmp = new StringBuilder();
  318. for (String bug : bugs) {
  319. if (tmp.length() > 0)
  320. tmp.append(",");
  321. tmp.append(bug);
  322. }
  323. item.setBugID(tmp.toString());
  324. }
  325. if (2 <= cnt) {
  326. item.setSize("(merge)");
  327. contributor.add(item);
  328. continue;
  329. }
  330. int addedLines = 0;
  331. if (1 == cnt) {
  332. final RevCommit parent = commit.getParent(0);
  333. tw.setFilter(TreeFilter.ANY_DIFF);
  334. tw.setRecursive(true);
  335. tw.reset(new RevTree[] { parent.getTree(), commit.getTree() });
  336. while (tw.next()) {
  337. if (tw.getFileMode(1).getObjectType() != Constants.OBJ_BLOB)
  338. continue;
  339. byte[] oldImage;
  340. if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB)
  341. oldImage = openBlob(0);
  342. else
  343. oldImage = new byte[0];
  344. EditList edits = new MyersDiff(new RawText(oldImage),
  345. new RawText(openBlob(1))).getEdits();
  346. for (Edit e : edits)
  347. addedLines += e.getEndB() - e.getBeginB();
  348. }
  349. } else { // no parents, everything is an addition
  350. tw.setFilter(TreeFilter.ALL);
  351. tw.setRecursive(true);
  352. tw.reset(commit.getTree());
  353. while (tw.next()) {
  354. if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
  355. byte[] buf = openBlob(0);
  356. for (int ptr = 0; ptr < buf.length;) {
  357. ptr = RawParseUtils.nextLF(buf, ptr);
  358. addedLines++;
  359. }
  360. }
  361. }
  362. }
  363. if (addedLines < 0)
  364. throw new IOException(MessageFormat.format(IpLogText.get().incorrectlyScanned, commit.name()));
  365. if (1 == addedLines)
  366. item.setSize("+1 line");
  367. else
  368. item.setSize("+" + addedLines + " lines");
  369. contributor.add(item);
  370. }
  371. }
  372. private byte[] openBlob(int side) throws IOException {
  373. tw.getObjectId(idbuf, side);
  374. ObjectLoader ldr = db.openObject(curs, idbuf);
  375. if (ldr == null)
  376. throw new MissingObjectException(idbuf.copy(), Constants.OBJ_BLOB);
  377. return ldr.getCachedBytes();
  378. }
  379. /**
  380. * Dump the scanned information into an XML file.
  381. *
  382. * @param out
  383. * the file stream to write to. The caller is responsible for
  384. * closing the stream upon completion.
  385. * @throws IOException
  386. * the stream cannot be written.
  387. */
  388. public void writeTo(OutputStream out) throws IOException {
  389. try {
  390. TransformerFactory factory = TransformerFactory.newInstance();
  391. Transformer s = factory.newTransformer();
  392. s.setOutputProperty(OutputKeys.ENCODING, characterEncoding);
  393. s.setOutputProperty(OutputKeys.METHOD, "xml");
  394. s.setOutputProperty(OutputKeys.INDENT, "yes");
  395. s.setOutputProperty(INDENT, "2");
  396. s.transform(new DOMSource(toXML()), new StreamResult(out));
  397. } catch (ParserConfigurationException e) {
  398. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  399. err.initCause(e);
  400. throw err;
  401. } catch (TransformerConfigurationException e) {
  402. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  403. err.initCause(e);
  404. throw err;
  405. } catch (TransformerException e) {
  406. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  407. err.initCause(e);
  408. throw err;
  409. }
  410. }
  411. private Document toXML() throws ParserConfigurationException {
  412. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  413. factory.setNamespaceAware(true);
  414. doc = factory.newDocumentBuilder().newDocument();
  415. Element root = createElement("iplog");
  416. doc.appendChild(root);
  417. if (projects.size() == 1) {
  418. Project soleProject = projects.values().iterator().next();
  419. root.setAttribute("name", soleProject.getID());
  420. }
  421. Set<String> licenses = new TreeSet<String>();
  422. for (Project project : sort(projects, Project.COMPARATOR)) {
  423. root.appendChild(createProject(project));
  424. licenses.addAll(project.getLicenses());
  425. }
  426. if (!consumedProjects.isEmpty())
  427. appendBlankLine(root);
  428. for (Project project : sort(consumedProjects, Project.COMPARATOR)) {
  429. root.appendChild(createConsumes(project));
  430. licenses.addAll(project.getLicenses());
  431. }
  432. for (RevCommit c : sort(commits))
  433. root.appendChild(createCommitMeta(c));
  434. if (licenses.size() > 1)
  435. appendBlankLine(root);
  436. for (String name : sort(licenses))
  437. root.appendChild(createLicense(name));
  438. if (!cqs.isEmpty())
  439. appendBlankLine(root);
  440. for (CQ cq : sort(cqs, CQ.COMPARATOR))
  441. root.appendChild(createCQ(cq));
  442. if (!committersByEmail.isEmpty())
  443. appendBlankLine(root);
  444. for (Committer committer : sort(committersById, Committer.COMPARATOR))
  445. root.appendChild(createCommitter(committer));
  446. for (Contributor c : sort(contributorsByName, Contributor.COMPARATOR)) {
  447. appendBlankLine(root);
  448. root.appendChild(createContributor(c));
  449. }
  450. return doc;
  451. }
  452. private void appendBlankLine(Element root) {
  453. root.appendChild(doc.createTextNode("\n\n "));
  454. }
  455. private Element createProject(Project p) {
  456. Element project = createElement("project");
  457. populateProjectType(p, project);
  458. return project;
  459. }
  460. private Element createConsumes(Project p) {
  461. Element project = createElement("consumes");
  462. populateProjectType(p, project);
  463. return project;
  464. }
  465. private void populateProjectType(Project p, Element project) {
  466. required(project, "id", p.getID());
  467. required(project, "name", p.getName());
  468. optional(project, "comments", p.getComments());
  469. optional(project, "version", p.getVersion());
  470. }
  471. private Element createCommitMeta(RevCommit c) {
  472. Element meta = createElement("meta");
  473. required(meta, "key", "git-commit");
  474. required(meta, "value", c.name());
  475. return meta;
  476. }
  477. private Element createLicense(String name) {
  478. Element license = createElement("license");
  479. required(license, "id", name);
  480. optional(license, "description", null);
  481. optional(license, "comments", null);
  482. return license;
  483. }
  484. private Element createCQ(CQ cq) {
  485. Element r = createElement("cq");
  486. required(r, "id", Long.toString(cq.getID()));
  487. required(r, "description", cq.getDescription());
  488. optional(r, "license", cq.getLicense());
  489. optional(r, "use", cq.getUse());
  490. optional(r, "state", cq.getState());
  491. optional(r, "comments", cq.getComments());
  492. return r;
  493. }
  494. private Element createCommitter(Committer who) {
  495. Element r = createElement("committer");
  496. required(r, "id", who.getID());
  497. required(r, "firstName", who.getFirstName());
  498. required(r, "lastName", who.getLastName());
  499. optional(r, "affiliation", who.getAffiliation());
  500. required(r, "active", Boolean.toString(who.isActive()));
  501. required(r, "hasCommits", Boolean.toString(who.hasCommits()));
  502. optional(r, "comments", who.getComments());
  503. return r;
  504. }
  505. private Element createContributor(Contributor c) {
  506. Element r = createElement("contributor");
  507. required(r, "id", c.getID());
  508. required(r, "name", c.getName());
  509. for (SingleContribution s : sort(c.getContributions(),
  510. SingleContribution.COMPARATOR))
  511. r.appendChild(createContribution(s));
  512. return r;
  513. }
  514. private Element createContribution(SingleContribution s) {
  515. Element r = createElement("bug");
  516. required(r, "id", s.getID());
  517. optional(r, "bug-id", s.getBugID());
  518. required(r, "size", s.getSize());
  519. required(r, "type", "A"); // assume attachment type
  520. required(r, "created", format(s.getCreated()));
  521. required(r, "summary", s.getSummary());
  522. return r;
  523. }
  524. private String format(Date created) {
  525. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(created);
  526. }
  527. private Element createElement(String name) {
  528. return doc.createElementNS(IPLOG_NS, IPLOG_PFX + name);
  529. }
  530. private void required(Element r, String name, String value) {
  531. if (value == null)
  532. value = "";
  533. r.setAttribute(name, value);
  534. }
  535. private void optional(Element r, String name, String value) {
  536. if (value != null && value.length() > 0)
  537. r.setAttribute(name, value);
  538. }
  539. private static <T, Q extends Comparator<T>> Iterable<T> sort(
  540. Collection<T> objs, Q cmp) {
  541. ArrayList<T> sorted = new ArrayList<T>(objs);
  542. Collections.sort(sorted, cmp);
  543. return sorted;
  544. }
  545. private static <T, Q extends Comparator<T>> Iterable<T> sort(
  546. Map<?, T> objs, Q cmp) {
  547. return sort(objs.values(), cmp);
  548. }
  549. @SuppressWarnings("unchecked")
  550. private static <T extends Comparable> Iterable<T> sort(Collection<T> objs) {
  551. ArrayList<T> sorted = new ArrayList<T>(objs);
  552. Collections.sort(sorted);
  553. return sorted;
  554. }
  555. }