How to call a POST method using gluon RESTClient - java

Below is the sample code . i want to call a rest api using gluon.
RestClient restClient = RestClient.create()
.host("https://abc.api.in")
.path("v1/signup")
.formParam("name",name)
.formParam("email",email)
.formParam("password",password)
.formParam("repeatPassword",repeatPassword)
.formParam("refID",refID)
.method("POST").contentType("text/plain");
GluonObservableObject<SignUpDAO> sample = DataProvider.retrieveObject(restClient.createObjectDataReader(SignUpDAO.class));
But it gives warning like and it is not showing any further progress.I am using Task to call rest client from my controller.
INFO: Created Rest Connection:
Method: POST
Request URL: urlname
Form Params: {password=[test123], repeatPassword=[test123], name=[pqr], refID=[dsfdfkdlfk], email=[test#gmail.com]}
ContentType: text/plain
Consumer Credentials: null / null
Aug 19, 2016 12:17:20 PM com.gluonhq.connect.converter.JsonConverter readFromJson
INFO: Property password not defined on json object for class class com.gluonapplication.com.coinsecureapp.controller.SignUpDAO.
Aug 19, 2016 12:17:20 PM com.gluonhq.connect.converter.JsonConverter readFromJson
INFO: Property repeatPassword not defined on json object for class class com.gluonapplication.com.coinsecureapp.controller.SignUpDAO.
Aug 19, 2016 12:17:20 PM com.gluonhq.connect.converter.JsonConverter readFromJson
INFO: Property name not defined on json object for class class com.gluonapplication.com.coinsecureapp.controller.SignUpDAO.
Aug 19, 2016 12:17:20 PM com.gluonhq.connect.converter.JsonConverter readFromJson
INFO: Property refID not defined on json object for class class com.gluonapplication.com.coinsecureapp.controller.SignUpDAO.
Aug 19, 2016 12:17:20 PM com.gluonhq.connect.converter.JsonConverter readFromJson
INFO: Property email not defined on json object for class class com.gluonapplication.com.coinsecureapp.controller.SignUpDAO.

Related

HttpURLConnection failing on POST with HTTP 400

HttpURLConnection sometimes fails on POST operations to a http URL. In my case the following fails about one of a hundred times:
byte[] formData = ("mgnlUserId=" + user + "&mgnlUserPSWD=" + user).getBytes(StandardCharsets.UTF_8);
URL url = new URL("http://localhost:8080/magnoliaAuthor/.magnolia/admincentral");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(formData.length));
connection.getOutputStream().write(formData);
connection.connect();
// Sometimes fails with response code being 400
assertEquals(200, connection.getResponseCode());
The server complains about the bad request too:
HTTP Status 400 – Bad Request
Invalid character found in method name [User-Agent:]. HTTP method names must be tokens
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
java.lang.IllegalArgumentException: Invalid character found in method name [User-Agent:]. HTTP method names must be tokens
Here's some example code for reproducing the problem.
For now this looks like a bug to me but I couldn't find anything related in the Java bug tracker.
Anyone experiencing similar issues and has a workaround?
This is indeed a bug of HttpURLConnection.
Looking at the HTTP request going over the wire I can see the HTTP method is set to User-Agent: instead of GET:
And the log output show the same faulty request being sent:
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: ProxySelector Request for http://localhost:8080/magnoliaAuthor/.magnolia/admincentral
Nov 03, 2021 8:37:01 PM sun.net.www.http.HttpClient logFinest
FINEST: KeepAlive stream retrieved from the cache, sun.net.www.http.HttpClient(http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=44DEE0C8C535782A6B4932E9F0D455ED)
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: Proxy used: DIRECT
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader#15b170d89 pairs: {POST /magnoliaAuthor/.magnolia/admincentral HTTP/1.1: null}{Content-Type: application/x-www-form-urlencoded}{Cookie: csrf=ZOxgq4P_WMgLjCm3J4mWPEFFNhmIUiHlq9of5JhtKys}{charset: utf-8}{User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-Length: 92}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader#15b170d89 pairs: {POST /magnoliaAuthor/.magnolia/admincentral HTTP/1.1: null}{Content-Type: application/x-www-form-urlencoded}{Cookie: csrf=ZOxgq4P_WMgLjCm3J4mWPEFFNhmIUiHlq9of5JhtKys}{charset: utf-8}{User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-Length: 92}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection getInputStream0
FINE: sun.net.www.MessageHeader#52ae5ad55 pairs: {null: HTTP/1.1 302}{Set-Cookie: JSESSIONID=88DCCC46C9E70CBA8262CF8060A033C0; Path=/magnoliaAuthor; HttpOnly}{Location: /magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0}{Content-Length: 0}{Date: Wed, 03 Nov 2021 19:37:01 GMT}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection followRedirect0
FINE: Redirected from http://localhost:8080/magnoliaAuthor/.magnolia/admincentral to http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: ProxySelector Request for http://localhost:8080/magnoliaAuthor/.magnolia/admincentral;jsessionid=88DCCC46C9E70CBA8262CF8060A033C0
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection plainConnect0
FINEST: Proxy used: DIRECT
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection writeRequests
FINE: sun.net.www.MessageHeader#774fca3c4 pairs: {User-Agent: Java/1.8.0_181}{Host: localhost:8080}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: close}
Nov 03, 2021 8:37:01 PM sun.net.www.protocol.http.HttpURLConnection getInputStream0
FINE: sun.net.www.MessageHeader#57256a0d6 pairs: {null: HTTP/1.1 400}{Content-Type: text/html;charset=utf-8}{Content-Language: en}{Content-Length: 2244}{Date: Wed, 03 Nov 2021 19:37:01 GMT}{Connection: close}
Digging deeper I found out that, when HttpURLConnection initiates a POST on a reused connection but finds the socket closed, it will internally recover and open a new connection. If this POST succeeds and the server sends a redirect status (302) it will attempt to follow the redirect. However, internally it fails to correctly initialise the request headers: after creating a new set of headers, it will not set the HTTP method because failedOnce is true at this point from the first POST on the closed socket
Update: this is now tracked as a bug.
Update 2: this has now been fixed

How to suppress htmlunit (Java library) warning/error messages?

I'm using htmlunit [http://htmlunit.sourceforge.net/] and it spews out a bunch of warnings/error:
Mar 24, 2017 6:37:30 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:31 PM com.gargoylesoftware.htmlunit.html.InputElementFactory createElementNS
INFO: Bad input type: "datetime", creating a text input
Mar 24, 2017 6:37:31 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'application/x-javascript'.
Mar 24, 2017 6:37:32 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'application/x-javascript'.
Mar 24, 2017 6:37:34 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:34 PM com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter runtimeError
SEVERE: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' error: Invalid selector: :x).] sourceName=[https://www.example.com/bundles/jquery?v=u8J3xxyrazUhSJl-OWRJ6I82HpC6Fs7PQ0-l8XzoZXY1] line=[1] lineSource=[null] lineOffset=[0]
Mar 24, 2017 6:37:35 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:35 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:35 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:36 PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'text/javascript'.
Mar 24, 2017 6:37:43 PM com.gargoylesoftware.htmlunit.javascript.host.dom.Document createElement
INFO: createElement: Provided string 'iframe name="rufous-frame-29_-1">https://platform.twitter.com/widgets.js] line=[9] lineSource=[null] lineOffset=[0]
I've looked at other resources and tried to turn it off by:
Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
Logger.getLogger("org.apache.http").setLevel(Level.OFF);
and:
final WebClient webClient = new WebClient(BrowserVersion.EDGE);
but it does not work.
What else can be done to suppress these warning/error messages?
If you are not going set the loggers to OFF in 'logging.properties' file then you need pin the loggers with a hard reference before you set the level to OFF.
Here is a corrected example based off your code:
private static final Logger[] PINNED_LOGGERS;
static {
System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "fatal");
PINNED_LOGGERS = new Logger[]{
Logger.getLogger("com.gargoylesoftware.htmlunit"),
Logger.getLogger("org.apache.http")
};
for (Logger l : PINNED_LOGGERS) {
l.setLevel(Level.OFF);
}
}
I put the following at the start of the application and the errors/warnings stopped:
System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "fatal");
Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
Logger.getLogger("org.apache.http").setLevel(Level.OFF);

