Categories
discuss

How do I catch jQuery $.getJSON (or $.ajax with datatype set to ‘jsonp’) error when using JSONP?

Is it possible to catch an error when using JSONP with jQuery? I’ve tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I’m testing. Here is what I’ve tried (keep in mind that these all work successfully, but I want to handle the case when it fails):

jQuery.ajax({
    type: "GET",
    url: handlerURL,
    dataType: "jsonp",
    success: function(results){
        alert("Success!");
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("Error");
    }
});

And also:

jQuery.getJSON(handlerURL + "&callback=?", 
    function(jsonResult){
        alert("Success!");
    });

I’ve also tried adding the $.ajaxError but that didn’t work either:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});

Thanks in advance for any replies!

Answer

It seems that JSONP requests that don’t return a successful result never trigger any event, success or failure, and for better or worse that’s apparently by design.

After searching their bug tracker, there’s a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can’t capture the error, you can at least timeout after waiting a reasonable amount of time for success.

Categories
discuss

How to refer to the outer class in another instance of a non-static inner class?

I’m using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:

import org.apache.commons.lang.builder.EqualsBuilder;

public class Foo {
    public class Bar {
        private Bar() {}

        public Foo getMyFoo() {
            return Foo.this
        }

        private int myInt = 0;

        public boolean equals(Object o) {
            if (o == null || o.getClass() != getClass) return false;

            Bar other = (Bar) o;
            return new EqualsBuilder()
                .append(getMyFoo(), other.getMyFoo())
                .append(myInt, other.myInt)
                .isEquals();
        }
    }

    public Bar createBar(...) {
        //sensible implementation
    }

    public Bar createOtherBar(...) {
        //another implementation
    }

    public boolean equals(Object o) {
        //sensible equals implementation
    }
}

Is there syntax by which I can refer to other‘s Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn’t work)?

Answer

No.

The best way is probably what you suggested: add a getFoo() method to your inner class.

Categories
discuss

How can I make a swing JButton repeat its action when it is held down?

I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down.
(First of all, I am not sure that the touch screen will allow the user to “hold down” the button, but pretend that they can for now)

I was going to go down the path of starting a loop when mousePressed was called and then ending the loop when mouseReleased was called. This will involve starting a thread and having to deal with synchronization as well as invokeLater() to get events back on the EventQueue.

Is there a very simple way to do what I want? I hope I am just not seeing the API to do it.

Answer

javax.swing.Timer is your friend. And here’s an article with some more info.

Categories
discuss

How to store a java.util.Date into a MySQL timestamp field in the UTC/GMT timezone?

I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.

How can I configure MySQL to store it in the UTC/GMT timezone?

I think, configuring the connection string will help but I don’t know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, …

Answer

The short answer is:

  • add “default-time-zone=utc” to my.cnf
  • in your code, always “think” in UTC, except when displaying dates for your users
  • when getting/setting dates or timestamps with JDBC, always use the Calendar parameter, set to UTC:

    resultset.getTimestamp(“my_date”, Calendar.getInstance(TimeZone.getTimeZone(“UTC”)));

  • either synchronize your servers with NTP, or rely only on the database server to tell you what time it is.

The long answer is this:

When dealing with dates and timezones in any database and with any client code, I usually recommend the following policy:

  1. Configure your database to use UTC timezone, instead of using the server’s local timezone (unless it is UTC of course).

    • How to do so depends on your database server. Instructions for MySQL can be found here: http://dev.mysql.com/doc/refman/5.0/en/time-zone-support.html. Basically you need to write this in my.cnf: default-time-zone=utc

    • This way you can host your database servers anywhere, change your hosting location easily, and more generally manipulate dates on your servers without any ambiguity.

    • If you really prefer to use a local timezone, I recommend at least turning off Daylight Saving Time, because having ambiguous dates in your database can be a real nightmare.
      • For example, if you are building a telephony service and you are using Daylight Saving Time on your database server then you are asking for trouble: there will be no way to tell whether a customer who called from “2008-10-26 02:30:00” to “2008-10-26 02:35:00” actually called for 5 minutes or for 1 hour and 5 minutes (supposing Daylight Saving occurred on Oct. 26th at 3am)!
  2. Inside your application code, always use UTC dates, except when displaying dates to your users.

    • In Java, when reading from the database, always use:

    Timestamp myDate = resultSet.getTimestamp(“my_date”, Calendar.getInstance(TimeZone.getTimeZone(“UTC”)));

    • If you do not do this, the timestamp will be assumed to be in your local TimeZone, instead of UTC.
  3. Synchronize your servers or only rely on the database server’s time

    • If you have your Web server on one server (or more) and your database server on some other server, then I strongly recommend you synchronize their clocks with NTP.

    • OR, only rely on one server to tell you what time it is. Usually, the database server is the best one to ask for time. In other words, avoid code such as this:

    preparedStatement = connection.prepareStatement(“UPDATE my_table SET my_time = ? WHERE […]”);
    java.util.Date now = new java.util.Date(); // local time! 🙁
    preparedStatement.setTimestamp(1, new Timestamp(now.getTime()));
    int result = preparedStatement.execute();

    • Instead, rely on the database server’s time:

    preparedStatement = connection.prepareStatement(“UPDATE my_table SET my_time = NOW() WHERE […]”);
    int result = preparedStatement.execute();

Hope this helps! 🙂

Categories
discuss

Java Transport.send() is it thread-safe?

The method is static, but I cannot find mention of if it is thread-safe or not. I plan on hitting this method with several threads at once and I would like to avoid a synchronized block if possible.

javax.mail.Transport.send(msg);

Answer

It is usually bad design and a violation of expectations to have a static method that is not thread-safe.

The documentation indeed appears to be devoid of any mention of thread-safety, but a quick glance through the code suggests that the implementation is thread-safe by creating a thread-confined Transport instance on every call and delegating to that.

To be absolutely sure I recommend pulling a couple of days out the calendar for a proper analysis.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..