gsp mail plugin autosending - grails

When I navigate to the page, why is the send() function being called automatically?
I want to be able to view the gsp page, fill in a few text fields, and THEN call the submit with an action of "send"
This is my gsp file
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="main"/>
<title>Contact Form</title>
</head>
<body>
<g:form name="contactForm" action = "send">
<g:render template = "contactFormFields"/>
<g:actionSubmit value = "submit" action = "send"/>
</g:form>
</body>
</html>
This is the contactFormFields template
<g:select name = 'subject' from = '${EmailService.options}' noSelection='Topic'/>
Contact Name: <g:textField name = "contact"/>
Contact Number: <g:textField name = "phone"/>
Contact Email: <g:textField name = "email"/>
Aditional Information:
<g:textArea name = "information" rows="5" cols="40"/>
EmailServiceController
class EmailServiceController {
def defaultAction = "contactService"
def send() {
sendMail(){
to "mygroovytest#gmail.com"
from params.email
subject params.subject
body params.information
}
}
}
domain class
class EmailService {
static constraints = {
def options = new ArrayList()
options.push("Qestions about service")
options.push("Feedback on performed service")
options.push("Other")
options.push("Why am I doing this")
}
}
gsp that calls the service
<div class="banner">
<h1>My HVAC company</h1>
Contact me today!
Services
Have Me Contact You!
</div>

You don't have a contactService action in your EmailServiceController so it's probably treating send() as the default action when you link to the controller with no action name. Try adding an empty contactService action
def contactService() { }

Related

Grails Stripe plugin error

i'm using Stripe plugin for Grails ,Grails version 2.5.1 i can't make any successful transaction i always get There was an error processing your credit card. as shown in the controller , i noticed that Charge method is not defined as shown in the screenshot
i tried to import com.stripe.Stripe but i'm getting unable to resolve class com.stripe.Stripe.
Here is the action:
def charge(String stripeToken, Double amount) {
//Stripe.apiKey = grailsApplication.config.grails.plugins.stripe.secretKey
def amountInCents = (amount * 100) as Integer
def chargeParams = [
'amount': amountInCents,
'currency': 'usd',
'card': stripeToken,
'description': 'customer#sample.org'
]
def status
try {
Charge.create(chargeParams)
status = 'Your purchase was successful.'
} catch(CardException) {
status = 'There was an error processing your credit card.'
}
redirect(action: "confirmation", params: [msg: status])
return
}
The question was about Grails 2.5.x. The plug-in is not available for Grails 3.x.x. I got it working and posted an online tutorial. There is a full, working Grails 3.2.3 application available for download. It also implements a shopping cart. The page is: http://www.databaseapplications.com.au/stripe_payments.jsp
Try this,
In build config add:
plugins {
...
compile "org.grails.plugins:stripe:2.8"
...
}
In your controller:
package stripesample
import com.stripe.model.Charge
import com.stripe.exception.CardException;
class CheckoutController {
def index() {}
def charge(String stripeToken, Double amount) {
def amountInCents = (amount * 100) as Integer
def chargeParams = [
'amount': amountInCents,
'currency': 'usd',
'card': stripeToken,
'description': 'customer#sample.org'
]
def status
Charge chargeStatus
try {
chargeStatus = Charge.create(chargeParams)
println chargeStatus
status = 'Your purchase was successful.'
} catch(CardException) {
println status
status = 'There was an error processing your credit card.'
}
render view: "confirmation", model:[msg: status,chargeObject:chargeStatus]
return
}
}
In your main layout file:
<html>
<head>
<g:javascript src="stripe-v2.js" />
<r:layoutResources/>
</head>
<body>
<g:layoutBody/>
<r:layoutResources/>
</body>
</html>
In your credit card form View:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
</head>
<body>
<h3>Checkout</h3>
<stripe:script formName="payment-form"/>
<g:form controller="checkout" action="charge" method="POST" name="payment-form">
<div class="payment-errors"></div>
<div class="form-row">
<label>Amount (USD)</label>
<input type="text" size="20" autocomplete="off" id="amount" name="amount"/>
</div>
<stripe:creditCardInputs cssClass="form-row"/>
<button type="submit">Submit Payment</button>
</g:form>
</div>
</body>
</html>
Create another view in the same controller folder in my case checkout/confirmation.gsp
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h3>Checkout</h3>
<p>${msg}</p>
<p>Data: </p>
<p>${chargeObject}</p>
</body>
</html>
Run grails clean
and then,
Run grails run-app
If you need to test a sample app you can clone my app here: Sample App
i did "refresh dependencies" in eclipse , and all worked fine