Remove square brackets from the JSON output

Hello all i wanted to remove the square brackets from the json output.
[
{
"author": "Mark Twain",
"book": "The Adventures of Tom Sawyer",
"cost": "$68",
"id": "1"
},
{
"author": "Arthur Conan Doyle",
"book": "The Adventures of Sherlock Holmes",
"cost": "$97",
"id": "2"
}
]
I have used the below one to remove the brackets and get the output if i am correct
List<Book> list = new ArrayList<Book>();
list=(List<Book>)JSONArray.toList(
JSONArray.fromObject(books.values()),
new Object(),
new JsonConfig()
);
return list;
added the required jars.But my i am getting an error(console output)
WARNING: Tried to assign property author:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property book:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property cost:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property id:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property author:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property book:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property cost:java.lang.String to bean of class java.lang.Object
Jul 29, 2016 5:16:45 PM net.sf.json.JSONObject toBean
WARNING: Tried to assign property id:java.lang.String to bean of class java.lang.Object
and my postman gives me a 500 internal server error
Any help appreciated
Thank you

Java multi-line regular expression debugging

In Java, the following regular expression
To: a#b\.com.*Subject: Please verify your email address
somehow doesn't find the match in this text:
Dez 21, 2012 10:29:58 AM com.google.appengine.api.datastore.dev.LocalDatastoreService init
INFO: Local Datastore initialized:
Type: High Replication
Storage: In-memory
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: MailService.send
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: From:
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: To: a#b.com
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: Subject: Please verify your email address
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: Body:
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: Content-type: text/plain
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: Data length: 4
My Java code looks like this:
Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(input);
if (matcher.find()) {
...
}
This is a bit strange, since the pattern seems to work when I test it online with this tool: http://regexpal.com
So, Java must be interpreting the pattern a bit differently. Is there any way to get error messages of the Matcher?
Update It should find:
To: a#b.com
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: Subject: Please verify your email address
You'll want to use Pattern.DOTALL instead of Pattern.MULTILINE.
DOTALL makes the . match newlines. (Which is what you want)
MULTILINE makes ^ and $ work on a per-line basis.

