Unable to call portlet resource url from javascript in liferay6.2 - javascript

I am using Liferay Portal 6.2 CE GA3
I need to call my custom portlet resource method from another portlet jsp file. Below is my code.
Click here
<script>
function myfunction(myVar){
AUI().use('aui-base','aui-io-request','liferay-portlet-url','aui-node',function(A){
var url = Liferay.PortletURL.createResourceURL();
url.setPortletId("MyCustomPortletId");
url.setResourceId('saveUserData');
A.io.request(url);
});
}
and my custom portlet ...
public class MyCustomPortlet extends MVCPortlet{
public void saveUserData(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
System.out.println("in save UserData");
}
render method----
}
Here serveResource method (in my case saveUserData ) is not getting called. Any suggestions ?

Did you try calling your method from your own custom portlet just to be sure your saveUserData method is being called and has no issues?
Please try and then read forward if it does not work ;-)
serveResource method is always named as serveResource and not by any other name as saveUserData when you use Liferay's MVCPortlet.
You cannot have multiple serveResource methods as you can have action methods.
So rename your method to serveResource() and it should work :-)

Related

Liferay - How to render JSP from #ResourceMapping annotated method. This method is being called from a JS file via AJAX

1st JSP: Calls a Javascript function:
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="continueTour" onclick="launchTutorial()">Take a Quick Tour</button>
</div>
Javascript function(s):
function launchTutorial(){
var enjoyhint_instance = new EnjoyHint({});
var enjoyhint_script_steps = [
{
"next #newAuthorizationActive": 'To create an authorization form'
}
];
enjoyhint_instance.set(enjoyhint_script_steps);
enjoyhint_instance.run();
//Here's where i'm accessing the 'exportFile' controller method (shown further below)
$.ajax({
type : "POST",
url : $('#authorizationResourceURL').val(),
data : {action: "redirectToEmpInfoForAuthTour", tourStatus : 0},
success : function(data){
alert('success');
document.open();
document.write(data);
document.close();
}
});
Method in the controller:
#ResourceMapping
protected void exportFile(ResourceRequest request, ResourceResponse response) throws IOException {
String action = ParamUtil.getString(request, "action", "");
if(action.equals("redirectToEmpInfoForAuthTour"))
{
//This is where I want to return the 2nd JSP from
}
A brief context to what exactly I'm looking for here:
I have a JSP (1st JSP), where I'm trying to show the user a tutorial (using enjoyhints) for the portlet. As a part of this tutorial, I need to highlight elements (select boxes, text fields) which are on different pages (JSPs) of the portlet. Hence, In the Javascript function, I first highlight (this highlighting part is whats taken care of by enjoyhints) the element that's there on the 1st JSP (and this works fine), and now I want to show the user the 2nd JSP, and using enjoyhints, highlight some element in the 2nd JSP, and so on in the 3rd and 4th JSPs too.
If anybody has an alternative way of how I can do this, kindly let me know. The main problem here is that the elements I need to highlight are on different JSP pages (of the same portlet). Had all the elements been on the same page, it would've been simple.
I'm using Liferay Portal, and Spring Portlet MVC as my design pattern.
UPDATE: Here's another thing that I've been trying to achieve the same thing, but no luck
You can define resource method as shown below with return type as
ModelAndView and show entire jsp content in popup or append to existing html.
#ResourceMapping
protected ModelAndView exportFile(ModelMap model,ResourceRequest request, ResourceResponse response){
}
You can simply change the signature of your ResourceMappingmethod to return a String.
The return value can be the name of your view (i.e. JSP).

cannot connect to Web API

I am new to WebAPI programming .Here is what have I done
Created ASP.NET web Application SampleWebApiProject in Visual Studio 2013
under .NET Framework 4.5.2
Selected MVC and checked Web API under [Add Folders and core references for].
using Nuget package installed knockout.js ,knockout-validation.js etc etc.
In my code for Login.cshtml I have html button
<div>
<button type="button" class="btn btn-info" data-bind="click:$parent.login">
Login
</button>
</div>
And on my click button I have
self.viewModelHelper.apiPost('api/account/login', unmappedModel,
function (result) {
}
And I have created API Controller called AccountApiController
public class AccountApiController : ApiController
{
[HttpPost]
[POST("api/account/login")]
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]AccountLoginModel accountModel)
{
return null;
}
}
However when I inspect the click event in Chrome developer tools I get an error response
POST http://localhost:64436/api/account/login 404 (Not Found).
this is my WebApiConfig
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Am I working with right type of application ?
Screenshot
Try:
self.viewModelHelper.apiPost('api/accountapi/login', unmappedModel,
function (result) {
}
and API Controller
public class AccountApiController : ApiController
{
[HttpPost]
[POST("api/accountapi/login")]
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]AccountLoginModel accountModel)
{
return null;
}
}
Your account controller is named accountapi and not account, so webapi can't find any controller called account.
I'm not sure, but your parameters look wrong in your webapi controller...
Why would you add HttpRequestMessage as a parameter?
You have called your controller AccountApiController and so api/account/login should be accountapi/login
Web API has a strict calls when it comes to MVC architecture.
If you call POST. It means that the API will really CREATE a new Entity, and Does NOT, make other request to be returned.
So meaning, the WebAPI is not custom API function Call that you thought it might be.
It is different from creating an individual API to Creating an web API inside an MVC Application.
Here is are some Notes.
GET : Retrieve an entity
PUT : update an entity
POST : create a new entity
DELETE : remove an existing entity.
so let us say you have an API for Account Models. I will say Models cause when creating an Web API. You need a Model. Unless you're creating your custom API. Outside the MVC.
Now you did this. api/account/test
What it will do is use the [GET] function.
Whatever function you have in the account controllers that have a Data Annotation of [GET] will be executed. And return you something.
And No. Don't use Login as the name of the Method just use GET as you can't really tell the Web API which function to use. It WILL use the one with the GET data annotation. So entering
api/account/ login <---- this will not call the login method, it is entering a string data to be passed to the Get Method.
[HttpGet]
public IEnumerable<string> Get()
{
return "No Value";
}
[HttpGet("{id}")]
public IEnumerable<string> Get(int id)
{
return "There is a value";
}
Now if you want the POST to be Called. Simply create a A Form that has a method of POST. Or JQuery Javascript and call generate the POST method for them. You can't write the Method call in the address bar. You just have to use the right kind of request to call the specific function or function with overload.

