All posts by admin

Effective Use of Technology in Legal Process

 RESEARCHING FOR YOUR CASE – A CURSE OR BOON?

Being into legal domain, I’m sure research is the backbone for building a strong case. Research is one of the most vital and time-consuming activities in a lawyer’s workload. While your industry has innovated by improving search efficiency, the effectiveness of search largely relies on the research expertise of lawyers, paralegals and law librarians.

The vast growth of available data adds additional challenges to the task of identifying the most critical and relevant information to a case. You might be dependent on the duopoly of Lexis.com and WestLaw to provide vast information databases, combined with your internal expertise and experience in searching, to uncover relevant results.

It is worth mentioning that these giants are capable for relevant data but it’s true sometimes you may not require the features for which you are paying for or may become tedious to explore them or you may need some custom features which are not in these products!

You may be using “pay-per-search” or flat-rate subscription model, which maybe forcing you to be judicious in your use of search. You may often negotiate flat-rate subscriptions to large comprehensive databases.

START QUESTIONING NOW…

Have you ever thought of finding efficiency while not sacrificing accuracy and comprehensiveness? As such, any ability that you have to quickly obtain the most accurate and complete set of results is likely to help you meet this efficiency goal and client needs.

Now question arises – What alternatives do you that will give accuracy and efficient results?

AND THE SOLUTION IS….

Here it is –You can build a search engine solutions that will help your business better organize, access, and search your digital content and the complete system will become handy.

So next time when you research on

  • State Law
  • Federal Law
  • Analytical Materials
  • Public Records
  • News and Periodicals
  • Patent
  • Cases/sues

Have your own enterprise search solutions and access your data of federal and state court decisions, statutes, regulations, court rules, topical databases, legal newspapers and periodicals, as well as law and related information from common law countries very easily and handy and making your research part as a boon!

TECHNOLOGY TO LOOK UPON…

There are number of technologies such as Lucene, Solr, dtSearch, elasticsearch, Nutch, Hibernate Search and Hadoop which can be used for search based solutions.

Look into technologies like Apache Solr – an HTTP search server built on top of Lucene.  Specifically Solr gives you REST-like HTTP/XML and JSON APIs.

What Solr gives you is the following:

  • Full-text search
  • Highlighting of hits
  • Faceted search
  • Dynamic clustering
  • Database integration
  • Rich document handling of formats like Word and PDF

LEGAL AND SOLR GO HAND IN HAND

 Now coming to your Legal domain, then here is how Solr can be useful:

  • E-discovery and forensics search: Server packaging for Lucene provides a wide range of enterprise search functions and a convenient RESTful/xml interface for e-discovery and forensics based search solutions.
  • Trademark search: We can use Solr for Trademark search. Solr is a highly tunable search engine and can be customized to search for trademarks with high precision and relevance. Trademarks can be searched using different algorithms – exact, slop match, fuzzy match, phonetic, synonym, starts with, contains, ends with, sounds-like, etc – and ranked in the decreasing order of relevance.
  • Patent Search: Patent can be filtered or faceted based on their categories, goods and services and other parameters as required. The results can also be sorted in the order as per requirement with some configurations and customizations.
  • Cases/sues Search: Solr offers lightning-fast response times for queries. If you are searching for your earlier cases or law orders, solr can be tuned to return results with high precision

And many more as per your field and practice.

ARE YOU DOUBTING ON SOLR? THEN WAIT

Are there companies using Solr today?  To be convinced that Solr is actually used in a lot of enterprise projects, take a look at this amazing list of public projects powered by Solr

Whom to look upon to build a custom search solution

ProsperaSoft offers Full text search. ProsperaSoft can help you with building a search solution at a very minimal and affordable budget. ProsperaSoft provides enterprise search solutions, data ingestion, and classification and taxonomy solutions for clients across a wide range of sectors including legal services, news, digital publishing, media monitoring, e-commerce, recruitment to customers by leveraging open-source and proprietary search solutions such as Lucene, Solr, dtSearch, elasticsearch, Nutch, Hibernate Search and Hadoop.