What is wrong with this upload in Grails?

In my aplication I need photo upload. I want that User first creates album folder and after cliking on that album, uploads photos. My album has: ID, album_name, username and my photo:ID, album_ID, photo_name, type
album controller:
import java.io.File
import grails.plugin.springsecurity.annotation.Secured
import java.text.SimpleDateFormat
#Secured(['ROLE_USER','ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'])
class AlbumController {
def springSecurityService
def index() { }
def create(){
def user = User.get(springSecurityService.currentUser.id)
def album = new Album()
album.a_name = params.name
album.user = user
album.save(failOnError:true)
def photo = new Photo()
def uploadedFile = request.getFile('myFile')
def name = System.currentTimeMillis()
if (uploadedFile.empty) {
flash.message = 'file cannot be empty'
redirect (action:'index')
return
}
photo.type = uploadedFile.contentType
photo.p_name = name
photo.album = album
uploadedFile.transferTo(new File("../test101111/web-app/album/" + user.username + "/"+ photo.getP_name() + ".jpg"))
//response.sendError(200, 'Done')
photo.save(failOnError:true)
redirect (action:'index')
}
}
Photo controller:
import java.io.File
import grails.plugin.springsecurity.annotation.Secured
import java.text.SimpleDateFormat
#Secured(['ROLE_USER','ROLE_ADMIN', 'IS_AUTHENTICATED_FULLY'])
class PhotoController {
def springSecurityService
def index() { }
def create(){
def photo = new Photo()
def uploadedFile = request.getFile('myFile')
def name = System.currentTimeMillis()
if (uploadedFile.empty) {
flash.message = 'file cannot be empty'
redirect (action:'index')
return
}
photo.type = uploadedFile.contentType
photo.p_name = name
photo.album = params.albumId
uploadedFile.transferTo(new File("../test101111/web-app/album/" + photo.getP_name() + ".jpg"))
//response.sendError(200, 'Done')
photo.save(failOnError:true)
redirect (action:'index')
}
}
Photo view:
<%# page contentType="text/html;charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="layout" content="main" />
<title>Photo</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("span.button").click(function() {
$("form.forma_album").toggle();
});
});
</script>
</head>
<body>
<div class="body">
<div class="album_title">
<span class="title1">Fotografije</span>
<div class="new_album">
<img class="plus" src="${resource(dir: 'images', file: 'plus.png')}" />
<span class="button">Dodaj novu sliku</span>
</div>
</div>
<hr class="usual">
<g:uploadForm action="create" class="forma_album">
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
</div>
</body>
</html>
Album view:
<%# page contentType="text/html;charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="layout" content="main" />
<title>Album</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("span.button").click(function() {
$("form.forma_album").toggle();
});
});
</script>
</head>
<body>
<div class="body">
<div class="album_title">
<span class="title1">Foto albumi</span>
<div class="new_album">
<img class="plus" src="${resource(dir: 'images', file: 'plus.png')}" />
<span class="button">Kreiraj novi album</span>
</div>
</div>
<hr class="usual">
<g:form action="create" class="forma_album">
<g:textArea class="album_name" name="name" placeholder="Ime albuma"></g:textArea>
<g:submitButton class="submit2" name="Dodaj" />
</g:form>
<g:each in="${albums}" var="album">
<g:link controller="photo" action="index" class="contact"
params="[albumId: album.id]">
${album.a_name}
</g:link>
</g:each>
<%--<g:uploadForm action="create" class="forma_album">
<g:textArea class="album_name" name="name" placeholder="Ime albuma"></g:textArea>
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
--%>
<div>
<%--<g:each in="${albums}" var="album" class="picture">
<div class="picture">
<img src="${resource(dir: 'images', file: 'picture.png')}" />
<div class="album_name">
${album.a_name}
</div>
</div>
</g:each>
--%>
</div>
</div>
</body>
</html>
My Error is: No signature of method: org.springframework.security.web.servletapi.HttpServlet3RequestFactory$Servlet3SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [myFile] Possible solutions: getXML(), getPart(java.lang.String), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON()
What is wrong? sorry for my English and thanks for the answer ;)
You can either set grails.servlet.version = "2.5" in your BuildConfig.groovy or in application.properties
or
use the request.getPart(String) instead of request.getFile(String)
see JavaDoc on Part interface
Could you please print the params and paste them here.
Alternatively you can try with request.getInputStream().