Cayenne null pointer error when trying to commit changes

I'm running the following code that errors when I try to commit my changes using Cayenne as my ORM. The code is pasted below and errors out on the context.commitChanges();line. The output messages are pasted below the code. Any help on figuring this out would be appreciated.
import org.apache.cayenne.access.DataContext;
import java.util.*;
import com.jared.*;
public class Main {
public static void main(String[] args) {
DataContext context = DataContext.createDataContext();
Stocks theStock=(Stocks) context.createAndRegisterNewObject(Stocks.class);
theStock.setAsk(3.4);
theStock.setAvgdailyvolume(323849);
theStock .setBid(5.29);
theStock.setChange(-1.22);
theStock.setDayhigh(9.21);
theStock.setDaylow(2.11);
theStock.setLasttradeprice(5.11);
theStock.setLasttradesize(3827);
theStock.setOpen(6.21);
theStock.setPriorclose(4.21);
theStock.setShortratio(1.1);
theStock.setSymbol("^SP%");
theStock.setVolume(28193);
theStock.setLasttradedate(new Date());
context.commitChanges();
System.out.println("Done with the database");
}
}
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate startedLoading
INFO: started configuration loading.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataDomain
INFO: loaded domain: stocks
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate loadDataMap
INFO: loaded .
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: loading .
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: using factory: org.apache.cayenne.conf.DriverDataSourceFactory
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory load
INFO: loading driver information from 'stocksNode.driver.xml'.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory$DriverHandler init
INFO: loading driver org.hsqldb.jdbcDriver
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.DriverDataSourceFactory$LoginHandler init
INFO: loading user name and password.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.access.QueryLogger logPoolCreated
INFO: Created connection pool: jdbc:hsqldb:file:/hsqldb/data/stocks
Driver class: org.hsqldb.jdbcDriver
Min. connections in the pool: 1
Max. connections in the pool: 1
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate shouldLoadDataNode
INFO: loaded datasource.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate initAdapter
INFO: no adapter set, using automatic adapter.
Nov 20, 2008 11:20:37 PM org.apache.cayenne.conf.RuntimeLoadDelegate finishedLoading
INFO: finished configuration loading in 203 ms.
Exception in thread "main" org.apache.cayenne.CayenneRuntimeException: [v.3.0M4 May 18 2008 16:32:02] Commit Exception
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:1192)
at org.apache.cayenne.access.DataContext.commitChanges(DataContext.java:1066)
at Main.main(Main.java:24)
Caused by: java.lang.NullPointerException
at org.apache.cayenne.access.DataDomainInsertBucket.createPermIds(DataDomainInsertBucket.java:101)
at org.apache.cayenne.access.DataDomainInsertBucket.appendQueriesInternal(DataDomainInsertBucket.java:76)
at org.apache.cayenne.access.DataDomainSyncBucket.appendQueries(DataDomainSyncBucket.java:80)
at org.apache.cayenne.access.DataDomainFlushAction.preprocess(DataDomainFlushAction.java:183)
at org.apache.cayenne.access.DataDomainFlushAction.flush(DataDomainFlushAction.java:135)
at org.apache.cayenne.access.DataDomain.onSyncFlush(DataDomain.java:821)
at org.apache.cayenne.access.DataDomain$2.transform(DataDomain.java:788)
at org.apache.cayenne.access.DataDomain.runInTransaction(DataDomain.java:847)
at org.apache.cayenne.access.DataDomain.onSync(DataDomain.java:785)
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:1164)
... 2 more
user name, password?
ClientConnection connection = new
HessianConnection("http://localhost:8080/cayenne-service",
"cayenne-user", "secret",
null);

Categories

Resources