With years of experience in the field and quest for delivering quality enterprise search solutions that meet our customers exact requirements, we can provide reliable, accurate, fast and economical search solutions.

WANT TO KNOW MORE?

Just get in touch with us and we can discuss how ProsperaSoft can contribute to your research

 

 

 

 

 

 

 

 

 

How to Configure Amazon Cloud Front with Grails Web Application

 How do you setup Amazon’s CloudFront?

The S3 just provides a way to put content on Amazon’s system, so that it can then be distributed to CloudFront.

Once you’ve signed up with S3, you create a “bucket”, which is a storage vessel: a way of organizing your content. I created a single bucket for my single site, but you may need to create more than one. Into this bucket you’d put any content that needs to be stored. Following are the steps to follow:

  1.  Login in to Amazon Cloud Front

https://console.aws.amazon.com/cloudfront/home

2.  Create a bucket.

Go to Service-> Select S3 , Create Bucket option is there.

3.  Create distribution.

Go to service -> Select Cloud front,  Create Distribution option is there

4.  After click on Create Distribution button. Select Delivery method  Web

5.  After selection of Web

Origin Setting has Origin domain name field.

In that created bucket option will show. Choose it.

6. Distribution Settings area has

Price Class Field (Choose the region)

7.  And Click on Create Distribution button on bottom.

8.  And Cloud Front Distribution Screen will appear , The Distribution is going to deploy it takes at least 15 minutes. Check the Status is in progress and state is enabled. Once the Status is deployed we can use it.

9.  To use this created resources we need to make bucket public just right click on bucket and make it public.

To Configure Amazon Cloud Front with Grails we need to configure some settings in Config.groovy.

Just put the below lines as per requirement either in dev mode or prod mode.

//Amazon Cloud Front Setting

grails.resources.mappers.baseurl.enabled = true

grails.resources.mappers.baseurl.default=

http://aersdeghyi.cloudfront.net // put here domain name.

grails.resources.mappers.bundle.excludes = ['**/*']

grails.resources.uri.prefix = “”

grails.resources.adhoc.patterns =

['/images/*', '/css/*', '/js/*', '/plugins/*']

To test it just hit the image request.

<img class=“imgSize” src=“http://amazoncloudfrontbucket.s3-us-west-2.amazonaws.com/resources/pump.jpg”/>

Reference links:

  • Upload our content to Amazon S3 and grant permission.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/GettingStarted.html

  • To automate upload and download. We need to Install bucket explorer.

http://www.bucketexplorer.com/

  • Serving Compressed or Uncompressed File doc.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

Configuration Of Quartz Scheduler with Database in Grails

 

In my steps below, I’m using Grails 2.2.0 and Quartz 2.1.1. I’m also connecting to a local mysql database.

1. Add the “quartz-all-2.1.1.jar” and “c3p0-0.9.1.1.jar” (in the lib folder of your Quartz download) to your lib directory.

2. Add your Quartz.properties file to your “conf” directory (or somewhere else on your classpath). Here’s the Quartz.properties file I used (you’ll need to change the username and password)

#============================================================================

# Configure Main Scheduler Properties

#============================================================================

quartz.scheduler.instanceName = MyClusteredScheduler

quartz.scheduler.instanceId = AUTO

#============================================================================

# Configure ThreadPool

#============================================================================

quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool

quartz.threadPool.threadCount = 25

quartz.threadPool.threadPriority = 5

#============================================================================

# Configure JobStore

#============================================================================

quartz.jobStore.misfireThreshold = 60000

quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX

quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate

quartz.jobStore.useProperties = false

quartz.jobStore.dataSource = myDS

quartz.jobStore.tablePrefix = QRTZ_

quartz.jobStore.isClustered = true

quartz.jobStore.clusterCheckinInterval = 20000

#============================================================================

# Configure Datasources

#============================================================================

quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver

quartz.dataSource.myDS.URL = jdbc:mysql://localhost/schedulerproject?useUnicode=yes&characterEncoding=UTF-8

quartz.dataSource.myDS.user = root

quartz.dataSource.myDS.password = root

