    1   /**
    2    * Licensed to Neo Technology under one or more contributor
    3    * license agreements. See the NOTICE file distributed with
    4    * this work for additional information regarding copyright
    5    * ownership. Neo Technology licenses this file to you under
    6    * the Apache License, Version 2.0 (the "License"); you may
    7    * not use this file except in compliance with the License.
    8    * You may obtain a copy of the License at
    9    *
    10   * http://www.apache.org/licenses/LICENSE-2.0
    11   *
    12   * Unless required by applicable law or agreed to in writing,
    13   * software distributed under the License is distributed on an
    14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    15   * KIND, either express or implied. See the License for the
    16   * specific language governing permissions and limitations
    17   * under the License.
    18   */
    19  package org.neo4j.examples.server;
    20
    21  import java.net.URI;
    22  import java.net.URISyntaxException;
    23
    24  import javax.ws.rs.core.MediaType;
    25
    26  import com.sun.jersey.api.client.Client;
    27  import com.sun.jersey.api.client.ClientResponse;
    28  import com.sun.jersey.api.client.WebResource;
    29
    30  public class CreateSimpleGraph {
    31
    32      private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/";
    33
    34      public static void main(String[] args) throws URISyntaxException {
    35          checkDatabaseIsRunning();
    36
    37          // START SNIPPET: nodesAndProps
    38          URI firstNode = createNode();
    39          addProperty(firstNode, "name", "Joe Strummer");
    40          URI secondNode = createNode();
    41          addProperty(secondNode, "band", "The Clash");
    42          // END SNIPPET: nodesAndProps
    43
    44          // START SNIPPET: addRel
    45          URI relationshipUri = addRelationship(firstNode, secondNode, "singer", "{ \"from\" : \"1976\", \"until\" : \"1986\" }");
    46          // END SNIPPET: addRel
    47
    48          // START SNIPPET: addMetaToRel
    49          addMetadataToProperty(relationshipUri, "stars", "5");
    50          // END SNIPPET: addMetaToRel
    51
    52          // START SNIPPET: queryForSingers
    53          findSingersInBands(firstNode);
    54          // END SNIPPET: queryForSingers
    55      }
    56
    57      private static void findSingersInBands(URI startNode) throws URISyntaxException {
    58          // START SNIPPET: traversalDesc
    59          // TraversalDescription turns into JSON to send to the Server
    60          TraversalDescription t = new TraversalDescription();
    61          t.setOrder(TraversalDescription.DEPTH_FIRST);
    62          t.setUniqueness(TraversalDescription.NODE);
    63          t.setMaxDepth(10);
    64          t.setReturnFilter(TraversalDescription.ALL);
    65          t.setRelationships(new Relationship("singer", Relationship.OUT));
    66          // END SNIPPET: traversalDesc
    67
    68          // START SNIPPET: traverse
    69          URI traverserUri = new URI(startNode.toString() + "/traverse/node");
    70          WebResource resource = Client.create().resource(traverserUri);
    71          String jsonTraverserPayload = t.toJson();
    72          ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).entity(jsonTraverserPayload).post(ClientResponse.class);
    73
    74          System.out.println(String.format("POST [%s] to [%s], status code [%d], returned data: " + System.getProperty("line.separator") + "%s", jsonTraverserPayload, traverserUri, response.getStatus(), response.getEntity(String.class)));
    75          // END SNIPPET: traverse
    76      }
    77
    78      // START SNIPPET: insideAddMetaToProp
    79      private static void addMetadataToProperty(URI relationshipUri, String name, String value) throws URISyntaxException {
    80          URI propertyUri = new URI(relationshipUri.toString() + "/properties");
    81          WebResource resource = Client.create().resource(propertyUri);
    82
    83          String entity = toJsonNameValuePairCollection(name, value);
    84          ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).entity(entity).put(ClientResponse.class);
    85
    86          System.out.println(String.format("PUT [%s] to [%s], status code [%d]", entity, propertyUri, response.getStatus()));
    87      }
    88      // END SNIPPET: insideAddMetaToProp
    89
    90      private static String toJsonNameValuePairCollection(String name, String value) {
    91          return String.format("{ \"%s\" : \"%s\" }", name, value);
    92      }
    93
    94      private static URI createNode() {
    95          // START SNIPPET: createNode
    96          final String nodeEntryPointUri = SERVER_ROOT_URI + "node"; // http://localhost:7474/db/manage/node
    97
    98          WebResource resource = Client.create().resource(nodeEntryPointUri); // http://localhost:7474/db/data/node
    99          ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).entity("{}").post(ClientResponse.class); // POST {} to the node entry point URI
    100
    101         System.out.println(String.format("POST to [%s], status code [%d], location header [%s]", nodeEntryPointUri, response.getStatus(), response.getLocation().toString()));
    102
    103         return response.getLocation();
    104         // END SNIPPET: createNode
    105     }
    106
    107     // START SNIPPET: insideAddRel
    108     private static URI addRelationship(URI startNode, URI endNode, String relationshipType, String jsonAttributes) throws URISyntaxException {
    109         URI fromUri = new URI(startNode.toString() + "/relationships");
    110         String relationshipJson = generateJsonRelationship(endNode, relationshipType, jsonAttributes);
    111
    112         WebResource resource = Client.create().resource(fromUri);
    113         ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).entity(relationshipJson).post(ClientResponse.class); // POST JSON to the relationships URI
    114
    115         System.out.println(String.format("POST to [%s], status code [%d], location header [%s]", fromUri, response.getStatus(), response.getLocation().toString()));
    116
    117         return response.getLocation();
    118     }
    119     // END SNIPPET: insideAddRel
    120
    121     private static String generateJsonRelationship(URI endNode, String relationshipType, String ... jsonAttributes) {
    122         StringBuilder sb = new StringBuilder();
    123         sb.append("{ \"to\" : \"");
    124         sb.append(endNode.toString());
    125         sb.append("\", ");
    126
    127         sb.append("\"type\" : \"");
    128         sb.append(relationshipType);
    129         if(jsonAttributes == null || jsonAttributes.length < 1) {
    130             sb.append("\"");
    131         } else {
    132             sb.append("\", \"data\" : ");
    133             for(int i = 0; i < jsonAttributes.length; i++) {
    134                 sb.append(jsonAttributes[i]);
    135                 if(i < jsonAttributes.length -1) { // Miss off the final comma
    136                     sb.append(", ");
    137                 }
    138             }
    139         }
    140
    141         sb.append(" }");
    142         return sb.toString();
    143     }
    144
    145     private static void addProperty(URI nodeUri, String propertyName, String propertyValue) {
    146         // START SNIPPET: addProp
    147         String propertyUri = nodeUri.toString() + "/properties/" + propertyName;
    148
    149         WebResource resource = Client.create().resource(propertyUri); // http://localhost:7474/db/data/node/{node_id}/properties/{property_name}
    150         ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).entity("\"" + propertyValue + "\"").put(ClientResponse.class);
    151
    152         System.out.println(String.format("PUT to [%s], status code [%d]", propertyUri, response.getStatus()));
    153         // END SNIPPET: addProp
    154     }
    155
    156     private static void checkDatabaseIsRunning() {
    157         // START SNIPPET: checkServer
    158         WebResource resource = Client.create().resource(SERVER_ROOT_URI);
    159         ClientResponse response = resource.get(ClientResponse.class);
    160
    161         System.out.println(String.format("GET on [%s], status code [%d]", SERVER_ROOT_URI, response.getStatus()));
    162         // END SNIPPET: checkServer
    163     }
    164 }