Mostrando postagens com marcador Maven. Mostrar todas as postagens
Mostrando postagens com marcador Maven. Mostrar todas as postagens

domingo, 27 de outubro de 2013

MongoDB + Java Course - In progress

MongoDB Course. Home work
=============================

GitHub on
https://github.com/romalopes/hw2-3

- MongoDB Course
Info:
https://education.mongodb.com/courses
Lenght of course: - 7 weeks
Using Maven
to run the project: mvn compile exec:java -Dexec.mainClass=course.BlogController
to test: mvn test
Using Gradle
   to rum the project: gradle run
   to test: gradle test

To create a project with gradle
- copy the directory Gradle to root

1:              - gradle  

2:                  wrapper
3:                      gradle-wrapper.jar
4:                      gradle-wrapper.properties
5:                  ide.gradle
6:          - copy the btch file to root
7:              gradlew (for X)
8:              gradle.bat ( for windows)
9:          - copy settings.gradle to root
10:              Only this inside: rootProject.name = "NAME PROJECT"


- Week 1
- Suports
Based on Json Documents(key, values). It is a document database
In same document Dynamic Schema.  Different collections of data.
- Scalability and performance VS Funcionality
Doesn't support joins and transactions. Documents are hierarchical
- Running
create a directory %MONGO_HOME%\data\db

1:  %MONGO_HOME%/bin/mongo.config  
2:                  ##store data here  
3:                  dbpath=%MONGO_HOME%\data\db  
4:                  ##all output go here  
5:                  logpath=%MONGO_HOME%\log\mongo.log  
6:                  ##log read and write operations  
7:                  diaglog=3  

- Server:
mongod --dbpath data\db
mongod --config %MONGO_HOME%\bin\mongo.config
As a server
mongod --config %MONGO_HOME%\bin\mongo.config --install
net start MongoDB
net stop MongoDB
mongod --remove (remove the service)
- Command line: mongo

Ex:

1:                      mongo test(connects to mongodb already in test collection)  

2:                      use test (switches to test collection)
3:                      show collections
4:                        (collection) (command)
5:                      db.objects.   save({a:1, b:2, c:3})
6:                      db.objects.   save({a:4, b:5, c:6, d:7, e:['a','b']})
7:                      db.objects.find() <- return all documents
8:                      db.objects.find({a:1}) <- Return all documents that have this element
9:                      db.course.hello.save({'name','maths'})
10:                      db.course.hello.find()


