Java embedded browser - java

I'm using the embedded browser.
import org.eclipse.swt.browser.Browser;
.....
final Browser g11_embedded_browser = new Browser(g11_capture_script, SWT.NONE);
g11_embedded_browser.setBounds(0, 0, 1000, 260);
g11_embedded_browser.setVisible(true);
...........
try {
uri = new URI("http://127.0.0.1:" + g11_txt_PATH_portnumber.getText());
} catch (URISyntaxException e1) {
System.out.println("failed setting uri");
e1.printStackTrace();
}
System.out.println("uri=" + uri.toString());
try {
url = uri.toURL();
The full url is: http://127.0.0.1:6500
The C program listening on 6500 sometimes responds first time. At other times it takes 2 attempts.
I believe it returns a 204 when the connection fails.
My questions in the hope someone can point me in the right direction are:
Is there any way I can detect the 204? It displays nothing in the browser as it is deemed a successful reply.
Any clue as to why the 204 as the C program never issues a 204 when the request comes from any browser on any OS, just when from the embedded browser.
Note:
The browser displays an internet page before the localhost request so it isn't an embedded browser start up issue. Tried it with and without that.
Tried interleaving requests to the C program from browsers and the Java browser but 100% success externally and about 50% failures from Java on first attempt. Occasionally needs three or even 4 attempts but always works in the end.
A 204 is "204 - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request." However the localhost call is a request for the display of a simple form.

Related

weather.gov API expired forecast grid

I've got a program that pulls a list of forecast links using the weather.gov API Web Service and then calls each link in order to pull and store weather data for zip codes, which can they be viewed on our home page based on a Users zip code preferences. Lately I'm seeing a lot of 503 errors in our error log, so when I went to check it out and run a few of the URLs using Postman, I am getting the following response:
{
"correlationId": "36eb9a42-990d-4ca8-a24a-cd0c67985903",
"title": "Forecast Grid Expired",
"type": "https://api.weather.gov/problems/ForecastGridExpired",
"status": 503,
"detail": "The requested forecast grid was issued 2020-02-11T02:50:40+00:00 and has expired.",
"instance": "https://api.weather.gov/requests/36eb9a42-990d-4ca8-a24a-cd0c67985903"
}
Unfortunately I do not know what it means when a requested forecast grid expires, and I could not find anything in their documentation for this, either. Maybe I've missed something, or maybe I've got a problem in my code that's causing this issue.
This is a java program and it uses javax.net.ssl.HttpsURLConnection and java.net.URL:
URL url = new URL("https://api.weather.gov/gridpoints/BOX/21,35/forecast");
HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection();
httpsConn.setRequestMethod(HttpMethod.GET);
httpsConn.setRequestProperty("Content-Type", "application/json");
httpsConn.setConnectTimeout((1000 * 60));
httpsConn.setReadTimeout((1000 * 60));
StringBuffer response = getApiResponse(httpsConn, 0);
private StringBuffer getApiResponse(HttpsURLConnection httpsConn, int counter){
StringBuffer response = new StringBuffer();
try{
BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}
in.close();
}catch(Exception e){
counter++;
errorLog.add("ERROR: " + e.getMessage());
errorLog.add("Number of attempted calls: " + counter);
if(counter < 5){
response = getApiResponse(httpsConn, counter);
}else{
errorLog.add("Max attempts made for this API Call.");
}
}
return response;
}
I wrapped the call within a function that will try to make the call 5 times, as I noticed while building this program that sometimes the call just simply times out. The url I used just happens to be one of the ones I am having trouble with, it seems to be that anywhere involving BOX is causing the above 503 error.
Has anyone else encountered an issue like this - and how did they solve it?
So it turns out that this is not something we can solve ourselves. While a 503 Status Code means that the server being called is unable to handle the request (and I know that it's not a fault on our end) I was perplexed by the error message being received and was wondering if it had anything to do with the way I had set up my call to the service.
This error message basically boils down to a service outage, which means there isn't anything we can do on our side except report the outage and wait for a result.
I feel silly marking this as the answer since it boils down to "contact their support system" but maybe if anyone comes across this in the future they'll at least know the reasoning - but hopefully they'll improve their error messages so that it's more clear what is a service outage and what is an issue with the call you made.

Keycloak is not maintaining session in browser

I am using keycloak(4.3.0) openid-connect flow. For my client app, I am using:
public class AuthenticationTest {
public static void main(String[] args) {
final String KEYCLOAK_JSON = Constants.KC_CONFIG_JSON_PATH;
InputStream config = Thread.currentThread().getContextClassLoader().getResourceAsStream(KEYCLOAK_JSON);
KeycloakInstalled keycloak;
try {
keycloak = new KeycloakInstalled(config);
config.close();
keycloak.loginDesktop();
AccessToken token = keycloak.getToken();
System.out.printf("UserId: %s%n", token.getSubject());
System.out.printf("Username: %s%n", token.getPreferredUsername());
System.out.printf("Email: %s%n", token.getEmail());
System.out.println(keycloak.getTokenString());
System.in.read();
} catch (IOException | VerificationException | OAuthErrorException | URISyntaxException | HttpFailure
| InterruptedException e) {
e.printStackTrace();
}
}
}
I have referred the example mentioned here: https://gist.github.com/thomasdarimont/ca16080145d226e50628d5696ffb9508
First time I launch the application and login, I get
"Login Successful.You may close this browser window and go back to
your console application."
However, if I launch second instance of my application/ relaunch my application even without closing the previous browser window , still the login page appears instead of you are already logged in message.
(The new login page is appearing in a new tab on the same window as the first login page, so it is not an issue of failure to maintain state across different windows. Also I have tried relaunching the app withing 20 seconds so it does not seem t be an issue of timeout either)
Browser: Firefox, chrome.
Any idea what I am doing wrong. Expectation is that browser must maintain a keycloak session for the same user until closed for at least a few minutes.
NOTE: I did not face this issue in Keycloak 3.4.3. But it started coming on 4.1.0 and 4.3.0
I see follwing difference in cookies on 3.4.3 and 4.x:
3.4.3: (same whther first login or subsequent login)
4.x First time login:
4.x Subsequent login: (an addition KC_RESTART cookie is seen)

Java jsoup checking button

I am trying to check whether a page contains next page to sroll. The idea is basic: get the current link, remove the index at the end and then put new index, try to connect to the new link, if it throws IOException that means it does not have next button so that can be scrolled. Here is my code, and the problem it returns false even to the links that Jsoup can connect:
public boolean checkNextButton(String linkToCheck) throws IOException {
boolean containsNextButton = true;
try {
//Here I am trying to connect to a link which is actually available but it still returns false
Document doc = Jsoup.connect(turnToNextPage(linkToCheck)).get();
specific.setPageChangeRate(specific.getPageChangeRate() - 1);
//Set back the counter to the previous one
} catch (IOException e) {
containsNextButton = false;
}
System.out.println("The page contains next button: " + containsNextButton);
return containsNextButton;
}
Solution provided by Pshemo:
It is hard to tell what exactly went wrong without more details.
Are you able to access resource from linkToCheck via browser? Did you need to log-in on that site first (maybe try accessing it via incognito mode to see if it is available for anyone without creating an account).
Other problem could be that some servers allow only specific browsers and they try to recognize them by using user-agent header browsers send, or if server is creating temporary session you may need to pass cookies from previous connection.

After 6 Serversocket event connection with same application futher ajax request is not getting sumitted

I am facing very strange problem when i am creating server socket event connection with java application deployed on tomcat .After making 6 server socket connection .it is not able to make new connection even when i am request simple url from ajax or from new tab it is not hitting application .I have checked through proxy tolls even request is not genearted from browser .if the same url i request from some other browser then request got submitted and response comes .
This means issue is at browser side not application side . I have checked with both mozila and google chrome but still no success .
Is there any kind of restriction with HTML 5 server socket Event .I am using following code
eventSource.addEventListener('trigger', function(event){
var data=event.data;
var oFormB = document.getElementById('a'+tabId);
var audioEnable;
var sound;
if(oFormB!=null&&data.charAt(data.length-1)=='b'){
audioEnable=oFormB.elements.audibleAlarm[0].checked;
if(audioEnable!=null&&audioEnable==true){
sound = new Howl({ urls: ['js/sounds.mp3'],buffer:false}).play();
//sound.stop();
}else{
// alert(" Alarm Id:"+event.data+" Triggered.Tabs Id: "+tabId);
}
alert(" Alarm Id:"+event.data+" Triggered. Tabs Id: "+tabId);
if(sound!=null){
sound.stop();
}
}
Any help would be really appreciated

Loop attempt to connect to JDBC

I'm trying to create an application for checking in and out devices. So far I've had success but I'm trying to have the main index.jsp page that is called display a message like "connecting" until a connection with the database can actually be made and then display the actual login form. So something to the effect of.
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
boolean connected = false;
while(!connected) {
try{
String url = "jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,"username","password");
connected = true;
//Display form allowing user to authenticate login
} catch(Exception e) {
//Display Message "Attempting to connect to database"
}
}
The problem I have is the same message will get repeated over and over on the web page but i just want it to display once and stay there until the connection is found and then be removed and replace with the login form. Any thoughts?
I suggest you use connection pooling.... it is quite easy to manage connections and the overheads will be reduced making your app efficient.
see the following:
Setup Connection pooling in jsp/servlets application based on MVC?
Am I Using JDBC Connection Pooling?
Setup Connection pooling in jsp/servlets application based on MVC?
Change your code in this way
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
boolean connected = false;
int errors = 0;
while(!connected) {
try{
String url = "jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,"root","ikkakumon");
connected = true;
//Display form allowing user to authenticate login
} catch(Exception e) {
if (errors == 0) {
//Display Message "Attempting to connect to database"
}
++errors;
Thread.sleep(1000); // wait a little before the next attempts
}
}
So you display the error message only the first time.
Then wait between one attempt and another.
However the loop is not the usual way to manage connections. Why do you choose this solution? What kind of exception do you receive?
Any thoughts?
Yes.
You need to get your head around HOW stuff gets displayed to the user. The normal model is that browser sends an HTTP request to the server, the server creates a response consisting of an HTML page, and the browser displays the page. In this model, if you want the user to see the results, the server has to finish and send the response. Until it does, the user sees a blank screen (or the page he / she was on previously).
So to get a page that updates you have two options:
You can create a page that contains a <meta> tag that requests that the browser resends the request after a fixed delay; see http://en.wikipedia.org/wiki/Meta_refresh
You can embed javascript in the page to send an AJAX request to the server asking for an update. On getting a response, the javascript then needs to modify the DOM of the displayed page with the new information.
But in either case, it should be clear to you that you cannot do this in a single call to a single JSP. So you don't want a while loop in the JSP, or in the controller that dispatches to the JSP. The looping has to happen at the browser end.

Categories

Resources