how to extract the requested URL in rest assured? - rest-assured

I want to extract the requested URL in rest assured, I tried with given().log().all()
which is logging everything, I just want to extract only my Request URI.

given().log().uri() would print the request uri in consloe

"QueryableRequestSpecification" is an interface in Rest-Assured, which provides methods like: getBaseUri(), getBasePath(), getBody(), getHeaders() etc.
In order to provide reference to above interface you need to use: SpecificationQuerier.query() method.
Note: You might need to do some changes in your existing code. Because you need to store all the given parameters in the reference of RequestSpecification and then it's reference needs to be used to call get/post/put/delete methods.
Refer below code: (You need to provide valid baseUri and basePath)
RequestSpecification requestSpec= RestAssured.given().baseUri("Some Base URI").basePath("/SomeBasePath");
requestSpec.get();
QueryableRequestSpecification queryRequest = SpecificationQuerier.query(requestSpec);
String retrieveURI = queryRequest.getBaseUri();
System.out.println("Base URI is : "+retrieveURI);
String retrievePath = queryRequest.getBasePath();
System.out.println("Base PATH is : "+retrievePath);

If like me you have a basePath with pathParameters, using queryRequest.getBasePath() will only return the value you built the path with:
example
RequestSpecification requestSpec= RestAssured.given().baseUri("http://example.com").basePath("/{someid}/info");
requestSpec.get();
QueryableRequestSpecification queryRequest = SpecificationQuerier.query(requestSpec);
String retrievePath = queryRequest.getBasePath();
System.out.println("Base PATH is : "+retrievePath);
will return Base PATH is : /{someid}/info
if you need the full url with resolved basePath, use getURI() instead
String retrievePath = queryRequest.getURI();
System.out.println("Full PATH is : "+retrievePath);
will return Full PATH is : http://example.com/1234/info
your IDE might show the method in red like mine did (intelliJ) not sure why,
but here is the reference for the method : https://javadoc.io/doc/io.rest-assured/rest-assured/3.1.1/io/restassured/specification/QueryableRequestSpecification.html#getURI--

Related

Vaadin URL Mapping

Is there a way do not enter a specifc url mapping (vaadin.urlMapping)? But I also want to still use swagger for example (ip:8080/swagger-ui/index.html)? It would be great to exclude some mappings from vaadin.
Thanks for your help!
Best Regards, Thomas
Put the URL/Part of URL/IP in the properties file.
Put the URL/Part of URL/IP in the web.xml file.
In some cases you want the remote URL to be different than the local URL (or remote SSL URL to be different than the local URL).
In that case, I placed both IP and domain on to web.xml in two different contexts.
final String serverUrl = new URL("" + ((VaadinServletRequest)VaadinService.getCurrentRequest())
.getHttpServletRequest().getRequestURL()).getAuthority();
final String serverProtocol =
((VaadinServletRequest)VaadinService.getCurrentRequest()).getHttpServletRequest().getProtocol();
final boolean serverSecure =
((VaadinServletRequest)VaadinService.getCurrentRequest()).getHttpServletRequest().isSecure();
if(!serverSecure){
UI.getCurrent().getSession().setAttribute(
ResourceProperty.configBundle.getString("APPLICATION_URL"),
"http:" + serverUrl);}
else{
UI.getCurrent().getSession().setAttribute(
ResourceProperty.configBundle.getString("APPLICATION_URL"),
"https:" + serverUrl);}

HttpContext AbsolutePath goes to wrong URL for aliased pages - C#

