Create request object from globals in TYPO3 - http

In Symfony you can do :
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
I'd like to know if there is something similar in TYPO3.
Thank you.

See this change https://review.typo3.org/#/c/40355/
[FEATURE] Introduce Request/Response based on PSR-7
The PSR-7 standard is adapted into the TYPO3 Bootstrap with a
backwards-compatible layer.
The PSR-7 implementation brings several new classes: * Message (the
base for Requests and Responses) * Request (for Requests made within
PHP) * ServerRequest and a factory based on the current system
environment * Response * Uri (a unified API for fetching several
parts of an URI)
At any TYPO3 request a new ServerRequest object is created inside the
Bootstrap and handed over to the RequestHandler which can then use
this object for checking certain GET and POST variables instead of
using GeneralUtility.
The proper call (usually a Controller) creates a Response object that
is handed back to the RequestHandler + Bootstrap. The TYPO3 Bootstrap
will output anything related in the shutdown() method.
An example is shown with the LoginController and currently hard-wired
as no proper routing/dispatching is there yet.
Currently this is an internal API as the rest (Dispatch/Router and
Controller API) will follow once the base is in.
Please note that the PSR-7 standard works with Value Objects meaning
that it is not possible to modify any object but instead new objects
will be created for Message, ServerRequest and Response if modified.
The next steps are:
* Integrate proper Routing + Dispatching for Backend Routes to register new BE requests
* Migrate all AJAX Calls to use the new API and request / response handling
* Introduce a common Base Controller for all regular BE requests which is based on Request/Response and works as a replacement for sc_base
* Then: proper documentation for the whole bootstrap / dispatch + routing / controller logic
* Integrate symfony console app into the CLI Bootstrap as alternative for Request/Response
* Refactor TSFE to use Response / Request objects properly
* Refactor redirects logic to use Response objects
see RequestHandler in EXT:backend/Classes/Http/ and EXT:frontend/Classes/Http for the usages in the core

Related

Service Fabric Web API Versioning issue

I'm working on a service fabric project with multiple stateless services. When i try to add versioning as in the code below
[Authorize]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class SessionController : Controller
{
...
}
it's not working when calling the service later using Postman or using some client winforms app i made just to call this service. And when i say it's not working i mean it's not looking for a specific version i placed in the controller.
e.g.
I'm calling http://localhost:1234/api/v1.0/session/set-session and as you can see in my controller i only have version 2.0. Now my API gets hit this way or another no matter what version number i put in.
I added code to the Startup.cs
services.AddApiVersioning(options => {
options.DefaultApiVersion = new ApiVersion(2, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
});
Specific API call looks like this:
[HttpPost]
[Route("set-session")]
public async Task<IActionResult> SetSession([FromBody] SessionModel model)
{ ... }
Can anyone tell me what am i missing or maybe api versioning is not supported in service fabric at all?
Thanks.
Does your solution work locally? Based on what I see, I would suspect - no. This should have nothing to do with Service Fabric at all.
Issue 1
I see that your base class inherits from Controller, which is allowed, but is usually ControllerBase. No concern there, just FYI. The crux of the problem is likely that your controller has not applied the [ApiController] attribute. API Versioning defines IApiControllerSpecification and IApiControllerFilter, which is used to filter which controllers should be considered an API. This is important for developers building applications that have the UI and API parts mixed. A controller is a controller in ASP.NET Core and it was difficult to distinguish these two in the early days. There is now a built-in IApiControllerSpecification that considers any controller with [ApiController] applied to be an API. This can be changed, replaced, or completely disabled using ApiVersioningOptions.UseApiBehavior = false.
If your library/application is only APIs, you can decorate all controllers at once using:
[assembly: ApiController]
Since your controller is not currently being considered an API, all requests matching the route are being directed there. The value 1.0 is being considered an arbitrary string rather than an API version. This is why it matches at all instead of HTTP 400. I suspect you must only have one API and it is defined as 2.0; otherwise, I would expect an AmbiguousActionException.
Issue 2
Your example shows that you are trying to version by URL segment, but you've configured the options to only consider the header x-api-version. This option should be configured with one of the following:
URL Segment (only)
options.ApiVersionReader = new UrlSegmentApiVersionReader();
URL Segment and Header
// registration order is irrelevant
options.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("x-api-version"));
Default (Query String and URL Segment)
// NOTE: this is the configuration
// options.ApiVersionReader = ApiVersionReader.Combine(
// new QueryStringApiVersionReader(),
// new UrlSegmentApiVersionReader());
Side Note
As defined, using the URL segment and header versioning methodologies don't make sense. You have a single route which requires an API version. A client will always have to include the API version in every request so there is no point to also supporting a header.
If you define 2 routes, then it makes sense:
[Route("api/[controller]")] // match by header
[Route("api/v{version:apiVersion}/[controller]")] // match by url segment
Versioning by URL segment, while common, is the least RESTful. It violates the Uniform Interface constraint. This issue demonstrates yet another problem with that approach. Query string, header, media type, or any combination thereof will all work with the single route template of: [Route("api/[controller]")]
Observation 1
You have configured options.AssumeDefaultVersionWhenUnspecified = true. This will have no effect when versioning by URL segment. It is impossible to provide a default value of route parameter in the middle of a template. The same would be true for api/value/{id}/subvalues if {id} is not specified.
This option will have an effect if you:
Add a second route template that doesn't have the API version parameter
You update your versioning strategy to not use a URL segment
It should be noted that is a highly abused feature. It is meant to grandfather in existing services that didn't previously have explicit versioning because adding it will break existing clients. You should be cognizant of that if that isn't your use case.

