How to Change Controller Name and function name URL in Grails 2.2.2? - spring

I am trying to change my controller name and method name in grails
e.g :abc.com/newUser/viewUser/4
i want to convert in below format
e.g :abc.com/new-user/view-user/4
Or
e.g :abc.com/new_user/view_user/4
for that i wrote a code :
package customize
import grails.web.UrlConverter
import org.apache.commons.lang.StringUtils
class CustomUrlConverter implements UrlConverter {
private static final String GRAILS_EXTENSION = '_'
String toUrlElement(String propertyOrClassName) {
if (StringUtils.isBlank(propertyOrClassName)) {
return propertyOrClassName
} else {
String[] r = propertyOrClassName.split("(?=\\p{Upper})");
String lowerPropertyOrClassName = propertyOrClassName.toLowerCase();
println r.length + "size()";
String extendedPropertyOrClassName="";
if(r.length > 1){
for(int i=0; i < r.length;i++){
extendedPropertyOrClassName = extendedPropertyOrClassName + r[i].toLowerCase()
if(i+1 < r.length ){
extendedPropertyOrClassName =addGrailsExtension(extendedPropertyOrClassName);
}
}
}else{
extendedPropertyOrClassName = propertyOrClassName.toLowerCase()
}
return extendedPropertyOrClassName
}
}
private String addGrailsExtension(String propertyOrClassName) {
if (propertyOrClassName.endsWith(GRAILS_EXTENSION)) {
return propertyOrClassName
} else {
return propertyOrClassName + GRAILS_EXTENSION
}
}
}
In Config.groovy
grails.web.url.converter = 'hyphenated'
// grails-app/conf/spring/resources.groovy
beans = {
"${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl)
}
In this when i am trying to get all character in small letter like below Url
e.g :abc.com/newuser/viewuser/4
its working fine
But when i add underscore in between two character like below Url
e.g :abc.com/new_user/view_user/4
Its gives an error 404..
Please Help me out. If you have any other option to change URL also welcome..
Thank you

One of the easiest way to achieve your requirement is UrlMappings.groovy
"/new_user/view_user/$id"(controller: 'newUser', action: 'viewUser')

Related

Is there a way to avoid the truncation of attached properties when using Appcenter with Xamarin?

