how to make 'Alert' or 'Popup' at the controller - java

Hello i just wanna get some advise.
My Problem is a little complicated.
summarize
Now, I am developing JAVA programming with SPRING FRAMEWORK.
client program is solution that is a kind of image viewer, (so I can't modify the code) bring some images from our NAS.
the problem is that the Search Condition of the solution program.
the more NAS has images, the more User have to wait( because result list don't have paging function)
when the Search Condition is so rough, my Server(service) is dead (out of memory)
So I want to Alert or Popup to User that use the solution. (without modifying the solution.)
here is my virtual scenario.
user search button click(Too rough condition)
call #RequestMapping("/***") and go to Controller
Server send to user Message that your search condition is too rough and stop searching.
Is it impossible?
if it is possible, how can i solve it?
there is code in google, i adapt my code, but it does't work, because 'HttpServletResponse response' make exception.
this code is not same to my trial, just motive.
My Core Question is this!
Is it possible that Server send to user Message without modifying client program?
#RequestMapping("/****")
public String loginaction(
#RequestParam(value="XXXX", required=true) String XXXX
, #RequestParam(value="XXXX",required=true) String XXXX
, HttpServletResponse response
) throws Exception{
if(rough condition search){
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('check your Search Condition');</script>");
out.flush();
}
return XXXX;
}

Related

Wicket: double login required due to extended browser info

I have a Wicket 8.6 application. Currently, when logging in to the application, mostly (does not always happen) the user has to login twice. After the first login (after entering the credentials and clicking the submit button) a white page appears saying "If you see this, it means that both javascript and meta-refresh are not support by your browser configuration. Please click this link to continue to the original destination." This is the BrowserInfoPage. After a few seconds the user is redirected to the login page again where he/she has to enter his/her credentials again and press the login button. This time, the user logs in successfully. My question is, how do I prevent that the user hast to enter his/her credentials twice.
From my research I know that it has something to do with the collection of extended browser info. In the init method of my WicketApplication class, I had the following code:
getRequestCycleSettings().setGatherExtendedBrowserInfo(true);
However, I already commented out this code several month ago. For some reason, the described effect occurs for every new deploy now. Maybe a newly added package in the application is the reason for it. I don't know. Is there a possibility to prevent this second login maybe by creating a customized bowser info page which forwards the login? Please point me in the right direction. Thanks.
After some research, I came up with a work around. It is probably not very efficient but it works for me so far. In my custom Session class which inherits from AuthenticatedWebSession, I added the following code.
#Override
protected WebPage newBrowserInfoPage() {
final Request request = RequestCycle.get().getRequest();
if(request.getUrl().toString().contains("LoginPage")) {
if(!isSignedIn()) {
signIn(username, password);
}
PageParametersEncoder encoder = new PageParametersEncoder();
PageParameters parameters = encoder.decodePageParameters(request.getUrl());
String url = parameters != null && parameters.get("originUrl") !=null && !parameters.get("originUrl").isNull() && !parameters.get("originUrl").isEmpty()?
parameters.get("originUrl").toString("pages/home"):"pages/home";
String finalUrl=url.startsWith("pages/")?url.substring("pages/".length()):url;
throw new RedirectToUrlException(finalUrl);
}
return super.newBrowserInfoPage();
}
Some explanation to the code. As mentioned in the question, I want to prevent the user from logging in multiple times. Thus, I check if the request comes from the LoginPage and perform my work around only in that case.
During my implementation, I realized, that the method newBrowserInfoPage is called in the process when I call session.signIn(username,password); on my LoginPage. In this signIn process the authenticate method of my custom Session is called but the signedIn flag in the AuthenticatedWebSession is not changed (keeps false on successfull authentication). Is this a bug? Thus, I have to login again to set the flag to true.
Finally, I read the URL of the LoginPage where I have stored the target URL and forward the user to the target URL.
I am aware this is probably not the best approach but it is the only solution I came up with. If someone has a better idea, I am happy to hear it.

How to create a poll system for IRC using Pirc

I'm a beginner java user, and beginning streamer on Twitch.tv. I have been working on developing an IRC bot all night that would streamline moderation on my channel (I want to have that level of customization that using a cookie cutter IRC bot can't give).
One thing that is stumbling me is poll creation. I have looked through the Pirc javadocs and there is no command as far as I can see that checks for messages sent by a channel op, which is crucial to keeping trolls from creating polls, and with my limited knowledge I do not know how to grab extra parameters from a message.
What I want is this:
!poll <question> <c1> <c2> <c3> <seconds>
Any help here? I will add you to my thanks screen on my outro for each stream.
From my quick look through the PIRC javadocs, it looks like the method you want is #onMessage(String channel,
String sender,
String login,
String hostname,
String message)
From here, you can get any information required. Now depending on how you're handling incoming messages, all you need to do it search for the command, which in this case is "!poll" which you'll receive from the message string. From there, you can further parse the information, and do what you want with it.
If you haven't been using them already, the javadocs for pirc are location here: http://www.jibble.org/javadocs/pircbot/index.html
As Jdsfighter said, you need to use the onMessage(...) method from the PircBot superclass. This method is called whenever a message is sent to your channel. I kinda assume you have understood this by now, as making the bot react to chat is alpha and omega when making an IRC bot.
When concerned with Moderators (Operators in IRC terms), the Twitch IRC servers behave in a way that isnt completely understood by PircBot, and I have not been successfull with the User.isOp(...) method from the User class. What I've found successfull is to include the following in my Bot class (not the main class):
Set<String> OPs = new HashSet<String>();
protected void onUserMode(String channel, String sourceNick, String sourceLogin, String sourceHostname, String recipient) {
recipient = recipient.split(" ")[2];
OPs.add(recipient);
}
This Method is called whenever you see a line begining with MODE in the console, like this one:
jtv MODE #channel +o moderatorName
Now, you need to make a method that is called whenever the message recieved starts with "!poll", and checks if the sender of the message is in the OPs Set.
Here's an outline for you, to be placed in the onMessage() method
if (message.toLowerCase().startsWith("!poll") {
if (OPs.contains(sender)) {
//TODO Add body
}
}
Now you just have to make some code that catches the rest of the line after "!Poll" and posts a message back to the channel about the different poll options.
You obviously need somewhere to store your alternatives and how many votes they get each, I suggest simply two arrays, one String[] and one int[].

How to Ensure Input from URL isn't from a Redirected Page

I have the following lines of code that gathers the source code from a given URL:
URL url = new URL(websiteAddress);
URLConnection connection = url.openConnection(); // throws an IOException
connection.setConnectTimeout(timeoutInMilliseconds);
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
outputString += line;
}
However, the problem that I'm having is that wi-fi hotspots often redirect you to a page where you have to click "I Agree." If you run this code before you have clicked that checkbox, then it gathers the source code from the hotspot login page, rather than the intended page.
What I want to do is have some way of checking whether or not the intended page was reached. I was hoping that calling connection.getURL() after creating the InputStreamReader would show me the actual web page that was arrived, but no such luck. How can I determine whether or not the intended URL has been redirected?
One way would be to look for any specific element in your web page, and if its not there then you know that you may be in some other page (possibly redirected to some login page).
The only thing I can suggest is to have a server where you know what the response is, and query that first to ensure connectivity to at least that server. That will (typically) be enough to assume full connectivity.
You can then go on to query the url you're interested in.
The challenege is that if a computer asks for the page at some url, the way a lot of wifi hotspots work is to intercept that request and return the page. There's often no clue, form the computer's POV that the page returned is not the page requested.
One option would be to call setFollowRedirects(false). By default, a connection will quietly follow redirects and try to reach a page which returns a 200 HTTP response. Disabling redirect following will make confirming the expected page is returned easier, simply confirm the response is a 200.
That said, #rec's comment is worth taking into account - it isn't enough to simply check the response code, because there are many different ways a router could interrupt your request, many of which are not detectable. A malicious router could, for instance, intercept all your requests and change the responding content in a subtle but dangerous way - this is called a man-in-the-middle attack.
By definition you cannot avoid MitM attacks unless you can open a secure and trusted connection (generally, HTTPS) between yourself and the remote site, however assuming you aren't really concerned about attacks, the better tactic is simply to assume the data you get back could be broken in any number of ways, and instead make your scraping logic more robust to that possibility.
I can't speak directly to how you would make your logic more robust without understanding your use case and the issues you've run into, however the gist would be to add checks where issues might arise, and throw an exception that you then handle gracefully higher up the stack.
For instance, if your code was:
System.out.println(outputString.subString(outputString.indexOf('A'));
This would fail if outputString didn't actually have an'A'` character. So check that explicitly:
int aPos = outputString.indexOf('A');
if (aPos < 0) {
throw new InvalidParseException("Didn't find an 'A', cannot proceed");
}
System.out.println(outputString.subString(aPos);
And handle the InvalidParseException wherever makes the most sense for your use case.

How to avoid saving details in database when a new user tries to create account with existing username?

I have a jsp page in my project where user fills up the details for creating an account.
when a user enters username and clicks on the check button, the button looks in the database if the same name exists or not(it is able to check because of the servlet code).
If username exists it shows not available.
Now the problem is even if username is not available when user clicks on sumbit button with existing username the details get saved. how to correct this?
(I'm nt able to post image otherwise it would have been more clear.)
Just add an if-else block to your servlet, something like this:
if (usernameExists) {
showError();
} else {
saveUser();
}
Do not do this:
if (usernameExists) {
showError();
}
saveUser();
I'd also add an UNIQUE constraint on the username column in the DB so that your DAO throws an SQLException or like.
See also:
Our Servlets wiki page - contains a basic Hello world example with server-side validation
First, you serlvet accepting the HTTP POST must validate the data sent to it, when the user clicks a button, if the receiver doesn't validate the information then bad data will get into your system regardless of what you do in the JSP.
Some people send raw HTTP POST messages from time to time just for fun (I don't know why :) ) to see if bad data can get into poorly written web applications.
Once the servlet accepting the POST rejects bad data, you can have it redirect back to the offending web page, filled out with the information that was sent in the bad request, perhaps highlighting the offending field or fields.
Later on, if you have the time, you can write up a bunch of javascript to pre-check the fields and deactivate the submit button. This saves the back end servlet the bother of receiving so many bad requests; however, you cannot use such a technique to avoid fixing the back end servlet. There's too many ways your servlet could get the POST message that don't involve your specific javascript code working.

Android/Java: Simulate a click on this webpage

Last year I made an Android application that scrapped the informations on my train company in Belgium ( application is BETrains: http://www.cyrket.com/p/android/tof.cv.mpp/)
This application was really cool and allowed users to talk with other people in the train ( a messagery server is runned by me) and the conversations wre also on Twitter: http://twitter.com/betrains
Everybody in Belgium loved it. The company tried to avoid us to use their data, make some users websites closed, but their was some lawyers that attack the company and finally we have no more problems and the websites are open: http://blog.tuinslak.org/2010/07/irail-is-back
So, legally my application is ( for now) totally correct and legal, but I get no help from the train company.
So my question is a little help to get the datas. I am now an android/java beginner and spend some weeks to try to find a solution, but maybe people like will fint it in a few minuts.
So the problem is the next one. You may have a look at the following URL, and you will find 2 cities names within URL: Mons and Tournai, and also informations on the date and time. That was the old method that worked one year:
http://hari.b-holding.be/Hafas/bin/query.exe/en?&REQ0JourneyStopsS0A=1&REQ0JourneyStopsS0G=MONS%20[b]&REQ0JourneyStopsZ0A=1&REQ0JourneyStopsZ0G=TOURNAI%20[b]&REQ0JourneyDate=27.010.10&REQ0JourneyTime=19:030&Timesel=depart&ViaName=&ViaMode=NEE&DateMode=ANDERS&PLANNER=TRUE&start=1&queryPageDisplayed=yes
But now, the URL bring me on a confirmation page and I have to click on the confirm button to get to the next page.
So my code won't work anymore, I need to click on this button programmatically to arrive on the correct webpage.
Have you any idea on how to simulate a click on this button? For now my code is the classic scrapping code with the URL given a few line on the top. I assumed that the Url give me the result page. That was the case till last week.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(mon_url);
HttpResponse response;
try {
response = httpclient.execute(get);
HttpEntity entity = response.getEntity();
BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent()));
etc...
Have you any idea on how to improve the code?
As the software is free, I cannot send paypal money, but a whole country would be really thankfull to the man that might help!
Thank a lot.
Instead of trying to automate clicking the JavaScript button, try monitoring what request is sent and then replicate this in your app. There are various firefox extensions that will help you do this, such as TamperData, Firebug, and LiveHttp.

Categories