Get HTTP POST parameter order in Spring WebFlux application

I have the following method setup in a #RestController annotated class to handle a POST request and get access to the POST parameters (application/x-www-form-urlencoded):
#PostMapping("/path")
fun postHandlingMethod(#RequestBody body: MultiValueMap<String,String>): Mono<String> {
...
}
For legacy system compatibility I need to know the order of the POST parameters in the request. This is of course not possible when using a Map.
Does anybody know a simple way to make all the POST parameters accessible together with the ordering information or will I have to write my own HttpMessageReader?

Symfony redirect to dynamic route name

I'm using the Symfony CMF Routing Bundle to create dynamic routes (I'm using one example here):
$route = new Route('/dynamic-url');
$route->setMethods("GET");
$route->setDefault('_controller', 'AppBundle:MyRoute:getResponse');
$routeCollection->add('my-dynamic-route', $route);
The response is loaded from the getResponseAction() function inside the MyRouteController:
/**
* No annotations here, because I want the url to be dynamic from the database
*/
public function getResponseAction(Request $request) {
return $this->render('dynamic-page-template.html.twig');
}
When I go to '/dynamic-url', it works.
When in another controller, I want to redirect to this dynamic route, like this:
return $this->redirectToRoute('my-dynamic-route');
But I get this error: "None of the chained routers were able to generate route: Route 'my-dynamic-route' not found"
Also interesting: when I go to '/dynamic-url', the dev bar actually says that the Route name is 'my-dynamic-route'.
Edit
When I load all the routes, I don't see my dynamic route names:
$this->get('router')->getRouteCollection();
I think they should be in this list.
Since it's a dynamic route, which wasn't saved anywhere (like routing.yml ) it will be only availabe for Request where it has been defined. So at the end of Request your app will immediately "forget" about new Route generated at runtime.
When I load all the routes, I don't see my dynamic route names:
$this->get('router')->getRouteCollection();
I think they should be in this list.
Actualy No. It depends on where you call $this->get('router')->getRouteCollection();
Just try to call
dump($this->get('router')->getRouteCollection();)
right before the return statement in your Action where you're adding the my-dynamic-route route. I'm sure you'll see your my-dynamic-route in the list of routes, but if you call it anywhere else - you won't see it.
It's less about symfony rather about stateless nature of web (see Why say that HTTP is a stateless protocol?)
I started to think about this and pointed your question to an routing issue on symfony-cmf. You tagged with #symfony-cmf and i think this would be important feature for us.
I also think, when you persist your route with /my-route you should also ask the router for that name (or in case of the CMF with an content object with that a route.)
If you use the CmfRoutingBundle dynamic router, you should persist your routes to doctrine. The idea of dynamic here is that they can be created at runtime, e.g. in an admin interface or elsewhere by code. The DynamicRouter loads routes from the database.
If you use PHPCR-ODM, the route name is the repository id, typically something like /cms/routes/my-route and you can generate it with that name. If you have access to the route object loaded from the database, you can also generate from that, rather than the path. If you have to hardcode a path in your application, its an indication that probably a normally configured route would be better.
If you just add a route to the route collection on the fly, you would have to make sure that happens in each request, its only available when you add it. With the CMF ChainRouter you could register your own router that does that, but i would not know of a good use case for that. Either you know the route, then you can configure it in the routing.xml|yml|php config file. Or routes are loaded dynamically, in which point you should use DynamicRouter, potentially with a custom route loader.

