weather.gov API expired forecast grid - java

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.

Related

Java embedded browser

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.

Checking if a Twitch.tv stream is online and receive viewer counts using Pircbot

I'm working on my IRC Bot for Twitch.tv (pircbot API) and want to make the bot connect automatically to the stream's chat as soon the stream is going live.
I've found a Twitch API (here), but I have no clue
how I can implement this into my bot since I'm pretty new to Java.
Would be cool if someone could tell me any hints on how I could retrieve if a stream is online and how I can check the amount of viewers watching right now.
Greetings
I realize that this question was posted about a year ago, but I feel its important to have it answered just in case others stumble on this post. What Cam.Stokes said is spot on. It's the answer to the question. However the questioner indicated he is new to Java so I want to use code snippets to work out what Cam.Stokes said.
Catching if a stream is live isn't too difficult. The following code is a snippet from my bot. I got a thread that periodically receives the JSON data from the twitch API and then loads it into a JSON object. The JSON library that I'm using is called "minimal-json". Excellent lightweight lib if you ask me. When you review the code you can see what I'm doing; call twitch-api, get the JSON from the target stream, see if the "stream" object is filled with data. if so, stream is live, otherwise, not live.
import com.eclipsesource.json.JsonObject; // minimal-json specific
private static String TWITCH_STREAM = "https://api.twitch.tv/kraken/streams/$c$";
private static String insertChannel(String url, String channel)
{
return url.replace("$c$", channel );
}
public boolean isStreamLive()
{
try
{
URL url = new URL( insertChannel(TWITCH_STREAM, targetChannel) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
Connecting the bot is rather straight forward with PircBot. Answered by Nicolai. Make sure you have an Oauth key from twitch that's linked to your bot account. The target channel is in lower case and with a # in front. And you should be good to go.
Good luck.
you need to get a auth key first
Link: http://twitchapps.com/tmi/
and then you need to set this in the main java file
bot.connect("irc.twitch.tv", 6667, "oauth:YOURAUTHKEY");
bot.joinChannel("#YOURCHANNEL-INLOWERCASE");
let me know if you have some other problems
Check out the chat section of the twitch API to see how to connect to the chat using PircBot:
https://github.com/justintv/Twitch-API/blob/master/IRC.md
As far as getting the live stream status, that is a little bit more difficult, but the url you want is:
https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
My suggestion would be to set a timed thread to check the stream status every 10 seconds or so, and if the "stream: " object in the json is not null, making the connection.
A good lib for parsing json (if you are doing twitch stuff, you will need to parse lots of json backwards and forwards by the looks) is gson.
(I need more than 10 rep to post more than 2 links apparently, but copy paste this without the space http:// code.google.com/p/google-gson/ )

How to handle (failed) login attempts with Smack XMPP API

I'm developing a chat server based on XMPP and Smack API, which connects to an Openfire server (Hosted by a friend who is also developing this with me).
So, I started programming it just a few days ago (Netbeans on OS X 10.8), and today I went on to the connection and login aspects.
I can login perfectly with the right choice of username+password :P but I don't know how to handle an invalid login attempt and let the app show a message and then allowing the user to retry.
Here's my code, which fires after user has pressed a button in my Swing JForm:
(Note: XMPPConnection object is already created in another class, and the connection has been made to the server. You can see I'm calling the object from that another class)
private void btnIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {
String Usuario = txtUsuario.getText();
String Password = new String (pwdContrasena.getPassword());
if (Usuario.equals("") || Password.equals("")){
// Missing data
JOptionPane.showMessageDialog(null, "Missing data");
}
else{
//Try to login
try{
Proyecto_chat.conexion.login(Usuario, Password, "x");
}
catch (XMPPException ex){
Logger.getLogger(Ventana_login.class.getName()).log(Level.SEVERE, null, ex);
// Problem
}
if (Proyecto_chat.conexion.isAuthenticated() == true){ //Login has been successful
jLabel1.setVisible(false);
System.out.println("Authenticated as " + Usuario);
JOptionPane.showMessageDialog(null, "Authenticated as " + Usuario);
//Exit login window and carry on
}
else{
JOptionPane.showMessageDialog(null, "login error");
}
}
}
Should I play with that exception I'm getting? ->
SEVERE: null
SASL authentication DIGEST-MD5 failed: not-authorized:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at proyecto_chat.Ventana_login.btnIniciarSesionActionPerformed(Ventana_login.java:159)
at proyecto_chat.Ventana_login.access$100(Ventana_login.java:15)
at proyecto_chat.Ventana_login$2.actionPerformed(Ventana_login.java:73)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
(...) more lines that I think are not critical for this
As passwords are stored in plain text (University project, so it doesn't matter) for simplifying changing them from inside the application, I can connect to the database (PostgreSQL in remote server) from the client computer, and check the passwords and only do 'conexion.login' if user&pass matches, but that would be... you know... wrong
After looking around on the web with no luck, I decided to head over here, ask, go to sleep and wake up next morning with some suggestions ;)
Help shall be appreciated
Not sure if I understand what you are asking but if it's "How can I determine the reason for a failed login attempt with Smack?" then here is my answer:
You have to evaluate the (XMPP)Exception's message string as of Smack 3.2.2 if you want to determine the reason for the failed login. These message strings that distinguish between the various failure reasons are currently hard-coded in the source, which is usually not a good idea.
A while ago I have created SMACK-416 "Improve Exceptions on connect() and login()" to address this issue. The idea is to replace the hard-coded strings/failure reasons with a class hierarchy. But it sure will take a few months until this is implemented (and maybe a few weeks/months/years until it is released).
Actually, the main problem was that when I tried to login using an invalid username/password, some exception was thrown (As well as an information display that I set up), but the application wouldn't let me log in again (As if I corrected my data and clicked the button again).
I finally solved this by placing the .connect() right behind the .login() method, and calling .disconnect() in case a bad login was made, so the server would be reconnected every time the user tried to log in .
This might not be the ideal approach, but I find it easy and do-able. Thanks for helping!

why does documentUrl return null

I'm making a web application for blackberry and I really need the current URL
In the description of documentUrl, it says
This method will return the URL of the currently loaded page of this BrowserField Instance
My code is:
_bf2.requestContent("google.com";);
add(_bf2);
Global.c = _bf2.getDocumentUrl();
Global.be=new BasicEditField("URL: "+Global.c,Global.c);
add(Global.be);
and the weird thing is that www.google.com gets loaded in the BrowserField and the documentUrl returns null.
This is my current code:
BrowserField _bf2 = new BrowserField();
MYBrowserFieldListener _listener = new MYBrowserFieldListener();
_bf2.requestContent("google.com";);
_bf2.addListener(_listener);
String url=_bf2.getDocumentUrl();
Global.be=new BasicEditField("URL: "+url,url);
add(Global.be);
add(_bf2);
I changed it to
final BrowserField _bf2 = new BrowserField();
_bf2.requestContent("google.com";);
//_bf2.addListener(listener);
Global.be=new BasicEditField("URL: "+Global.c,Global.c);
add(Global.be);
add(_bf2);
_bf2.addListener(new BrowserFieldListener(){
public void documentLoaded(BrowserField _bf2, Document document) throws Exception {
Global.c=_bf2.getDocumentUrl();
}
});
But it still returns null. Can someone please tell me how to fix this? Thanks in advance!
I would say that Arhimed has answered your question. An HTTP request is a very time consuming process (from a CPU perspective) and will block until the server responds. I suspect that RIM programmers have coded the requestContent() method as per their own recommendations and are fetching the web content on a separate thread. So, requestContent() will return immediately, when you call getDocumentUrl() it is still null since the fetch thread has probably not even connected to the server at this point.
You will need to implement a BrowserFieldListener and listen for documentLoaded().

Complete CONNECTIVITY_SERVICE test

My application connects to the internet onCreate, it does this in an AsyncTaks class and all works fine. I have some error checking in place to make sure there is internet available and works great if I say put my phone on Flight Mode.
My problem is when I’m on WIFI, where I live the WWW drops out from time to time but the phone still thinks it’s connected. E.g.. the phone is still connected to the WIFI dongle but the WIFI dongle is not connected to the WWW, so when the application opens and tries to connect it gets an error and I get a force close.
How can I do a complete internet connection check onCreate that will cover all bases???
Cheers,
Mike.
One possibility is just to handle the error that you are getting in a better manner. You are getting a force close right now because (I assume) you are getting a RuntimeException from your application. Handling the exceptions and putting up proper messaging to your user might be adequate.
Another way is just make one (or a couple) connections to some high available servers to see if it works. For example, something like the following should work:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com/");
try {
HttpResponse response = client.execute(request);
txtResult.setText(HttpHelper.request(response));
// internet is working
} catch(Exception ex) {
// internet is not working
txtResult.setText("Internet ENOWORK");
}
If you post the exception/error that you are getting and comment on my answer I can edit it with more specifics.

Categories

Resources