Here's my code:
Crashes.TrackError(ex,
new Dictionary<string, string> {
{"RunQuery", "Exception"},
{"sql", s },
{"Device Model", DeviceInfo.Model },
{"Exception", ex.ToString()}
});
Everything works but I find that Appcenter limits the length of the parameters to 125 characters so it's useless for me as I can never see all of the sql or the ex string.
Has anyone found a way to get around this?
I ran into the same problem. My solution was to break my string into groups of 125 character strings and iterate through while logging. I chatted with AppCenter support. They have no way of extending this length currently.
Here is a scrubbed version of my code:
var tokenChunks = LoggingHelper.SplitBy(extremelyLongString, 120);
string title = "Long string here";
var props = new Dictionary<string, string>();
int item = 0;
foreach(string chunk in tokenChunks)
{
string chunkIndex = string.Format("item: {0}", item++);
props.Add(chunkIndex, chunk);
}
Analytics.TrackEvent(title, props);
Where the LoggingHelper class is:
public static class LoggingHelper
{
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
I should give credit to this post https://stackoverflow.com/a/8944374/117995 by #oleksii for the SplitBy method.

pass string to server side with ajax in tapestry

<t:if test="needsSetName">
<label for="userfunction">${message:setname}</label>
<t:textfield
t:mixins="zoneUpdater"
tabindex="-1"
autofocus="false"
ZoneUpdater.clientEvent="keyup"
ZoneUpdater.event="valueChangedSetName"
ZoneUpdater.zone="transferZone"
ZoneUpdater.timeout="3000"
t:id="setName"
value="setName"/>
</t:if>
#OnEvent(value = "valueChangedSetName")
protected void onValueChangedSetName(#RequestParameter(value = "param", allowBlank = true) String setName)
{
TransferOrder to = baskets.getTransferOrder();
this.setName = setName;
to.setComment("Rename from " + this.setName + " to " + setName);
nextSetName = setName;
zoneHubService.updatePendingTransfer();
zoneHubService.addCallback(new JavaScriptCallback()
{
#Override
public void run(JavaScriptSupport javascriptSupport)
{
javascriptSupport.addScript(
String.format("var thing=jQuery('#%s'); thing.focus();thing[0].setSelectionRange(10000, 10000);",
setNameField.getClientId()));
}
});
}
So my problem is, when i type some text into the textfield, it removes symbols like #,&,.. and everything else that comes after these symbols
When i use +, it turns into space.
The string that i get from the server in my method is already "edited".
I'm new to tapestry and ajax and i don't know how to solve this problem.
What do i have to do, so that i get the string back from the server without the server removing these symbols?
I solved my problem.
In my zone-updater.js I had to use encodeURIComponent on my string.
For anyone who has the same problem here is the link to the zoneUpdater.js code.
http://tinybits.blogspot.com/2010/03/new-and-better-zoneupdater.html
The link I, that I found to solve the bug is down.
define([ "jquery", "t5/core/zone" ], function($, zoneManager) {
return function(elementId, clientEvent, listenerURI, zoneElementId, timeout) {
var $element = $("#" + elementId);
var mytimeout;
if (clientEvent) {
$element.on(clientEvent, updateZone);
}
function updateZone() {
jQuery($element).removeClass('saved');
if (mytimeout != null) {
clearTimeout(mytimeout);
}
mytimeout = setTimeout(function() {
var listenerURIWithValue = listenerURI;
if ($element.val()) {
listenerURIWithValue = appendQueryStringParameter(
listenerURIWithValue, 'param', $element.val());
listenerURIWithValue = appendQueryStringParameter(
listenerURIWithValue, 'element', elementId);
}
zoneManager.deferredZoneUpdate(zoneElementId,
listenerURIWithValue);
}, timeout);
}
}
function appendQueryStringParameter(url, name, value) {
if (url.indexOf('?') < 0) {
url += '?'
} else {
url += '&';
}
value = encodeURIComponent(value);
url += name + '=' + value;
return url;
}
});

No need to check this! skip

So what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute isSo what I'm trying to do but clearly struggling to execute is
a single line in the text f
import java.util.Scanner;
import java.io.*;
public class hello
{
public static void main(String[] args) throws IOException
{
Scanner Keyboard = new Scanner(System.in);
System.out.print();
String response = Keyboard.nextLine();
File inFile = new File(response);
Scanner route = new Scanner(inFile);
while ()
{
System.out.print(");
String word = Keyboard.next();
String Street = route.next();
String stopNum = route.next();
You are closing your file after you read one "line" (actually, I'm not sure how many lines you're reading - you don't call nextLine). You also aren't parsing the line. Also, I'd prefer a try-with-resources over an explicit close (and many of your variables look like class names). Finally, you need to check if the line matches your criteria. That might be done like,
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter filename >> ");
String response = keyboard.nextLine();
File inFile = new File(response);
System.out.print("Enter tram tracker ID >> ");
String word = keyboard.nextLine(); // <-- read a line. Bad idea to leave trailing
// new lines.
try (Scanner route = new Scanner(inFile)) {
while (route.hasNextLine()) {
String[] line = route.nextLine().split("\\^");
String street = line[0];
String stopNum = line[1];
String trkID = line[2];
String road = line[3];
String suburb = line[4];
if (!trkID.equals(word)) {
continue;
}
System.out.printf("street: %s, stop: %s, id: %s, road: %s, suburb: %s%n",
street, stopNum, trkID, road, suburb);
}
}
Your code print everything in the file.
To print a line with an given ID:
You can first buffer all lines of the file into a ArrayList like this in the main method:
ArrayList<String> lines = new ArrayList<>();
while (route.hasNextLine())
{
lines.add(route.nextLine());
}
Then create a method to find a line with a specific ID:
public static int find(ArrayList information, int ID)
{
String idString = "" + ID;
ListIterator<String> li = information.listIterator();
String currentLine = "";
int index = 0;
while(li.hasNext())
{
currentLine = li.next();
int count = 0;
int index1 = 0;
int index2 = 0;
/*Trying to locate the string between the 2nd and 3rd ^ */
for(int i = 0; i < currentLine.length(); i++)
{
if(currentLine.substring(i, i+1).equals("^"))
{
count++;
if(count == 2)
index1 = i;
else if(count == 3)
{
index2 = i;
break;
}
}
}
if(currentLine.substring(index1+1, index2).equals (idString))
return(index);
index++;
}
//If no such ID found, return -1;
return -1;
}
In the main method:
System.out.println("enter an ID")
int ID = Integer.parseInt(Keyboard.next());
int lineNumber = find(lines, ID);
if(lineNumber == -1)
System.out.println("no information found");
else
System.out.println(lines.get(lineNumber));

Saving of grails domain object with an attribute type object fails

I'm trying to save a domain object with grails 2.3.3 But it is not saved. How can I save it and why is it not saving?
The domain code:
package berg
import nl.jappieklooster.Log
class FieldValue {
Object value
public String toString(){
Log.debug "Field value: {0}", value
return value.toString()
}
static constraints = {
}
}
The code that saves:
// an extract from the bootsrap file
def init = { servletContext ->
def blueFV = new FieldValue(value: Color.blue)
def smallFV = new FieldValue(value: "small")
def fieldVals = [blueFV, smallFV]
saveData(fieldVals,berg.FieldValue)
}
public void saveData(List list, Class type){
def wholeList = type.list() ?: []
println("Started with adding the "+type.getName()+" classes.")
int saved = 0;
int failed = 0;
if(!wholeList){
list.each{ i ->
if(i.validate()){
i.save(flush:true, failOnError: true)
saved++
}
else{
println("! - - - Warning: '"+i.toString()+"' could not be created! - - - !")
failed++
}
}
if(failed > 0)//if one fails, let the message appear more clearly
println(".v.v.")
println("When saving the "+type.getName()+" classes: "+saved+" were saved, "+failed+" failed to be saved.")
if(failed > 0)
println(".^.^.")
}
}
The entire value column does not show up in the database

How do I Get Full Html Field Name for an item in a list on my model at controller level?

*First Post
I have a JQuery error handler for my Ajax posts that I must use, it appends an error to the html based on the field name for that element like this
$(document).ready(function () {
function myHandler(e, error) {
var tag = "";
if (error.Success == true) { $('.field-validation-error').remove(); return; } // if success remove old validation and don't continue
if (error.Success == false) { $('.field-validation-error').remove(); } // if success remove old validation and continue
for (i = 0; i < error.Errors.length; i++) {
var t = error.Errors[i];
//get error key and assign it to id
tag = t.Key;
//clear down any existing json-validation
for (j = 0; j < t.Value.length; j++) {
//this part assumes that our error key is the same as our inputs name
$('<span class="field-validation-error">' + t.Value[j].ErrorMessage + '</span>').insertAfter('input[name="' + tag + '"], textarea[name="' + tag + '"], select[name="' + tag + '"], span[name="' + tag + '"]');
}
}
}
$.subscribe("/******/errors", myHandler);
});
This works perfectly out of the box with our fluent validation setup until I try to add a custom modelstate error at controller level like so:
foreach (var item in model.Locations)
{
var cityRepos = new CityRepository(NhSession);
var cityItem = cityRepos.GetAll().FirstOrDefault(o => o.Country.Id == item.CountryID && o.Name == item.City);
if (cityItem == null)
item.City
ModelState.AddModelError("City", string.Format(#"The city ""{0}"" was not found, please ensure you have spelt it correctly. TODO: add a mail to link here with city not found subject", item.City));
}
the problem is that the modelstate error needs to be attached to the html field name not my magic string "City". The html name property is MVC Generated and looks something like this:
name="Locations[0].City"
I have encountered this problem in a html helper before and used the method:
.GetFullHtmlFieldName(
ExpressionHelper.GetExpressionText(propertySelector)
);
which resolved my problem in that case.
My question is can I use this method on my model property in an MVC post action to obtain the html name property it has come from?
Thanks in advance
ok so it's not ideal but I have implemented this Helper method until I can find a better solution that doesn't involve magic strings:
public static class ModelStateErrorHelper
{
public static string CreateNameValidationAttribute(string collectionName, int index, string propertyName)
{
string template = "{0}[{1}].{2}";
return string.Format(template, collectionName, index.ToString(), propertyName);
}
}

Resources