Grails: Unable to resolve class groovyx.net.http.HTTPBuilder - web-services

I have developped some web services that I would like tu use in my grails application.
These services can be called using Get or POST protocols.
I have seen that I need to use the HTTP builder object to do that.
This is my code:
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
def http = new HTTPBuilder( 'http://localhost:8086' )
http.request( GET, JSON ) {
uri.path = '/RegistrationService/webresources/users/isRegistered'
uri.query = [ login:'aa', password: 'bb' ]
response.success = { resp, xml ->
def xmlResult = xml
}
}
The problem I have is that in Netbeans I have an error for each import:
Unable to resolve class groovyx.net.http.HTTPBuilder
Unable to resolve class groovyx.net.http.ContentType
...
However I tried to run the application and this is the error when I run my code:
| Error 2013-02-25 23:33:32,596 [http-bio-8080-exec-3] ERROR errors.GrailsExceptionResolver - MissingPropertyException occurred when processing request: [POST] /WordGame/user/authenticate
No such property: uriPath for class: groovyx.net.http.HTTPBuilder$RequestConfigDelegate. Stacktrace follows:
Message: No such property: uriPath for class: groovyx.net.http.HTTPBuilder$RequestConfigDelegate
Line | Method
->> 21 | doCall in wordgame.UserController$_closure2_closure4
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 425 | doRequest in groovyx.net.http.HTTPBuilder
| 359 | request . in ''
| 19 | doCall in wordgame.UserController$_closure2
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
I have installed the rest plugin using the command: grails install-plugin rest
And I have already tried to install it with the netbeans interface and it tells me that it is correctly instaled.
I have seen on some forums that I need to had dependencies in the file BuildConfig.groovy like that:
dependencies {
runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') {
excludes 'xalan'
excludes 'xml-apis'
excludes 'groovy'
}
}
But this is not resolving the problem.
For information I am using netbeans 7.2.1 and Grails 2.2.0.
Is there something wrong with my code or is there a simplier way to request a web service?
Thanks in advance.

so, I read through the Exception you posted and your code snippet again and it seems that you have omitted the req variable within the http.request(){} closure. also you have not imported the GET method and TEXT content type. try:
import groovyx.net.http.HTTPBuilder
//import groovyx.net.http.ContentType // this doesn't import ContentType
//import groovyx.net.http.Method // this doesn't import Method
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
// ContentType static import
import static groovyx.net.http.ContentType.*
// Method static import
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://localhost:8086' )
http.request( GET, JSON ) { req -> // 'req ->' is not present in your code snippet!
uri.path = '/RegistrationService/webresources/users/isRegistered'
uri.query = [ login:'aa', password: 'bb' ]
response.success = { resp, xml ->
def xmlResult = xml
}
}
also I would recommend to read through the documentation of HTTPBuilder at this location: http://groovy.codehaus.org/modules/http-builder/doc/index.html as the code is well explained and some howtos and tutorials are also listed ;)

i just solved my problem.
Download this: http://repository.codehaus.org/org/codehaus/groovy/modules/http-builder/http-builder/0.5.2/
Copy the httpBuilder.jar and all the jars from dependencies directory in your groovy_installed_directory/lib. Then restart console and try again.
Hope it helps.
BR

Related

TypeOrmModule and MongooseModule not connecting to databases in ElasticBeanstalk Docker application

