Advertisement
jbjares2

Untitled

Jul 27th, 2015
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Servlet
  2. ===============================================================
  3. package com.jbjares.jvisualrdf.servlet;
  4.  
  5. import java.io.IOException;
  6. import java.io.Writer;
  7.  
  8. import javax.servlet.ServletException;
  9. import javax.servlet.annotation.WebServlet;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13.  
  14. /**
  15.  * Servlet implementation class RdfToJsonServlet
  16.  */
  17. @WebServlet("/RdfToJsonServlet")
  18. public class RdfToJsonServlet extends HttpServlet {
  19.     private static final long serialVersionUID = 1L;
  20.    
  21.     private static final String resultJson = "{\"nodes\": [{\"name\": \"g: visualRDF\", "+
  22.             "\"uri\": \"http: \\\\graves.cl\\/visualRDF\", "+
  23.             "\"type\": \"uri\", "+
  24.             "\"reflexive\": true, "+
  25.             "\"id\": 0 "+
  26.         "}, "+
  27.         "{ "+
  28.             "\"name\": \"http: \\\\alvaro.graves.cl\", "+
  29.             "\"uri\": \"http: \\\\alvaro.graves.cl\", "+
  30.             "\"type\": \"uri\", "+
  31.             "\"reflexive\": false, "+
  32.             "\"id\": 1 "+
  33.         "}, "+
  34.         "{ "+
  35.             "\"name\": \"http: \\\\github.com\\/alangrafu\\/visualRDF\", "+
  36.             "\"uri\": \"http: \\\\github.com\\/alangrafu\\/visualRDF\", "+
  37.             "\"type\": \"uri\", "+
  38.             "\"reflexive\": false, "+
  39.             "\"id\": 2 "+
  40.         "}, "+
  41.         "{ "+
  42.             "\"name\": \"g:visualRDF\\/css\\/bootstrap-responsive.min.css\", "+
  43.             "\"uri\": \"http: \\\\graves.cl\\/visualRDF\\/css\\/bootstrap-responsive.min.css\", "+
  44.             "\"type\": \"uri\", "+
  45.             "\"reflexive\": false, "+
  46.             "\"id\": 3 "+
  47.         "}, "+
  48.         "{ "+
  49.             "\"name\": \"g:visualRDF\\/css\\/bootstrap.min.css\", "+
  50.             "\"uri\": \"http:\\\\graves.cl\\/visualRDF\\/css\\/bootstrap.min.css\", "+
  51.             "\"type\": \"uri\", "+
  52.             "\"reflexive\": false, "+
  53.             "\"id\": 4 "+
  54.             "}, "+
  55.             "{ "+
  56.                 "\"name\": \"jbjares\", "+
  57.                 "\"uri\": \"http:\\\\jbjares\", "+
  58.                 "\"type\": \"uri\", "+
  59.                 "\"reflexive\": true, "+
  60.                 "\"id\": 5 "+
  61.             "} "+
  62.     "], "+
  63.     "\"links\": [ "+
  64.     "{ "+
  65.             "\"source\": 0, "+
  66.             "\"target\": 1, "+
  67.             "\"name\": \"dc: creator\", "+
  68.             "\"right\": true, "+
  69.             "\"felt\": false, "+
  70.             "\"value\": 10 "+
  71.         "}, "+
  72.         "{ "+
  73.             "\"source\": 0, "+
  74.             "\"target\": 2, "+
  75.             "\"name\": \"dc:source\", "+
  76.             "\"right\": true, "+
  77.             "\"felt\": false, "+
  78.             "\"value\": 10 "+
  79.         "}, "+
  80.         "{ "+
  81.             "\"source\": 0, "+
  82.             "\"target\": 3, "+
  83.             "\"name\": \"xhtml:stylesheet\", "+
  84.             "\"right\": true, "+
  85.             "\"felt\": false, "+
  86.             "\"value\": 10 "+
  87.         "}, "+
  88.         "{ "+
  89.             "\"source\": 0, "+
  90.             "\"target\": 4, "+
  91.             "\"name\": \"xhtml:stylesheet\", "+
  92.             "\"right\": true, "+
  93.             "\"felt\": false, "+
  94.             "\"value\": 10 "+
  95.         "} "+
  96.     "], "+
  97.         "\"literals\": [ "+
  98.             "{ "+
  99.                 "\"p\": \"dc:title\", "+
  100.                 "\"o\": \"VisualRDF\", "+
  101.                 "\"l\": \"\", "+
  102.                 "\"d\": \"\" "+
  103.             "}, "+
  104.             "{ "+
  105.                 "\"p\": \"dc:modified\", "+
  106.                 "\"o\": \"2012-05-18\", "+
  107.                 "\"l\": \"\", "+
  108.                 "\"d\": \"\" "+
  109.             "} "+
  110.         "] "+
  111.     "} ";
  112.    
  113.    
  114.     /**
  115.      * @see HttpServlet#HttpServlet()
  116.      */
  117.     public RdfToJsonServlet() {
  118.         super();
  119.     }
  120.  
  121.     /**
  122.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  123.      */
  124.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  125.         doExecute(request, response);
  126.     }
  127.  
  128.     /**
  129.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  130.      */
  131.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  132.         doExecute(request, response);
  133.     }
  134.    
  135.     /**
  136.      * @see HttpServlet#doExecute(HttpServletRequest request, HttpServletResponse response)
  137.      */
  138.     protected void doExecute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  139.         Writer writer = response.getWriter();
  140.         writer.write(resultJson);
  141.         writer.flush();
  142.         writer.close();
  143.     }
  144.  
  145. }
  146.  
  147. ==============================================================
  148.  
  149. main js of the app: var drag_line = null;
  150. var force = null;
  151. // handles to link and node element groups
  152. var path = null,
  153.     circle = null;
  154. var loaded = false;
  155. //var lastNodeId = 4;
  156. var lastNodeId = null;
  157. // set up SVG for D3
  158. var width  = 2100,
  159.     height = 950,
  160.     colors = d3.scale.category10();
  161.  
  162. var svg = d3.select('body')
  163.   .append('svg')
  164.   .attr('width', width)
  165.   .attr('height', height);
  166.  
  167. // set up initial nodes and links
  168. //  - nodes are known by 'id', not by index in array.
  169. //  - reflexive edges are indicated on the node (as a bold black circle).
  170. //  - links are always source < target; edge directions are set by 'left' and 'right'.
  171. var nodes = [
  172.     {id: 0, reflexive: false},
  173.     {id: 1, reflexive: true },
  174.     {id: 2, reflexive: false}
  175.   ],
  176.  
  177.   links = [
  178.     {source: nodes[0], target: nodes[1], left: false, right: true },
  179.     {source: nodes[1], target: nodes[2], left: false, right: true }
  180.   ];
  181.  
  182. // init D3 force layout
  183. function initD3ForceLayout(nodes,links){
  184.         force = d3.layout.force()
  185.         .nodes(nodes)
  186.         .links(links)
  187.         .size([width, height])
  188.         .linkDistance(150)
  189.         .charge(-500)
  190.         .on('tick', tick)
  191.            
  192.  
  193.     // define arrow markers for graph links
  194.     svg.append('svg:defs').append('svg:marker')
  195.         .attr('id', 'end-arrow')
  196.         .attr('viewBox', '0 -5 10 10')
  197.         .attr('refX', 6)
  198.         .attr('markerWidth', 3)
  199.         .attr('markerHeight', 3)
  200.         .attr('orient', 'auto')
  201.       .append('svg:path')
  202.         .attr('d', 'M0,-5L10,0L0,5')
  203.         .attr('fill', '#000');
  204.  
  205.     svg.append('svg:defs').append('svg:marker')
  206.         .attr('id', 'start-arrow')
  207.         .attr('viewBox', '0 -5 10 10')
  208.         .attr('refX', 4)
  209.         .attr('markerWidth', 3)
  210.         .attr('markerHeight', 3)
  211.         .attr('orient', 'auto')
  212.       .append('svg:path')
  213.         .attr('d', 'M10,-5L0,0L10,5')
  214.         .attr('fill', '#000');
  215.  
  216.     // line displayed when dragging new nodes
  217.      drag_line = svg.append('svg:path')
  218.       .attr('class', 'link dragline hidden')
  219.       .attr('d', 'M0,0L0,0');
  220.  
  221.     // handles to link and node element groups
  222.      path = svg.append('svg:g').selectAll('path'),
  223.         circle = svg.append('svg:g').selectAll('g');
  224.        
  225. }
  226.  
  227. // mouse event vars
  228. var selected_node = null,
  229.     selected_link = null,
  230.     mousedown_link = null,
  231.     mousedown_node = null,
  232.     mouseup_node = null;
  233.  
  234. function resetMouseVars() {
  235.   mousedown_node = null;
  236.   mouseup_node = null;
  237.   mousedown_link = null;
  238.  
  239. }
  240.  
  241. // update force layout (called automatically each iteration)
  242. function tick() {
  243.   // draw directed edges with proper padding from node centers
  244.   path.attr('d', function(d) {
  245.     var deltaX = d.target.x - d.source.x,
  246.         deltaY = d.target.y - d.source.y,
  247.         dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
  248.         normX = deltaX / dist,
  249.         normY = deltaY / dist,
  250.         sourcePadding = d.left ? 17 : 12,
  251.         targetPadding = d.right ? 17 : 12,
  252.         sourceX = d.source.x + (sourcePadding * normX),
  253.         sourceY = d.source.y + (sourcePadding * normY),
  254.         targetX = d.target.x - (targetPadding * normX),
  255.         targetY = d.target.y - (targetPadding * normY);
  256.    
  257.    
  258.  
  259.     return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
  260.   });
  261.  
  262.   circle.attr('transform', function(d) {
  263.       for(var key in d) {
  264.             var value = d[key];
  265.         }
  266.     return 'translate(' + d.x + ',' + d.y + ')';
  267.   });
  268. }
  269.  
  270. //function createPredicateFilters(up){
  271. //  updateFilters();
  272. //}
  273. // update graph (called when needed)
  274. function load() {
  275.     if(loaded){
  276.         return;
  277.     }
  278.    
  279. //  literals = json.literals;
  280. //  for(i in json.links){
  281. //      uniquePredicates[json.links[i].name] = 1;
  282. //  }
  283. //  createPredicateFilters(uniquePredicates);
  284.    
  285.     console.log("===> restart");
  286.     //d3.json('http://localhost:8080/JVisualRDFApp/RdfToJsonServlet?url='+encodeURIComponent(myUrl), function(json){
  287.     d3.json('http://localhost:8080/JVisualRDFApp/RdfToJsonServlet?url=<abc>', function(json){
  288.  
  289.             d3.select("#waiting").style("display", "none");
  290.             console.log("===> restart: json content "+json);
  291.             // path (link) group
  292.             console.log("===> init: json.links content "+json.links);
  293.             if(json.links!=null){
  294.                 links = json.links;
  295.             }else{
  296.                 console.log("===> error: json.links is null");
  297.             }
  298.            
  299.             if(json.nodes!=null){
  300.                 nodes = json.nodes;
  301.             }else{
  302.                 console.log("===> error: json.nodes  is null");
  303.             }
  304.             if(json.nodes!=null){
  305.                 console.log(json.nodes.length);
  306.                 lastNodeId = json.nodes.length-1;
  307.             }else{
  308.                 console.log("===> error: json.nodes  is null");
  309.             }
  310.            
  311.             initD3ForceLayout(nodes,links);
  312.             restart();
  313.             loaded = true;
  314.  
  315.     });
  316.    
  317. }
  318.  
  319.  
  320. function restart(){
  321.     path = path.data(links);
  322.     console.log("===> init: links content "+links);
  323.    
  324.       // update existing links
  325.       path.classed('selected', function(d) { return d === selected_link; })
  326.         .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
  327.         .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });
  328.  
  329.  
  330.       // add new links
  331.       path.enter().append('svg:path')
  332.         .attr('class', 'link')
  333.         .classed('selected', function(d) { return d === selected_link; })
  334.         .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
  335.         .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
  336.         .style('label', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
  337.         .on('mousedown', function(d) {
  338.           if(d3.event.ctrlKey) return;
  339.  
  340.           // select link
  341.           mousedown_link = d;
  342.           if(mousedown_link === selected_link) selected_link = null;
  343.           else selected_link = mousedown_link;
  344.           selected_node = null;
  345.           restart();
  346.         });
  347.      
  348.      
  349.  
  350.       // remove old links
  351.       path.exit().remove();
  352.  
  353.  
  354.       // circle (node) group
  355.       // NB: the function arg is crucial here! nodes are known by id, not by index!
  356.       circle = circle.data(nodes, function(d) { return d.id; });
  357.  
  358.       // update existing nodes (reflexive & selected visual states)
  359.       circle.selectAll('circle')
  360.         .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id); })
  361.         .classed('reflexive', function(d) { return d.reflexive; });
  362.  
  363.       // add new nodes
  364.       var g = circle.enter().append('svg:g');
  365.  
  366.       g.append('svg:circle')
  367.         .attr('class', 'node')
  368.         .attr('r', 12)
  369.         .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id); })
  370.         .style('stroke', function(d) { return d3.rgb(colors(d.id)).darker().toString(); })
  371.         .classed('reflexive', function(d) { return d.reflexive; })
  372.         .on('mouseover', function(d) {
  373.           if(!mousedown_node || d === mousedown_node) return;
  374.           // enlarge target node
  375.           d3.select(this).attr('transform', 'scale(1.1)');
  376.         })
  377.         .on('mouseout', function(d) {
  378.           if(!mousedown_node || d === mousedown_node) return;
  379.           // unenlarge target node
  380.           d3.select(this).attr('transform', '');
  381.         })
  382.         .on('mousedown', function(d) {
  383.           if(d3.event.ctrlKey) return;
  384.  
  385.           // select node
  386.           mousedown_node = d;
  387.           if(mousedown_node === selected_node) selected_node = null;
  388.           else selected_node = mousedown_node;
  389.           selected_link = null;
  390.  
  391.           // reposition drag line
  392.           drag_line
  393.             .style('marker-end', 'url(#end-arrow)')
  394.             .classed('hidden', false)
  395.             .attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + mousedown_node.x + ',' + mousedown_node.y);
  396.  
  397.           restart();
  398.         })
  399.         .on('mouseup', function(d) {
  400.           if(!mousedown_node) return;
  401.  
  402.           // needed by FF
  403.           drag_line
  404.             .classed('hidden', true)
  405.             .style('marker-end', '');
  406.  
  407.           // check for drag-to-self
  408.           mouseup_node = d;
  409.           if(mouseup_node === mousedown_node) { resetMouseVars(); return; }
  410.  
  411.           // unenlarge target node
  412.           d3.select(this).attr('transform', '');
  413.  
  414.           // add link to graph (update if exists)
  415.           // NB: links are strictly source < target; arrows separately specified by booleans
  416.           var source, target, direction;
  417.           if(mousedown_node.id < mouseup_node.id) {
  418.             source = mousedown_node;
  419.             target = mouseup_node;
  420.             direction = 'right';
  421.           } else {
  422.             source = mouseup_node;
  423.             target = mousedown_node;
  424.             direction = 'left';
  425.           }
  426.  
  427.           var link;
  428.           link = links.filter(function(l) {
  429.             return (l.source === source && l.target === target);
  430.           })[0];
  431.  
  432.           if(link) {
  433.             link[direction] = true;
  434.           } else {
  435.             link = {source: source, target: target, left: false, right: false};
  436.             link[direction] = true;
  437.             links.push(link);
  438.           }
  439.  
  440.           // select new link
  441.           selected_link = link;
  442.           selected_node = null;
  443.           restart();
  444.         });
  445.  
  446.       // show node names
  447.       g.append('svg:text')
  448.           .attr('x', 0)
  449.           .attr('y', 4)
  450.           .attr('class', 'name')
  451.           .text(function(d) { return d.name; });
  452. //        .attr('class', 'id')
  453. //        .text(function(d) { return d.id; });
  454.      
  455.       // remove old nodes
  456.       circle.exit().remove();
  457.  
  458.       // set the graph in motion
  459.       force.start();
  460. }
  461.  
  462. function mousedown() {
  463.   // prevent I-bar on drag
  464.   //d3.event.preventDefault();
  465.  
  466.   // because :active only works in WebKit?
  467.   svg.classed('active', true);
  468.  
  469.   if(d3.event.ctrlKey || mousedown_node || mousedown_link) return;
  470.  
  471.   // insert new node at point
  472.   var point = d3.mouse(this),
  473.       node = {id: ++lastNodeId, reflexive: false};
  474.   node.x = point[0];
  475.   node.y = point[1];
  476.   nodes.push(node);
  477.  
  478.   restart();
  479. }
  480.  
  481. function mousemove() {
  482.   if(!mousedown_node) return;
  483.  
  484.   // update drag line
  485.   drag_line.attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + d3.mouse(this)[0] + ',' + d3.mouse(this)[1]);
  486.  
  487.   restart();
  488. }
  489.  
  490. function mouseup() {
  491.   if(mousedown_node) {
  492.     // hide drag line
  493.     drag_line
  494.       .classed('hidden', true)
  495.       .style('marker-end', '');
  496.   }
  497.  
  498.   // because :active only works in WebKit?
  499.   svg.classed('active', false);
  500.  
  501.   // clear mouse event vars
  502.   resetMouseVars();
  503. }
  504.  
  505. function spliceLinksForNode(node) {
  506.   var toSplice = links.filter(function(l) {
  507.     return (l.source === node || l.target === node);
  508.   });
  509.   toSplice.map(function(l) {
  510.     links.splice(links.indexOf(l), 1);
  511.   });
  512. }
  513.  
  514. // only respond once per keydown
  515. var lastKeyDown = -1;
  516.  
  517. function keydown() {
  518.   d3.event.preventDefault();
  519.  
  520.   if(lastKeyDown !== -1) return;
  521.   lastKeyDown = d3.event.keyCode;
  522.  
  523.   // ctrl
  524.   if(d3.event.keyCode === 17) {
  525.     circle.call(force.drag);
  526.     svg.classed('ctrl', true);
  527.   }
  528.  
  529.   if(!selected_node && !selected_link) return;
  530.   switch(d3.event.keyCode) {
  531.     case 8: // backspace
  532.     case 46: // delete
  533.       if(selected_node) {
  534.         nodes.splice(nodes.indexOf(selected_node), 1);
  535.         spliceLinksForNode(selected_node);
  536.       } else if(selected_link) {
  537.         links.splice(links.indexOf(selected_link), 1);
  538.       }
  539.       selected_link = null;
  540.       selected_node = null;
  541.       restart();
  542.       break;
  543.     case 66: // B
  544.       if(selected_link) {
  545.         // set link direction to both left and right
  546.         selected_link.left = true;
  547.         selected_link.right = true;
  548.       }
  549.       restart();
  550.       break;
  551.     case 76: // L
  552.       if(selected_link) {
  553.         // set link direction to left only
  554.         selected_link.left = true;
  555.         selected_link.right = false;
  556.       }
  557.       restart();
  558.       break;
  559.     case 82: // R
  560.       if(selected_node) {
  561.         // toggle node reflexivity
  562.         selected_node.reflexive = !selected_node.reflexive;
  563.       } else if(selected_link) {
  564.         // set link direction to right only
  565.         selected_link.left = false;
  566.         selected_link.right = true;
  567.       }
  568.       restart();
  569.       break;
  570.   }
  571. }
  572.  
  573. function keyup() {
  574.   lastKeyDown = -1;
  575.  
  576.   // ctrl
  577.   if(d3.event.keyCode === 17) {
  578.     circle
  579.       .on('mousedown.drag', null)
  580.       .on('touchstart.drag', null);
  581.     svg.classed('ctrl', false);
  582.   }
  583. }
  584.  
  585. // app starts here
  586. svg.on('mousedown', mousedown)
  587.   .on('mousemove', mousemove)
  588.   .on('mouseup', mouseup);
  589. d3.select(window)
  590.   .on('keydown', keydown)
  591.   .on('keyup', keyup);
  592.  
  593. load();
  594. restart();
  595. ================================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement