When the `wp-config.php` file doesn’t exist in the WordPress folder, the installer is triggered along with database set-up. When you first download/clone WordPress a file name `wp-config-sample.php` exists. This file is updated with the database settings and site name you enter during set-up, and then renamed to `wp-config.php`. This is how WordPress knows it has been installed.
Twitter Bootstrap Single Page App with Node.JS
This is Part 1 of a 3 part series on a single page application for Node.JS.
I love Twitter Bootstrap. Yes, there are several similar frameworks, but I like the fact that Bootstrap works on nearly all modern browsers (Firefox, Chrome, Safari (Stinkin) IE 8+). Although Twitter Bootstrap was not initially great for Mobile apps, they have done some recent updates that provide near compatibility on mobile devices like iPad, iPhone and Android.
I started this project as a boilerplate for single-page apps, and later realized that it’s a good backend for Bootstrap. There are several great Bootstrap mods, themes and UI layer tools have emerged: Bootswatch, Font Awesome and tons more (thus this amazing list on The Big Badass List of Bootstrap Resources). But, I couldn’t find an adequate starter-kit for the server side so I decided to write my own.
Node.js is a good fit for single-page apps. While Socket.IO would seemingly provide cleaner HTTP better suited to single-page apps, I decided to go with Express 3.0 because I’m more comfortable with it’s session management, templating, form parsing and routing features.
The idea of the single-page app is heavy use of AJAX for the server calls which minimizes full page reloads in the browser. This app is in the long scrolling vertical page style, and I hope later to add a parallax style. Since it is a one page app, it would also be well suited for a tabbed layout which is something I intend to implement later. I’ll get into the details later, but here is a demo the single page application.
Part 1: Server-side Code
If you’re new to Node.JS, there is great getting started tutorial here. Once Node and NPM are up and running you’re ready to look at the backend of this single page app. As stated earlier, this app uses the Express framework which is high-performance layer that simplifies app fundamentals such as routing, sessions and request/response.
Express Configuration
app.js
This file uses “require” to load Express, EJS-locals and defines the app settings.
var express = require('express'), engine = require('ejs-locals'), app = express(); exports.init = function(port) { app.locals({ _layoutFile:'layout.ejs' }) app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/static')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.cookieSession({cookie:{path:'/',httpOnly:true,maxAge:null},secret:'skeletor'})); app.use(app.router); app.enable("jsonp callback"); }); app.engine('ejs', engine); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); app.use(function(err, req, res, next){ res.render('500.ejs', { locals: { error: err },status: 500 }); }); server = app.listen(port); console.log("Listening on port %d in %s mode", server.address().port, app.settings.env); return app; }
Session and Cookie Management
. . app.use(express.cookieParser()); app.use(express.cookieSession({cookie:{path:'/',httpOnly:true,maxAge:null},secret:'skeletor'})); . .
Serving Static Pages
. . app.use(express.static(__dirname + '/static')); . .
Routing
server.js
This is the startup file for our app. Server.js loads the app settings from app.js and defines each app route. Express 3.0 is most of the magic here. Express uses app. methods to provide the routing functionality, where is one of the HTTP methods (ie; get, post, del). Below is a stubbed view of server.js that defines each route in the application. Notice the use of “app.get”, “app.post” and “app.del” accordingly:
var port = process.env.PORT || 4000, app = require('./app').init(port), dirty = require('dirty'); // define the routes app.get('*', function(req,res,next){ // this is called for every GET request }); /* home page route */ app.get('/', function(req,res){ console.log("render home page"); }); /* contact form route */ app.post('/contact', function(req,res){ console.log("post from contact form"); }); /* login routes */ app.get('/login', function(req,res){ console.log("render login page"); }); app.post('/login', function(req,res){ console.log("logging in"); }); app.get('/logout', function(req,res){ console.log("logging out"); }); /* administration routes */ app.get('/admin', function(req,res){ console.log("render admin page"); }); app.post('/admin/app', function(req,res){ console.log("saving app settings"); }); app.post('/admin/page', function(req,res){ console.log("saving page settings"); }); app.post('/admin/sections/:k', function(req,res){ console.log("saving section"); }); app.del('/admin/sections/:k', function(req,res){ console.log("deleting section"); }); app.post('/admin/sections', function(req,res){ console.log("saving sections"); }); . . /* The 404 Route (ALWAYS Keep this as the last route) */ app.get('/*', function(req, res){ res.render('404.ejs', locals); });
As you can see the routes define 4 HTTP GET (app.get) endpoints:
- / (default/home page)
- /login
- /logout
- /admin
Persistence
For this single-page app I wanted to keep the database lightweight and simple. I chose “Dirty“, a file-based schemaless data store for Node which is ideal for apps with Connect modules. I found Dirty well suited for this app as it eliminates the need to stand-up a separate database server, and keeps deployment stupid simple.
In our server.js we load the node-dirty module using require:
. dirty = require('dirty'); . .
There are 5 database files that provide persistence:
- app.db – Stores application level settings
- sections.db – Stores section settings and content
- user.db – Stores user credentials for /admin authentication
- snippet.db – Stores code snippets to pre-populate section content
- post.db – Stores results posted from contact and email forms
Code Details
Lets look closer at the code that executes when the default URL (http://www.myapp.com/) is requested:
app.get('/', function(req,res){ console.log("show home page"); var appDb = dirty('app.db'), sectionsDb; appDb.on('load', function() { sectionsDb = dirty('sections.db'); sectionsDb.on('load', function() { if (typeof req.session.once=="undefined") { // once per user session to display message/alert locals.once=appDb.get('page').once; req.session.once=1; } res.render('index.ejs', {locals:locals,sections:sectionsDb,app:appDb.get('app'),page:appDb.get('page'),msg:req.query.msg,err:req.query.err}); }); }); });
The code above provides an example of reading from the ‘dirty’ database, and is fairly self-explanatory. First, the application settings are loaded into variable ‘appDb‘. When the appDb ‘load’ event occurs, we get the section content and load it into variable ‘sectionDb‘. With node-dirty, we always wait for the ‘load’ event when reading from the databases, and use ‘.get’ to read a record (based upon its’ unique key). The call to res.render passes the loaded data as a JSON object to the ‘index.ejs’ template file. The JSON object contains the data for ‘sections’ and ‘app’ that can be referenced in the ‘index.ejs’ template (ie. <%= section.title %>). I also use the ‘msg’ and ‘err’ to pass in any notifications that we need to display when ‘index.ejs’ is rendered.
In Part 2, I’ll cover the UI (presentation) portion of the single page app including a detailed look at the EJS templates and Twitter Bootstrap.
Cross Domain (External) Ajax calls with JQuery / Javascript
Thanks, I wasn’t aware of this crossDomain option in JQuery, but I found James Padolseys’ cross-domain Jquery guide helpful. The Use jQuery site also has a good example and demo of cross domain, Flash Proxy and YQL.
Issues
1. As of jQuery 1.5, the success callback function receives a “jqXHR” object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
2. Cross-domain requests are inherently insecure. Either you are sending credentials over clear text, OR, you cannot make cross-domain requests (not without an ugly client side warning atleast) on HTTPS.
Solution
jQuery 1.5, there has been a new property added to $.ajax. It’s called ‘crossDomain’.Default: false for same-domain requests, true for cross-domain requests. If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true.
The server side redirection is quite simple to do in PHP, as shown below,
1: $data = '{"name" : "hello world"}';
2: echo $_GET['jsoncallback'] . '(' …
View original post 216 more words
Find the right side (value) of expression in Java.
A simple example using RegEx:
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile("[\\d\\w\\s'\"]+\\z"); Matcher matcher = pattern.matcher("value=\"hello my name is bob\""); while (matcher.find()) { System.out.print("found:'"+matcher.group()+"'"); }
prints…
found:'”hello my name is bob”‘
This will work for strings containing apostrophes and quotes too. Any quotes (“) must first be escaped with a \ in the search string.
JSON Serializers on C# / .NET – Late 2011
JSON has been around for a while now, and it’s appeal is still growing in the interest of things like REST services and the NoSQL (A.K.A Document) database movement (FYI – I’m much more fond of the NoSQL movement than the Occupy movement). But, yet, it still seems that a good JSON serializer is hard to come by.
I’m in the habit of making my apps simply aware of an ISerializer so that I can choose to implement the JSON-serializer-of the-day. I have toyed with a few JSON serializers:
Json.NET
JayRock
DataContractJsonSerializer
JSONSharp
LitJSON
JavaScriptSerializer
They’re all sort of <OK>, and each one presents various performance and other anomalies to work around. However, with my new found excitement with CouchDB, (hey just stinkin’ relax) I really wanted to find a good JSON serializer. To my pleasure I found some promising new ones:
The performance was great! But the maturity was lacking. (Sound familiar ladies?) Despite fastJSON showing some impressive results, it didn’t actually work on many of my not-so-exotic POCO’s. ServiceStack turned out much better. My only suggestion was better recognition of the [DataMember] attributes (ie; name=) so that it provided more Deserialization flexibilty when the JSON string didn’t exactly match the POCO properties. So here is how my latest ISerializer impl looks:
————————————————————————————
using System; using ServiceStack.Text; namespace MyProject.Serializers { /// <summary> /// This is an implementaion ISerializer that uses the ServiceStackText JSON /// </summary> public class ServiceStackJsonSerializer : ISerializer { public string Serialize<T>(T obj) { string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString<T>(obj); return jsonText; } public T Deserialize<T>(string json) { T obj; obj = (T)ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(json); return obj; } public Object Deserialize(string json, Type type) { Object obj; obj = ServiceStack.Text.JsonSerializer.DeserializeFromString(json, type); return obj; } } }
————————————————————————————
Does anyone have other recommendations? Reading through Stackoverflow, it looks like JSON.Net is very popular, and — in the end I like it too. However, I still hope to find a JSON serializer that’s faster.
Hibernate and Postgres – a custom UserType to handle arrays
Here is a custom Hibernate UserType that will work to persist Java array types (string[], int[], boolean[], etc..) in a single column. I have seen Oracle implementations, but here is one that uses Java.sql.array and works for Postgres. If you’d like to know more about how this works, Andrew Phillips has written a great explanation of custom Hibernate UserTypes.
Enjoy!
_______________________
import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.sql.Array;
import org.hibernate.*; import org.hibernate.usertype.UserType;
/* * Custom UserType implemented to store java array (ie; String[]) types */ public class CustomArrayType implements UserType { public int[] sqlTypes() { return new int[] {Types.VARCHAR}; }
public Class returnedClass() { return String[].class; }
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
Array result = null; Array array = (Array) resultSet.getArray(names[0]); if (!resultSet.wasNull()) result = array; return result; }
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException { if (value == null) statement.setNull(index, 0); else { statement.setArray(index, (Array)value); } }
public Object deepCopy(Object value) throws HibernateException { return value; }
public boolean isMutable() { return false; }
@Override public Object assemble(Serializable arg0, Object arg1) throws HibernateException { // TODO Auto-generated method stub return null; }
@Override public Serializable disassemble(Object arg0) throws HibernateException { // TODO Auto-generated method stub return null; }
@Override public boolean equals(Object arg0, Object arg1) throws HibernateException { // TODO Auto-generated method stub return false; }
@Override public int hashCode(Object arg0) throws HibernateException { // TODO Auto-generated method stub return 0; }
@Override public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException { // TODO Auto-generated method stub return null; }
}
How to map smallint type in Hibernate to Postgres
Hibernate does define a “smallint” type. If you try to set the Type to smallint, you’ll get an error stating “Could not determine type for: smallint”. So what type should be used when mapping to a smallint field? The answer is to use “short:
RegEx Pattern (Java) for Finding or Matching Operators
Here is a regular expression pattern that can be used to find the operator in a SQL expression. For that matter any F=V type expression. Given a “field (operator) value” expression, this regex pattern will match and find the operator portion in strings such as…
field = value, field > value, field >=, field <= value, field value, etc..
Pattern: [=\\]*[^a-zA-Z0-9]
Note – The above pattern worked for Java 1.6, and on other languages it maybe possible to remove so of the escape slashes in the “[=\\]” portion to “[=]”.
If you would like to find other RegEx patterns, I recommend GSkinner’s RegExr. Click the “community” tab on the right and you’ll discover a lot of useful patterns:
How I defeated the maven-release-plugin in a flat structured multi module project (via warpedjavaguy)
Thanks for clearing my M2 multi-module confusion. My problem was trying to mavenize multiple “flat” ANT projects. I created a new Maven parent project, and was then able to add child modules to it using your guidance.
via warpedjavaguy
Awesome Blog-of-the-Day
In my quest for good blogs, I will find by daily favorite and post it in this category. This may sound like a cliche idea, but I hope to stick with a few equally weighted criteria for my “Blog of the day” selections:
- up-to-date content (a.k.a Fresh)
- visually pleasing (at least to me)
- not too long or philosophical
- useful, unique and informative
I hope that my selections don’t look like the WordPress popular list. Let me know about your blog and an elevator pitch as to why you think it should be an awesome blog of the day.