quartz.dataSource.myDS.maxConnections = 5

quartz.dataSource.myDS.validationQuery=select 0 from dual.

3. In your Config.groovy file, add or modify your “grails.config.locations” property. Here’s what I added

grails.config.locations = [

"classpath:conf/Quartz.properties"

]

4. I added the JobScheduler.java and HelloJob.java classes to my src/java directory. These could be groovy or whatever, but I just stole the example from Quartz to get it working correctly.

JobScheduler.java

package sample.quartz.scheduler;

import static org.quartz.JobBuilder.newJob;

import static org.quartz.TriggerBuilder.newTrigger;

import static org.quartz.CronScheduleBuilder.*;

import org.apache.log4j.Logger;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SchedulerException;

import org.quartz.Trigger;

import org.quartz.impl.StdSchedulerFactory;

 

public class JobScheduler {

private static Logger log = Logger.getLogger(JobScheduler.class);

private static JobScheduler JOB_SCHEDULER = new JobScheduler();

private Scheduler scheduler = null;

public JobScheduler() {

}

public static JobScheduler getInstance() {

return JOB_SCHEDULER;

}

public void startup() {

try {

// and start it off

scheduler = StdSchedulerFactory.getDefaultScheduler();

System.out.println(“NAME: ” + cheduler.getSchedulerName());

scheduler.start();

// define the job and tie it to our HelloJob class

JobDetail job = newJob(HelloJob.class)

.withIdentity(“job1″, “group1″)

.build();

// Trigger a job that repeats every 20 seconds

Trigger trigger = newTrigger()

.withIdentity(“trigger1″, “group1″)

.withSchedule(cronSchedule(“0/20 * * * * ?”))

.build();

System.out.println(“Starting Jobs”);

// Tell quartz to schedule the job using our trigger

scheduler.scheduleJob(job, trigger);

scheduler.start();

} catch (SchedulerException se) {

se.printStackTrace();

}

}

public void shutdown() {

try {

scheduler.shutdown();

} catch (SchedulerException se) {

se.printStackTrace();

}

}

}

5. I added the JobScheduler and HelloJob java classes to my src/java directory.

HelloJob.java

package sample.quartz.scheduler;

import java.util.Date;

import org.apache.log4j.Logger;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

 

public class HelloJob implements Job {

private static Logger log = Logger.getLogger(HelloJob.class);

public HelloJob() {

}

public void execute(JobExecutionContext context)

throws JobExecutionException {

System.out.println(“Hello!  HelloJob is executing. ” + new Date());

}

}

6. In your BootStrap.groovy file, add…

import sample.quartz.scheduler.JobScheduler

class BootStrap {

def init = { servletContext ->

JobScheduler.getInstance().startup()

}

def destroy = {

JobScheduler.getInstance().shutdown()

}

}

7. Create database. Here, my database name is schedulerproject.

and create table like as given below .

DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;

DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;

DROP TABLE IF EXISTS QRTZ_LOCKS;

DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;

DROP TABLE IF EXISTS QRTZ_CALENDARS;

CREATE TABLE QRTZ_JOB_DETAILS

(

SCHED_NAME VARCHAR(120) NOT NULL,

JOB_NAME  VARCHAR(200) NOT NULL,

JOB_GROUP VARCHAR(200) NOT NULL,

DESCRIPTION VARCHAR(250) NULL,

JOB_CLASS_NAME   VARCHAR(250) NOT NULL,

IS_DURABLE VARCHAR(1) NOT NULL,

IS_NONCONCURRENT VARCHAR(1) NOT NULL,

IS_UPDATE_DATA VARCHAR(1) NOT NULL,

REQUESTS_RECOVERY VARCHAR(1) NOT NULL,

JOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)

);

 

CREATE TABLE QRTZ_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

JOB_NAME  VARCHAR(200) NOT NULL,

JOB_GROUP VARCHAR(200) NOT NULL,

DESCRIPTION VARCHAR(250) NULL,

NEXT_FIRE_TIME BIGINT(13) NULL,

PREV_FIRE_TIME BIGINT(13) NULL,

