experiencing issue with route in play 1.2.5 - playframework-1.x

I probably have misconfigured my route file for play-1.2.5 - below is the relevant route file part & the URL being used:
URL:
GET /application/autoComplete?term=mac
Route:
GET /autoComplete/{term} controllers.Application.AutoCompleteTerm
I also have the following route defined but its not getting picked up:
GET /autoComplete/ controllers.Application.AutoCompleteTerm
The route does not get hit - instead, I get a template not found exception:
play.exceptions.TemplateNotFoundException: Template not found
Any suggestions to help troubleshoot this will be quite welcome. thanks

The route:
GET /autoComplete/{term} controllers.Application.AutoCompleteTerm
...is wrong. It should be like this:
GET /autoComplete/{term} Application.autoCompleteTerm
This would correspond to the following URL:
GET http://127.0.0.1:9000/autoComplete/mac
The corresponding method in Application would look like this:
public static void autoCompleteTerm(String term) {
...
}
The URL:
GET http://127.0.0.1:9000/autoComplete?term=mac
...would need the following route:
GET /autoComplete Application.autoCompleteTerm
...and the same method as above:
public static void autoCompleteTerm(String term) {
...
}

Related

Math regex express route

I'm tring to filter a route with param, but no success. I have 2 routes:
/all
/:id
I'm using typescript-rest to dynamic load, so there's no way to add the all route first.
Server.loadServices(this.appWebApi, 'app/resources/*.js', `${__dirname}`);
I have this 2 methods:
#GET
#Path("all")
async all(#Context context: ServiceContext) {}
#GET
#Path(":id")
async findById(#Context context: ServiceContext, #PathParam("id") id: string) {}
But both is called when i use /all. I tried to use ^(?!all):id but the parameter is not working.
So, how to filter this 2 routes?
I found a solution, the problem is related to typescript-rest package.
Here the proposed solution:
https://github.com/thiagobustamante/typescript-rest/issues/78#issuecomment-469232775

Yesod route interpolation in Julius via widgetFile

I think #{SomeRouteR} should work in .julius files, as described in:
https://www.yesodweb.com/book/shakespearean-templates#shakespearean-templates_julius_javascript
Everything was working when I first had this in my Handler:
toWidget [julius|
$("#examplespan").click(function(){
$.ajax({
url: #{ExampleR},
type: "POST",
...
|]
But now that I've changed my Handler to work like this:
$(widgetFile "example")
I added this code in example.julius:
$("#examplespan").click(function(){
$.ajax({
url: #{ExampleR},
type: "POST",
...
I now get the error:
[Error#yesod-core] expected EUrl but got Nothing for: DerefIdent (Ident "ExampleR")
CallStack (from HasCallStack):
error, called at ./Text/Shakespeare.hs:441:27 in shakespeare-2.0.20-3iMfZ8A5DXH3Twhu6IoWNc:Text.Shakespeare #(yesod-core-1.6.9-7g4SwkDmJJ261rdNBKrLzX:Yesod.Core.Class.Yesod ./Yesod/Core/Class/Yesod.hs:662:5)
What am I doing wrong?
There might not be anything wrong here. I will copy in a troubleshooting note I have written previously for my company.
DerefBranch Error from a Template File
I made a change in a template ({*.hamlet,*.cassius,*.lucius,*.julius}) and I get an error like this:
\"rawJS\")) (DerefBranch (DerefIdent (Ident \"tshow\")) (DerefIdent (Ident
\"errors\")))\nCallStack (from HasCallStack):\n error
This is an issue with [I believe] template Haskell and the way that we're compiling. Maybe it's some GHC flags, maybe it's GHCi itself, I'm not sure.
You can resolve this by touching the file that references the template, e.g., if your template file is templates/foo.julius, and you reference it with $(widgetFile "foo") in the Handler.Foo module, then touch (or save from your editor) the src/Handler/Foo.hs file and reload GHCi.

How can I create an Express route that handles URLs that look like this?

app.get('/:service[SOMETHING GOES HERE]', function(req, res, next){
console.log('Service is:', req.params.service);
});
This needs to catch URLs that can look like any one of:
/foo
/foo/bar
/foo/bar/baz
The call back isn't concerned with anything that comes after foo, but ideally should be able to access foo as a parameter called service without having to manually parse the path.
I've been using this to test and still haven't found anything that does exactly that. Closest so far is /:service*.
Edit: No it's not a duplicate of the one where the answer is /:service/* because that doesn't cover /foo.
Using /:service* in actual Express routes does exactly what you want:
/foo maps to { '0': '', service: 'foo' }
/foo/bar maps to { '0': '/bar', service: 'foo' }
/foo/bar/blah maps to { '0': '/bar/blah', service: 'foo' }
The Express Route Tester, for some reason, maps these URL's differently for that these kinds of patterns (it might be configured differently than Express).
You can use the app.use() function for that. Read the doc about path handling for more info. Your code once modified will be:
app.use('/foo', function(req, res, next){
console.log('Service is:', req.params.service);
});
The downside is that you are not going to recover foo as the service parameter.

Getting the "no type was found that matches the controller named" error message during Ajax Request

I've seen a lot of topics about this, but unfortunately I believe that each case is a different case (or most of them), and I really would love some experts opinion about my case in particular since I cannot make my code work even after reading through some of the other topics.
Situation: I am using an Ajax Request call in jQuery to a WebService method I have created in an WebApi project together with a MVC 4 Application.
My WebService controller class looks like the default, like this:
public class AdditionalInfoController : ApiController
{
//GET api/AdditionalInfo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
//GET api/AdditionalInfo/5
public string Get(int id)
{
return "value";
}
//PUT api/AdditionalInfo/5
public void Put(int id)
{
string test = "";
}
}
My Ajax Request from jQuery looks like this:
function GetAdditionalInfo(obj)
{
var request = jQuery.ajax({
url: "/api/AdditionalInfo/Get",
type: "GET",
data: { id: obj.id },
datatype: "json",
async: false,
beforeSend: function () {
},
complete: function () {
}
})
.done(function (a,b,c) {
alert("Additional info was retrieved successfully!");
})
.fail(function (a,b,c) {
alert("An error happened while trying to get the additional info!");
});
}
My WebAPIConfig file looks like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And last but not least, this is my problem: this error message keeps appearing when I browse the returned data variable in .fail and this is what is written:
"{
"Message":"No HTTP resource was found that matches the request URI 'http://localhost:59096/api/AdditionalInfo/Get?id=1'.",
"MessageDetail":"No type was found that matches the controller named 'AdditionalInfo'."
}"
I would really appreciate it if someone could help me as soon as possible. Thanks in advance!
Best regards,
Mad
Looking at the error looks like Web API is unable to find the controller 'type' AdditionalInfo. Web API uses assemblies resolver to scan through the assemblies and finds out the controller types. In your case for some reason its unable to find your 'AdditionalInfo' controller probably because it has some problem loading the assembly having this controller.
Try the following and see if there are any errors logged in your EventLog. If you notice any errors then probably you should check if your controllers are present in those assemblies.
Make the following change in Web.config to view errors in EventLog
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="WebApiDiagnostics" />
</listeners>
</trace>
</system.diagnostics>
In your WebApiConfig.cs, you can do the following:
IAssembliesResolver assembliesResolver = config.Services.GetAssembliesResolver();
ICollection<Assembly> assemblies = assembliesResolver.GetAssemblies();
StringBuilder errorsBuilder = new StringBuilder();
foreach (Assembly assembly in assemblies)
{
Type[] exportedTypes = null;
if (assembly == null || assembly.IsDynamic)
{
// can't call GetExportedTypes on a dynamic assembly
continue;
}
try
{
exportedTypes = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
exportedTypes = ex.Types;
}
catch (Exception ex)
{
errorsBuilder.AppendLine(ex.ToString());
}
}
if (errorsBuilder.Length > 0)
{
//Log errors into Event Log
Trace.TraceError(errorsBuilder.ToString());
}
BTW, some of the above code is actually from the DefaultHttpControllerTypesResolver which Web API uses to resolve the controller types.
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Dispatcher/DefaultHttpControllerTypeResolver.cs
Edited:
One more scenario where you could hit this problem is if your controller is nested inside another class. This was a bug which was fixed later though.
Ok, so I believe I found out what was going on. I am not entirely certain, but at least my problem got fixed.
Simply by changing what was inside of the "data" field in the Ajax call and I have created a class for an object in the application to hold the whole data. It seems that for some reason the method could not have the syntax "Get(int ID)".
Instead, I did something like "Get( object)" and in the Ajax Request something like "data: obj.ID" and voila, it worked.
Also, since the framework is picky about the names of the REST methods (Get, Post, Put and Delete), I changed the name of the method to something else (like Retrieve or something).
Hopefully this will help someone in the future as well.
Best regards,
Mad
Be sure that you have the same parameter names in your methods (int id) as well as in your WebApiConfig/RouteConfig. Try it by changing
public string Get(int id)
{
return "hello";
}
to
public string Get(int? id = null)
{
return "hello";
}
I had the same problem. with me it happens due to a crush in the visual studio (2012). I had the controller file open in visual studio but it wasn't a part of my solution - I couldn't find him in the controllers directory in the solution explorer.
I just added the file to the solution by right clicking on controllers directory => add => existing item.
that fixed the problem for me.
if that doesn't work maybe try to delete the controller and add a new one with the same code . . .

route query for play framework 1.2.5

I need to add a route for the following syntax:
http://www.testsite.com/select?term=query1
In my routes file, I tried using the following
GET /select/{term}
However, the above does not catch the URL - instead it goes to another handler in the config (placed beneath the handler for select/{term}:
GET /{auth}
Any thoughts on fixing or troubleshooting this would be most welcome. thanks
?term= means that term is a parameter - not part of the route you are trying to match
so you'd write
GET /select YourControllerClass.yourMethod
....
YourControllerClass extends Controller {
public static void yourMethod(String term){
Logger.debug("term=" + term);
}
}
If your URL was http://www.testsite.com/select/query1 then the route definition you provided above should work