PageRenderTime 23ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/jgraph-5.13.0.0/examples/com/jgraph/layout/JGraphWordBrowser.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 480 lines | 364 code | 36 blank | 80 comment | 60 complexity | 939eb16cefb8b894785aff80bc6cf934 MD5 | raw file
  1. /*
  2. * $Id: JGraphWordBrowser.java,v 1.1 2009/09/25 15:17:49 david Exp $
  3. * Copyright (c) 2001-2005, Gaudenz Alder
  4. *
  5. * All rights reserved.
  6. *
  7. * This file is licensed under the JGraph software license, a copy of which
  8. * will have been provided to you in the file LICENSE at the root of your
  9. * installation directory. If you are unable to locate this file please
  10. * contact JGraph sales for another copy.
  11. */
  12. package com.jgraph.layout;
  13. import java.awt.BorderLayout;
  14. import java.awt.Color;
  15. import java.awt.Cursor;
  16. import java.awt.Font;
  17. import java.awt.Rectangle;
  18. import java.awt.event.KeyAdapter;
  19. import java.awt.event.KeyEvent;
  20. import java.awt.event.MouseEvent;
  21. import java.awt.geom.Rectangle2D;
  22. import java.io.BufferedReader;
  23. import java.io.DataOutputStream;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.net.URL;
  27. import java.net.URLConnection;
  28. import java.net.URLEncoder;
  29. import java.util.ArrayList;
  30. import java.util.Collection;
  31. import java.util.Hashtable;
  32. import java.util.Iterator;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import javax.swing.JFrame;
  37. import javax.swing.JScrollPane;
  38. import javax.swing.JTextField;
  39. import javax.swing.JViewport;
  40. import javax.swing.SwingConstants;
  41. import org.jgraph.JGraph;
  42. import org.jgraph.graph.CellView;
  43. import org.jgraph.graph.ConnectionSet;
  44. import org.jgraph.graph.DefaultEdge;
  45. import org.jgraph.graph.DefaultGraphCell;
  46. import org.jgraph.graph.DefaultGraphModel;
  47. import org.jgraph.graph.GraphConstants;
  48. import org.jgraph.graph.VertexRenderer;
  49. import org.jgraph.graph.VertexView;
  50. import org.jgraph.plaf.basic.BasicGraphUI;
  51. import com.jgraph.layout.graph.JGraphSimpleLayout;
  52. import com.jgraph.layout.hierarchical.JGraphHierarchicalLayout;
  53. import com.jgraph.layout.organic.JGraphFastOrganicLayout;
  54. import com.jgraph.layout.organic.JGraphOrganicLayout;
  55. /**
  56. * A simple example to browse a word database.
  57. */
  58. public class JGraphWordBrowser extends DefaultGraphModel {
  59. /**
  60. * Internal mapping of user objects to cells.
  61. */
  62. protected Map mapping = new Hashtable();
  63. /**
  64. * Shortcut to {@link #addVertex(Object, String)} with an empty style.
  65. */
  66. public Object addVertex(Object data) {
  67. return addVertex(data, null);
  68. }
  69. /**
  70. * Adds a vertex to the model.
  71. */
  72. public Object addVertex(Object data, String stylename) {
  73. if (data != null) {
  74. Object vertex = mapping.get(data);
  75. if (vertex == null) {
  76. vertex = createCell(data, stylename, false);
  77. insert(new Object[] { vertex }, null, null, null, null);
  78. }
  79. }
  80. return data;
  81. }
  82. /**
  83. * Shortcut to {@link #addEdge(Object, Object, Object)} with an empty user
  84. * object.
  85. */
  86. public Object addEdge(Object source, Object target) {
  87. return addEdge(source, target, null);
  88. }
  89. /**
  90. * Shortcut to {@link #addEdge(Object, Object, Object, String)} with an
  91. * empty style.
  92. */
  93. public Object addEdge(Object source, Object target, Object data) {
  94. return addEdge(source, target, data, null);
  95. }
  96. /**
  97. * Shortcut to {@link #addEdge(Object, Object, Object, String, String)} with
  98. * an empty vertex style.
  99. */
  100. public Object addEdge(Object source, Object target, Object data,
  101. String edgeStylename) {
  102. return addEdge(source, target, data, edgeStylename, null);
  103. }
  104. /**
  105. * Adds an edge between source and target to the model.
  106. */
  107. public Object addEdge(Object source, Object target, Object data,
  108. String edgeStylename, String vertexStylename) {
  109. if (source != null && target != null) {
  110. Collection newCells = new ArrayList(3);
  111. // Creates the source
  112. Object sourceVertex = mapping.get(source);
  113. if (sourceVertex == null) {
  114. sourceVertex = createCell(source, vertexStylename, false);
  115. newCells.add(sourceVertex);
  116. }
  117. // Creates the neighbour
  118. Object targetVertex = mapping.get(target);
  119. if (targetVertex == null) {
  120. targetVertex = createCell(target, vertexStylename, false);
  121. newCells.add(targetVertex);
  122. }
  123. // Creates the edge to the neighbour
  124. Object edge = (data != null) ? mapping.get(data) : null;
  125. ConnectionSet cs = null;
  126. if (edge == null) {
  127. edge = createCell(data, edgeStylename, true);
  128. newCells.add(edge);
  129. if (getChildCount(sourceVertex) > 0
  130. && getChildCount(targetVertex) > 0)
  131. cs = new ConnectionSet(edge, getDefaultPort(sourceVertex),
  132. getDefaultPort(targetVertex));
  133. }
  134. // Inserts the new cells into the graph model
  135. if (!newCells.isEmpty()) {
  136. insert(newCells.toArray(), null, cs, null, null);
  137. }
  138. }
  139. return data;
  140. }
  141. /**
  142. * Uses the factory to create a vertex or edge for a specified stylename and
  143. * registers the mapping.
  144. */
  145. protected Object createCell(Object data, String stylename, boolean isEdge) {
  146. Object cell = (isEdge) ? createEdge(data) : createVertex(data);
  147. if (data != null) {
  148. mapping.put(data, cell);
  149. }
  150. // Stores the stylename in the attribute map
  151. if (stylename != null) {
  152. //Map attributes = getAttributes(cell);
  153. // JSPGraphConstants.setStyle(attributes, stylename);
  154. }
  155. return cell;
  156. }
  157. /**
  158. * Hook for subclassers to create the vertex.
  159. */
  160. public Object createVertex(Object data) {
  161. DefaultGraphCell vertex = new DefaultGraphCell(data);
  162. GraphConstants.setAutoSize(vertex.getAttributes(), true);
  163. GraphConstants.setInset(vertex.getAttributes(), 4);
  164. vertex.addPort();
  165. return vertex;
  166. }
  167. /**
  168. * Hook for subclassers to create the vertex.
  169. */
  170. public Object createEdge(Object data) {
  171. DefaultEdge edge = new DefaultEdge(data);
  172. int len = String.valueOf(data).length();
  173. int size = (len > 20) ? ((len > 40) ? 8 : 10) : 12;
  174. GraphConstants
  175. .setFont(edge.getAttributes(), new Font("Serif", 0, size));
  176. GraphConstants.setLabelAlongEdge(edge.getAttributes(), true);
  177. GraphConstants.setLineColor(edge.getAttributes(), Color.GRAY);
  178. // GraphConstants.setRouting(edge.getAttributes(),
  179. // JSPGraphParallelEdgeRouter.sharedInstance);
  180. return edge;
  181. }
  182. /**
  183. * Removes a cell from the model.
  184. */
  185. public Object remove(Object data) {
  186. Object vertex = mapping.remove(data);
  187. if (vertex != null) {
  188. // Includes all connections to/from the cell
  189. Set cells = DefaultGraphModel.getEdges(this,
  190. new Object[] { vertex });
  191. cells.add(vertex);
  192. // Removes the cells from the model
  193. remove(cells.toArray());
  194. }
  195. return vertex;
  196. }
  197. /**
  198. * Returns the default port for the specified vertex.
  199. */
  200. public Object getDefaultPort(Object vertex) {
  201. return getChild(vertex, 0);
  202. }
  203. /**
  204. *
  205. *
  206. */
  207. public void add(String word, String wordType) {
  208. if (word.endsWith(")")) {
  209. int index = word.indexOf(" (");
  210. wordType = word.substring(index + 1);
  211. word = word.substring(0, index);
  212. }
  213. try {
  214. List page = getContent(word);
  215. Iterator it = page.iterator();
  216. String type = "";
  217. Object vertex = null;
  218. while (it.hasNext()) {
  219. String line = (String) it.next();
  220. if (line.indexOf("<h3>Noun</h3>") >= 0) {
  221. type = "(N)";
  222. if (wordType.equals(type)) {
  223. vertex = addVertex(word + " " + type);
  224. } else {
  225. vertex = null;
  226. }
  227. } else if (line.indexOf("<h3>Adjective</h3>") >= 0) {
  228. type = "(A)";
  229. if (wordType.equals(type)) {
  230. vertex = addVertex(word + " " + type);
  231. } else {
  232. vertex = null;
  233. }
  234. } else if (line.indexOf("<h3>Verb</h3>") >= 0) {
  235. type = "(V)";
  236. if (wordType.equals(type)) {
  237. vertex = addVertex(word + " " + type);
  238. } else {
  239. vertex = null;
  240. }
  241. }
  242. if (vertex != null) {
  243. if (line.indexOf("<li>") >= 0) {
  244. List words = getWords(line);
  245. String edge = "";
  246. int index = line.lastIndexOf("(") + 1;
  247. if (index >= 0) {
  248. edge = line.substring(index, line.indexOf(")",
  249. index));
  250. }
  251. int counter = 1;
  252. Iterator it2 = words.iterator();
  253. while (it2.hasNext()) {
  254. String target = it2.next() + " " + type;
  255. if (!target.startsWith("S:")
  256. && !target.equals(vertex)) {
  257. addEdge(vertex, target, edge + " (" + counter++
  258. + ")");
  259. System.out.println(vertex + " -> " + edge
  260. + " -> " + target);
  261. }
  262. }
  263. }
  264. }
  265. }
  266. sendEdgesToBack();
  267. } catch (Exception e) {
  268. e.printStackTrace();
  269. }
  270. }
  271. public List getWords(String line) {
  272. List words = new ArrayList();
  273. int index = line.indexOf("<a href=\"");
  274. while (index > 0) {
  275. index = line.indexOf("\">", index) + 2;
  276. int end = line.indexOf("</a>", index);
  277. String word = line.substring(index, end);
  278. words.add(word);
  279. index = line.indexOf("<a href=\"", end + 4);
  280. }
  281. return words;
  282. }
  283. public List getContent(String word) throws IOException {
  284. URL url = new URL("http://wordnet.princeton.edu/perl/webwn");
  285. URLConnection urlConn = url.openConnection();
  286. urlConn.setDoInput(true);
  287. urlConn.setDoOutput(true);
  288. urlConn.setUseCaches(false);
  289. urlConn.setRequestProperty("Content-Type",
  290. "application/x-www-form-urlencoded");
  291. DataOutputStream printout = new DataOutputStream(urlConn
  292. .getOutputStream());
  293. String content = "s=" + URLEncoder.encode(word, "UTF-8")
  294. + "&o2=&o0=1&o6=&o1=1&o5=&o4=&o3=&h=";
  295. printout.writeBytes(content);
  296. printout.flush();
  297. printout.close();
  298. BufferedReader ireader = new BufferedReader(new InputStreamReader(
  299. urlConn.getInputStream()));
  300. ArrayList webpage = new ArrayList(100);
  301. String line;
  302. while ((line = ireader.readLine()) != null) {
  303. webpage.add(line);
  304. }
  305. ireader.close();
  306. return webpage;
  307. }
  308. public static void layout(JGraph graph, boolean organic, boolean horizontal) {
  309. JGraphFacade facade = createFacade(graph);
  310. if (!organic) {
  311. JGraphHierarchicalLayout layout = new JGraphHierarchicalLayout();
  312. if (horizontal) {
  313. layout.setOrientation(SwingConstants.WEST);
  314. }
  315. layout.setInterRankCellSpacing(50);
  316. layout.setIntraCellSpacing(60);
  317. try {
  318. layout.run(facade);
  319. } catch (Exception e) {
  320. System.err.println(e.getMessage());
  321. organic = true;
  322. }
  323. }
  324. if (organic) {
  325. JGraphLayout layout = new JGraphSimpleLayout(
  326. JGraphSimpleLayout.TYPE_CIRCLE);
  327. layout.run(facade);
  328. JGraphFastOrganicLayout fastOrganicLayout = new JGraphFastOrganicLayout();
  329. fastOrganicLayout.setForceConstant(80);
  330. fastOrganicLayout.run(facade);
  331. JGraphOrganicLayout organicLayout = new JGraphOrganicLayout();
  332. organicLayout.setRadiusScaleFactor(0.9);
  333. organicLayout.setNodeDistributionCostFactor(8000000.0);
  334. organicLayout.setOptimizeBorderLine(false);
  335. organicLayout.setDeterministic(true);
  336. organicLayout.run(facade);
  337. }
  338. Map map = facade.createNestedMap(true, true);
  339. graph.getGraphLayoutCache().edit(map, null, null, null);
  340. }
  341. /**
  342. * Sends all edges to the background. TODO: Create special graph model with
  343. * keepEdgesInBack option.
  344. */
  345. public void sendEdgesToBack() {
  346. Object[] cells = DefaultGraphModel.getAll(this);
  347. List edges = new ArrayList(cells.length);
  348. for (int i = 0; i < cells.length; i++) {
  349. if (isEdge(cells[i])) {
  350. edges.add(cells[i]);
  351. }
  352. }
  353. toBack(edges.toArray());
  354. }
  355. /**
  356. * Creates a {@link JGraphFacade}.
  357. *
  358. * @param graph
  359. * The graph to use for the facade.
  360. * @return Returns a new facade for the specified graph.
  361. */
  362. protected static JGraphFacade createFacade(JGraph graph) {
  363. JGraphFacade facade = new JGraphFacade(graph);
  364. facade.setIgnoresUnconnectedCells(true);
  365. facade.setIgnoresCellsInGroups(true);
  366. facade.setIgnoresHiddenCells(true);
  367. facade.setDirected(true);
  368. return facade;
  369. }
  370. public static void main(String[] args) {
  371. final boolean organic = true;
  372. VertexView.renderer = new SynonymRenderer();
  373. JGraphWordBrowser synModel = new JGraphWordBrowser();
  374. final JGraph graph = new JGraph(synModel) {
  375. public void updateUI() {
  376. setUI(new BasicGraphUI() {
  377. protected boolean startEditing(Object cell, MouseEvent e) {
  378. if (!getModel().isEdge(cell)) {
  379. Cursor previous = graph.getCursor();
  380. graph.setCursor(new Cursor(Cursor.WAIT_CURSOR));
  381. ((JGraphWordBrowser) getModel()).add(String
  382. .valueOf(cell), null);
  383. graph.setSelectionCell(cell);
  384. JGraphWordBrowser.layout(graph, organic, true);
  385. scrollCellToVisible(cell);
  386. Rectangle2D bounds = getCellBounds(cell);
  387. if (getParent() instanceof JViewport) {
  388. Rectangle dim = ((JViewport) getParent())
  389. .getBounds();
  390. int w = (int) dim.getWidth();
  391. int h = (int) dim.getHeight();
  392. Rectangle rect = new Rectangle((int) (bounds
  393. .getX() - w / 2),
  394. (int) (bounds.getY() - h / 2), w, h);
  395. scrollRectToVisible(rect);
  396. } else {
  397. scrollCellToVisible(cell);
  398. }
  399. graph.setCursor(previous);
  400. return true;
  401. }
  402. return false;
  403. }
  404. });
  405. invalidate();
  406. }
  407. };
  408. graph.getGraphLayoutCache().setSelectsAllInsertedCells(false);
  409. graph.setEditClickCount(1);
  410. graph.setAntiAliased(true);
  411. JFrame frame = new JFrame("Graph Word Browser Example");
  412. frame.getContentPane().setLayout(new BorderLayout());
  413. final JTextField text = new JTextField(
  414. "Type a word and type and press [ENTER] Supported types are (V), (N) and (A)");
  415. frame.getContentPane().add(text, BorderLayout.NORTH);
  416. text.addKeyListener(new KeyAdapter() {
  417. public void keyPressed(KeyEvent e) {
  418. if (e.getKeyCode() == KeyEvent.VK_ENTER) {
  419. JGraphWordBrowser synModel = new JGraphWordBrowser();
  420. graph.setModel(synModel);
  421. String type = (text.getText().indexOf("(") >= 0) ? null
  422. : "(V)";
  423. if (type != null) {
  424. text.setText(text.getText() + " (V)");
  425. }
  426. synModel.add(text.getText(), type); // graph
  427. layout(graph, organic, true);
  428. }
  429. }
  430. });
  431. frame.getContentPane().add(new JScrollPane(graph), BorderLayout.CENTER);
  432. frame.setSize(640, 480);
  433. frame.setVisible(true);
  434. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  435. }
  436. public static class SynonymRenderer extends VertexRenderer {
  437. public void installAttributes(CellView cellView) {
  438. super.installAttributes(cellView);
  439. if (selected) {
  440. setForeground(Color.RED);
  441. }
  442. }
  443. }
  444. }