accessing host ip and port in play framework scala template? - scala

How to access the server host ip and port in playframework template?
Background
Let say I start play using the command on a server with ip: 192.168.1.10:
./activator "run 12345"
How to make the app/views/index.scala.html when I visit 192.168.1.10/index.html (assumed I have setup the appropriate route)?
<html>
<body>
192.168.1.10:12345
</body>
</html>

Maybe the simplest solution for you is using the HTTP request. Check out play.api.mvc.Http
/**
* The HTTP host (domain, optionally port)
*/
lazy val host: String = headers.get(HeaderNames.HOST).getOrElse("")
In Play! you can get access to the HTTP request by using the Action builder that accepts the function (Request) => Result
def getHostPort = Action { request =>
Ok(s"This page served from ${request.host}")
}
If your server is listening for HTTP on 192.168.1.10:12345 hitting that endpoint will render the string "This page served from 192.168.1.10:12345"
But you can easily modify it to pass request.host to your template

Related

Strange issue with Vertx Http request

I configured an HTTPS website on AWS, which allows visiting from a white list of IPs.
My local machine runs with a VPN connection, which is in the white list.
I could visit the website from web browser or by the java.net.http package with the below code:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://mywebsite/route"))
.GET() // GET is default
.build();
HttpResponse<Void> response = client.send(request,
HttpResponse.BodyHandlers.discarding());
But if I replaced the code with a Vertx implementation from io.vertx.ext.web.client package, I got a 403 forbidden response from the same website.
WebClientOptions options = new WebClientOptions().setTryUseCompression(true).setTrustAll(true);
HttpRequest<Buffer> request = WebClient.create(vertx, options)
.getAbs("https://mywebsite/route")
.ssl(true).putHeaders(headers);
request.send(asyncResult -> {
if (asyncResult.succeeded()) {
HttpResponse response = asyncResult.result();
}
});
Does anyone have an idea why the Vertx implementation is rejected?
Finally got the root cause. I started a local server that accepts the testing request and forwards it to the server on AWS. The testing client sent the request to localhost and thus "Host=localhost:8080/..." is in the request header. In the Vert.X implementation, a new header entry "Host=localhost:443/..." is wrongly put into the request headers. I haven't debug the Vert.X implementation so I have no idea why it behaviors as this. But then the AWS firewall rejected the request with a rule that a request could not come from localhost.

grab full url from ESP8266WebServer

This question must be a duplicate, but I cannot find the answer.
Using the ESP8266WebServer library, there is an uri() method to grab the uri. So in the example: http://example.com/index, it will grab /index, but I would also like to get the example.com. IS there a method for that?
The http(s)://host:port part is not sent to server. The client uses the hostname to resolve the IP address and then the client makes a connection to the IP address on the specified port.
But HTTP 1.1 has a mandatory Host header in requests to a HTTP server.
The ESP8266 Arduino ESP8266WebServer library makes the current request's headers accessible on the ESP8266WebServer instance. To get the Host header there is a hostHeader() method.
Example:
void handleRoot() {
Serial.print("The Host: header value: ");
Serial.println(server.hostHeader());
server.send(200, "text/plain", "hello from esp8266!\r\n");
}
Documentation for the ESP8266WebServer is here.

RestEASY + Jboss 7.x - can you default to first #Path when Accepts doesn't match #Produces value?