- Json
Types of Data
- Array -> list of items -> [...]
- Dictionaries ->associative maps  {key:value} -> {name:"value",city:"value", interests:[ ___, ___, ___]
- Embeded data into documents
If the embeded data exceed 16Mb, because each document should have the maximum of 16Mb
Home Work:
1 - 42
2- 2,3,5
3-366
4- 2805
- Week 2
- CRUD
Create=Insert.  Read=Find.  Update=Update.  Delete=Remove
Does not have a language such as SQL.

1:  - db.people.insert( doc )  
2:              - db.people.find()  
3:              - db.people.findOne({"name": "Anderson"}, {"name":true,"_id":false})  


- all object has a primary key called (_id)
- BSON - Binary JSON Object
- Query
- $gt, $lt,

1:  db.people.findOne({name:{$gt:    "B", $lt:"D"}})  
2:                  db.people.findOne({name:{$gt:    "B"}, {name:{$lt:"D"}} }) --Will return all docs less than D. Ignore the first statement.  


- exists
- To verify if a field exists
- db.people.findOne({name:{ $exists : true}})  -- return all documents that has the field name.
- regex
- db.people.find({name: { $regex : "^A"}}) -> returns everything that starts with A.
ex:db.users.find( {name: {$regex:"q"}, email: {$exists:true} } )
- or //ends with e
- db.people.find( { $or : [ {name: { $regex : "e$" } } , {age : {$exists: true}]})
- db.scores.find( {$or : [ {score : {$lt: 50}}, {score : {$gt: 90}} ]})
- and
- all - return the documents that have all the specified elements in a array
db.accounts.find( { favorites : { $all, [ "a", "b", "c" ] } } )
- in - return all documents that has on of the objects IN a array
db.accounts.find( { name : { $in, [ "Anderson", "Cida"] } } ) -- returns the docs that have Anderson and Cida
- Queries
db.users.find( {email : {work: "romalopes@yahoo.com.br" } } )
or
db.users.find( {email.work: "romalopes@yahoo.com.br" } )
- Cursor


1:                  db.people.insert( {name: "Anderson", email : {work:"111", home:"222"}});  

2:                  db.people.insert( {name: "Cida", email : {work:"111", home:"222"}});
3:                  - cur = db.people.find(); null; //NULL avoid the return.
4:                  - cur.limit(5); null; get only 5 elements.
5:                  - cur.sort( {name: -1 }); null;
6:                  - cur.sort( {name: -1 }).limit(5); null;
7:                  - while(cur.hasNext()) printjson(cur.next());
8:                  - db.scores.find( { type : "exam" } ).sort( { score : -1 } ).skip(50).limit(20)

- count
db.score.count({type:"exam"})
- db.scores.count( {"type":"essay", score: {$gt: 90 } } )
- Update
- db.people.update( { name: "Anderson"} , {name:"Anderson Lopes", address:"114 Hargrave"})
- Creates, remove and replace all the attributes.
- $set
db.people.update( { name: "Anderson"} , {$set: {age:30}} )
- set only the values we want to change.
db.people.update( { name: "Anderson"} , {$inc: {age:3} } )
- increment 3 in age.
- ex:

1:                          db.arrays.insert( {_id:0, a:[1,2,3,4]});  

2:                          db.arrays.update( {_id:0, {$set : {"a.2" : 5 }});
3:                              change the third element from 3 to 5.
4:                          db.arrays.update( {_id:0, {$push : {a : 6 }});
5:                              add at the end of array
6:                          db.arrays.update( {_id:0, {$pop : {a : 1 }}); //remove the last element
7:                          db.arrays.update( {_id:0, {$pop : {a : -1 }}); //remove the first element
8:                          db.arrays.update( {_id:0, {$pushAll : {a : [6, 7, 8, 9 }});
9:                          db.arrays.update( {_id:0, {$pull : {a : 3} }); //remove the element that the value is 3
10:                          db.arrays.update( {_id:0, {$pullAll : {a : [6, 7, 8, 9 }}); // remove all elements with the values in the second array


- $unset (remove a field from a collection)
db.people.update( { name: "Anderson"} , {$unset: {age:1} } )
- Multi-update
Update multiple documents
db.people.update( {} , {$set :{"title": "Dr" } }, {multi: true} );
db.scores.update ( { score: {$lt:70} }, {$inc: {score:20}}, {multi:true});
- Remove a database

1:                  use DATABASE  

2:                  db.dropDatabase()

- remove

1:                  db.people.remove() //remove everything from the collection.  

2:                  db.people.drop() //faster than remove
3:                  db.people.remove( {name:"Alice"})
4:                  db.people.remove( {name: {$gt: "M" }} )
5:                  db.scores.remove( {score: { $lt: 60 }})
6:              - db.runCommand( {getLastError:1})

return the last result of a command.  It can be a error, a result of a update and so on.
With Java
CRUD


1:                  INSERT DBOBject(interface) . BasicDBObject with is a LinkedHashMap<String, Object>  

2:                   BasicDBObject doc = new BasicDBObject();
3:                      doc.put("userName", "anderson");
4:                      doc.put("birthDate", new Date(2344242));
5:                      doc.put("programmer", true);
6:                      doc.put("age", 8);
7:                      doc.put("languages", Arrays.asList("Java", "C++"));
8:                      doc.put("address", new BasicDBObject("street", "114 Hargrave")
9:                                  .append("town", "Paddington")
10:                                  .append("zipCode", 2021));
11:                      { "_id" : "user1",
12:                        "interests" : [ "basketball", "drumming"]    }
13:                      new BasicDBObject("_id", "user1").append("interests", Arrays.asList("basketball", "drumming"));

FIND


1:                  DB courseDB = client.getDB("course");  

2:                      DBCollection collection = courseDB.getCollection("findCriteriaTest");
3:                      collection.drop();
4:                      for(int i=0; i<10; i++) {
5:                          collection.insert(new BasicDBObject( "x", new Random().nextInt(2)).
6:                                                            append("y", new Random().nextInt(100)));
7:                      }
8:                      System.out.println("\n Find All");
9:                      DBCursor cursor1 = collection.find();
10:                      try {
11:                          while(cursor1.hasNext()) {
12:                              DBObject all = cursor1.next();
13:                              System.out.println(all);
14:                        }
15:                      } finally {
16:                          cursor1.close();
17:                      }
18:                      DBObject query = new BasicDBObject("x", 0)
19:                                                                          //AND in Y
20:                                      .append("y", new BasicDBObject("$gt", 10).append("$lt", 90));
21:      //OR
22:                      QueryBuilder builder = QueryBuilder.start("x").is(0)
23:                              .and("y").greaterThan(10).lessThan(90);
24:                      System.out.println("\n Count");
25:                      long count = collection.count(query); // builder.get()
26:                      System.out.println(count);
27:                      System.out.println("Find One");
28:                      DBObject one = collection.findOne(query); //builder.get()
29:                      System.out.println(one);
30:                      System.out.println("\n Find All");
31:                      DBCursor cursor = collection.find(query); //builder.get()
32:                      try {
33:                          while(cursor.hasNext()) {
34:                              DBObject all = cursor.next();
35:                              System.out.println(all);
36:                          }
37:                      } finally {
38:                          cursor.close();
39:                      }
40:                      for(int i=0; i<10; i++) {
41:                          collection.insert(new BasicDBObject( "_id", i).
42:                append("start",
43:                    new BasicDBObject("x", new Random().nextInt(90) + 10)
44:                          .append("z", new Random().nextInt(90) + 10)
45:                ).append("end",
46:                  new BasicDBObject("x", new Random().nextInt(90) + 10)
47:                      .append("z", new Random().nextInt(90) + 10)
48:                  )
49:                          );
50:                      }
51:                      //QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);
52:                      //DBCursor cursor = collection.find(builder.get(),
53:                      //    new BasicDBObject("start.x", true).append("_id", false).append("end.z", true));
54:                      DBCursor cursor = collection.find()
55:                                  .sort(new BasicDBObject("_id", -1)).skip(5).limit(3);
56:                      DBCursor cursor = collection.find()
57:                                  .sort(new BasicDBObject("start.x", -1).append("end.z",1)).skip(5).limit(3);

UPDATE
REMOVE

1:                                                  //query  
2:                      collection.update(new BasicDBObject("_id", "alice"),  
3:                              new BasicDBObject("age", 35));//update  
4:                      collection.update(new BasicDBObject("_id", "alice"),  
5:                              new BasicDBObject("gender", "Female"));//update  
6:                      //will remove the gender - Female and insert the Title Srs  
7:                      collection.update(new BasicDBObject("_id", "alice"),  
8:                              new BasicDBObject("$set" , new BasicDBObject("Title", "Srs")));//update  
9:                      //To insert, it is needed two last parameters  
10:                      collection.update(new BasicDBObject("_id", "frank"),         //to insert  
11:                              new BasicDBObject("$set" , new BasicDBObject("Title", "Sr")), true, false);//update  
12:                      collection.update(new BasicDBObject(),//every document        //to update  
13:                              new BasicDBObject("$set" , new BasicDBObject("Graduation", "Masters")), false, true);//update  
14:                      //collection.remove(new BasicDBObject());  
15:                      collection.remove(new BasicDBObject("_id", "alice"));  


- About blog
View - ftl - freemarker
controller/model java/spark.

- Home Work -
1 - db.grades.find({score:{$gte:65}}).sort( { score : 1 } ).limit(1)
2 - 124
3 - fhj837hf9376hgf93hf832jf9
- Week 3
- MongoDB Schema Design
Application-Driven Schema
. Features
Rich Documents
Pre join data for fast access
No Joing
No Constraina like MySql
Atomic operations(no transactions)
No Declared Schema

Basics of Maven

- Maven
                Features and goals:
                               - Simplify the build process, sharing JARs, publishing informations in a easy way.
                               - Deploy a system
                               - Manage Documentation, dependencies, releases, distribution, report
                               - Maven works on top of ANT
                                               Ant needs you to write the logic and provide de data
                                               Maven needs you to provide the data and know how to do most things.
                               - Maven has a local repository and well named jars, docs, etc.
                                               Provide a single location for downloads which versions are created automatically
                - POM (Project Object Model)
                              
                - Create a Project
                               Simple way:
                                                - mvn archetype:generate
                                                - There are over 850 archetypes.  Use the 314(
                                                -archetype-quickstart), sugested but maven
                                                - Version of maven-archetype-quickstart: Use the sugested(1.1), number 6.
                                                - groupId: The groupId that will be inside the pom.xml. I use: br.com.romalopes.meven2Test
                                                - artifactId: mavenToGradle.  The project will be created inside this directory.
                                                - Version: Accept the sugested.
                                                - Value for property papckage: The package that will be create inside the structure:br.com.romalopes.meven2Test
                                                - Confirm
                              
                               - A more sofisticated way
                                               - mvn archetype:generate -DgroupId=br.com.romalopes.maven2Test -DartifactId=maven-test -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
                It creates a structure like that:
                - my-app
                               |-- pom.xml
                               -- src
                                               |-- main
                                               |   `-- java.
                                               |       `-- com.
                                               |           `-- mycompany-
                                               |               `-- app
                                               |                   `-- App.java
                                               |-- resources
                                                              -- META-INF
                                                              -- application.properties   -->  InputStream is = getClass().getResourceAsStream( "/test.properties" );
                                               -- test
                                                               -- java
                                                                               -- com
                                                                                              -- mycompany
                                                                                                              -- app
                                                                                                                              -- AppTest.java
                - Phases to buil a project
                               Validate
                               generate-sources
                               process-sources
                               generate-resources
                               process-resources
                               compile
                               mvn package
                               integration-test
                               verify
                               install - install into the local repository
                               deploy - copies the final package to the remote repository
                               - others
                                               clean
                                               test
                                               dependency:copy-dependencies
                                               mvn site - generate a site for project documentation
                                               can call
                                                               mvn clean dependency:copy-dependencies package
                              
                - maven to Eclipse
                               Simple java
                                               mvn eclipse:eclipse
                               Dynamic Web Project
                                               mvn eclipse:eclipse -Dwtpversion=1.5
                                               In Eclipse:
                                                               Properties->Modify Project->Change Facet
                - plugins
                               To customize the build for a Maven Project
                                               
- Example

1:          <project xmlns="http://maven.apache.org/POM/4.0.0"  
2:           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
4:                               http://maven.apache.org/xsd/maven-4.0.0.xsd">  
5:           <modelVersion>4.0.0</modelVersion>  
6:           <groupId>com.mycompany.app</groupId>  
7:           <artifactId>my-app</artifactId>  
8:           <version>1.0-SNAPSHOT</version>  
9:           <packaging>jar</packaging>  
10:           <name>Maven Quick Start Archetype</name>  
11:           <url>http://maven.apache.org</url>  
12:           <dependencies>  
13:              <dependency>  
14:               <groupId>junit</groupId>  
15:               <artifactId>junit</artifactId>  
16:               <version>3.8.1</version>  
17:               <scope>test</scope>  
18:              </dependency>  
19:           </dependencies>  
20:           <build>  
21:              <resources>  
22:               <resource>  
23:                  <directory>src/main/resources</directory>  
24:                  <filtering>true</filtering>  
25:               </resource>  
26:              </resources>  
27:           </build>  
28:           <properties>  
29:              <my.filter.value>hello</my.filter.value>  
30:           </properties>  
31:          </project>