org.javalite.http.HttpException: Failed URL: "https://google.in" - httpexception

I'm facing an issue when executing a simple program in Javalite where I'm testing an API GET call.
The method fetches the URL and reads the response code. But JavaLite is throwing as exception:
org.javalite.http.HttpException: Failed URL: "https://google.in"
Could someone help me understanding this issue?
My code is:
package com.java.lite;
import org.javalite.http.Get;
import org.javalite.http.Http;
import org.testng.annotations.Test;
public class GetCallTest {
#Test
public void getCall() throws Exception {
System.out.println(ConfigPropertyFile.getPropertyValues()); //This line is executed
Get get = Http.get(ConfigPropertyFile.getPropertyValues()); //URL being call from another class where I defined a static method.
System.out.println("Response code" + get.responseCode());
System.out.println("Response message = `enter code here`" + get.responseMessage());
}
}

The URL you are trying returns a redirect to https://www.google.co.in/
Please try:
System.out.println(Http.get("https://www.google.co.in/").text());
and you will get a text of the Google home page.

Related

How to assert the content of a service message exception in a Grails unit test

I am using Grails 4.0.3 and want to assert that an exception is thrown in a given situation. Below, my PidService.
def validatePidIssuingConclusionDocument(JSONObject pidIssuingConclusionDocument){
String message = "Document issuing number is mandatory"
if(!pidIssuingConclusionDocument.has("docIssuingNumber")){throw new Exception(message)}
}
Below, my test case:
void "wrong document"() throws Exception {
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
pidService.buildPidIssuingOrder(documentWithoutIssuingNumber)
// How can I assert that the exception is thrown and verify it message.
}
I tried to use try/catch in the test case without success. Could anyone help me? I need to assert that the exception is thrown and the message is Document issuing number is mandatory in the given case.
I need to assert that the exception is thrown and the message is
Document issuing number is mandatory in the given case.
I can't provide an executable example around the code you provided because some things are missing (like buildPidIssuingOrder). See the project at https://github.com/jeffbrown/dnunesexception which contains an example that shows a way to deal with the exception in a test though.
grails-app/services/dnunesexception/PidService.groovy
package dnunesexception
import org.grails.web.json.JSONObject
class PidService {
def buildPidIssuingOrder(JSONObject pidIssuingConclusionDocument) {
throw new Exception('Document issuing number is mandatory')
}
}
src/test/groovy/dnunesexception/PidServiceSpec.groovy
package dnunesexception
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification
import org.grails.web.json.JSONObject
class PidServiceSpec extends Specification implements ServiceUnitTest<PidService>{
void "test something"() {
when:
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
service.buildPidIssuingOrder(documentWithoutIssuingNumber)
then:
def e = thrown(Exception)
and:
e.message == 'Document issuing number is mandatory'
}
}

How to check a cookie name is “not” present on page using Katalon Studio?

I need to check that a cookie is "NOT" present on-page.
Based on this post, I have tried the following on the scripted Katalon mode:
added these to the standard import from the test case:
import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory
import org.openqa.selenium.WebDriver as WebDriver
then I wrote:
WebUI.verifyMatch(driver.manage().getCookieNamed('foo'), is(null()))
and then I get the following error on null pointer
FAILED Reason:
java.lang.NullPointerException: Cannot invoke method call() on null object
Is there a way to write a check on "none" existing cookies using the script mode for Katalon Studio?
P.S:
I have tried this other approach
try {
_fbp = driver.manage().getCookieNamed('_fbp').getName()
}
catch (Exception e) {
String _fbp = new String('Something went wrong')
System.out.println('Something went wrong')
}
WebUI.verifyMatch('Something went wrong', _fbp, false)
It fails only on the verifyMatch part. It seems that 'something went wrong' does not really get stored in the variable _fbp.
FAILED.
Reason:
groovy.lang.MissingPropertyException: No such property: _fbp for class:
WebUI.verifyMatch() is used for checking matching between two strings.
You can do that using the plain Groovy assert. Instead of
WebUI.verifyMatch(driver.manage().getCookieNamed('foo'), is(null()))
do this:
assert driver.manage().getCookieNamed('foo').is(null)

FOP image not found error

