Accessing messages.properties works in development but not when deployed - grails

The following code works fine when deployed locally in a dev environment from a controller (using run-app). It's used to create a JavaScript object with all messages in the current language.
class LocaleController {
private Map<String, String> getMessages() {
// This is the line in question, the rest is just context
def bundle = ResourceBundle.getBundle("grails-app/i18n/messages");
def map = [:]
bundle.keys.each { msg ->
map[msg] = message(code: msg)
}
return map
}
def index() {
header("Cache-Control", "public, max-age=31536000")
render(view: "index", model: [messages: getMessages()], contentType: "text/javascript")
}
}
However, when this is run from a deployed server, I get the following error message
errors.GrailsExceptionResolver - MissingResourceException occurred when processing request: [GET] /compose/locale/index
Can't find bundle for base name grails-app/i18n/messages, locale en_US. Stacktrace follows:
java.util.MissingResourceException: Can't find bundle for base name grails-app/i18n/messages, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028)
at com.accelrys.compose.app.LocaleController.getMessages(LocaleController.groovy:13)
at com.accelrys.compose.app.LocaleController.index(LocaleController.groovy...
I would have preferred not to read the file directly, so I tried http://mrhaki.blogspot.com/2011/11/grails-goodness-internationalize.html which uses http://grails.org/plugin/jawr but that page has been offline for the past 10 days.
I also tried following the steps in How can I create a map with all i18n-messages in Grails but it wouldn't use my customized message source, I copied the answer verbatim (clean/comile/run-app) but it was still using PluginAwareResourceBundleMessageSource instead of ExtendedPluginAwareResourceBundleMessageSource
2014-09-29 17:15:33,447 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - MissingMethodException occurred when processing request: [GET] /compose/locale/index - parameters: jklgfdgdfg:
No signature of method: org.codehaus.groovy.grails.context.support.PluginAwareResourceBundleMessageSource.getMessageCodes() is applicable for argument types: () values: []. Stacktrace follows:
Message: No signature of method: org.codehaus.groovy.grails.context.support.PluginAwareResourceBundleMessageSource.getMessageCodes() is applicable for argument types: () values: []
Line | Method
->> 15 | getMessages in com.accelrys.compose.app.LocaleController$$EOrHmJbB
Any suggestions on what else I can try?

It turns out that How can I create a map with all i18n-messages in Grails does work correctly.
I am not sure why it wasn't working, as one can see from the error message in the question. Maybe it had something to do with the following error at startup.
java.lang.RuntimeException: Reloading agent exited via exception, please raise a jira
Error |
at org.springsource.loaded.agent.ClassPreProcessorAgentAdapter.transform( ClassPreProcessorAgentAdapter.java:104)
Error |
In any case, if you try this and it doesn't work at first, don't give up. Try again later.
Update
It turns out that the reason the plugin didn't work was because grails install-plugin is deprecated, adding compile ":jawr:3.5.1" to the plugins section of BuildConfig.groovy made it work.

Related

How can I fix the error: "Cannot POST /users. StatusCode: 404" while making a POST request in Postman?

I'm following the article while working on the project.
When making a POST request in Postman:
http://localhost:3000/users
With Body request:
{
"name": "Jose Luis",
"lastName": "Campos Bautista"
}
I'm getting the issue as:
{
"statusCode": 404,
"message": "Cannot POST /users",
"error": "Not Found"
}
Am I missing something in the steps of the article? Does it the problem related specifically to API?
Inside the controller I have annotated as users:
#Controller('users')
Before executing a Postman request, I run the command:
npm run start:dev
Also I use the Postgres database with the next format of configuration:
DB_URL=postgres://user:password#localhost:5444/dataBaseName
ENTITY_PATH=dist/**/**/*.entity{.js, .ts}
Thanks in advance for any reasonable advice/ideas on how I can overcome this issue.
I have looked in your git repo. You should insert some route inside your controller like this
#Post('/create')
Your service is also lacking await before calling the save method in your service. It should be like
async create(user: UserDto): Promise<UserDto> {
return await this.userRepository.save(user);
}
and your controller should be like
#Post()
async create(#Body() user: UserDto): Promise<UserDto> {
return await this.userService.create(user);
}
You also don't have a connection initialization inside your app.module.ts so your API wouldn't be able to save data inside database.
Your UserModule is never registered with the application. The AppModule needs to have UserModule in its imports array. Just because the file exists and is written doesn't mean Nest knows what to do with it. You have to tell the application that the module should be used by having it in the imports path of some module that eventually makes its way back to the root module (usually AppModule)
Side Note: when you do that, you will get an error from TypeORM because you call TypeormModule.forFeature() without ever importing TypeormModule.forRoot(), so just a heads up that you need to add that

Serverless - Change the content before deploy

I'm using Serverless for working with our aws lambda / appsync.
For Error Handling, we are keep erro code with message in a json file. The Codes will be unique. Something like this:
//error-code.json
{
"1"": { code: 1, message: "Invalid User Input"},
"2"": { code: 2, message: "Invalid Input"},
//... so on
}
This wil lbe deploy as layer and all the lambda will use it. Issue is we cannot use it in the resolve template. There are some of the resolver will be only template file. These template files cannot access the json file nor can access the layer. How can I use the error-code.json here?
Solution 1:
Manually write the error code in templates and make sure there are alway unique. Something like this:
#set(#errorInfo = {
"erroCode": "1",
"errorMessage": "Invalid Input"
})
$util.error("Invalid Input", "errorType", $ctx.arguments,#errorInfo)
Rejected: Becasue we have to manually check everytime for the unique of error code. In case of lot of template file, we cannot rely on it.
Solution 2:
Create a table with error code (unique) and error message. Use this table to send error from template.
Rejected: Because we use multiple app sync instance and they all connect to dirferent database. So we have to make this table in all database, and thus unique across the app-sync is not maintained.
Solution 3:
Write the placeholder in vtl where we want to send the error. Before Deploy, replace the placeholder with the actual code using pre-hook script, but not in the actual vtl file but in the generated package that serverless deploy. Does Serverless even such thing?
if your errors are all static, there is one more option for consideration.
You create one more file that holds all errors defined in Velocity.
$util.qr( $ctx.stash.put("errors", {}) ) $util.qr(
$util.qr( $ctx.stash.errors.put("ONE", { "code": 1, "message": "Invalid User
Input"} )
...
$util.qr( $ctx.stash.errors.put("TWENTY", { "code": 20, "message": "20th error description"} )
For every velocity resolver that throws errors, you inject pre-defined errors at the beginning of its request mapping's file. Whenever you want to throw an error, it's done by retrieving a pre-defined error from $ctx.stash
$util.error ( $ctx.stash.errors.ONE.message, $ctx.stash.errors.ONE.code )
The error file is generated from error-code.json, or manually typed again for simplicity. $ctx.stash is used because stash is accessible from everywhere in a resolver, including pipeline ones.

Can't get transports in SignalR

When I run $.connection.hub.start() I get these errors from "resources" (I traced it).
These are the errors i'm getting
errorOnNegotiate -> "Error during negotiation request.".
errorParsingNegotiateResponse -> "Error parsing negotiate response.".
errorSourceError -> "Error raised by EventSource".
eventSourceFailedToConnect -> "EventSource failed to connect.".
longPollFailed -> "Long polling request failed.".
noConnectionTransport -> "Connection is in an invalid state, there is
no transport active.". nojQuery -> "jQuery was not found. Please
ensure jQuery is referenced before the SignalR client JavaScript
file.". noTransportOnInit -> "No transport could be initialized
successfully. Try specifying a different transport or none at all for
auto initialization.".
Part of the error is this : "jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.""
you need to add jQuery reference this can be done like so (Please note that in this sample the signalR version is 2.0.2 you need to add the correct reference to the version you are using):
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
It looks like you've pasted the contents of the resources object within signalR._.error(). That object contains a list of possible errors, not the error your're getting. For example, here it's being used to get the error message when the negotiation response couldn't be parsed:
try {
res = connection._parseResponse(result);
} catch (error) {
onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
return;
}
To see which error you're actually getting, look at what the code is trying to utilize from this object.

Ember.js / Rails / Devise - Handling Validation Errors from Server

Hiyo
I'm pretty new to ember - working on building an Ember front, Rails back authentication with Devise. Trying to show server side errors on the Client...
I've read a bunch of stuff about this but nothing seems to work.
Login Page is at /sessions/new
Sessions New Template (Emblem.js)
Ember.TextField valueBinding="email" placeholder="Email" type="text"
= errors.email
Sessions New Route
SiloStore.SessionsNewRoute = Ember.Route.extend
model: -> #store.createRecord('session')
setupController: (controller, model) ->
controller.set('content', model)
Sessions New Controller
SiloStore.SessionsNewController = Ember.ObjectController.extend
needs: ['admin']
actions:{
logIn: ->
self = #
content = #content
#content.save().then(->
self.get('controllers.admin').set('content', content);
self.transitionToRoute 'admin.dashboard'
)
}
Sessions Controller (Rails)
render json: {
errors: {
email: ["invalid email or password"]
}
}, status: :unprocessable_entity
JSON Error from Rails Server in Console
{"errors":{"email":["invalidemailorpassword"]}}
Now instead of my Error showing under the Ember.TextField in my template - I'm getting a big ugly red error that looks like this:
POST http://dev.siloarts.net:3000/api/v1/sessions 422 (Unprocessable Entity)
Error: The backend rejected the commit because it was invalid: {email: invalid email or password}
Any Ideas?? I'm sure it's a dumb thing...
Oh oh oh and here is my debug info:
DEBUG: -------------------------------
DEBUG: Ember : 1.4.0-beta.1+canary.011b67b8
DEBUG: Ember Data : 1.0.0-beta.5+canary.d9ce2a53
DEBUG: Handlebars : 1.1.2
DEBUG: jQuery : 1.10.2
DEBUG: -------------------------------
THANKYOU IN ADVANCE LOVE HUGH
This error is also preventing errors structure binding. You can fix/patch it this way: call person.save().catch(->)always when you need to save. This will catch the error and do noting but one could still use becameError: and becameInvalidon the model or just implement the function on its own. You can also change your model class as follows:
App.Model = DS.Model.extend
save: (catchErr=true) ->
if catchErr
fail = ->
console.log('Save failed')
retutn #_super().catch(fail)
#_super()
Than change your base callas for a Person object
App.Person = App.Model.extend
...
And then when you need real catch use person.save(false).catch(fn)
I ran into the same error after upgrading. Downgrading to Ember 1.2.0 should solve your problem:)

Grails filter does not redirect in production mode

I have a strange problem with Grails filter.
I am using PayPal plugin and I have a filter for filtering payments as below.
after = {
if(payment && payment.status == org.grails.paypal.Payment.COMPLETE) {
...
paypalPayment.shipIt()
redirect(controller:"mycontroller", action:"myaction", id:myid)
return
}
}
Actually, everything is fine in development mode. But in production mode, it does not redirect the request, and gets an exception as below :
Template not found for name [txsummary] and path [/paypal/_txsummary.gsp]. Stacktrace follows:
org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error processing GroovyPageView: Template not found for name [txsummary] and path [/paypal/_txsummary.gsp]
By the way, I can see that it enters to the method "paypalPayment.shipIt()" from the log file.
Any help is much appreciated
Tuncay

Resources