PRIORITY INTEGER NULL,

TRIGGER_STATE VARCHAR(16) NOT NULL,

TRIGGER_TYPE VARCHAR(8) NOT NULL,

START_TIME BIGINT(13) NOT NULL,

END_TIME BIGINT(13) NULL,

CALENDAR_NAME VARCHAR(200) NULL,

MISFIRE_INSTR SMALLINT(2) NULL,

JOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)

REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)

);

 

CREATE TABLE QRTZ_SIMPLE_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

REPEAT_COUNT BIGINT(7) NOT NULL,

REPEAT_INTERVAL BIGINT(12) NOT NULL,

TIMES_TRIGGERED BIGINT(10) NOT NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_CRON_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

CRON_EXPRESSION VARCHAR(200) NOT NULL,

TIME_ZONE_ID VARCHAR(80),

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_SIMPROP_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

STR_PROP_1 VARCHAR(512) NULL,

STR_PROP_2 VARCHAR(512) NULL,

STR_PROP_3 VARCHAR(512) NULL,

INT_PROP_1 INT NULL,

INT_PROP_2 INT NULL,

LONG_PROP_1 BIGINT NULL,

LONG_PROP_2 BIGINT NULL,

DEC_PROP_1 NUMERIC(13,4) NULL,

DEC_PROP_2 NUMERIC(13,4) NULL,

BOOL_PROP_1 VARCHAR(1) NULL,

BOOL_PROP_2 VARCHAR(1) NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_BLOB_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

BLOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_CALENDARS

(

SCHED_NAME VARCHAR(120) NOT NULL,

CALENDAR_NAME  VARCHAR(200) NOT NULL,

CALENDAR BLOB NOT NULL,

PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)

);

CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_GROUP  VARCHAR(200) NOT NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_FIRED_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

ENTRY_ID VARCHAR(95) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

INSTANCE_NAME VARCHAR(200) NOT NULL,

FIRED_TIME BIGINT(13) NOT NULL,

PRIORITY INTEGER NOT NULL,

STATE VARCHAR(16) NOT NULL,

JOB_NAME VARCHAR(200) NULL,

JOB_GROUP VARCHAR(200) NULL,

IS_NONCONCURRENT VARCHAR(1) NULL,

REQUESTS_RECOVERY VARCHAR(1) NULL,

PRIMARY KEY (SCHED_NAME,ENTRY_ID)

);

CREATE TABLE QRTZ_SCHEDULER_STATE

(

SCHED_NAME VARCHAR(120) NOT NULL,

INSTANCE_NAME VARCHAR(200) NOT NULL,

LAST_CHECKIN_TIME BIGINT(13) NOT NULL,

CHECKIN_INTERVAL BIGINT(13) NOT NULL,

PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)

);

CREATE TABLE QRTZ_LOCKS

(

SCHED_NAME VARCHAR(120) NOT NULL,

LOCK_NAME  VARCHAR(40) NOT NULL,

PRIMARY KEY (SCHED_NAME,LOCK_NAME)

);

commit;

8. Finally  run on different port or server.

grails –Dserver.port=8080 run-app

and

grails –Dserver.port=8090 run-app

clean when we get proxy related classCastException.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to get Connected With LinkedIn in Grails ??

Following are the steps to get connected to linkedIn in grails:

1. First of all install oauth plugin ,

Plugins{

 runtime “:oauth:2.1.0″

}

alternatively install it by grails install-plugin oauth

2. In Config.groovy file, add following

oauth {
providers {
linkedin {
api = org.scribe.builder.api.LinkedInApi
key = ‘xxx’
secret = ‘yyy’

callback = “http://localhost:8080/test2/oauth/linkedin/callback”
successUri = “http://localhost:8080/test2/oauthCallBack/linkedin”

failureUri = “http://localhost:8080/test2/oauthCallBack/linkedinFailure”

requestTokenUrl = “https://api.linkedin.com/uas/oauth/requestToken”
accessTokenUrl = “https://api.linkedin.com/uas/oauth/accessToken”
authUrl = “https://api.linkedin.com/uas/oauth/authorize”
}
}
}

