GWT Window redirection problem - gwt

Hi I have this code in my gwt app which purpose is to chage to URL as follows:
public void goToSignUpPage(boolean isDeployed) {
String url = (isDeployed == true ? "signup.html" : "signup.html?gwt.codesvr=127.0.0.1:9997");
Window.Location.replace(url);
However what happens it redirects into this URL:
http://127.0.0.1:8888/mygwtapp/signup.html?gwt.codesvr=127.0.0.1:9997
Where the working URL is this:
http://127.0.0.1:8888/signup.html?gwt.codesvr=127.0.0.1:9997
BTW, mygwtapp is the gwt module named defined in MyGwtApp.gwt.xml
<module rename-to='mygwtapp'>
Any ideas why the URL is appended by the gwt module name? Any way to fix this?

All you needed was to add in GWT.getHostPageBaseURL() to get the full URL for your web application without it appending to the module name.
Try this out:
public void goToSignUpPage() {
String url = GWT.getHostPageBaseURL() + "signup.html";
if(!GWT.isProdMode()) {
Window.alert("We are in development mode!");
url += "?gwt.codesvr=127.0.0.1:9997";
}
Window.Location.replace(url);
}
I've also removed your parameter "isDeployed" and replaced it with GWT.isProdMode() within the method to check if you're in production or development mode.
With a paramater:
public void goToSignUpPage(Boolean isDeployed) {
String url = GWT.getHostPageBaseURL() + "signup.html";
if(!isDeployed) {
url += "?gwt.codesvr=127.0.0.1:9997";
}
Window.Location.replace(url);
}
Hope this helps!

Related

Wicket 6.x https with other host

I have a webpage with a area where users can login. This area
www.host.com/mypage/myarea
should be under https.
The problem is that my https is running on a another host:
www.something-foo.host.com/mypage/myarea
. (loadbalancer stuff...??? I dont know why)
My try is to annotate the Pages with #RequireHttps, an than rewrite the urls of the Pages.
But how and where? Has someone please an example?
Thanks for your help.
Well if you really want to this with Wicket your best option would be to write an implementation of IRequestMapperDelegate and set them during the onInit() process of your WicketApplication.
To give you an idea how to do this I've written an example of raping the HttpsMapper of Wicket:
setRootRequestMapper(new HttpsMapper(getRootRequestMapper(), new HttpsConfig(8080, 8443)) {
private final static String SUBDOMAIN = "www.something-foo.";
#Override
protected Scheme getSchemeOf(Request request) {
HttpServletRequest req = (HttpServletRequest) ((WebRequest) request).getContainerRequest();
// well that's basically cheating and not so nice... but we're not allowed to overwrite mapRequest()
// but that means that every request that doesn't start with the subdomain will be treated as HTTP aka
// insecure.
if (req.getServerName().startsWith(SUBDOMAIN) == false) {
return Scheme.HTTP;
}
return super.getSchemeOf(request);
}
#Override
protected String createRedirectUrl(IRequestHandler handler, Request request, Scheme scheme) {
// stolen from super implementation
HttpServletRequest req = (HttpServletRequest) ((WebRequest) request).getContainerRequest();
String url = scheme.urlName() + "://";
// except the part where we insert the subdomain
url += SUBDOMAIN;
url += req.getServerName();
if (!scheme.usesStandardPort(getConfig())) {
url += ":" + scheme.getPort(getConfig());
}
url += req.getRequestURI();
if (req.getQueryString() != null) {
url += "?" + req.getQueryString();
}
return url;
}
});
Depending on your question I can't really determine if this is a good solution ... it really depends on how many frameworks are working on top of Wicket. Since you didn't mention anything else I'm assuming none.

How to get currentPagePath in Slingservlet?

From some javascript I call the following Slingservlet with ("/bin/fooServlet?"+params);
#SlingServlet(paths = "/bin/fooServlet", methods = "GET", metatype = true)
public class FooServlet extends SlingAllMethodsServlet {
..
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
Session session = resourceResolver.adaptTo(Session.class);
Page currentPage = pageManager.getPage(request.getPathInfo());
String currentPagePath = currentPage.getPath();
...
}
My Question is: How to get the currentPagePath of the current Page in FooServlet? currentPagePath in the code is null.
As Thomas mentioned, if you define a servlet with fixed paths property, you wouldn't have reference to a Resource.
One way of achieving this is by passing your page path along with the request to the servlet. Also CQ.WCM.getPagePath() returns only /libs/wcm/core/content/siteadmin, as the current page is siteadmin and you may need to tweak your script a bit in order to access the selected page within siteadmin.
To get your page path either from siteadmin or from the page itself, you can use the following script and then pass the value to your servlet for further processing.
var currentPagePath = null;
/* if accessed via siteadmin */
if(CQ.wcm.SiteAdmin.hasListSelection()) {
var grid = CQ.wcm.SiteAdmin.getActiveGrid();
var selections = grid.getSelectionModel().getSelections();
/*Assuming that you are selecting only one page at a time. */
currentPagePath = selections[0].id;
} else { /* accessed via page */
currentPagePath = CQ.WCM.getPagePath();
}
And then you can call the servlet with the currentPagePath as one of the parameters.
GET /bin/fooServlet?currentPagePath=' + currentPagePath + '&foo=bar';
UPDATE
The above code works fine for CQ 5.5 + , for older versions you can use this.
var currentPagePath = null;
/* if accessed via siteadmin */
if(CQ.wcm.SiteAdmin.hasListSelection()) {
var grid = CQ.Ext.getCmp(window.CQ_SiteAdmin_id + "-grid");
if (grid) {
var selections = grid.getSelectionModel().getSelections();
currentPagePath = selections[0].id;
}
} else { /* accessed via page */
currentPagePath = CQ.WCM.getPagePath();
}
If you define the servlet with a fixed paths property you don't have any reference to a Resource or Page
You either need to define resourceTypes that matches to a page component or use cq:Page, but this will then be active for every request to a page and is not recommended without at least some selectors
Then you can get the Resource with request.getResource(). To get a Page you'll need to adapt the ResourceResolver to a PageManager and use getContainingPage(Resource resource).
Have a look at the documentation:
http://sling.apache.org/documentation/the-sling-engine/servlets.html
request.getPathInfo() in this case presumably is /bin/fooServlet?[parameterString], which is why PageManager is returning null for its path — from the PageManager's point of view, no resource exists at this location.
One simple option would be to send an additional callingPage parameter when hitting the Servlet. This way you could just read it from the parameter map:
GET /bin/fooServlet?foo=bar&callingPage=/en/home.html
void doGet() {
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
String callingPage = request.getParameter("callingPage");
String callingPagePath = pageManager.getPage(callingPage).getPath();
}
I don't know if it's a good pratice, but perhaps you could use the referer.
import java.net.URI;
import java.net.URISyntaxException;
try {
String currentPagePath = new URI(request.getHeader("referer")).getPath();
} catch (java.net.URISyntaxException e) {
}

Get track.stream_url returning garbage

I am trying to stream SoundCloud songs using JPlayer in a Ruby on Rails application. I try to get the stream url server-side using this:
#stream_url = client.get(#track.stream_url, :allow_redirects => true)
I then try to load this URL using JPlayer like so:
<script type="text/javascript">
$("#jquery_jplayer_1").jPlayer({
ready: function() {
$(this).jPlayer("setMedia", {
mp3: "<%= #stream_url %>"
});
},
swfPath: "/js",
supplied: "mp3"
});
</script>
But when I load the page, the browser chokes on the URL string. The returned markup and script looks like this:
$(this).jPlayer("setMedia", {
mp3: "���DInfo+4F��!$&)+.0368;=#..."
That string goes on for much longer than I'll post here.
My best guess is that this is an encoding issue, but I can't figure it out. I've tried in the rails console to debug, but that got me nowhere.
Any ideas would be appreciated. Thanks!
It seems like there are some encoding issues you are facing with.
When I send the HTTP request manually and get the endpoint URL in C#, I don't face the same problem and the end the endpoint URL of the audio is perfectly fine.
public void Run()
{
if (!string.IsNullOrEmpty(TrackUrl))
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TrackUrl + ".json?client_id=YOUR_CLIENT_ID");
request.Method = "HEAD";
request.AllowReadStreamBuffering = true;
request.AllowAutoRedirect = true;
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
this.AudioStreamEndPointUrl = myResponse.ResponseUri.AbsoluteUri;
this.SearchCompleted(this);
}
myResponse.Close();
}
Don't know how that is it applies to Ruby on Rails but you get the idea.
You can try a similar trick to this one instead of using the client.get method.

Liferay Portlet and JSF : Redirect during Render Phase

I have a problem to implement a simple HTTP redirection.
I use Liferay 6.0.6, our portlets are build with JSF2.0 / PortletFaces.
I want to call a redirection when a view is loaded (and not when an action is triggered). Currently, my function is called by the PreRenderView listener.
<f:metadata>
<f:event listener="#{myControler.dispatch}" type="preRenderView" />
</f:metadata>
In this function, i can check the permissions, do other stuff, and in some cases I want to redirect the user to a new page (not another view).
I tried several methods, unsuccessfully.
Specifically, I thought that this method would work :
getFacesContext().getExternalContext().redirect(url);
getFacesContext().responseComplete()
// => Can only redirect during ACTION_PHASE
This error is logical, but is there a solution to force the redirection.
It could be realized in another function, called otherwise, I only need the Hibernate Session (set at the beginning of the Render Phase)
Have you ideas to resolve this problem?
Thanks!
ps : <redirect /> or ?faces-redirect don't work with the portlets.
You can't do this in the render phase by design. Reasons:
It's possible that portlets are rendered asynchronously, so the page might already be displayed when your portlet is being rendered
It's possible that parts of the page are already delivered to the client, so that the HTTP Headers are already sent - for this reason, by design you don't have access to them in the render phase
What would be the expected outcome if two portlets rendered on the same page would decide that they'd like to forwards to another page? Who would win?
A hacky workaround is to render some javascript redirect, but this is veeeery un-portal-like and can mess up other's expectations (plus, parts of the page might already be rendered, causing your users to fill a form only to be redirected by your javascript routine.
Please rethink the problem and come up with a different solution - it's really worth doing this in a portal environment.
I use this and it works for me:
public void preRenderView() throws IOException {
if (!checkUtente()) {
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "errore.xhtml?faces-redirect=true");
fc.renderResponse();
}
}
Use the below method it will work
public static void redirect(final String url) throws IOException {
final javax.portlet.PortletResponse portletResponse
= getPortletResponse();
if (portletResponse instanceof ActionResponse) {
final javax.portlet.ActionResponse actionResponse
= (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(url);
} else if (portletResponse instanceof ResourceResponse) {
final FacesContext ctx = FacesContext.getCurrentInstance();
if (ctx.getPartialViewContext().isPartialRequest()) {
final ResourceResponse portletResResp
= (ResourceResponse) portletResponse;
PartialResponseWriter pwriter;
final ResponseWriter writer = ctx.getResponseWriter();
if (writer instanceof PartialResponseWriter) {
pwriter = (PartialResponseWriter) writer;
} else {
pwriter = ctx.getPartialViewContext()
.getPartialResponseWriter();
}
portletResResp.setContentType(Constants.CONTENT_TYPE);
portletResResp.setCharacterEncoding(Constants.ENCODING_TYPE);
// addResponseHeader("Cache-Control", "no-cache");
pwriter.startDocument();
pwriter.redirect(url);
pwriter.endDocument();
ctx.responseComplete();
} else {
throw new UnsupportedEncodingException(
"Can only redirect during RESOURCE_PHASE "
+ "if a Partial-(JSF AJAX)-Request has "
+ "been triggered");
}
} else {
throw new UnsupportedEncodingException(
"Can not redirect during the current phase: "
+ portletResponse.getClass().getSimpleName());
}
}

multiple pages with C# Web browser control

I am trying to download HTML content from any URL through webbrowser control in C#.net.
I choose webrowser to handle Javascript issues. I am using webbrowser control without placing
it on the form. It works great for one url, but when I call it for multiple urls I am unable
to download the page.
Here is the code
GetWebpage()
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(sURI, false);
bDocumentLoaded = false;
while (!bDocumentLoaded)
{
Application.DoEvents();
Thread.Sleep(100);
}
sHTML = wb.DocumentText;
bDocumentLoaded = false;
}
Event:
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser webBrowser1;
webBrowser1 = sender as WebBrowser;
string strTit = webBrowser1.DocumentTitle;
string str = webBrowser1.DocumentText;
bDocumentLoaded = true;
}
Cheers,
Karthik
You can use webclient object to fetch data from some url.
Try using Downloading String
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);
}
You can also use ASYC method of same downloading string.
I think your problem is that some sites are detecting specific browsertype and then they are returning HTML
Try setting the HeaderProperty of WebClient Object this is a list of HttpWebRequest Object
For Example
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
Modify the useragent of HTTPWEBRequest then add to headers.
HTTPWEBRequest.UserAgent=".NET Framework Test Client";
You can check more information about this in MSDN Link
I might recommend using the mshtml and SHDocVW libraries and using approach found in the answer here:
Unable to to locate and click a submit button using mshtml.HTMLInputElement