How to render a Vaadin view from backend

In my application, the remote client is making a restful call to a backend method, say
#POST Response lookup(#Context HttpServletRequest request).
Then, if the request parameters satisfy certain conditions,
an Vaadin view, say ResultView is supposed to be rendered to client's browser. in other cases, lookup() returns without any confrontation with MyUI.
This boils down to creating a UI instance from the backend(?) How to do this? I tried (1) below and found out about (2).
1.) put #POST Response lookup(#Context HttpServletRequest request) into myUI. For this, i added to MyUI #Path("/lookup"). This is the only change I made to MyUI.
The following are the annotations on MyUI now:
#SuppressWarnings("serial")
#Theme("mytheme")
#Path("/lookup")
I havent changed web.xml mapping for the restful calls:
This didn't show any errors. However, didn't invoke lookup().
2.) make UIProvider create a UI instance as suggested in this post.
Vaadin #Push wouldn't work for this, i have to invoke a UI explicitly.
This may be a naive question, however i'm a backend developer-- not well familiar with servlet containers and this is my first time with Vaadin.
TIA

What is the query string of a BlazeDS request?

I have a Tomcat service running on localhost:8080 and I have installed BlazeDS. I created and configured a simple hello world application like this...
package com.adobe.remoteobjects;
import java.util.Date;
public class RemoteServiceHandler {
public RemoteServiceHandler()
{
//This is required for the Blaze DS to instantiate the class
}
public String getResults(String name)
{
String result = “Hi ” + name + “, the time is : ” + new Date();
return result;
}
}
With what query string can I invoke RemoteServiceHandler to my Tomcat instance via just a browser? Something like... http://localhost:8080/blazeds/?xyz
Unfortunately you can't. First the requests (and responses) are encoded in AMF and second I believe they have to be POSTs. If you dig through the BlazeDS source code and the Flex SDK's RPC library you can probably figure out what it's sending. But AFAIK this hasn't been documented anywhere else.
I think that AMFX (which is AMF in XML) will work for you, using HTTPChannel instead of AMFChannel.
From http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=lcarch_2.html#1073189, Channels and channel sets:
Flex clients can use different channel
types such as the AMFChannel and
HTTPChannel. Channel selection depends
on a number of factors, including the
type of application you are building.
If non-binary data transfer is
required, you would use the
HTTPChannel, which uses a non-binary
format called AMFX (AMF in XML). For
more information about channels, see
Channels and endpoints.
This way you can use simple netcat to send the request.
Not sure how authentication will be handled though, you will probably need do a login using Flash, extract the authentication cookie and then submit it as part of your request.
Please update this thread once you make progress so that we all can learn.

Resources