Couldn't get started with clojure kORMa - mysql

I am trying to use clojure kORMa with compojure, the webapp is here nepleaks.
First I added kORMa dependency
[korma "0.3.0-RC4"]
lein deps works cool, then created src/hotel/conf/datasource.clj which looks as follows :
(ns hotel.conf.datasource)
(use [korma.db])
(use [korma.core])
)
(defdb db (mysql {:db "nepleaks"
:user "root"
:password "mysql55"}))
(defentity users)
lein ring server is neither throwing any exception nor creating the database entity.
Am I missing something? Do I need more configuration?

My understanding is that Korma does not create the database nor the database tables for you, so you need to create them beforehand manually.

In the spirit of an example being worth 1000 words, I would recommend checking out the luminus clojure web framework. See http://www.luminusweb.net/ This framework sets up a lot of really useful libraries with very basic example use, including korma, ragtime, ring, compojure and some other nice libs. The default templates show you lots of nice ways of using these libraries and how to integrate them. You can then pick the bits you want. All you need to do to get started is run
lein new luminus <your project> +mysql
The web site has good documentation and the code is pretty clean and easy to understand. Saves hours when wanting to get up and running with a new library you are still comming to terms with.

you need lein ragtime plugin manage the database.

Related

Alternatives to CGI.pm for header() and param()?