grails.linkedin.api.url = “http://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,date-of-birth)?format=json”

3. In your GSP file add this ,

 

<oauth:connect provider=”linkedin”>Connect</oauth:connect>

4. Add handler for response, i.e. edit  OauthCallBackController  as following:

def linkedin() {
Token linkedinAccessToken = (Token)          session[oauthService.findSessionKeyForAccessToken('linkedin')]
def linkedInResponse = oauthService.getLinkedInResource(linkedinAccessToken, grailsApplication.config.grails.linkedin.api.url)
def linkedinParsedResponse = JSON.parse(linkedInResponse?.getBody())

User user = User.findByLinkedInId(linkedinParsedResponse['id'])
if (user) {
springSecurityService.reauthenticate(user.username)
} else {

}
}

def linkedinFailure() {
render “I am back..,.”
}


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to always set “www” in grailsUrl?

 

To always set “www” in grailsUrl, we have to create filter. Following is the example :

class HostFilters {

def filters = {
all(controller:’*’, action:’*’) {
before = {
if(request.getHeader(“host”) ==”changeme.com” ){

redirect(url: “http://www.changeme.com”)

}
}

}
}


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to transform Grails Java/Groovy objects to JSON/XML?

There are 4 classes that can be used as Converters:

  • for JSON Conversion
    • grails.converters.JSON
    • grails.converters.deep.JSON
  • for XML Conversion
    • grails.converters.XML
    • grails.converters.deep.XML

1. Initializing Converter

To create a converter instance you can choose any one from  the following notations:

default initialization

def converter = new JSON(target: Book.list());

the “as” operator

def converter = Book.list() as JSON

2. Using Converter  instance

  •      In order to get String representation of JSON/XML result , you can use toString()  on converter’s instance as shown below:

def converter = User.get(1) as JSON;
println converter.toString();

  •   In order to render result to a java.io.Writer, you can use render() as shown below:

def converter = User.list() as XML

converter.render(new java.io.FileWriter(“/path/to/my/file.xml”));

  • In order to render result to a HttpServletResponse, you can use render() as shown below:

import grails.converters.*;
class AjaxController {

def list1 = {
def converter = User.list() as JSON
        converter.render(response)

       return false

}

def list2 = {
render User.list() as JSON
}

  def xmllist = {
         render User.list as XML
   }

}

3. Codecs

The Converters plugin also provides codecsto quickly convert arbitary objects to JSON/XML without the need to import a Converter class.

  • encodeAsJSON

String result = someObject.encodeAsJSON();

  • encodeAsXML

String result = someObject.encodeAsXML();

4. Reverse Conversion

Both Converters have 3 different static parse methods.

  •      parse(String)

     import grails.converters.*
     import org.codehaus.groovy.grails.web.json.*;

// package containing JSONObject, JSONArray,…

    def o = JSON.parse(“{ foo: ‘bar’ }”); // Parse a JSON String
    assert o instanceof JSONObject

// In this case, JSON.parse returns a JSONObject instance
    assert o instanceof Map // which implements the Map interface
assert o.foo == ‘bar’ // access a property

// Parse another JSON String containing a Javascript Array
def a = JSON.parse(“[ 1, 2, 3]“)
assert a instanceof JSONArray
assert a instanceof List
assert a[0] == 1

// The following works in Grails >= 1.0.5
def rootNode = XML.parse “””<foo><bar ding=”dong”></foo>”””

// Same as Groovy’s XmlSlurper.parseText(String)
assert rootNode instanceof groovy.util.slurpersupport.GPathResult
assert rootNode.bar.@ding == ‘dong’

  • parse(InputStream, String)

Both Converters feature a static method for parsing the content from an java.io.InputStream. The second parameter of this method is the character encoding to use.
import grails.converters.*
def json = JSON.parse(new FileInputStream(“/path/to/file.json”), “UTF-8″)
def xml = XML.parse(new FileInputStream(“/path/to/file.xml”), “UTF-8″)

  • parse(HttpServletRequest)

A convenience method which checks the Request Content-Type, tries to detect the character encoding of the request and then parses the Request Body using the request’s inputStream.

request.XML and request.JSON

When you access request.XML or request.JSON the appropriate Converters’ parse method is automatically invoked which then checks the Content-Type header of the Request and in the case of a match parses the Request Body
import grails.converters.*
class SomeController {
// We assume the client requests this action using the request Content-Type
// “application/json” and { foo: ‘bar’ } as Request Body
def postJson = {
def json = request.JSON
assert json.foo == ‘bar’
}
// We assume the client requests this action using the request Content-Type
// “text/xml” and <foo><bar ding=”dong”></foo> as Request Body
def postXml = {
def xml = request.XML
assert xml.bar.@ding == ‘dong’
}
}

5. Configuration:

Example of Configuration in Config.groovy file:

grails.converters {
encoding = “ISO-8859-1″
json.date = “javascript”
default.pretty.print = true
}

6. Customizing Converters Results

You can customize which properties of class should be included in JSON representation by registering a specific Object Marshaller(grails.converters.JSON.registerObjectMarshaller) :

// a class to output in JSON
class User {
      String login
      String passwd

// JSON definition of the User object

static {
      grails.converters.JSON.registerObjectMarshaller(User) {
// you can filter here the key-value pairs to output:
          return it.properties.findAll {k,v -> k != ‘passwd’}
      }

   }

// a controller action

def myAction() {
         def a = new User(login:’bob’, passwd:’1234′)
        def list = [a, a]
        render list as JSON
    }


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to generate customize auto generated ids in grails?

You can customize random ids generated by GORM.

For this Hibernate has provided id-generator. You can customize the id generator and the column it maps to as follows:

class Person {

static mapping = {
table ‘people’
version false
id generator: ‘hilo’,
params: [table: 'hi_value',
column: 'next_value',
max_lo: 100]
}
}

Here , ‘hilo’ is  Hibernate’s built in generator that uses a separate table to generate ids.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

 

 

 

How to get mails from OFFICE365 Server in Java?

We are using REST API of OFFICE 365 to get mails/messages from mail server. This REST API includes following operations that we can perform on OFFICE 365 Mailbox:

  1. Get Messages:

It includes two types:

  • Get a message collection
  • Get a single message
  1. Create and send messages:
  • Send a new message
  • Create a draft message
  • Send a draft message
  1. Reply to messages:
  • Reply to a single message
  • Reply to all
  1. Forward message:
  • Forward a message directly
  • Create a draft of forward message
  1. Delete Messages
  2. Get attachments
  • Get collection of attachment
  • Get a single attachment

These above mentioned REST API are mentioned here.

Now if we take an example of ‘Get Messages from Mailbox’, we will need a username and password of the mailbox. Through these security credentials we need to connect to the server and fetch the mails. It’s seems a lot of work of connections, basic authentications and then getting mails. Any ways we need to follow these steps, but to save our time, we are going to use a Unirest.

One can get all the information related to Unirest here.

It is nothing but a set of lightweight HTTP libraries available in multiple languages. I’ve used it just to simplify HTTP requests as it can be used to make all GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests. Also it does non-blocking synchronous and asynchronous requests.  It supports form parameters, file uploads and custom body entities. Easily add route parameters without ugly string concatenations. Supports Basic Authentication natively. Customizable default headers for every request (DRY). Customizable HttpClient and HttpAsyncClient implementation. Automatic JSON parsing into a native object for JSON responses.

So as to get started let’s consider the first operation, that is to ‘Get messages’.

Get Messages

You can get a message collection or an individual message from a mailbox folder.

Get collection of messages

Required scope: Mail.Write or Mail.Read

To get messages from ‘inbox’ folder,

Req: GET https://outlook.office365.com/api/v1.0/me/messages

To get messages from different mailbox folder,

Req: GET https://outlook.office365.com/api/v1.0/me/folders/{folder_id}/messages 

{Folder_id} is a String type parameter which can be Inbox, Drafts, SentItems or DeletedItems.

Sample Req:

 GET https://outlook.office365.com/api/v1.0/me/folders/sentitems/messages

Now we are going to implement this in a Java program with the help of Unirest.

public class ConnectToOffice365REST{

  /**

* This methods accepts a username and password of the Office 365   * mailbox and send API request to Office 365 Server. Which returns * json object with list of unread mails.

* @param user

* @param password

* @return JSON object in string format.

    */

 public String getMessagesFromOffice(String user, String password){

                     JsonNode jsonObject = null;

                     HttpResponse<JsonNode> response;

                     String returnString = “”;

                     try {

                           // It send request to get list of unread mails from                                             // inbox folder of mailbox and does basic                                                               // authentication with provided username and password

                           response =                                                    Unirest.get(“https://outlook.office365.com/api/v1.0/me/messages?$filter=” +         java.net.URLEncoder.encode(“IsRead eq false”, “UTF-    8″)).basicAuth(user,password).asJson();

                           System.out.println(“response : ” +response.getBody());

                           jsonObject = response.getBody();

                           if(response.getBody() == null){

                                  returnString = “NULL”;

                           }

                           else{

                                  returnString = jsonObject.toString();

                           } 

                     } catch (UnsupportedEncodingException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     } catch (UnirestException e) {

                           // TODO Auto-generated catch block

                     e.printStackTrace();

                     }            

                     return returnString;

              }

}

 


ProsperaSoft offers Java development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

What is “Groovy” and “Grails” ?

Groovy…

  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java objects and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java

Grails…

Grails (previously known as “Groovy on Grails”) is a programming framework based on Groovy and inspired by Ruby on Rails (there are differences, but there are lots of similarities too). Like RoR, Grails promotes “coding by convention”, development best practices, and is meant to be highly productive.

Grails is used to build web applications that run on the JVM.

Advantages:

High productivity, focusing on business instead of plumbing.

 

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

Grails Environments

Grails supports the concept of environments. You can specify the environment to use before any command:

grails run-app // runs with the default “development” data source
grails dev run-app // runs with the “development” data source
grails prod run-app // runs with the production data source
grails -Dgrails.env=mycustomenv run-app// specific a custom environment

grails test run-app // runs with the test data source

These options are also available when packaging the application as a WAR file, although in this case the default data source used is _production_:

grails war// Packages the application with the “production” data source

grails dev war // Packages the application with the “development” data source
grails prod war // Packages the application with the “production” data source

You can use word ‘production‘ instead of ‘prod‘ and use ‘development‘ instead of ‘dev‘.

The short and full names of the environments defined by Grails are shown below:

 

You can take advantage of these environments you can have different DataSource settings per environment or different Config settings.

Datasource settings:

// environment specific settings
environments {
       development {
              dataSource {
                       dbCreate = “update” // one of ‘create’, ‘create-drop’,            ‘update’, ‘validate’, ”
                       url = “jdbc:mysql://localhost/database_name?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                       username = “XXX”
                       password = “XXX”
         }
}
test {
         dataSource {
                     dbCreate = “update”
                     url = “jdbc:mysql://localhost/database_name?                  useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                      username = “XXX”
                       password = “XXX”
           }
}
production {
               dataSource {
                           dbCreate = “update”
                           url = “jdbc:mysql://localhost/database_name? useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                          username = “XXX”
                          password = “XXX” 
                          pooled = true
                          properties {
                                  maxActive = -1
                                  minEvictableIdleTimeMillis=1800000
                                  timeBetweenEvictionRunsMillis=1800000
                                  numTestsPerEvictionRun=3
                                  testOnBorrow=true
                                  testWhileIdle=true
                                  testOnReturn=true
                                  validationQuery=”SELECT 1″
            }
     }
    }
}

Config.groovy settings:

environments {
          production {
                 grails.serverURL = “http://www.changeme.com”
                 grails.dbconsole.enabled = true
                 grails.dbconsole.urlRoot = ‘/admin/dbconsole’
 }
development {
                 grails.serverURL = “http://localhost:8080/${appName}”
}
test {
          grails.serverURL = “http://localhost:8080/${appName}”
}
}


 

ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.