Biblioteca Java - Rev 18
Subversion Repositories:
(root)/Frameworks and Technologies/Neo4J Samples/Neo4JTutorial/src/main/java/com/linkscreens/graphsin/repository/SocNet.java @ 19
package com.linkscreens.graphsin.repository;
/**
* Licensed to Neo Technology under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Neo Technology licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.index.Index;
import org.neo4j.helpers.collection.IteratorUtil;
public class SocNet
{
private static final Random r = new Random( System.currentTimeMillis() );
private static final int nrOfPersons = 10;
private static final int nrOffFriends = 3;
private static final int nrOfPosts = 5;
private static final int nrOfAlbums = 5;
private static final int nrOfMediaItems = 4;
private static final int nrOfComments = 3;
private GraphDatabaseService graphDb;
private PersonRepository personRepository;
private AlbumRepository albumRepository;
private MediaItemRepository mediaRepository;
public void setup(String storeDir) throws Exception
{
this.graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir );
try ( Transaction tx = graphDb.beginTx() )
{
Index<Node> index = graphDb.index().forNodes( "nodes" );
personRepository = new PersonRepository( graphDb, index );
Index<Node> indexA = graphDb.index().forNodes( "albums" );
albumRepository = new AlbumRepository(graphDb, indexA);
Index<Node> indexM = graphDb.index().forNodes( "mediaitems" );
mediaRepository = new MediaItemRepository(graphDb, indexM);
createPersons();
setupFriendsBetweenPeople( nrOffFriends );
multipleStatusesGenerator();
tx.success();
}
Transaction tx = graphDb.beginTx();
try{
createAlbums();
tx.success();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
tx.close();
}catch(org.neo4j.graphdb.TransactionFailureException exx){
exx.printStackTrace();
}
}
}
//GRAPH GENERATOR
private void createAlbums() throws Exception{
System.out.println("Create albums");
//iterate all persons
for ( PersonNode person : personRepository.getAllPersons() )
{
int albumsCount = r.nextInt( nrOfAlbums ) + 1;
//add a random number of albums to user
for ( int j = 0; j < albumsCount; j++ )
{
AlbumNode a = albumRepository.createAlbum(person.getName()+" album "+j);
person.addAlbum(a); //add album to peson
//for each album add a number of media items and for each item a number of comments
for ( int k = 0; k < nrOfMediaItems; k++ ){
MediaItemNode item = mediaRepository.createMediaItem(person.getName()+a.getTitle()+" item "+k);
a.addMediaItemInAlbum(item);
ArrayList<String> comments = new ArrayList<>();
//create some comments
for(int i=0;i<nrOfComments;i++){
comments.add( "Comment msg "+i );
}
for(String text:comments){
item.addStatus(text);
}
}
System.out.println("Add item for"+person.getName()+" in album "+a.getTitle());
}
}
}
private void setupFriendsBetweenPeople( int maxNrOfFriendsEach )
{
for ( PersonNode person : personRepository.getAllPersons() )
{
int nrOfFriends = r.nextInt( maxNrOfFriendsEach ) + 1;
for ( int j = 0; j < nrOfFriends; j++ )
{
person.addFriend( getRandomPerson() );
}
}
}
private PersonNode getRandomPerson()
{
return personRepository.getPersonByEmail( "person#"
+ r.nextInt( nrOfPersons ) );
}
private void deleteSocialGraph()
{
try ( Transaction tx = graphDb.beginTx() )
{
for ( PersonNode person : personRepository.getAllPersons() )
{
personRepository.deletePerson( person );
}
}
}
private PersonNode getRandomFriendOf( PersonNode p )
{
ArrayList<PersonNode> friends = new ArrayList<>();
IteratorUtil.addToCollection( p.getFriends().iterator(), friends );
return friends.get( r.nextInt( friends.size() ) );
}
public String getRandomPersonWithFriends()
{
PersonNode p;
try ( Transaction tx = graphDb.beginTx() ){
do
{
p = getRandomPerson();
}
while ( p.getNrOfFriends() == 0 );
return p.getName();
}
}
private void createPersons() throws Exception
{
for ( int i = 0; i < nrOfPersons; i++ )
{
personRepository.createPerson( "person#" + i );
}
}
private void multipleStatusesGenerator() throws Exception
{
ArrayList<String> statuses = new ArrayList<>();
for(int i=0;i<r.nextInt( nrOfPosts );i++){
statuses.add( "Test msg "+i );
}
for(int i=0;i<r.nextInt( nrOfPersons );i++){
PersonNode person = getRandomPerson();
for ( String status : statuses )
{
person.addStatus( status );
}
}
}
////////////// END NETWORK GENERATOR ////////////
///////////////////////// API /////////////////////////
public void addStatus(String name, String text){
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = personRepository.getPersonByEmail(name);
p.addStatus(text);
}
}
public void createFriend(String name1, String name2){
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p1 = this.personRepository.getPersonByEmail(name1);
PersonNode p2 = this.personRepository.getPersonByEmail(name2);
p1.addFriend(p2);
}
}
public String getFriendRecommandation(String name){
String reco = null;
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = this.personRepository.getPersonByEmail(name);
PersonNode recommendation = IteratorUtil.single( p.getFriendRecommendation( 1 ).iterator() );
reco = recommendation.getName();
}
return reco;
}
public ArrayList<String> getFriendsOf(String name){
ArrayList<String> friends = new ArrayList<>();
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = personRepository.getPersonByEmail(name);
for (Iterator iterator = p.getFriends().iterator(); iterator.hasNext();) {
PersonNode person = (PersonNode) iterator.next();
friends.add(person.getName());
}
}
return friends;
}
public ArrayList<String> getAllPersons(){
ArrayList<String> persons = new ArrayList<>();
try ( Transaction tx = graphDb.beginTx() )
{
for (Iterator iterator =personRepository.getAllPersons().iterator(); iterator.hasNext();) {
PersonNode person = (PersonNode) iterator.next();
persons.add(person.getName());
}
}
return persons;
}
public ArrayList<String> retrieveStatusUpdates(String name) throws Exception
{
PersonNode person;
ArrayList<String> updates = new ArrayList<String>();
try ( Transaction tx = graphDb.beginTx() )
{
person = this.personRepository.getPersonByEmail(name);
Iterator<StatusUpdateNode> i = person.friendStatuses();
while(i.hasNext()){
StatusUpdateNode su = i.next();
updates.add(su.getPerson().getName()+":+"+su.getDate().toString()+":"+su.getStatusText());
}
}
return updates;
}
public ArrayList<String> retreivePersonMediaAlbums(String name){
PersonNode person;
ArrayList<String> list = new ArrayList<String>();
try ( Transaction tx = graphDb.beginTx() )
{
person = this.personRepository.getPersonByEmail(name);
Iterator<AlbumNode> i = person.getAlbums().iterator();
while(i.hasNext()){
AlbumNode su = i.next();
list.add(su.getId());
}
}
return list;
}
public ArrayList<String> getMediaItems(String albumId){
ArrayList<String> list = new ArrayList();
try ( Transaction tx = graphDb.beginTx() )
{
AlbumNode album = albumRepository.getAlbumById(albumId);
Iterator<MediaItemNode> i = album.getMediaItems().iterator();
while(i.hasNext())
list.add(i.next().getId());
}
return list;
}
public ArrayList<String> getMediaItemComments(String itemId){
ArrayList<String> list = new ArrayList();
try ( Transaction tx = graphDb.beginTx() )
{
MediaItemNode item = this.mediaRepository.getMediaItemById(itemId);
Iterator<CommentNode> i = item.getComments().iterator();
while(i.hasNext()){
list.add(i.next().getCommentText());
}
}
return list;
}
///////////////Utility methods/////////////////////////////////////
private <T> ArrayList<T> fromIterableToArrayList( Iterator<T> iterable )
{
ArrayList<T> collection = new ArrayList<>();
IteratorUtil.addToCollection( iterable, collection );
return collection;
}
public void displayCollection(ArrayList<String> list){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
}
////////////////////////////////////////////////////
public static void main(String[] args) throws Exception{
SocNet net = new SocNet();
net.setup("d://temp//_socnet4");
System.out.println("Network created!");
//System.out.println("All persons in the net:");
//net.displayCollection(list);
for(int i=0;i<1;i++){
T t = new T(net);
t.start();
}
}
}
class T extends Thread{
SocNet net;
T(SocNet n){net = n;}
public void run(){
long t = System.currentTimeMillis();
String p = net.getRandomPersonWithFriends();
/*ArrayList list = net.getAllPersons();
System.out.println(">>>>Get all persons in "+(t - System.currentTimeMillis()));
t = System.currentTimeMillis();
String reco = net.getFriendRecommandation(p);
System.out.println("Recommandation for person :"+p+" is "+reco);
System.out.println(this.getName()+">>>>Get friend recommandation in "+(t - System.currentTimeMillis()));
t = System.currentTimeMillis();
System.out.println("Friends of :"+reco);
list = net.getFriendsOf(reco);
//net.displayCollection(list);
System.out.println(this.getName()+">>>>Get friends of in"+(t - System.currentTimeMillis()));
*/
t = System.currentTimeMillis();
p = net.getRandomPersonWithFriends();
System.out.println(this.getName()+"Status updates for "+p+" :");
ArrayList<String> sups = null;
try {
sups = net.retrieveStatusUpdates(p);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName()+">>>>Get status updates in "+(t - System.currentTimeMillis()));
//net.displayCollection(sups);
String name = net.getRandomPersonWithFriends();
System.out.println("List of media albums for user "+name);
sups = net.retreivePersonMediaAlbums(name);
net.displayCollection(sups);
//show comments on all media items in each person albums
System.out.println("Show comments on all media items in each person albums.");
for(String aid:sups){
ArrayList<String> items = net.getMediaItems(aid);
System.out.println("Media items of album:"+aid+" are:");
net.displayCollection(items);
for(String itemid:items){
System.out.println("Comments of media item "+itemid+" are:");
net.displayCollection(
net.getMediaItemComments(itemid)
);
}
}
}
}
/**
* Licensed to Neo Technology under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Neo Technology licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.index.Index;
import org.neo4j.helpers.collection.IteratorUtil;
public class SocNet
{
private static final Random r = new Random( System.currentTimeMillis() );
private static final int nrOfPersons = 10;
private static final int nrOffFriends = 3;
private static final int nrOfPosts = 5;
private static final int nrOfAlbums = 5;
private static final int nrOfMediaItems = 4;
private static final int nrOfComments = 3;
private GraphDatabaseService graphDb;
private PersonRepository personRepository;
private AlbumRepository albumRepository;
private MediaItemRepository mediaRepository;
public void setup(String storeDir) throws Exception
{
this.graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir );
try ( Transaction tx = graphDb.beginTx() )
{
Index<Node> index = graphDb.index().forNodes( "nodes" );
personRepository = new PersonRepository( graphDb, index );
Index<Node> indexA = graphDb.index().forNodes( "albums" );
albumRepository = new AlbumRepository(graphDb, indexA);
Index<Node> indexM = graphDb.index().forNodes( "mediaitems" );
mediaRepository = new MediaItemRepository(graphDb, indexM);
createPersons();
setupFriendsBetweenPeople( nrOffFriends );
multipleStatusesGenerator();
tx.success();
}
Transaction tx = graphDb.beginTx();
try{
createAlbums();
tx.success();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
tx.close();
}catch(org.neo4j.graphdb.TransactionFailureException exx){
exx.printStackTrace();
}
}
}
//GRAPH GENERATOR
private void createAlbums() throws Exception{
System.out.println("Create albums");
//iterate all persons
for ( PersonNode person : personRepository.getAllPersons() )
{
int albumsCount = r.nextInt( nrOfAlbums ) + 1;
//add a random number of albums to user
for ( int j = 0; j < albumsCount; j++ )
{
AlbumNode a = albumRepository.createAlbum(person.getName()+" album "+j);
person.addAlbum(a); //add album to peson
//for each album add a number of media items and for each item a number of comments
for ( int k = 0; k < nrOfMediaItems; k++ ){
MediaItemNode item = mediaRepository.createMediaItem(person.getName()+a.getTitle()+" item "+k);
a.addMediaItemInAlbum(item);
ArrayList<String> comments = new ArrayList<>();
//create some comments
for(int i=0;i<nrOfComments;i++){
comments.add( "Comment msg "+i );
}
for(String text:comments){
item.addStatus(text);
}
}
System.out.println("Add item for"+person.getName()+" in album "+a.getTitle());
}
}
}
private void setupFriendsBetweenPeople( int maxNrOfFriendsEach )
{
for ( PersonNode person : personRepository.getAllPersons() )
{
int nrOfFriends = r.nextInt( maxNrOfFriendsEach ) + 1;
for ( int j = 0; j < nrOfFriends; j++ )
{
person.addFriend( getRandomPerson() );
}
}
}
private PersonNode getRandomPerson()
{
return personRepository.getPersonByEmail( "person#"
+ r.nextInt( nrOfPersons ) );
}
private void deleteSocialGraph()
{
try ( Transaction tx = graphDb.beginTx() )
{
for ( PersonNode person : personRepository.getAllPersons() )
{
personRepository.deletePerson( person );
}
}
}
private PersonNode getRandomFriendOf( PersonNode p )
{
ArrayList<PersonNode> friends = new ArrayList<>();
IteratorUtil.addToCollection( p.getFriends().iterator(), friends );
return friends.get( r.nextInt( friends.size() ) );
}
public String getRandomPersonWithFriends()
{
PersonNode p;
try ( Transaction tx = graphDb.beginTx() ){
do
{
p = getRandomPerson();
}
while ( p.getNrOfFriends() == 0 );
return p.getName();
}
}
private void createPersons() throws Exception
{
for ( int i = 0; i < nrOfPersons; i++ )
{
personRepository.createPerson( "person#" + i );
}
}
private void multipleStatusesGenerator() throws Exception
{
ArrayList<String> statuses = new ArrayList<>();
for(int i=0;i<r.nextInt( nrOfPosts );i++){
statuses.add( "Test msg "+i );
}
for(int i=0;i<r.nextInt( nrOfPersons );i++){
PersonNode person = getRandomPerson();
for ( String status : statuses )
{
person.addStatus( status );
}
}
}
////////////// END NETWORK GENERATOR ////////////
///////////////////////// API /////////////////////////
public void addStatus(String name, String text){
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = personRepository.getPersonByEmail(name);
p.addStatus(text);
}
}
public void createFriend(String name1, String name2){
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p1 = this.personRepository.getPersonByEmail(name1);
PersonNode p2 = this.personRepository.getPersonByEmail(name2);
p1.addFriend(p2);
}
}
public String getFriendRecommandation(String name){
String reco = null;
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = this.personRepository.getPersonByEmail(name);
PersonNode recommendation = IteratorUtil.single( p.getFriendRecommendation( 1 ).iterator() );
reco = recommendation.getName();
}
return reco;
}
public ArrayList<String> getFriendsOf(String name){
ArrayList<String> friends = new ArrayList<>();
try ( Transaction tx = graphDb.beginTx() )
{
PersonNode p = personRepository.getPersonByEmail(name);
for (Iterator iterator = p.getFriends().iterator(); iterator.hasNext();) {
PersonNode person = (PersonNode) iterator.next();
friends.add(person.getName());
}
}
return friends;
}
public ArrayList<String> getAllPersons(){
ArrayList<String> persons = new ArrayList<>();
try ( Transaction tx = graphDb.beginTx() )
{
for (Iterator iterator =personRepository.getAllPersons().iterator(); iterator.hasNext();) {
PersonNode person = (PersonNode) iterator.next();
persons.add(person.getName());
}
}
return persons;
}
public ArrayList<String> retrieveStatusUpdates(String name) throws Exception
{
PersonNode person;
ArrayList<String> updates = new ArrayList<String>();
try ( Transaction tx = graphDb.beginTx() )
{
person = this.personRepository.getPersonByEmail(name);
Iterator<StatusUpdateNode> i = person.friendStatuses();
while(i.hasNext()){
StatusUpdateNode su = i.next();
updates.add(su.getPerson().getName()+":+"+su.getDate().toString()+":"+su.getStatusText());
}
}
return updates;
}
public ArrayList<String> retreivePersonMediaAlbums(String name){
PersonNode person;
ArrayList<String> list = new ArrayList<String>();
try ( Transaction tx = graphDb.beginTx() )
{
person = this.personRepository.getPersonByEmail(name);
Iterator<AlbumNode> i = person.getAlbums().iterator();
while(i.hasNext()){
AlbumNode su = i.next();
list.add(su.getId());
}
}
return list;
}
public ArrayList<String> getMediaItems(String albumId){
ArrayList<String> list = new ArrayList();
try ( Transaction tx = graphDb.beginTx() )
{
AlbumNode album = albumRepository.getAlbumById(albumId);
Iterator<MediaItemNode> i = album.getMediaItems().iterator();
while(i.hasNext())
list.add(i.next().getId());
}
return list;
}
public ArrayList<String> getMediaItemComments(String itemId){
ArrayList<String> list = new ArrayList();
try ( Transaction tx = graphDb.beginTx() )
{
MediaItemNode item = this.mediaRepository.getMediaItemById(itemId);
Iterator<CommentNode> i = item.getComments().iterator();
while(i.hasNext()){
list.add(i.next().getCommentText());
}
}
return list;
}
///////////////Utility methods/////////////////////////////////////
private <T> ArrayList<T> fromIterableToArrayList( Iterator<T> iterable )
{
ArrayList<T> collection = new ArrayList<>();
IteratorUtil.addToCollection( iterable, collection );
return collection;
}
public void displayCollection(ArrayList<String> list){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
}
////////////////////////////////////////////////////
public static void main(String[] args) throws Exception{
SocNet net = new SocNet();
net.setup("d://temp//_socnet4");
System.out.println("Network created!");
//System.out.println("All persons in the net:");
//net.displayCollection(list);
for(int i=0;i<1;i++){
T t = new T(net);
t.start();
}
}
}
class T extends Thread{
SocNet net;
T(SocNet n){net = n;}
public void run(){
long t = System.currentTimeMillis();
String p = net.getRandomPersonWithFriends();
/*ArrayList list = net.getAllPersons();
System.out.println(">>>>Get all persons in "+(t - System.currentTimeMillis()));
t = System.currentTimeMillis();
String reco = net.getFriendRecommandation(p);
System.out.println("Recommandation for person :"+p+" is "+reco);
System.out.println(this.getName()+">>>>Get friend recommandation in "+(t - System.currentTimeMillis()));
t = System.currentTimeMillis();
System.out.println("Friends of :"+reco);
list = net.getFriendsOf(reco);
//net.displayCollection(list);
System.out.println(this.getName()+">>>>Get friends of in"+(t - System.currentTimeMillis()));
*/
t = System.currentTimeMillis();
p = net.getRandomPersonWithFriends();
System.out.println(this.getName()+"Status updates for "+p+" :");
ArrayList<String> sups = null;
try {
sups = net.retrieveStatusUpdates(p);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName()+">>>>Get status updates in "+(t - System.currentTimeMillis()));
//net.displayCollection(sups);
String name = net.getRandomPersonWithFriends();
System.out.println("List of media albums for user "+name);
sups = net.retreivePersonMediaAlbums(name);
net.displayCollection(sups);
//show comments on all media items in each person albums
System.out.println("Show comments on all media items in each person albums.");
for(String aid:sups){
ArrayList<String> items = net.getMediaItems(aid);
System.out.println("Media items of album:"+aid+" are:");
net.displayCollection(items);
for(String itemid:items){
System.out.println("Comments of media item "+itemid+" are:");
net.displayCollection(
net.getMediaItemComments(itemid)
);
}
}
}
}