URL Routes with Java Servlets

I wanted to know if there is a way to do similar code in java servlet like I do in express.js
In express I can say for example:
app.get('/:name',function(bla bla)){}
the :/name its a parameter in which the url of the get can be
localhost/kevin
localhost/joe
or whatever... This is great because I can take then for example that name (request.params.name) and so something with it. And it is also great because there is no limit(As far as I know) as to how many routes I can create, it just serves as a placeholder.
Is there a way I can do this using Java servlets?? I want to be able to have an html page that when I click a button it goes to localhost/button1 If I click another button it goes to localhost/button2.. and so on.. But also I'm letting the user create buttons dynamically so I don't want to create jsp pages beforehand, I just want the servletto create one..?
Thanks
Almost. With help of a prefix mapping /foo/* and HttpServletRequest#getPathInfo().
#WebServlet("/name/*")
public class NameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getPathInfo().substring(1);
// ...
}
}
Invoke it as
http://localhost:8080/context/name/kevin
http://localhost:8080/context/name/joe
...
You can optionally map the servlet on /*, but then it will act like a global front controller which isn't necessarily a good idea as you'd have to take static resources like CSS/JS/images and such into account.
In case you actually intend to create a REST service, rather look at JAX-RS instead of "plain vanilla" servlets. It would further reduce boilerplate code. See also a.o. Servlet vs RESTful.

Accessing HTML element values(Webview) through Monoandroid

Unable to access HTML element values(Webview) through Monoandroid.
Context: - The Monoandroid App we are developing has a Webview Component in one of the layouts. We are loading/reusing our existing (registration page) HTML/JavaScript: having radio buttons(Male/female rdBtns).
But not able to access the selected radioButton values on "Submit" Button(outside the webview) click event.
Tried using the JavaScriptInterface with WebView,but not available.
Got the Value to a Java class through JNI, there to my C#(Unsuccessful)
Assumptions for the issue:
No Klue.
Question:
How can i get the value to mono event code?
Please suggest some alternative way to access the HTML element value outside the webview through MONODROID?
You should capture all request that are send by the website inside your webview like the submit of the data you`re interested in. Therefore you should add a WebViewClient to your WebView and implement
public bool ShouldOverrideUrlLoading (WebView view, string url)
Here is an example that I`m using to get the id of the currently (in the webview) selected feature of a map that is inside a WebView to display the corresponding details the user requested by clicking this object on the map.
The JavaScript-Code is just the href that is calling a function:
"Details...";
This is the function (where eventFeature is a global variable)
function getDetailsForSelectedStation() {
window.location.href = "www.ANFANGP" + eventFeature.attributes.saeulenid + "PDETAILANFRAGE";
}
(You could also directly set the href to our "fake"-url)
It should start like a usual adress so I used www. and then I used P to be able to tokenize the string in C#. The End-Tag "DETAILANFRAGE" will be used to catch this call in C#.
Now this is the WebViewClient to receive the message:
class MyWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading (WebView view, string url)
{
//check, whether this was a details-url
if (url.EndsWith ("DETAILANFRAGE")) {
//tokenize the url
string[] tokens = url.Split ('P');
long saeulenid;
if (long.TryParse (tokens [1], out saeulenid)) {
//Here you can work with the data retrieved from the webview
ShowDetailsByID(saeulenid);
...
}
}
return true;
}
}
The WebViewClient has to be added to the WebView:
MyWebView.SetWebViewClient(new MyWebViewClient());
If you need more context information you should override the constructor, too. I`m handing over the current activity to be able to start a new Activity (StartActivity() ) to display a view for details in my app.
By the way, to call JavaScript code from C# you just have to load an url like:
MyWebView.LoadUrl("javascript:myFunction(myParams)");
Very useful for debugging is the WebChromeClient.
See this tutorial from xamarin for more details
And of course you may find interesting information in the WebView reference

Wicket: How to show Javascript dialog when Form.MultiPart(true)

When I try to upload file in Wicket I've got the following exception:
"ERROR org.apache.wicket.RequestCycle.logRuntimeException(RequestCycle.java:1529) - ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
java.lang.IllegalStateException: ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
at org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest.<init>(MultipartServletWebRequest.java:113)..."
However, when I set form.MultiPart(true) I can't get Javascript dialog by using:
target.appendJavascript("Some Message");
Does somebody know how to use Javascript when Form.Multipart(true)?
Thanks!
If you want to call the alert dialog as a response for an ajax request, you can use the appendJavascript() method (the argument is javascript code, not a simple string, like the code you posted):
target.appendJavaScript("alert('Some message');");
If you want to call the alert when the page loads, you could use a behavior:
add(new AbstractBehavior() { // or Behavior, on Wicket 1.5
#Override
public void renderHead(Component component, IHeaderResponse response) {
response.renderOnLoadJavaScript("alert('Some message');");
}
});
It's also possible use a Label, and render directly to a <script> tag. Just remember to call setEscapeModelStrings(false):
add(new Label("alert", "alert('Some message');").setEscapeModelStrings(false));
and
<script type="text/javascript" wicket:id="alert"></script>

Categories