I'm trying to use an external graphic with xslt for PDF generation. Most images are working fine but every now and again one is 'not found' despite being viewable on a web browser. Here's the error that FOP spits out:
11:29:15.653 [main] ERROR org.apache.fop.apps.FOUserAgent - Image not found. URI: http://memesvault.com/wp-content/uploads/Derp-Meme-031.jpg. (No context info available)
And here's my external-graphic section:
<xsl:variable name="mediaUrl">
<xsl:value-of select="mediaUrl" />
</xsl:variable>
<fo:external-graphic src="url('{$mediaUrl}')"
height="200"
max-width="200"
content-width="scale-to-fit" />
Any idea what I'm doing wrong?
Edit: it looks like this problem is related to a server not permitting access for the automated request. Is there a way to set the User Agent's URIResolver in fop 2.1? It appears that this functionality existed in prior versions but I can't seem to find a way to do it with 2.1.
So the reason why this happened is because, as suggested by lfurini, the server was blocking the request because of the user agent. One can work around this by using a custom URIResolver with FOP:
URIResolverAdapter uriResolverAdapter = new URIResolverAdapter(new UserAgentUriResolver());
FopFactoryBuilder builder = new FopFactoryBuilder(URI.create("/"), uriResolverAdapter);
fopFactory = builder.build();
And here's a very simple URIResolver which adds in the user agent.
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class UserAgentUriResolver implements URIResolver {
private static final String USER_AGENT = "whatever";
#Override
public Source resolve(String href, String base) throws TransformerException {
try {
URL url = new URL(href);
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", USER_AGENT);
return new StreamSource(connection.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Selenium test to test cookie

I want to write a selenium test that will check that when I log in to my application, and then re-open the browser, I'm automatically logged in using the saved cookie.
I thought that this may be possible to calling clearSession() between two #{selenium} blocks, but that seems to clear the cookie too. I've tested that this functionality works manually.
Any ideas how I'd test this.
For reference: Here's what I've tried.
#{fixture delete:'all', load:'../conf/User.yml' /}
#{selenium}
deleteAllVisibleCookies()
// Open the home page, and check that no error occurred
open('/')
waitForPageToLoad(1000)
assertNotTitle('Application error')
open('/login')
type('usernameOrEmail', 'marchaos')
type('password', 'password')
clickAndWait('css=input[type=submit]')
assertTextPresent('Welcome marchaos')
clearSession()
#{/selenium}
#{selenium}
// Open the home page, and check that no error occurred
open('/')
waitForPageToLoad(1000)
assertTextPresent('Welcome marchaos')
#{/selenium}
it fails at the last assertTextPresent()
I don't know about Selenium but you can do this in a functional test.
I do something like this:
Response loginResponse = FunctionalTest.GET("/user/login?login=test&password=test");
Map<String, Cookie> loginResponseCookies = loginResponse.cookies;
....
Request request = FunctionalTest.newRequest();
request.cookies = loginResponseCookies;
request.url = url;
return FunctionalTest.GET(request, url);

How does one save cookies in HTTP Builder 0.5.0/HTTPClient

I am trying per instructions here:
http://www.innovation.ch/java/HTTPClient/advanced_info.html
However, if I am using HTTP Builder, the following lines
System.setProperty("HTTPClient.cookies.save","true")
System.setProperty("HTTPClient.cookies.jar","/home/misha/.httpclient_cookies")
do not seem to create a file:
~/.httpclient_cookies
I will post a solution as always when figure it out.
:)
Misha
The HTTPClient you've linked is not the same as the apache HTTPClient that's bundled with the groovy HTTPBuilder. Take a look at this documentation for persisting cookies with apache HTTPClient.
Thank you. I went with a hackier solution:
#!/usr/bin/env groovy
import com.gargoylesoftware.htmlunit.WebClient
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT
import java.io.File
import org.apache.http.impl.cookie.BasicClientCookie
class HTTPBuilder extends groovyx.net.http.HTTPBuilder {
...
/**
* Load cookies from specified file
*/
def loadCookies(file) {
file.withObjectInputStream { ois->
ois.readObject().each { cookieMap->
def cookie=new BasicClientCookie(cookieMap.name,cookieMap.value)
cookieMap.remove("name")
cookieMap.remove("value")
cookieMap.entrySet().each { entry->
cookie."${entry.key}"=entry.value
}
client.cookieStore.addCookie(cookie)
println cookie
}
}
}
/**
* Save cookies to specified file
*/
def saveCookies(file) {
def cookieMaps=new ArrayList(new LinkedHashMap())
client.cookieStore.getCookies().each { cookie->
def cookieMap=[:]
cookieMap.version=cookie.version
cookieMap.name=cookie.name
cookieMap.value=cookie.value
cookieMap.domain=cookie.domain
cookieMap.path=cookie.path
cookieMap.expiryDate=cookie.expiryDate
cookieMaps.add(cookieMap)
println cookie
}
file.withObjectOutputStream { oos->
oos.writeObject(cookieMaps)
}
}
...
}