So initially, I deployed a nestjs application to elasticbeanstalk with docker-compose. The application was working perfectly with the configured elasticbeanstalk RDS database, at the same time running well with a remote mongodb atlas cluster. But after adding a new feature to my code (this feature has nothing to do with the database configurations), and eb deployed, the elastic beanstalk application just stopped working.
It gave this error:
| [31m[Nest] 1 - [39m07/03/2022, 6:04:51 PM [31m ERROR[39m [38;5;3m[TypeOrmModule] [39m[31mUnable to connect to the database. Retrying (7)...[39m
app_name | [31m[Nest] 1 - [39m07/03/2022, 6:04:54 PM [31m ERROR[39m [38;5;3m[MongooseModule] [39m[31mUnable to connect to the database. Retrying (8)...[39m
app_name | [31m[Nest] 1 - [39m07/03/2022, 6:04:54 PM [31m ERROR[39m [38;5;3m[TypeOrmModule] [39m[31mUnable to connect to the database. Retrying (8)...[39m
app_name | [31m[Nest] 1 - [39m07/03/2022, 6:04:57 PM [31m ERROR[39m [38;5;3m[ExceptionHandler] [39m[31mThe `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.[39m
app_name | at __awaiter (/usr/src/app/node_modules/#nestjs/mongoose/dist/mongoose-core.module.js:16:12)
app_name | at Function.<anonymous> (/usr/src/app/node_modules/#nestjs/mongoose/dist/mongoose-core.module.js:60:69)
app_name | at Generator.next (<anonymous>)
app_name | at Mongoose.createConnection (/usr/src/app/node_modules/mongoose/lib/index.js:286:10)
app_name | at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:689:11)
app_name | at new Promise (<anonymous>)
app_name | at Observable._subscribe (/usr/src/app/node_modules/rxjs/dist/cjs/internal/observable/defer.js:8:31)
app_name | at Observable._trySubscribe (/usr/src/app/node_modules/rxjs/dist/cjs/internal/Observable.js:41:25)
app_name | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16)
app_name | at /usr/src/app/node_modules/#nestjs/mongoose/dist/mongoose-core.module.js:20:71
app_name | at /usr/src/app/node_modules/#nestjs/mongoose/dist/mongoose-core.module.js:59:80
app_name | Error: connect ECONNREFUSED 127.0.0.1:5432
app_name | MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
current_app_name exited with code 1
This is my database configurations for the nestjs application:
// app.module.ts file.
#Module({
imports: [
// MONGO_DATABASE_URI here is the connection string to a remote mongodb atlas cluster
MongooseModule.forRoot(process.env.MONGO_DATABASE_URI),
TypeOrmModule.forRoot({
type: 'postgres',
// these environment variables are related to AWS RDS variables
host: process.env.RDS_HOSTNAME, .
port: parseInt(process.env.RDS_PORT),
username: process.env.RDS_USERNAME,
password: process.env.RDS_PASSWORD,
database: process.env.RDS_DB_NAME,
entities: [<My Entities here>],
synchronize: true,
}),
PLease I need help.

Registered URL not found

We had implemented a two-in-one backend with Flask. For the website itself (which we call it tekid), we're having no trouble. But for the management portal (which we call it tekid-admin), even though using the same view registries, the WSGI server (both dev and prod) returns 404 NOT FOUND for all requests.
Related Codes
The CLI entries are registered as
tekid -> tekid.cli.www:cli
tekid-admin -> tekid.cli.adm:cli
Following is the code we used to hold Flask application object:
# -*- coding: utf-8 -*-
"""Module entrypoint of TekID website."""
# in `tekid/app/www.py` for `tekid`
from tekid.urls.www import app
# in `tekid/app/adm.py` for `tekid-admin`
from tekid.urls.adm import app
Following is the code we used for CLI entry:
# -*- coding: utf-8 -*-
"""CLI for TekID website."""
import click
import flask
import tekid.core.typing as typing
# in `tekid/cli/www.py` for `tekid`
from tekid.app.www import app
# in `tekid/cli/adm.py` for `tekid-admin`
from tekid.app.adm import app
__all__ = ['cli']
#click.group(cls=flask.cli.FlaskGroup, create_app=lambda: app)
def cli() -> typing.NoneType:
"""Management script for the TekID website."""
Following is the code we used for routing registry (we're using a centralised registering mechanism as proposed by Flask itself):
# tekid/urls/www.py & tekid/urls/adm.py (same when testing)
# -*- coding: utf-8 -*-
"""URL routing for TekID website."""
# pylint: disable=wrong-import-position
from tekid.core.macro import FLASK as app
__all__ = ['app']
###############################################################################
# load HTML pages
from tekid.urls.pages import * # pylint: disable=unused-wildcard-import
# index.html
app.add_url_rule('/', view_func=load_index)
... # same routing registry codes
Expected Behavior
NB: tekid and tekid-admin should give the same output
The routes command would give like this:
$ tekid routes
# or
$ tekid-admin routes
Endpoint Methods Rule
-------------- ----------------- -----------------------------------
load_contact GET, POST /contact/
load_expertise GET /expertise/
load_index GET /
load_news GET, POST /news/
...
static GET /static/<path:filename>
We try curl http://127.0.0.1:5000/ after run on the website (tekid):
$ tekid run
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 332-955-135
/fakepath/.venv/lib/python3.7/site-packages/flask/sessions.py:220: UserWarning: The session cookie domain is an IP address. This may not work as intended in some browsers. Add an entry to your hosts file, for example "localhost.localdomain", and use that instead.
"The session cookie domain is an IP address. This may not work"
127.0.0.1 - - [07/Nov/2019 17:20:03] "GET / HTTP/1.1" 200 -
$ curl http://127.0.0.1:5000
<!--
_______ _ _____ _____ _ _ _
|__ __| | | |_ _| __ \ | | | | | |
| | ___| | __ | | | | | | | | | |_ __| |
| |/ _ \ |/ / | | | | | | | | | __/ _` |
| | __/ < _| |_| |__| | | |___| || (_| |_
|_|\___|_|\_\_____|_____/ |______\__\__,_(_)
-->
... (the actual HTML page)
Actual Behavior
With the same configs as above, we try curl http://127.0.0.1:5000/ after run on the management portal (tekid-admin):
$ tekid-admin run
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: ***-***-***
/fakepath/.venv/lib/python3.7/site-packages/flask/sessions.py:220: UserWarning: The session cookie domain is an IP address. This may not work as intended in some browsers. Add an entry to your hosts file, for example "localhost.localdomain", and use that instead.
"The session cookie domain is an IP address. This may not work"
127.0.0.1 - - [07/Nov/2019 17:06:25] "GET / HTTP/1.1" 404 -
$ curl http://127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
Environment
Python version: 3.7.4
Flask version: 1.1.1
Werkzeug version: 0.16.0
So, basically from the Flask and/or Werkzeug documentation (which I could not recall the original source), Flask can only recognise the imported application instance from no more than 2 (?) layers recursively.
That is to say, the application failed to identify which one was the actual instance to be used and rather make an empty instance without any registered URLs.
The solution was to simply reconstruct the code and just import the application instance in each file and do the same thing to import the URL registries in the CLI files as for tekid/urls/www.py & tekid/urls/adm.py.

vue cli 3 - ProvidePlugin doesn't work (vue.config.js)

I am trying to add webpack.ProvidePlugin which isn't working on Vue-cli 3.
I also tried to set lodash as a global import (so I won't have to import it in each store module).
vue.config
const webpack = require("webpack");
module.exports = {
configureWebpack: {
plugins: [new webpack.ProvidePlugin({ _: "lodash" })]
}
};
build Error:
Module Warning (from ./node_modules/eslint-loader/index.js):
error: '_' is not defined (no-undef) at src/store/modules/templates.js:24:10:
22 | export default Object.assign({}, base, {
23 | namespaced: true,
> 24 | state: _.cloneDeep(initialState),
| ^
25 | mutations: {
26 | addTemplate(state, template) {
27 | if (!template) throw new Error("template is missing");
I built the project after adding the lines to vue.config and they gave me the aforementioned error.
The issue doesn't seem to be with Vue CLI but with eslint. See this question for a similar issue (just replace d3 with _): Webpack not including ProvidePlugins
In short, adding this to your eslint config (often found in .eslintrc.js) should make it work:
"globals": {
"_": true
}

Grails - Apache Tika plugin test-app failure

I'm learning how to use the Apache Tika plugin. I've just copied the code from github and I get failure error when unit testing.
This is the unit test
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* Test for tikaService: try to parse test data.
*/
#TestFor(TikaService)
class TikaServiceSpec extends Specification {
def 'Parse a word file to XML'() {
given:
def file = new File('parserTest.doc')
when:
def xml = service.parseFile(file)
then:
def doc = new XmlSlurper().parseText(xml)
doc.body.p.find{
it.text() == 'This is a simple test document'
}
}
}
This is the error I get.
Running 5 unit tests... 8 of 8
| Failure: Parse a word file to XML(com.myApp.TikaServiceSpec)
| Condition not satisfied:
doc.body.p.find{ it.text() == 'This is a simple test document' }
| | | |
| | | groovy.util.slurpersupport.NoChildren#4c2a4e84
| | Tika Parser Test
| | This is a simple test document
| Tika Parser Test
| This is a simple test document
Tika Parser Test
This is a simple test document
at com.myApp.TikaServiceSpec.Parse a word file to XML(TikaServiceSpec.groovy:21)
What am I doing wrong?
dependencies {
compile('org.apache.tika:tika-core:0.7')
compile('org.apache.tika:tika-parsers:0.7') { excludes "xercesImpl", "xmlParserAPIs", "xml-apis", "log4j" }
}
Thanks to #Gagravarr, the problem has been solved. I used the version 1.12 and it worked.
The repo is https://repo1.maven.org/maven2/org/apache/tika/

Error calling an external SOAP web service with WSClient

I have created a SOAP webservice that I would like to access from Grails.
I have installed the plugin ws-client in order to use the object WSClient.
I have tried with the example given here: http://groovy.codehaus.org/Using+WSClient+in+Grails
So my code is:
def index = {
def proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize()
def result = proxy.CelsiusToFahrenheit(0)
result = "You are probably freezing at ${result} degrees Farhenheit"
flash.message = result
}
This is the error I get:
javac: target release 1.5 conflicts with default source release 1.7
| Error 2013-02-27 17:47:06,901 [http-bio-8080-exec-10] ERROR errors.GrailsExceptionResolver - JAXBException occurred when processing request: [POST] /WordGame/game/create
"org.tempuri" doesnt contain ObjectFactory.class or jaxb.index. Stacktrace follows:
Message: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
Line | Method
->> 197 | createContext in com.sun.xml.bind.v2.ContextFactory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 172 | newInstance in javax.xml.bind.ContextFinder
| 132 | newInstance . in ''
| 334 | find in ''
| 431 | newInstance . in javax.xml.bind.JAXBContext
| 349 | createClient in org.apache.cxf.endpoint.dynamic.DynamicClientFactory
| 196 | createClient in ''
| 175 | createClient in ''
| 198 | createClient in groovyx.net.ws.AbstractCXFWSClient
| 107 | initialize in groovyx.net.ws.WSClient
| 30 | conversion . in wordgame.GameController$$ENyfXWG9
| 42 | doCall in wordgame.GameController$_closure1$$ENyfXWG9
| 195 | doFilter . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1110 | runWorker . . in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . in java.lang.Thread
I know there is no error calling the method proxy.CelsiusToFahrenheit(0) because I have the same error just doing:
def proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize()
I have tried with an other webservice I have created but I have the same error.
I have search on Google and I have seen a lot of people having this issue and I didn't find how to fix it.
Config:
Windows 7 x64
Netbeans 7.2.1
Grails 2.2.0
Do someone know how to fix this problem?
Thanks for the answer but the problem was from plugins. In order to work, It was needed to install the plugins:
cxf
cxf-client
Installing these two plugins resolved the problem.
From the error message
javac: target release 1.5 conflicts with default source release 1.7
I think it's about JDK version. WSClient needs JDK to compile something in the run-time, so you have to deploy a 1.7 version JDK to support that.