I have a Play 2.0 application with 3 different configurations (application.conf, test.conf and prod.conf)
Now I have a robots.txt file that should be delivered for only test.conf and for the rest environments it should give a 404 if someone tries to access it.
How can I configure my routes file to check if my application is using test.conf? Can I set some variable in test.conf that I can check in the routes file?
Something like this? (pseudo code)
#{if environment = "test"}
GET /robots.txt controllers.Assets.at(path="/public", file="robots.txt")
#{/if}
#{else}
GET /robots.txt controllers.Application.notFoundResult()
#{/else}
You can't add logic in the routes file.
I'd write a controller to serve the robots.txt file. Something like this:
In the routes file:
GET /robots.txt controllers.Application.robots
Then, in the controller, I'll test if I'm in a testing environment :
def robots = Action {
if (environment == "test") { // customize with your method
Redirect(routes.Assets.at("robots.txt"))
} else {
NotFound("")
}
}
I'm using Scala, but it can be easily translated to Java.
Edit - java sample
You can check if application is in one of three states: prod, dev or test, ie, simple method returning current state:
private static String getCurrentMode() {
if (play.Play.isTest()) return "test";
if (play.Play.isDev()) return "dev";
if (play.Play.isProd()) return "prod";
return "unknown";
}
you can use as:
play.Logger.debug("Current mode: "+ getCurrentMode());
of course in your case that's enough to use these condition directly:
public static Result robots() {
return (play.Play.isProd())
? notFound()
: ok("User-agent: *\nDisallow: /");
}
Related
When using feathersjs on both client and server side, in the app hooks (in the client) we receive an object with several fields, like the service, the method, path, etc.
I would like, with socket io, to add a custom field to that object. Would that the possible? To be more precise, I would like to send to the client the current version of the frontend app, to be able to force or suggest a refresh when the frontend is outdated (using pwa).
Thanks!
For security reasons, only params.query and data (for create, update and patch) are passed between the client and the server. Query parameters can be pulled from the query into the context with a simple hook like this (where you can pass the version as the __v query parameter):
const setVersion = context => {
const { __v, ...query } = context.params.query || {};
context.version = __v;
// Update `query` with the data without the __v parameter
context.params.query = query;
return context;
}
Additionally you can also add additional parameters like the version number as extraHeaders which are then available as params.headers.
Going the other way around (sending the version information from the server) can be done by modifying context.result in an application hook:
const { version } = require('package.json');
app.hooks({
after: {
all (context) {
context.result = {
...context.result,
__v: version
}
}
}
});
It needs to be added to the returned data since websockets do not have any response headers.
I am setting up Swagger for documenting my API.
I have set up the SwaggerEndpoint with a relative path the the specification json, like you see below:
When I debug locally, everything resolves fine. But my site just runs as http://localhost:44348/index.html.
When I deploy to IIS, which is on a virtual path, it blows apart:
Note that the URL in the browser has /imaging4castapi_UAT/ as part of the path
Note that the actual request for the swagger.json is missing that base part of the path.
Here's what I've tried:
I tried removing the RoutePrefix override. But that doesn't resolve.
I tried using an application path like "~/swagger/..." but that's translated by the server on view elements like Razor pages and css and doesn't work here in Startup.
I'm struggling to understand if this is a client setup issue or something related to how my site is hosted on IIS.
Thoughts?
Try using a relative path:
setupAction.SwaggerEndpoint("../swagger/Imaging4CastApiSpecification/swagger.json", "4Cast API");
Please note answer and explanation from the following issue: SwashBuckle
Here is my Swagger config for once of PRD application. Hope it helps
public static IServiceCollection AddSwaggerConfig(this IServiceCollection services, IHostingEnvironment env,
string title, string version)
=> services.AddSwaggerGen(c =>
{
//Ensure XML Document File of project is checked for both Debug and Release mode
c.IncludeXmlComments("Your App.xml");
//Display Enum name
c.DescribeAllEnumsAsStrings();
//c.OperationFilter<AddRequiredHeaderParameter>();
//Authentication for Bearer
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter JWT with Bearer into field",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", Enumerable.Empty<string>()}
});
c.SwaggerDoc(version, new Info
{
Title = title,
Version = version,
Description = "",
Contact = new Contact
{
Email = "Support#ABC.com",
Name = ""
}
});
});
Startup file
app.
//Swagger
.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./{_version}/swagger.json", Title);
});
The version is app variable from Config file which will be filtered by CI/CD
Swagger does not support Virtual Directory by default. Try and add this to your Startup.cs
app.UseSwagger(c =>
{
c.RouteTemplate = "virtual_path/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
//Include virtual directory
c.RoutePrefix = "virtual_path";// add your virtual path here.
c.SwaggerEndpoint("v1/swagger.json", "Api v1");
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./v1/swagger.json", "Api v1");
});
My fix was following Killnines last comment to remove the preceding forward slash so that it looks like the following;
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("swagger/v1/swagger.json", "Your API v1");
});
I am trying to test an ajax request with a basic install of Yii2. I am just using the SiteController::actionAbout() method to try this out.
public function actionAbout()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'hello world',
'code' => 100,
];
}
And in the test:
public function sendAjax(\FunctionalTester $I)
{
$I->sendAjaxGetRequest('site/about');
$r = $I->grabResponse();
die(var_dump($r));
}
The grab response method is one I wrote myself in a \Helper\Functional.php file:
public function grabResponse()
{
return $this->getModule('Yii2')->_getResponseContent();
}
When I dump out the response, I just see the html from the site/index page.
This happens for any route except the site default. If I try to do the same thing using site/index then it returns:
string(36) "{"message":"hello world","code":100}"
What am I missing / doing wrong?
Note the difference between a Yii route and the actual URL.
The argument to sendAjaxGetRequest() is the URL, not the route (at least if you pass it as a string, see below).
Dependent on your UrlManager config you might have URLs like /index.php?r=site/about, where the route is site/about. You can use the Url helper of Yii to create the URL:
$I->sendAjaxGetRequest(\yii\helpers\Url::to(['site/about']));
I am not sure about this but if you have the Codeception Yii2 module installed you should also be able to pass the route like this:
$I->sendAjaxGetRequest(['site/about']);
In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}
I want to send a request as JSON and in my controller I want to parse this JSON and get the parameters I want. for example this is the request:
{"param1":"val1"}
I want to parse this request and get "param1" value. I used request.JSON but still I got null. Is there any other way to solve this?
Thanks,
You can use one of the following to test your stuff (both options could be re-used as automated tests eventually - unit and integration):
write a unit test for you controller like (no need to start the server):
void testConsume() {
request.json = '{param1: "val1"}'
controller.consume()
assert response.text == "val1"
}
and let's say your controller.consume() does something like:
def consume() {
render request.JSON.param1
}
Or you can use for example the Jersey Client to do a call against your controller, deployed this time:
public void testRequest() {
// init the client
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
// create a resource
WebResource service = client.resource(UriBuilder.fromUri("your request url").build());
// set content type and do a POST, which will accept a text/plain response as well
service.type(MediaType.APPLICATION_JSON).accept(MediaType.TEXT_PLAIN).put(Foo.class, foo);
}
, where foo is a Foo like this:
#XmlRootElement
public class Foo {
#XmlElement(name = "param1")
String param1;
public Foo(String val){param1 = val;}
}
Here are some more examples on how to use the Jersey client for various REST requests:
https://github.com/tavibolog/TodaySoftMag/blob/master/src/test/java/com/todaysoftmag/examples/rest/BookServiceTest.java
Set it in your UrlMappings like this:
static mappings = {
"/rest/myAction" (controller: "myController", action: "myAction", parseRequest: true)
}
Search for parseRequest in latest Grails guide.
Then validate if it works correctly with curl:
curl --data '{"param1":"value1"}' --header "Content-Type: application/json" http://yourhost:8080/rest/myAction
In the controller method, check request.format. It should specify json. I'm guessing it won't here, but it may give you clues as to how your payload is being interpreted.
In your Config.groovy file, I would set the following values:
grails.mime.file.extensions = false
grails.mime.use.accept.header = false
In that same file, check your grails.mime.types. make sure it includes json: ['application/json', 'text/json'], which it probably will, but put it above */*. These entries are evaluated in order (this was true in pre 2.1 versions, havent' verified it is now, but what the heck). In conjunction with that, as aiolos mentioned, set your content-type header to one of the above mime-types.
Finally, test with curl, per Tomasz KalkosiĆski, or, to use RESTClient for FF, click on "Headers" in the very top of the client page (there are 4 clickable items at the top-left; headers is one. From a fresh RESTClient, you may have to choose "Custom Header". I can't recall)