I've been an avid user of CGI.pm since the previous millennium so I was a bit surprised when it disappeared from my old Ubuntu server when I upgraded it recently. My short-term fix was sudo cpan install CGI, but a quick web search to find out why it was missing in the first place revealed CGI::Alternatives which explains why it has gone and offers some suggestions for alternatives. For my purposes, HTML::Tiny looks best for replacing my programmatic HTML generation, but Alternatives is strangely silent on the subject of HTTP headers and CGI parameters.
I broadened by search and found lighter alternatives to CGI.pm on perlmonks where one response suggests CGI::Simple, but the recommendation is less than whole-hearted - "its not quite as up to date as CGI.pm".
So is CGI::Simple the way to go, or is there a better alternative?
Please don't spend time suggesting "rewrite everything using framework XXX". I really don't have the time or energy for that. I'm happy to replace all my HTML generation with HTML::Tiny, so I'm looking for something with a similar (or lower!) amount of rework to replace header() and param().
You're missing the point if you're looking for an alternative that provides header and param.
The argument for the removal of CGI.pm from core (but not from CPAN) is that you shouldn't have to deal with CGI yourself; you should be using a framework that handles this for you.
If you don't agree with this — if you're looking for an equivalent to header and param — go ahead and keep using CGI.pm.
If you do agree, CGI::Simple is no better than CGI.pm.
As others have said, there's no reason not to use CGI together with HTML::Tiny. So that's the answer to your question. For the last five years that I was using CGI, my programs all started something like:
use CGI qw[param header];
which is the approach you're talking about here.
If you wait a year or two, the plan is for the HTML generation functions to be removed from the main module, so your problems will all go away at that point.
But that's not what I'd do in your situation. I'd switch to using PSGI and Plack. You said that you don't want anyone to suggest a new framework, so I'm not going to do that. Plack isn't a framework, it's a toolbox for writing PSGI applications. Certainly, I'd use a framework like Dancer, but you don't have to. You can happily use Plack without any of the frameworks built on top of it.
You'll still get most of the advantages of PSGI. You'll be able to deploy your applications in any way you like. You'll have access to all the awesome Plack middleware. Testing your program will be far easier.
When you're using "raw" Plack, the equivalent of CGI::param is Plack::Request::parameters and the equivalent of CGI::header is Plack::Response::headers.
So there are three answers to your question.
Carry on using CGI.pm. Just stop using the HTML generation functions and replace them with HTML::Tiny
Use raw PSGI/Plack and bring your web development into the 21st century
Use one of Perl's many great web frameworks.
Unfortunately, you don't seem to like any of those answers.
The issue with CGI.pm is not that it's going away, merely that it will no longer be distributed as part of the core Perl distribution. However that doesn't mean you have to install from CPAN. On your Ubuntu system you can just do:
sudo apt-get install libcgi-pm-perl
and you'll be off and running with the same old CGI you know and love :-)
The correct answer to my question is that use CGI::Simple is better than use CGI qw(header param) because it loads faster.
Answers along the lines of "Use Plack, it's the future of Perl for websites" weren't helpful to me because I didn't have time to learn a new programming paradigm or to discover how to reconfigure my web server to make it work, no matter how insistent the Plack Evangelists were that I was wrong in what I was trying to do.
I've now had a bit of time to wade through the links to documentation and presentation slides I was offered and I can see what they were getting at, but one failing in what I've read so far is the lack of a concise end-to-end working example to help get my head around things ... so here's what I knocked together to get me started (and, no, I haven't finished yet!). I hope that others beginning the journey from CGI to PSGI will find this useful to help get them underway...
First you need to install Plack. I'm running an Ubuntu 14.04 installation so it was simply a matter of running sudo apt-get install libplack-perl. The generic way is to install Task::Plack from CPAN.
Next you need to know where your cgi-bin directory is located. You ought to know already if you're a CGI die-hard! Since I'm running Apache mine is defined in /etc/apache2/conf-available/serve-cgi-bin.conf by ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/.
Now for the magic. We're going to create a CGI script that runs a PSGI app, handing it data from the CGI environment. This is good for experimentation and testing but NOT for deployment, as you don't get any of the speed benefit that PSGI can give you (for that you need something like Plack::Handler::Apache2, Plack::Handler::FCGI or mod_psgi in Apache, or a dedicated PSGI server such as Starman or Starlet, or one of the other handlers mentioned on PlackPerl.org). Create /usr/lib/cgi-bin/psgi-cgi.pl with the following contents and make it executable:-
#!/usr/bin/perl
use Plack::Util;
use Plack::Handler::CGI;
my $app = Plack::Util::load_psgi($ENV{PATH_TRANSLATED});
Plack::Handler::CGI->new->run($app);
Next we need to tell Apache to pass PSGI app files to this handler. I did this by creating /etc/apache2/conf-available/psgi-cgi.conf containing:-
Action psgi-cgi /cgi-bin/psgi-cgi.pl
AddHandler psgi-cgi .psgi
then loaded it into my Apache server by running sudo a2enconf psgi-cgi and sudo service apache2 reload. Basically you need to get these lines into your httpd.conf file and restart the server.
Finally, my first PSGI script, which I created in my server's DocumentRoot as /var/www/html/hello.psgi:-
use Plack::Request;
my $app = sub {
my $env = shift;
my $req = Plack::Request->new($env);
my $par = $req->parameters;
return [
200,
[ 'Content-Type', 'text/plain' ],
[ "Hello world!\n",
map("$_ = ".join(", ", $par->get_all($_))."\n", sort keys %$par),
]
];
};
The application is a coderef which returns a 3-element arrayref: the first is the HTTP status code, the second is the name,value pairs for the HTTP header, the third is the body of the response (which could be generated using HTML::Tiny for a web page). The first 2 elements answer the question of what you need instead of the CGI::header function - nothing! (though for more complex handling you'll need Plack::Response::headers). The example also shows how to replace CGI::param - use Plack::Request::parameters, which returns a Hash::MultiValue object containing the values of URL (GET) and BODY (POST) parameters, including the ones with multiple values.
Finally, a test:-
$ wget -q -O- 'http://localhost/hello.psgi?a=1&a=2&a=3&b=1&b=4'
Hello world!
a = 1, 2, 3
b = 1, 4
I hope this is useful to other CGI die-hards in taking their first steps towards PSGI proficiency, and I hope the Plack Evangelists will acknowledge that it takes a lot of reading and comprehension to get even this far.
CGI::Minimal would a good option, it is much lighter than CGI & CGI::Simple, but it lacks advanced methods like CGI & CGI::Simple

Is this a job for Yeoman?

I use Yeoman, and I dig it.
However recently I have been wanting more complex code generation tools - now I know I can build custom generators, but I am wondering if people think this is the role/job/whatever that Yeoman is built to play.
Examples are,
Generating a base REST API (in Node) from a JSON schema
Generating MySQL DB Schema from JSON schema etc.
Although I could bend Yeoman to do this - do people think this is a realistic direction?
Is there a better tool for the job?
(Currently I have a bunch of custom Node scripts that suffice).
My humble opinion:
Yeoman is first and foremost a front end tool to create webapps.
Your task seems to be backend related.
You can still use grunt to scaffold your project though.
http://gruntjs.com/project-scaffolding
Cheers

Project structure to use jquery ajax in spring mvc using json data in eclipse

I am new to spring mvc. I have a lot of doubts to be cleared before i can continue.
I want to create a simple application wherein an employee details such as name age phone etc is entered and through ajax call the form data has to be to sent to server using json. For server side i am using spring. And the submitted data has to be shown in a jquery data table. And again to retrieve data an ajax call has to be used to get the data as a json. And no binding tool like jackson should be used.
1.) how do i go about creating an application in eclipse. If i should do a simpel java project or a dynamic web project?
2.) Could any one pls provide a sample code of each of the steps.
Thank you in advance
First, I think it's easier to start with Maven, create a WAR project, and use that to generate the Eclipse project files, which you can then import. This has the advantage of allowing Maven to not only create the correct folder structure, but also let it manage your dependencies. There are plugins for Eclipse that help you work with Maven, and you should be able to find lots of How-Tos using Google. Otherwise, you would have to create a project type that generates the WAR, one of which I believe is a Web Project, and layout the folder structure manually.
After you have the proper folder layout, you will need to setup your web.xml to enable Spring, add your Java classes and view files (html, jsps, whatever), and build a WAR. The final step would be to deploy that WAR to a web container of some sort, like maybe Tomcat or Jetty. You can ether run it externally, or configure Eclipse to deploy and launch your WAR in the IDE directly. I prefer the latter approach, as it makes it easier to setup debugging, not that running it external makes it impossible.
In addition, I would recommend adding the Spring pluggins to Eclipse, or just download their STS (Spring Tool Suite), which is just Eclipse with all the Spring plugins already added and configured. STS has the bonus of already having tcServer available, which is Spring Source's flavor of Tomcat. Again, loads of how-tos available on how to do all of this.
Edit to answer first comment
I don't know if I can address your comment here fully, as it's a very broad request. You are basically asking how do I write a full application using jQuery and Spring MVC. The volumes of books dedicated to this subject, as well as many websites you could visit that give tutorials on how to start developing. In fact, I think the Spring website has a tutorial for building their demo Pet Clinic site using Spring MVC. What I will try to do is give you some direction on what you should be asking.
Spring MVC, as the name suggests, is a Model-View-Controller framework that leverages the Spring Framework. I will not attempt to go into any great detail, as again there are volumes of books out there on the subject of Spring and all its wonders, but in general Spring MVC wants an application broken into the following chunks:
1. The Model
These are the objects you are using to represent your "data". This can be data from a Database, flat file, some other web service call, or maybe just passed around in your Controller. You will hear them commonly referred to as domain objects or entities to name a few. But, no matter how you refer to them they are typically POJO (Plain Old Java Objects) Java Beans with no real business logic, who's only existence is to represent some "data" and how it relates to other "data".
Some people prefer to have this object know how to read/write itself to its data store, some people like to have an external object that is only used to handle the read/writes. These are sometime referred to as a DAO (Data Access Object) or a Repository. There are also frameworks you can use for dealing with this stuff, like Hibernate or JPA for databases.
2. The Service Layer
This isn't represented in the MVC acronym, and one might argue this is part of the "Controller", but it's usually a good idea to put your business logic into a service layer. This is typically a POJO class that has methods to do the things you need to do with your Model objects. It houses your business logic so all the business rules are in one place. These are usually split to represent business functions. For instance, if you had an application dealing with car purchases you might have one service class to deal with the User related functions (create a user, update a password, get his preferences), one to deal with inventory (what is in stock, what is on its way, what is the current sales price), and one to deal with making a purchase (validate the customer's credit, start the tag process, etc). Its also common for these services to have reference to each other. For instance, the User service above might use the Inventory service to get a list of VIN numbers for cars Bill sold last week.
3. The Controller
The controller is what glues the "view" to the service layer. It provides the mapping of the URLs in your app to the function(s) they perform in the service layer. Most people try not to clutter the Controller object with too much code, and try to push as much down into the Service layer as they can. But, as long as it's simple logic I personally don't mind having a tad bit of code in the Controller.
4. The View
This is what you are sending to the user. It may be a web page backed by a JSP. It may be an Excel spreadsheet report generated from user input. It may be a simple JSON response to a REST call. It's sort of "the sky's the limit" here. But, for the most part this is either a JSP view or a JSON or XML response from a web service call.
Now to address your comment more directly...
Since you are a novice, I would recommend one of 3 approaches:
Go get a book...do what the book says to do. There are tons out there. Find one that has a good walk-through of a project, and copy/paste their procedures. A good book will usually have a chapter on how to setup all the necessary tools (Eclipse, Tomcat/Jetty, etc)
Find a good how-to on the Internet. There are lots of people that have tutorials. Find one and copy/paste their procedures.
Use something like Spring Roo. Spring Roo is a code generation tool that can be used to build a fully working site with little to no code. I am a big fan of Roo, especially for lone developers not working in a team, as it can generate a TON of the boiler plate code most developers hate to write. It also does things in a very Spring-like fashion, since after all it was created by the Spring folks.
These will get you past the "how do I create the project in Eclipse" problem. Part 2 of question one is a little more tricky. I would say, for now, don't focus on AJAX and stuff. Focus on simply understanding how Spring MVC works. The problem is, you are basically trying to cram 10 things down at once. Spring MVC is hard enough to get your head wrapped around (the annotations, JSTL, EL, and the Spring custom tag libraries, not to mention all the other things you will probably be touching like Spring Data, etc), but then you want to add dynamic web pages, which is JavaScript (and most likely some framework like jQuery), and to cap it off you don't want to use anything like Jackson (not sure why, but ok...) to help ease the transition from Java to JavaScript. That's a tall order. Again, I would cut out AJAX/JavaScript stuff at first, get a good handle on how a SIMPLE application is built, and then you can jump into all the dynamic stuff.
For the last question, providing code samples, I would point you to mkyong's fantastic blog full of Spring-related tutorials as well as Spring's own Tutorial site and Spring's Sample site as a good starting point.

Loading Elixir/SQLAlchemy models in .NET?

A new requirement has come down from the top: implement 'proprietary business tech' with the awesome, resilient Elixir database I have set up. I've tried a lot of different things, such as creating an implib from the provided interop DLL (which apparently doesn't work like COM dlls) which didn't work at all. CPython doesn't like the MFC stuff either, so all attempts to create a Python lib have failed (using C anyway, not sure you can create a python library from .NET directly).
The only saving grace is the developer saw fit to provide VBA, .NET and MFC Interop C++ hooks into his library, so there are "some" choices, though they all ultimately lead back to the same framework. What would be the best method to:
A) Keep my model definitions in one place, in one language (Python/Elixir/SQLAlchemy)
B) Have this new .NET access the models without resorting to brittle, hard-coded SQL.
Any and all suggestions are welcome.
After a day or so of deliberation, I'm attempting to load the new business module in IronPython. Although I don't really want to introduce to python interpreters into my environment, I think that this will be the glue I need to get this done efficiently.