How can I send an email with a layout

I am using grails mail plugin. When I submit my form, it will send an email from aaa#example.com to textField name="email successfully but how can I send an email with a layout...not blank like this picture http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html or maybe some CSS..
FORM
<g:form action="send">
<table style="width:500px">
<tbody>
<tr>
<td>Your Email Address </td>
<td><g:textField style="width:250px" name = "email"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><g:textField style="width:250px" name = "user"/></td>
</tr>
<tr>
<td><input type="submit"/></td>
</tr>
</tbody>
</table>
</g:form>
MAIL CLOSURE
def send = {
sendMail {
to params.email
from "aaa#yahoo.com"
subject "Test Reset Password"
body(view:"/user/layoutmail",model:[name:params.user])
}
render "Email Terkirim"
}
Well you could actually use a layout for emails, similarly how you would use layouts for view pages. What you would want to do is create a new layout and a view file for your email body content.
Layout: eg. ../views/layouts/emailLayout.gsp
<%# page contentType="text/html" %>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
a {color: #348eda;}
</style>
</head>
<body>
<g:layoutBody/>
</body>
</html>
View eg. ../views/emails/welcomeEmail.gsp
<%# page contentType="text/html" %>
<g:applyLayout name="emailLayout">
<html>
<body
Your Welcome ${welcome.username}
</body>
</html>
</g:applyLayout>
And to send the mail heres an example
def sendWelcomeMail(User user, String url){
def rtn = [success:false]
if(user) {
def fooBar = [
username: user.username,
email: user.email,
url: url
]
sendMail {
async true
to fooBar.email.trim()
subject "Welcome Email"
body(view: '/emails/welcomeEmail', model: [welcome: fooBar])
}
rtn.success = true
}
return rtn
}
It isn't going to pick up a grails layout. And you don't really want it to. You should construct your email in a fashion that it could be a stand alone web page with no other dependencies. All the static resources used should be accessible via a public URL.

using check box and arraylist in struts 2

I have an array list in action class. I want to access this arraylist in my jsp page along with a checkbox. if the checkbox is checked i want to get the associated value of checkbox in another actionclass. how can i do this??
Action class:
public class CreateModuleAction extends ActionSupport{
private List modNameList=new ArrayList();
private int size;
public String manageModule()
{
ManageModule ob=new ManageModule();
modNameList=ob.selectModule();
if(modNameList.isEmpty()) {
addActionError("Module list is empty!!!");
return ERROR;
}
else{
setSize(modNameList.size());
return SUCCESS;
}
}
public List getModNameList() {
return modNameList;
}
public void setModNameList(List modNameList) {
this.modNameList = modNameList;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
jsp page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<title>Admin Module Management</title>
</head>
<body>
<div class="main">
<div class="header">
<!-- Page heading-->
<jsp:include page="/templates/heading.jsp" flush="true"/>
</div>
<div class="menu">
<!-- Page menu-->
<jsp:include page="/templates/menu.jsp" flush="true"/>
</div>
<div class="content">
<!-- page content-->
<div id="right_top" style="position:absolute; left:900px; top:300px;;">
<img src="../images/add.jpg"/>Add
<img src="../images/edit.jpg"/>Edit
<img src="../images/add.jpg"/>Delete
</div>
<s:iterator status="size" value="modNameList">
<s:checkbox name="modNameCheck" fieldValue="true" value="modNameList"/>
<s:property value="modNameList"/>
</s:iterator>
<s:actionerror/>
</div>
<div class="footer" style="margin-left: 50%">
<!-- page footer-->
<jsp:include page="/templates/footer.jsp" flush="true"/>
</div>
</div>
</body>
</html>
Why dont you use struts2 checkboxlist tag
<s:form action="myAction">
<s:checkboxlist list="modNameList" name="modNameCheck"/>
</s:form>
Now in yoyr myAction action class declare
private List modNameCheck; //with getter/setter
It will have entries which were checked in the jsp
If you want submit values from checkboxes to action then you need form in your JSP. If you want to display checked/unchecked checkboxes depending on some values from action then you need some condition check in value attribute.
<s:checkbox name="modNameCheck" value="list.contains(something)"/>

Render Errors From A Service

I call a service that creates a parent and a child record. If an error happens, the service throws a RuntimeException. The RuntimeExceptionis is caught by the controller and then there there is a redirect back to the gsp. But the error is not being rendered.
In this case, I guess the controller and thus the gsp doesn't really no anything about the objects, since everything is done in the service. So how do I render the errors?
Simple Data Entry GSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sample title</title>
</head>
<body>
<h1>Add A Record</h1>
<g:hasErrors bean="${parent}">
<div class="errors">
<g:renderErrors bean="${parent}" as="list" />
</div>
</g:hasErrors>
<g:hasErrors bean="${child}">
<div class="errors">
<g:renderErrors bean="${child}" as="list" />
</div>
</g:hasErrors>
<g:form action="add" name="doAdd">
<table>
<tr>
<td>
Parent Name
</td>
<td>
Child Name
</td>
</tr>
<tr>
<td>
<g:textField name="parentName" />
</td>
<td>
<g:textField name="childName" />
</td>
</tr>
<tr><td><g:submitButton name="update" value="Update" /></td></tr>
</table>
</g:form>
</body>
</html>
Controller
class AddrecordController {
def addRecordsService
def index = {
redirect action:"show", params:params
}
def add = {
println "do add"
try {
addRecordsService.addAll(params)
} catch (java.lang.RuntimeException re){
println re.message
flash.message = re.message
}
redirect action:"show", params:params
}
def show = {}
}
Service
class AddRecordsService {
static transactional = true
def addAll(params) {
def Parent theParent = addParent(params.parentName)
def Child theChild = addChild(params.childName,theParent)
}
def addParent(pName) {
def theParent = new Parent(name:pName)
if(!theParent.save()){
throw new RuntimeException('unable to save parent')
}
return theParent
}
def addChild(cName,Parent theParent) {
def theChild = new Child(name:cName,parent:theParent)
if(!theChild.save()){
throw new RuntimeException('unable to save child')
}
return theChild
}
}
You need to get a reference to the invalid object somehow and pass it to the view via the model so I would extend RuntimeException and add fields to contain the objects with validation errors e.g.
}catch(MyCustomException m){
render view:'show', model:[parent:m.getParent(), child:m.getChild()]
}
This whole exercise might be easier using Parent.withTransaction instead of the automatic rollback via RuntimeExceptions. Then you could manually rollback the transaction if there's validation errors and just return the objects instead of having to contain them in the exception.

Resources