By Vinícius Cavalcanti
Hello there, this post will show how to send an email using javamail api.
First download the api here
Step 1: We need of a Properties to create some properties and get the default Session
Properties properties = new Properties ();
We set the e-mail protocol and the host that will use the Properties that instantiate
String host = "mail.example.com";
props.put("mail.smtp.host", host);
Step 2: With the properties we get set up an instance of Session to send email
Session session = Session.getInstance(props, null);
Note: The second parameter would be an Authenticator to authenticate our mail but
we don’t need to consider because the smtp server does not need authentication to send email
Step 3: Creating our message
Create a MimeMessage that serves as the container for our message
MimeMessage msg = new MimeMessage(session);
We set the sender
msg.setFrom (new InternetAddress("me@mail.com"));
create an array of InternetAddress to be the recipients
InternetAddress [] address = (new InternetAddress (”somebody@mail.com”));
We set the recipients of our message
msg.setRecipients(Message.RecipientType.TO, address);
By setting the subject of our email
msg.setSubject("How to send mail using the JavaMail api");
Step 4: Creating the contents of our email
Creates the first part of the content of the message
MimeBodyPart mbp1 MimeBodyPart = new ();
Msgtext String = "Is very easy to send mail with JavaMail ";
mbp1.setText (msgText1);
Create the second message part is an attachment
MimeBodyPart mbp2 MimeBodyPart = new ();
Attaching a file to create a first message FileDataSource with attachment
FileDataSource fds = new FileDataSource("/home/myHome/file.txt");
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
Step 5: Create a Multipart to join our objects message
Multipart mp = new Multipart create ();
Adding text message email
mp.addBodyPart (mbp1);
Adding e-mail attachment
mp.addBodyPart (mbp2);
Step 6: Sending the message
Add the Multipart to the message container
msg.setContent (mp);
Setting the date in the header
msg.setSentDate (new Date ());
Sending the message
Transport.send (msg);
By Vinícius Cavalcanti
Hi staff, in this post we will show how to feed rss 2.0 using api ROME.
Let’s create a feed using ROME API, so we need some software: JDOM 1.0 and ROME 0.5.
We using the interface SyndFeed ROME API. With it we set the header of our RSS.
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(”rss_2.0″);
feed.setTitle(”Sample Feed (created with ROME)”);
feed.setLink(”http://rome.dev.java.net“);
feed.setDescription(”This feed has been created using ROME (Java syndication utilities”);
Here we instantiate a SyndFeedImpl to be our RSS and set data and the header of the channel.
Each entry will be created and added to the list of entries to our feed. Each entry is set with a title, link, published date and a description. The description for entry can also be text and html code. After each entry is created is added to the list.
List entries = new ArrayList();
SyndEntry entry;
SyndContent description;
entry = new SyndEntryImpl();
entry.setTitle(”My first Item”);
entry.setLink(”http://efforts.embedded.ufcg.edu.br“);
entry.setPublishedDate(DATE_PARSER.parse(”2009-06-25″));
description = new SyndContentImpl();
description.setType(”text/plain”);
description.setValue(”Create Feed”);
entry.setDescription(description);
entries.add(entry);
entry = new SyndEntryImpl();
entry.setTitle(”Web Effort”);
entry.setLink(”http://embedded.ufcg.edu.br/“);
entry.setPublishedDate(DATE_PARSER.parse(”2009-06-25″));
description = new SyndContentImpl();
description.setType(”text/html”);
description.setValue(”<p>Embedded Systems and Pervasive Computing Lab - UFCG</p>”+
“<p>For details check the <a href=\”http://embedded.ufcg.edu.br/“>Click Here</a></p>”);
entry.setDescription(description);
entries.add(entry);
Finally the list with entries is added to the SyndFeed bean.
feed.setEntries(entries);
ROME includes generators that allow producing syndication feed XML documents from SyndFeed instances. The SyndFeedOutput class handles the generation of the syndication feed XML documents on any of the supported feed formats (RSS and Atom). The developer does not need to worry about selecting the right generator for a syndication feed, the SyndFeedOutput will take care of it by looking at the information in the SyndFeed bean. All it takes to write a syndication feed XML document using ROME -assuming you have a SyndFeed bean and a Writer instance- are the following lines of code:
SyndFeed feed = new SyndFeedImpl();
Writer writer = new FileWriter(”myRss”);
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed,writer);
By admin
yuricariry 23.03.09
Using FCKEditor grails plugin
FCKEditor is a HTML text editor that can be used to integrate rich web editing functionality in Grails applications.
Like a Microsoft Office or a BrOffice text editor, this plugin shows a short editor for you format your text.
You can do:
- bold/italic/underline/stroke words;
- insert/edit a image, a Flash file, tables;
- insert special characters;
- insert numered lists;
- change the font format, size, the color of text;
- align text;
1) Instalation
grails install-plugin fckeditor
2) Example
Suppose that you have one class Book, with attribute description, and you want integrate rich web editing functionality in this attribute.
Example:
class Book {
String title
String description
static constraints = {
description (blank:false, maxSize:1000000 )
}
}
In class: Book and view: create
<tr class="prop">
<td valign="top" class="name">
<label for="description">Description:</label>
</td>
<td valign="top" class="value ${hasErrors(bean:bookInstance,field:'description','errors')}">
<fckeditor:editor
name="description"
value="${book?.description}"
width="100%"
height="400"
toolbar="Standard"
fileBrowser="default">
Initial text fck editor
</fckeditor:editor>
</td>
</tr>
where :
| Attribute |
Description |
| name |
Field name (default: “editor”) |
| width |
Width of the editing space (default: “100%”) |
| height |
Height of the editing space (default: “200″) |
| toolbar |
Toolbar to use as defined in fckconfig.js (default: “Default”) |
| fileBrowser |
Name of the file browser to use. Possible values are default or extended. The extended file browser supports deletion and rename of files and folders (default: “default”) |
OBS: If you wanna edit one attribute that exists, then insert this code:
In class: Book and view: edit
<fckeditor:editor
name="description"
value="${book?.description}"
width="100%"
height="400"
toolbar="Standard"
fileBrowser="default">
${book?.description}
</fckeditor:editor>
6) References
. Sites:
- http://www.grails.org/plugin/fckeditor
- http://www.fckeditor.net/
By admin
Using remoteFunction with javascript to insert/update objects in table
This article aims show how select a list of names of one table
and if you need insert a new name in table, you can do.
We use a javascript function to update the database and show the updated database in time of execution.
For this we use :
- grails g:select;
- grails g:remoteFunction;
- javascript ( function onclick() )
Step 1: Domain Classes
We have a class Publication with a relationship one-to-many to class ExternalAuthor (Publication-ExternalAuthors),
and we want show a table ExternalAuthors
This is the domain-class Publication :
class Publication {
String title
int year
String homePage
String meansOfDissemination
String otherInformation
// relationship one-to-many (Publication-ExternalAuthors)
static hasMany = [externalAuthors : ExternalAuthors ]
}
This is the domain-class ExternalAuthors :
class ExternalAuthors {
String name
}
Step 2: Views
In grails-app views -> publication -> create.gsp
we add this code to create a new externalAuthor.
<tr class="prop">
<td valign="top" class="name">
<label for="externalAuthors">External Authors: (select your list)
</label>
</td>
<td valign="top" class="value ${hasErrors(bean:publication,field:'externalAuthors','errors')}">
<form name='myForm'>
<div id="botaoDiv">
<g:render template="/grails-app/views/myExternalAuthorsTemplate" />
</div>
<g:render template="/grails-app/views/myAddExternalAuthorsTemplate" />
</form>
</td>
</tr>
In grails-app views -> _myExternalAuthorsTemplate.gsp (you should create a new template)
we add this code to select a list of externalAuthor.
<g:select id="sel"
multiple="multiple"
size="10"
optionKey="id"
optionValue="name"
name="publication.externalAuthors"
from="${ExternalAuthors.list( sort:'name' )}"
/>
Testing insert a new external author : Test 1 (before addAuthor, obs: asdf already exists)
Step 3: Views with javascript
In grails-app views -> _myAddExternalAuthorsTemplate.gsp (you should create a new template)
we add this code to create a new externalAuthor.
<g:javascript library="prototype" />
Type a name of a new author:: <input name="name" id="name" type="text"></input>
<input name="botao"
value="addAuthor"
type="button"
onclick="${ remoteFunction( controller:'externalAuthors',
action:'saveAList',
update:'botaoDiv',
params:'\'name=\'+document.getElementById(\'name\').value')
}"
/>
Testing: after insert the externalAuthor: Test0
Step 4: Controllers
In grails-app controllers-> ExternalAuthorsController
you should insert saveAList method to create a new external author instantly
and insert in database ( in external_author table)
and after render myExternalAuthorsTemplate for show a list of ExternalAuthor
and you select multiple.
/**
* This method save objects another way to save a new external author.
* the user save any author without link with a publication
* @param id id of userPublication
*/
def saveAList = {
println params
def externalAuthors = new ExternalAuthors(name: params.name )
// only save if not exists in database
if( ExternalAuthors.find(externalAuthors) == null) {
externalAuthors.save()
}
render ( template:"/grails-app/views/myExternalAuthorsTemplate" )
}
Final Step : Test yourself :)!
By ivocalado
This code example shows how to use the ‘feeds’ grails plugin to generate a RSS file and how you can customize the RSS content of this file. You’ll need install the ‘feeds’ plugin in your grails project.
grails install-plugin feeds
First of all, you’ve to import the following packages:
import com.sun.syndication.io.SyndFeedOutput
import feedsplugin.FeedBuilder
//define a 'action' that must generate the RSS file when called from the browser.
def feed = {
//Define a builder of the FeedBuilder type.
def builder = new FeedBuilder()
builder.feed(){
//The content of the 'title' tag of the channel
title = 'title 1'
//The content of the 'description' tag of the channel
description = 'description 1'
//The content of the 'link' tag of the channel
link = 'link 1'
//One or more entries. Each entry is one 'item' tag in the RSS file.
entry(title:'title 1.1',link:'link 1.1'){
content(type:'type 1.1'){
"The content of this item 1.1"
}
}
entry(title:'title 1.2',link:'link 1.2'){
content(type:'type 1.2'){
"The content of this item 1.2"
}
}
}
//Generate the RSS file to the output (browser).
response.contentType = "application/rss+xml"
response.characterEncoding = "UTF-8"
SyndFeedOutput output = new SyndFeedOutput()
output.output(builder.makeFeed("rss","2.0"),response.writer)
}
If you want to generate the items of the RSS file based on external parameters (User parameters or Database data), you can use the following code:
...
description = 'description 1'
//The content of the 'link' tag of the channel
link = 'link 1'
//'yourData' object is a list of elements generate from user parameters or database data.
//Each element of 'yourData' has the following attributes 'yourTitle','yourLink',
// 'yourType' and 'yourContent'
yourData.each(){ item ->
entry(title:item.yourTitle,link:item.yourLink){
content(type:item.yourType){
item.yourContent
}
}
}
//Generate the RSS file to the output (browser).
response.contentType = "application/rss+xml"
...
This example works fine with grails 1.0.3
This post was created by our contributer Marcos Fábio
By Vinícius Cavalcanti
In this post I will show how to create a Web Service using grails and the plugin Metro
– First step: create a simple grails application, for this, grails MUST be installed on your PC.
create an application using the command
grails crate-app WebService
Note: That step is created a grails project that can be easily imported into eclipse as a java project.
– Second Step: Download the plugin Metro for its application and install it using the following command in the directory project
grails install-plugin grails-metro-1.0.2.zip
Download the plugin links below:
Version Changes
1.0.2 Download Included patch from Alex Peters - fixes issue with web services in packages.
– Third step: Generate groovy service, as in previous steps, type the command
grails create-service Test
With that already we have our class Web Service, which can find it in the directory grails-app/services/TestService.groovy
– Fourth step: Implement the class of Web Service
Note: should be add annotations in service groovy class with @WebService, @WebMethod.The resulting class should look like below.
import javax.jws.*
@WebService(targetNamespace="http://com.test")
class TestService {
@WebMethod
def String concat(String str1, String str2) {
return str1 + str2;
}
@WebMethod
def boolean isOdd(int i) {
return (i%2==0)? false: true;
}
}
– Run your application, using
grails run-app
– Test if your service is deployed, by pointing your browser to:
http://localhost:8080/WebService/services/TestService
WEB SERVICES
| ENDPOINT |
|
| Service Name: |
{http://com.test} TestServiceService |
| Port Name: |
| {http://com.test} TestServicePort |
|
| INFORMATION |
|
| Address: |
http://localhost:8080/WebService/services/TestService |
| WSDL: |
http://localhost:8080/WebService/services/TestServicePwsd |
| Implementation classe: |
TestService |
By admin
Introduction
This article aims to show how uses your own templates and also how use <g:render template.
In this article you will learn how create a new template to make a choice in a list of options and how access using grails tags.
First step: create a file .gsp in the package grails-app;
Example 1) the name file is: _myCountriesTemplate.gsp ( obs: rename with “_” before the name is standard )
- The name of attribute in the domain class is “country”
<!–
this template show a list of countries
–>
<select name=”country” style=”width:px;”>
<option value=”United States”>United States</option>
<option value=”Brazil”>Brazil</option>
<option value=”null” >——————-</option>
<option value=”Spain”>Spain</option>
<option value=”Switzerland”>Switzerland</option>
</select>
- Example 2) the name file is: _myLanguagesTemplate.gsp
- The name of attribute in the domain class is “language“
<!–
this template show a list of languages
–>
<select name=”language” style=”width:px;”>
<option value=”English”>English </option>
<option value=”Spanish”>Spanish</option>
<option value=”Portuguese”>Portuguese</option>
<option value=”null” >——————-</option>
</select>
Second step: use the tag g:render in some create view.
- Second the grails.org documentation, the render tag is used to:
“Applies an inbuilt or user defined Groovy template against a model
so that templates can be re-used for lists or instance or a single instance. ”
- Example of create.gsp class;
<tr class=”prop”>
<td valign=”top” class=”name”>
<label for=”language”>Language:</label>
</td>
<td valign=”top” class=”value ${hasErrors(bean:article,field:’language’,'errors’)}”>
<g:render template=”/grails-app/views/myLanguagesTemplate” />
</td>
</tr>
<tr class=”prop”>
<td valign=”top” class=”name”>
<label for=”country”>Country:</label>
</td>
<td valign=”top” class=”value ${hasErrors(bean:article,field:’country’,'errors’)}”>
<g:render template=”/grails-app/views/myCountriesTemplate” />
</tr>
After:
- will be show to you something like this, to you choose a country.
- and will be show to you something like this, to you choose a country.
By admin
Introduction
This article aims to show how uses grails with MySql database
and show the types of enviroments (development, test, prodution) in grails.
In this article you will learn how configure your application to use the database.
First Step:
- You should install the DBMS Mysql. You can get it in: http://dev.mysql.com/downloads/mysql/5.0.html#downloads
- Create the username and the password. (ex: username= “root”, password=”admin”)
- Create a database for your application. (ex: create database publicationsTest )
Second step:
- You should import a JDBC driver for MySQL. You can get it in http://dev.mysql.com/downloads/connector/j/5.1.html
- Put the file mysql-connector-java-5.1.6-bin.jar, in the package lib.
- Go to buid path and add the external jar mysql-connector-java-5.1.6-bin.jar.
After:
- You should config your application class;
- Go to package: grails-app/conf;
- Go to class: DataSource.groovy;
- and after alter the class, ( in this case the mysql was installed with: username = “root” and password = “admin” )
development{
dataSource {
driverClassName = "com.mysql.jdbc.Driver"
dbCreate = "create-drop" // "create"
// or "update" (after you run with create-drop )
username = "root"
password = "admin"
url = "jdbc:mysql://localhost/publicationsTest"
// publicationsTest is the name of database
}
}
obs: - In the first run you should create the tables, use dbCreate = “create-drop” ,
- After you should change to dbCreate = “update”. ( to keep the informations inserted before ), and run the application.
obs: Enviroments in grails (source: the definite guide to grails)
In grails DataSource.groovy, there are 3 types of enviroments;
- development
- test
- production
1) Development
- Is used for the developments and enables him to configure applications to work with a locally installed database;
- auto-reloading is enabled;
- Is started with the command: grails run-app
2) Test
- Is used for test developments to test the work produced by developers in other machine;
- obs: also saves the data in the database;
- Is started with the command: grails test run-app
3) Production
- Is used for the developments when the system is released;
- auto-reloading is disabled to increase performance and minimize any potential security risk;
- Is started with the command: grails prod run-app
Example:
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop','update'
url = "jdbc:hsqldb:mem:devDB"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:file:prodDb;shutdown=true"
}
}
By admin
Using Grails Object Relational Mapping (GORM)
GORM is the Object Relational Mapping (ORM) implementation in Grails, implicitly Grails uses Hibernate, it is used to map the domain classes as tables in database, including their relationships.
Relationships define how domain classes interact with each other.
There are five types of relationships:
- one-to-one
- one-to-many
- many-to-many
- composition
- inheritance
A one-to-one relationship exists when one record in table A references exactly one record in table B, and vice versa.
Example 1 (unidirectional one-to-one relationship):
class Publication {
User user // unidirectional relationship one-to-one
String title
int year
String homePage
}
class User{
String login
String password
}
Example 2 ( bidirectional one-to-one relationship):
obs: in this case no updates are cascading from either side of the relationship.
class Publication {
User user // bidirectional relationship one-to-one
String title
int year
String homePage
}
class User{
Publication publication // bidirectional relationship one-to-one
String login
String password
}
Example 3 (bidirectional one-to-one relationship, with belongsTo)
obs: It means that Publication “belongs to” User.
The result of this is that we can create a User and save it and the database updates/inserts will be cascaded down to Publication.
And if you delete a User instance, the Publication will be deleted too.
// Weaker side
class Publication {
String title
int year
String homePage
// bidirectional relationship one-to-one.
// We can refer at least one relation
static belongsTo = [ user:User ]
}
// Stronger side
class User{
Publication publication // bidirectional relationship one-to-one
String login
String password
}
A one-to-many relationship in defined when one class, for instance User, has many instances of a another class, example Publication.
A one-to-many relationship exists when a record in table A can reference many records in table B, but those records in table B can only reference one record in table A.
Example 1)
// one side
class User {
String login
String password
// relationship one-to-many (User-Publication)
static hasMany = [ publications: Publication ]
}
// many side
class Publication {
String title
int year
String homePage
User user
// relationship one-to-many (User-Publication)
static belongsTo = User
}
obs: Use of mappedBy: the mappedBy is used when you have two properties of the same type on the many side. It is used to specify which the collection is mapped.
Example 2)
// one side
class User {
String login
String password
// relationship one-to-many (User-Publication)
static hasMany = [ publications: Publication ]
static mappedBy = [ publications:"user"]
}
// many side
class Publication {
String title
int year
String homePage
// relationship one-to-many (User-Publication)
User root
User user
}
In a many-to-many relationship, a record in table A can reference multiple records in table B, and conversely.
A many-to-many relationship is used when the two class, example User and Publication,
has many instances of a another class.
The relationship many-to-many has the hasMany on both sides of relationship
and with one belongsTo in one side of relationship.
obs:Its recommended that the belongsTo stay in the weaker side,
because when the weaker class instance is deleted, the stronger side( or owning side) is not removed.
The owner side (stronger side) takes responsibility for persisting the relationship
and is the only side that can execute cascade saves.
Example 1)
// stronger side
class User {
String login
String password
// relationship many-to-many (User-Publication)
static hasMany = [ publications: Publication ]
static mappedBy = [publications : "users"]
}
// weaker side
class Publication {
String title
int year
String homePage
// relationship many-to-many (User-Publication)
static hasMany = [users : User]
static belongsTo = User
}
obs: Cascade Saves is when we have one class what will be save when the owning side was be save.
This happens because only one side of a many-to-many can take responsibility for managing the relationship.
Example 2) ( the owning side is User, so the cascade saves will be OK,
if we had the weaker side Publication call the add to User, will not save the class User (stronger side) )
new User(login:“Pink Floyd “)
.addToPublication(new Publication(title:“Time”))
.addToPublication(new Publication(title:“Money”))
.save()
A composition in grails is used when we want use some classes in the same table.
Or be, one class is composed of another class, and the both classes will be saved in the same table in database.
Example 1)
class User{
Job homeJob
Job workJob
// composition
static embedded = ['homeJob', 'workJob']
}
class Job {
String task
String time
}
Inheritance is used in Grails when we want reuse the code of another class,
since what the class uses many properties of another class.
obs: Grails supports inheritance both from abstract and concrete classes.
Example 1)
class Publication {
String title
int year
String homePage
String meansOfDissemination
boolean moreRelavance
String translates
String otherInformation
def externalAuthors =[] // is a array list
// relationship one-to-many (Project-Publication)
Project project
// relationship one-to-many (Project-Publication)
// relationship many-to-many (User-Publication)
static hasMany = [ users : User ]
static belongsTo = [ Project , User ]
}
class Article extends Publication {
String DOI
String language
String ISSN
String titleOfMagazinePublished
int volume
int initialPage
int finalPage
}
obs:By default, it keeps only one table for your entire hierarchy.
So instead of having a Article and an Publication table, it has only a Publication table with all the data in it for all the classes.
If you have complex inheritance with lots of properties in the child domains, you can create many tables.
obs: to create tables for each sub-class ( insert this in the super classe)
static mapping ={
tablePerHierarchy false
}
When set to true, this tells GORM to create a different table for each object in the
class, so you’ll have separate Article and Publication tables.
Conclusion
This article describes of a simple and direct way how to implement relationships
between domain classes using the grails language, but if you want learn more,
you should try to run these examples and make changes to test different behaviors
and also that you use this sample only as a simple reference of GORM.
I advise you to look for other sources, as a way of through other examples and different points of view
You can learn more.
References
Sites:
Books:
- beginning-groovy-and-grails-from-novice-to-professional
- Groovy in action
By admin
Welcome to Web Effort’s blog. In this place, we will show the applications which we’re developping.
The team aims the study of many techonologies and the implementation of small applications. Currently, we’re focusing the Groovy on Grails technology.