CGI language choice

Ok, I've asked a few related questions here and only ended up with more questions and I realized now it's because I don't have enough background info. So I'll make it more generic:
I need to make a simple web application. Static HTML/JQuery pages will send AJAX POST requests to some server side code, which will:
Read the POST variables passed in
Run some very simple logic
Hit a MySQL database for simple CRUD ops
Return a plain string of data to be consumed by the javascript on the page
I was assuming Ruby was a good choice for this as everyone is raving about how well it's designed, and I've been playing with it - not RoR, just Ruby for simple scripting tasks - and I kind of like it.
My question is, I'm hopelessly confused by the trillion helper libraries and frameworks out there. I don't know what these are and therefore if I need any/all of them: Rack, Sinatra, Camping, mod_ruby, FastCGI, etc.
Would it be easier to just learn PHP and us that? Or can I get away with just dropping my .rb files into the cgi-bin folder(I'm using Apache for hosting) and use the ruby cgi library to get my variables?
EDIT: As far as Rails, I'm just assuming that it's overkill for what I want but I might be wrong. I looked at it, and it seemed cool for generating data based web sites quickly, but that's not what I'm trying to do. I don't want any forms pages for the user. I don't want them entering data or viewing records. I don't even want to return any HTML. I just want a ruby script to sit on the server, get passed a few variables in a post request, and return a JSON string in response. I will need some basic cookie/session/state managment
This is a really easy thing to do in C# and ASP.NET with webservices, but it seems very confusing with the open source technologies.
You don't want to use any feature from a fully blown framework so don't use one. Less code = less bugs = less security nightmares.
CGI
CGI has some performance drawbacks in comparison to other methods, but is still (in my opinion) the simplest and easiest to use one. This is how you use the builtin cgi library:
require "cgi"
cgi= CGI.new
answer= evaluate(cgi.params)
cgi.out do
answer
end
rack
Another low tech easy to use variant would be rack. Rack is an abstraction layer which works for many webserver interfaces (cgi, fastcgi, webrick, …). It's simplicity can be compared to the one of only using cgi. Put the following into a file wich ends with .ru into your cgi directory.
#!/usr/bin/rackup
require "rack/request"
run (lambda do |env|
request= Rack::Request(env)
anwser= evaluate(request.params)
return [200, {}, answer]
end)
This does not seem very different from cgi, but it gives you much more possibilities. If youst execute this file on your local machine rackup will start the webrick webserver. This webserver will deliver the webpages you described in your .ru file.
Other interfaces
fast-cgi
fast-cgi works almost like CGI. The difference is, in CGI your script get's started for every request it has to work on. With fast-cgi, your script only starts once for all requests. There is a library available to write fast-cgi script in ruby.
mod_ruby
mod_ruby is a builtin ruby interpreter for apache. It works analog to mod_php in apache.
mongrel
mongrel is a standalone webserver for ruby applications. This is a simple hello world example with it.
require 'mongrel'
class SimpleHandler < Mongrel::HttpHandler
def process(request, response)
response.start(200) do |head,out|
head["Content-Type"] = "text/plain"
out.write("hello world!\n")
end
end
end
h = Mongrel::HttpServer.new("0.0.0.0", "3000")
h.register("/hello", SimpleHandler.new)
h.run.join
Mongrel is often used for rails and other ruby frameworks. Most people use an apache or something else on port 80. This webserver than distributes the requests to several mongrel servers running on other ports. I think this is totaly overkill for your needs.
phusion passenger
passenger is also called mod_rails or mod_rack. It is a module for apache and nginx to host rails and rack applications. According to their websites rails with passenger uses 1/3 less ram than rails alone. If you write your software for rack, you could make it a little faster by using passenger, instead of cgi or fast-cgi.
Use jQuery and PHP.
Both technologies are well documented, and you should be able to get an application up and running in a matter of hours. You sound like you know a thing or two - talking about CRUD operations and so on - so I won't bore you with examples. And as far as JSON goes, there are probably a million PHP libraries out there, for outputting JSON objects.
Sinatra is very simple to learn and use. It's also easy to deploy with the use of Phusion Passenger (which is like mod_php for ruby frameworks like Rails and Sinatra). Instructions here: http://blog.squarefour.net/2009/03/06/deploying-sinatra-on-passenger/
If you find that you need more than what Sinatra will give you, I recommend Rails. Setting up that with Passenger is even easier since hardly any configuration is required. (see modrails.com).
PHP is very easy to use because it's designed specifically for this sort of thing. Want to read POST variables? They're in $_POST. Want to query MySQL? mysql_query("SELECT `something` FROM `table`");. And if you ever need help, Google searches for "php what_you_need_to_do" almost always return results on php.net, which is very helpful.
And for what you're doing, you don't need any additional frameworks.
I am curious about what I perceive to be your resistance to trying Rails. You say that you want "to spend more time on the scripting itself and less on configuration", and yet you seem to dismiss Rails out of hand. Rails is all about convention over configuration. If you take the time to learn how Rails does things, you can get an incredible amount of functionality "for free" just by following the conventions of the framework.
If you want to make a simple web app, Rails is really a very painless and good way to start. You can use a sqlite database and not even mess with MySQL (won't scale, but for learning or simple apps it's fine). It's true that there are simpler frameworks, but since you seem new to web programming, I'd recommend that you start with what will get you the most support in terms of documentation and knowledgeable folks. Follow the old adage: Get it working first, then optimize later.
The only sticking point I can see is the Apache integration... The consensus on Rails deployment these days seems to be focused on using lightweight httpds in place of Apache. There is a mod_fcgid which seems to be the best way to do it with Apache (mod_ruby is deprecated, buggy and slow, last I read) if you can do custom mods. Or there's Phusion Passenger, which seems to be the latest and greatest way to do it. Running Rails in a standard CGI environment will yield awful performance (but that goes for any CGI framework, really) due to the overhead of executing the interpreter + framework for every request. You'll get much better performance if you go with something that keeps the interpreter + framework in memory.
I personally like Django. I had a problem with Ruby on Rails where I just got overwhelmed by everything when I just wanted to do something simple, which it sounds like you want to do (since you said ROR feels like overkill). The cool thing I found with Django is that if you WANT everything, then you can get everything by plugging it in...but if you want less then you just don't plug in that technology and it's that much more lightweight.
Take for example "views". Django, like ROR, uses MVC. But if you just want to return a string of data and don't need the view, then you don't need to plug in the view. But if later on you decide that it will be more organized in a view then you can easily plug it in at that time.
Here's their website: http://www.djangoproject.com/