On my website each page has links that are created in the codebehind, where the links are the current URL with one query parameter changed. To do this, I've been using this method (this specific example is for the pagination):
var queryValues = HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
queryValues.Set("page", num);
string url = HttpContext.Current.Request.Url.AbsolutePath;
string updatedQueryString = "?" + queryValues.ToString();
string newUrl = url + updatedQueryString;
return newUrl;
This worked on my local version fine. However, when I created each page in Ektron and added a manual alias, the URLs generated still went to the file location in the solution. For example, my original page was /WebAssets/Templates/EventListView.aspx. I created the page in Ektron as /Alumni/Events/List. I can go to /Alumni/Events/List, but then when I click on a page button the page that loads is /WebAssets/Templates/EventListView.aspx?page=2 instead of /Alumni/Events/List/?page=2
I found one solution:
var rawUrl = HttpContext.Current.Request.RawUrl;
var url = rawUrl.Split('?')[0];
string newUrl = url + updatedQueryString;
Use the QuickLink property of the primary contentblock for /Alumni/Events/List, this will be the alias use want to use for your page links or for redirects to the same page. This is probably ContentData.QuickLink if you're already loading the ContentData at some point in the code.
Notes:
Aliasing may remove your "page" querystring parameter by default, to resolve this issue, edit your alias in the Workarea to have a "Query String Action" of "Append".
Make sure you preprend a "/" to the QuickLink value (if it's not absolute and not prepended already) if using it on the frontend, otherwise your links will bring you to something like /Alumni/Events/List/Alumni/Events/List?page=2, which is no good.

get absolute path for an image to send in email

I have a view (with one or more images) that I also want to use as the body of an email message. The Model serving the view uses Url.Content() to retrieve the absolute image path. This approach works fine for web pages, but when I render the exact same view as the body of the email, then the image can not be found which is suggested by the incomplete path from the rendered html.
<img src="/Media/fe882a1d-3b77-4264-ab91-cade985ecbed.JPG"/>
I know that this problem can be fixed if I could access the full url such as with Url.Action with the
Request.Url.Scheme
overload for protocol. Is there a way to determine the fully qualified URL from Url.Content?
Try writting your own url extension method and resolve with the help of Uri.GetLeftPart & UriPartial.Authority
public static class UrlExtensions
{
public static string AbsoluteContent(this UrlHelper urlHelper
, string contentPath)
{
Uri requestUrl = urlHelper.RequestContext.HttpContext.Request.Url;
string absolutePath = string.Format("{0}{1}",
requestUrl.GetLeftPart(UriPartial.Authority),
urlHelper.Content(contentPath));
return absolutePath;
}
}
Then use Url.AbsoluteContent("~/media/image.jpeg") in your pages. It will render http://domain/media/image.jpeg

Map routes with combined URL parameter

User can download price information PDFs located in a folder PriceInformations with subfolders specifying the document type, e.g.:
/PriceInformations/Clothes/Shoes.pdf
/PriceInformations/Clothes/Shirts.pdf
/PriceInformations/Toys/Games.pdf
/PriceInformations/Toys/Balls.pdf
Consider following action in Controller Document to download those PDFs:
// Filepath must be like 'Clothes\Shoes.pdf'
public ActionResult DownloadPDF(string filepath)
{
string fullPath = Path.Combine(MyApplicationPath, filepath);
FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
return base.File(fileStream, "application/pdf");
}
To get a PDF document, my client wants URLs to be like:
/PriceInformations/Clothes/Shoes.pdf
I could easily create an overload function for this case:
public ActionResult DownloadPDF(string folder, string filename)
{
return this.DownloadPDF(Path.Combine(folder, filename);
}
And map it like
routes.MapRoute(
"DownloadPriceInformations",
"DownloadPriceInformations/{folder}/{filename}",
new
{
controller = "Document",
action = "DownloadPDF"
});
But I'm curious if it would be possible to work without an overload function and to map this case in RegisterRoutes in Global.asax, so to be able to create one single parameter out of of multiple parameters:
routes.MapRoute(
"DownloadPriceInformations",
"DownloadPriceInformations/{folder}/{filename}",
new
{
controller = "Document",
action = "DownloadPDF",
// How to procede here to have a parameter like 'folder\filename'
filepath = "{folder}\\{filename}"
});
Question became a bit longer but I wanted to make sure, you get my desired result.
Sorry, this is not supported in ASP.NET routing. If you want multiple parameters in the route definition you'll have to add some code to the controller action to combine the folder and path name.
An alternative is to use a catch-all route:
routes.MapRoute(
"DownloadPriceInformations",
"DownloadPriceInformations/{*folderAndFile}",
new
{
controller = "Document",
action = "DownloadPDF"
});
And the special {*folderAndFile} parameter will contain everything after the initial static text, including all the "/" characters (if any). You can then take in that parameter in your action method and it'll be a path like "clothes/shirts.pdf".
I should also note that from a security perspective you need to be absolutely certain that only allowed paths will be processed. If I pass in /web.config as the parameter, you must make sure that I can't download all your passwords and connection strings that are stored in your web.config file.

What's the best way to get the current URL in Spring MVC?

I'd like to create URLs based on the URL used by the client for the active request. Is there anything smarter than taking the current HttpServletRequest object and it's getParameter...() methods to rebuilt the complete URL including (and only) it's GET parameters.
Clarification: If possible I want to resign from using a HttpServletRequest object.
Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:
public static String makeUrl(HttpServletRequest request)
{
return request.getRequestURL().toString() + "?" + request.getQueryString();
}
I don't know about a way to do this with any Spring MVC facilities.
If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
And then use this to get the request bound to the current Thread:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Instead of using RequestContextHolder directly, you can also use ServletUriComponentsBuilder and its static methods:
ServletUriComponentsBuilder.fromCurrentContextPath()
ServletUriComponentsBuilder.fromCurrentServletMapping()
ServletUriComponentsBuilder.fromCurrentRequestUri()
ServletUriComponentsBuilder.fromCurrentRequest()
They use RequestContextHolder under the hood, but provide additional flexibility to build new URLs using the capabilities of UriComponentsBuilder.
Example:
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
builder.replaceQueryParam("someBoolean", false);
URI newUri = builder.build().toUri();
Java's URI Class can help you out of this:
public static String getCurrentUrl(HttpServletRequest request){
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
String userInfo = url.getUserInfo();
String scheme = url.getProtocol();
String port = url.getPort();
String path = request.getAttribute("javax.servlet.forward.request_uri");
String query = request.getAttribute("javax.servlet.forward.query_string");
URI uri = new URI(scheme,userInfo,host,port,path,query,null)
return uri.toString();
}
in jsp file:
request.getAttribute("javax.servlet.forward.request_uri")
You can also add a UriComponentsBuilder to the method signature of your controller method. Spring will inject an instance of the builder created from the current request.
#GetMapping
public ResponseEntity<MyResponse> doSomething(UriComponentsBuilder uriComponentsBuilder) {
URI someNewUriBasedOnCurrentRequest = uriComponentsBuilder
.replacePath(null)
.replaceQuery(null)
.pathSegment("some", "new", "path")
.build().toUri();
//...
}
Using the builder you can directly start creating URIs based on the current request e.g. modify path segments.
See also UriComponentsBuilderMethodArgumentResolver
If you need the URL till hostname and not the path use Apache's Common Lib StringUtil, and from URL extract the substring till third indexOf /.
public static String getURL(HttpServletRequest request){
String fullURL = request.getRequestURL().toString();
return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3));
}
Example: If fullURL is https://example.com/path/after/url/ then
Output will be https://example.com
System.out.println(((HttpServletRequest)request).getRequestURI());
I used it. hope it's useful.

Resources