how do I create a const URL in Dart? - dart

A (constructor) method (FirebaseOptions) in Dart expects a constant String.
Simply passing a string results in a URISyntaxException (even though it's a perfectly fine URL), so apparently I have to encode the String.
But the String has to be const and the Uri encoder doesn't return a const String.
mucking about

It is not possible with Uri implementation due constructor of the Uri class is not constant.
By the way you are able to create own, constant implementation of Uri interface:
class MyConstUri implements Uri {
const MyConstUri();
//... implement or generate all necessary methods
}
const Uri reallyConstUri = MyConstUri();

Related

Dart Encapsulation - private data

I know i can create a private property by prefixing its name with an underscore (_).
but if I put the class and the main function in the same file I can access to private properties
class User {
late String email;
late String _password;
User({required String email, required String password})
: email = email,
_password = password;
}
void main() {
User u = User(email: 'myemail#gmail.com', password: 'mypassword');
print(u._password); // I can access to this private property
}
if I move the User class to a separate file everything works like expected, and i can't access private properties
import 'user.dart';
void main() {
User u = User(email: 'myemail#gmail.com', password: 'mypassword');
print(u._password); // I can't access to this private property
}
I didn't understand the reason.
Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore (_), it's private to its library.
https://dart.dev/guides/language/language-tour#important-concepts.
So basically the underscore does not make "variable private" the way we are used to (from languages like Java or C#) but it makes private to the library (which, roughly saying, is the same as a Java package).
That's why if you put the directive part of 'main.dart'; in the user.dart and the directive part 'user.dart'; in the main.dart file you will be able to access the private field, even the class being in a different file. The part of and part directives makes two files the same library.
If you are curious why Dart uses underscores instead of access modifier keywords like public or private, see SDK issue #33383 https://github.com/dart-lang/sdk/issues/33383.
In a nutshell, from what I have understood: since the Dart language supports dynamic member access, it's far more performant use library level visibility than class-based visibility, as #eernstg said:
I think it's important to note that this is actually not about syntax. You could choose lots of different syntactic forms for the same thing, but it's the underlying structure that matters.
If you want to access a variable from a class, use this
class User {
late String email;
late String _password;
User({required String email, required String password})
: email = email,
_password = password;
//this is called a get function, which you can call from class instance.
String get getUserPassword => _password;
}
import 'user.dart';
void main() {
User u = User(email: 'myemail#gmail.com', password: 'mypassword');
print(u.getUserPassword); // changes here
}
Happy coding!!

AngularDart CurrentInstruction

I am trying to update angular2 to latest version. Several of the functions are missing
I would like to know what is the alternate for the following function
final RouteParams _params;
String get routeName => _router.currentInstruction.component.routeName;
How to get routeName from new AngularDart
Not possible to access current component route anymore.
I don't know what you want to do exactly and how you define your routeName, but you probably need to use additionalData of RoutePath or RouteDefinition
class AdditionalRouteData {
final String routeName;
const AdditionalRouteData({this.routeName});
}
final routePath = RoutePath(
path: '/',
additionalData: AdditionalRouteData(routeName: 'Home'),
);
// then get it that way
(router.current.routePath.additionalData as AdditionalRouteData).routeName;
However, if your routeName is dynamic, you must find a new way to access it (without the router, using a service via dependency injection)

how to extract the requested URL in 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--

OData routing for function with 2 parameters

Im creating OData controller and want it to support function with 2 params.
Here is my current code.
OData cofig:
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "hop";
builder.EntitySet<ScheduleDTO>("Schedules");
var function = builder.Function("GetByEntityAndJurisdiction");
function.Parameter<Guid>("EntityId");
function.Parameter<Guid>("JurisdictionId");
function.ReturnsCollectionFromEntitySet<ScheduleDTO>("Schedules");
Controller:
[ODataRoutePrefix("Schedules")]
public class ScheduleODataController : BaseODataManager, IScheduleODataManager
{
[ODataRoute]
public async Task<IHttpActionResult> GetAsync(ODataQueryOptions<ScheduleDTO> options)
{
.....
return Ok(schedules.Select(x => Mapper.Map<ScheduleDTO>(x)));
}
[HttpGet]
[ODataRoute("GetByEntityAndJurisdiction(EntityId={entityId}, JurisdictionId={jurisdictionId})")]
public async Task<IHttpActionResult> GetByEntityAndJurisdiction(ODataQueryOptions<ScheduleDTO> options, [FromODataUri] Guid entityId, [FromODataUri] Guid jurisdictionId)
{
.....
return Ok(schedules.Select(x => Mapper.Map<ScheduleDTO>(x)));
}
}
Starting my app, I have following error:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.OData.dll
Additional information: The path template 'Schedules/GetByEntityAndJurisdiction(EntityId={entityId}, JurisdictionId={jurisdictionId})' on the action 'GetByEntityAndJurisdiction' in controller 'ScheduleOData' is not a valid OData path template. The request URI is not valid. Since the segment 'Schedules' refers to a collection, this must be the last segment in the request URI or it must be followed by an function or action that can be bound to it otherwise all intermediate segments must refer to a single resource.
How to resolve this problem? Thanks in advance.
#Vladimir
In your controller, you add a prefix attribute [ODataRoutePrefix("Schedules")] on the controller. Doing so will add the prefix string at head of all the [ODataRoute] in the same controller. So, for below action
public async Task<IHttpActionResult> GetByEntityAndJurisdiction(ODataQueryOptions<ScheduleDTO> options, [FromODataUri] Guid entityId, [FromODataUri] Guid jurisdictionId)
{...}
the full Uri template should be:
Schedules/GetByEntityAndJurisdiction(EntityId={entityId}, JurisdictionId={jurisdictionId})
Obviously, This Uri is invalid because:
The collection of Schedules doesn't have a bound function named GetByEntityAndJurisdiction
Even though GetByEntityAndJurisdiction is a bound function, you should call the bound function through it's namespace-qualified function name.
Maybe, It's confused that you have build the function as the following codes:
var function = builder.Function("GetByEntityAndJurisdiction");
However, it means to build an unbound function. An unbound function is called through function import by issuing a GET request to a URL identifying the function import and passing parameter values using inline parameter syntax. The canonical URL for a function import is the service root, followed by the name of the function import.
So, you can change your codes as follows to make it work:
If you want to keep the model schema unchanged, that is to build GetByEntityAndJurisdiction as unbound function, please remove the ODataRoutePrefix("Schedules")] from your controller. Or create a new controller (any controller), move the action into the new controller but don't add the Prefix attribute.
If you want to change the schema and keep the controller unchanged, that is to GetByEntityAndJurisdiction as bound function.
Please do as follows :
var entity = builder.EntitySet<ScheduleDTO>("Schedules").EntityType;
var function = entity.Collection.Function("GetByEntityAndJurisdiction");
...
For more information about function, you can refer to OData.Org or Function Sample page, or Function blog.

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