Categories
discuss

How to programmatically send a 404 response with Express/Node?

I want to simulate a 404 error on my Express/Node server. How can I do that?

Answer

Since Express 4.0, there’s a dedicated sendStatus function:

res.sendStatus(404);

If you’re using an earlier version of Express, use the status function instead.

res.status(404).send('Not found');
Categories
discuss

Add method to string class

I’d like to be able to say something like this in javascript :

   "a".distance("b")

How can I add my own distance function to the string class?

Answer

You can extend the String prototype;

String.prototype.distance = function (char) {
    var index = this.indexOf(char);

    if (index === -1) {
        alert(char + " does not appear in " + this);
    } else {
        alert(char + " is " + (this.length - index) + " characters from the end of the string!");
    }
};

… and use it like this;

"Hello".distance("H");

See a JSFiddle here.

Categories
discuss

Should calls to a Content Resolver be done in a Service (i.e separate thread)?

I’m learning more about content providers in Android and they’re performance. For example, if I write my own content provider (subclass ContentProvider) for SQLite operations and then I want to do an operation in an Activity’s onPause() method, then in my Activity I would do:

@Override
protected void onPause (){
    super.onPause();

    // ...prepare myTransactionValues

    // This could be anything like insert, bulkInsert, query, delete, etc.
    getContentResolver().insert(CONTENT_URI, myTransactionValues)
}

However, it looks likes this database operation is being done on the main thread. Is the work being done in a separate thread behind the scenes? Should it be in it’s own thread? If it should, is there a recommended way (perhaps a Service)?

Answer

If you want to do something in a Non-UI thread, you should usually use an AsyncTask. A service, on the other hand, is best kept for long tasks.

Categories
discuss

Is it possible to listen for join and leave events on a room?

I want to do something like:

var room = io.sockets.in('some super awesome room');
room.on('join', function () {
    /* stuff */
});
room.on('leave', function () {
    /* stuff */
});

This doesn’t seem to work. Is it possible?

To illustrate the desired behavior:

io.sockets.on('connection', function (socket) {
    socket.join('some super awesome room'); // should fire the above 'join' event
});

Answer

In Socket.IO, a “room” is really just a namespace, something to help you filter your giant bag of sockets down to a smaller bag of sockets. Calling io.sockets.in('room').on('something') will cause the event handler to fire for every socket in the room when the event fires. If that’s what you want, something like this should do the trick:

var room = io.sockets.in('some super awesome room');
room.on('join', function() {
  console.log("Someone joined the room.");
});
room.on('leave', function() {
  console.log("Someone left the room.");
});

socket.join('some super awesome room');
socket.broadcast.to('some super awesome room').emit('join');

setTimeout(function() {
  socket.leave('some super awesome room');
  io.sockets.in('some super awesome room').emit('leave');
}, 10 * 1000);

Important to note is that you’d get the same effect if you (1) got a list of all sockets in a room and (2) iterated over them, calling emit('join') on each. Thus, you should make sure that your event name is specific enough that you won’t accidentally emit it outside the “namespace” of a room.

If you only want to emit/consume a single event when a socket joins or leaves a room, you’ll need to write that yourself, as, again, a room isn’t a “thing” as much as it’s a “filter”.

Categories
discuss

UTF-8 encoding a servlet form submission with Tomcat

I’m attempting to post a simple form that includes unicode characters to a servlet action. On Jetty, everything works without a snag. On a Tomcat server, utf-8 characters get mangled.

The simplest case I’ve got:

Form:

<form action="action" method="post">
  <input type="text" name="data" value="It’s fine">`
</form>`

Action:

class MyAction extends ActionSupport {   
  public void setData(String data) {
    // data is already mangled here in Tomcat
  } 
}
  • I’ve got URIEncoding=”UTF-8″ on <Connector> in server.xml
  • The first filter on the action calls request.setCharacterEncoding(“UTF-8”);
  • The content type of the page that contains the form is “text/html; charset=UTF-8”
  • Adding “accept-charset” to the form makes no difference

The only two ways I can make it work are to use Jetty or to switch it to method=”get”. Both of those cause the characters to come through without a problem.

Answer

I’ve got URIEncoding=”UTF-8″ on <Connector> in server.xml

That’s only relevant for GET requests.


The first filter on the action calls request.setCharacterEncoding("UTF-8");

Fine, that should apply on POST requests. You only need to make sure that if you haven’t called getParameter(), getReader(), getInputStream() or anything else which would trigger parsing the request body before calling setCharacterEncoding().


The content type of the page that contains the form is "text/html; charset=UTF-8"

How exactly are you setting it? If done in a <meta>, then you need to understand that this is ignored by the browser when the page is served over HTTP and the HTTP Content-Type response header is present. The average webserver namely already sets it by default. The <meta> content type will then only be used when the page is saved to local disk and viewed from there.

To set the response header charset properly, add the following to top of your JSP:

<%@page pageEncoding="UTF-8" %>

This will by the way also tell the server to send the response in the given charset.


Adding “accept-charset” to the form makes no difference

It only makes difference in MSIE, but even then it is using it wrongly. The whole attribute is worthless anyway. Forget it.

See also:

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..