I have the following web service in RestEASY 3.6.2 on JBoss 7.1.0.
#GET
#Path("/getstuff")
#Produces(MediaType.APPLICATION_JSON + "," + MediaType.APPLICATION_XML)
public Response getStuff() {
I send a request with the following: Accept = application/json, text/javascript, */*; q=0.01
http://localhost:8080/myapp/getstuff
returns:
<html>
<head>
<title>Error</title>
</head>
<body>Internal Server Error</body>
</html>
When I specify Accept = application/json it returns the correct response.
Is there some "default fallback" I can use to make Resteasy use the first matching Path instead of failing?
Hello,
Accept header is used by HTTP clients specify for the server what content types will be accepted. The server will then send back a response, which will include a Content-Type header specifying to the client the kind of content actually is.
This is relevant because the requests might be POST or PUT requests.
This would explain the issue, therefore, cause the content type is conflicting with the Json.

Failed to connect GWT to BigCommerce API

Criteria: I'm trying to connect to a secured web service API called BigCommerce using GWT RequestBuilder.
This is my entry point:
public class GwtTest implements EntryPoint {
String url = "http://my-url-api/api/v2/products.xml"; // not the original url i'm using
#Override
public void onModuleLoad() {
url = URL.encode(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
builder.setHeader("Authorization", "Basic XXX"); // I generated this from Postman app on Chrome where things work perfectly
builder.setHeader("Access-Control-Allow-Credentials", "true");
builder.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8888/");
builder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
builder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");
builder.setHeader("Content-Type", "application/xml");
try {
builder.sendRequest(url, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
RootPanel.get().add(new HTML("Success: "+response.getText()));
}
#Override
public void onError(Request request, Throwable exception) {
RootPanel.get().add(new HTML("Failure (Response Error): "+exception));
}
});
} catch (RequestException e) {
RootPanel.get().add(new HTML("Failure Request Exception: "+e));
}
}
}
Errors encountered: I encounter the Same Origin Policy error at first:
Then After I disabled CORS on my browser I get the Perflight error:
Work-around: I was able to get results by disabling web security on Chrome but I don't think it's the right solution.
Trivial note: Please guide me on this one, guys, because I'm new to GWT and BigCommerce thanks.
Use a proxy servlet.
This is also the solution the GWT Openlayers wrappers uses.
https://github.com/geosdi/GWT-OpenLayers/blob/c3becee0cdd5eefdc40b18e4999c2744dc23363a/gwt-openlayers-server/src/main/java/org/gwtopenmaps/openlayers/server/GwtOpenLayersProxyServlet.java
Based on Rob Newton answer, if your application is pure front end, you can host your files on nginx and add some proxy_pass directive to your configuration, for example:
location ~* ^/bigcommerce/(.*) {
proxy_pass http://api.bigcommerce.com/$1$is_args$args;
}
So whenever you call http://hostaddress/bigcommerce/something, this will be forwared to http://api.bigcommerce.com/something. Headers are not forwared in this config, you can add more directives for that.
You could include a servlet in your webapp that acts as a proxy between the client and BigCommerce.
An alternative is to run a reverse proxy such as Apache httpd that makes requests to the BigCommerce server appear to be on the same host as your webapp.
Here is an example of an Apache httpd config file that will act as a reverse proxy for your webapp and an external service on a different host. To the browser both the webapp and the external service will appear to be running on the same host, which is what your want.
# file: /etc/httpd/conf.d/mywebapp.conf
<VirtualHost *:80>
ProxyPreserveHost On
# Forward requests to path /SomeExternalService to an external service
ProxyPass /SomeExternalService http://externalhost/
# Forward all other requests to a local webserver hosting your webapp,
# such as Tomcat listening on port 8081
ProxyPass / http://127.0.0.1:8081/
ProxyPassReverse / http://127.0.0.1:8081/
</VirtualHost>

How to add SSL Encryption to my http rest server on Spray

I'm building a http rest server on spray that routes Post Requests and I want to make it encrypted with ssl.
This is the example from official spray webstie i used to builed the server and i want to change it to be with ssl :
https://github.com/spray/spray-template/tree/on_spray-can_1.3/src/main/scala/com/example.
I have read here : http://spray.io/documentation/1.2.3/spray-can/http-server/#ssl-support
That i need to add ServerSSLEngineProvider Parameter to Http.Bind (its in the Boot.scala in example git above ) . But i don't know how to build right the ServerSSLEngineProvider and what to give it .
IO(Http) ? Http.Bind(service, interface = "0.0.0.0", port = 81 , ServerSSLEngineProvider = ???)
My question is what i need to put insted of the ??? here so my server will be ssl secured .
Thanks to the helpers.