Archive for April, 2008

Uploading a file into a database with JSP

Posted on April 11th, 2008 in Uncategorized | No Comments »

These days I’ve came uppon the problem of uploading an image to a web server and save it into a database as a Blob field with JSP. After some research and some experiencing on my own the solution that worked for my case looked like this:

  • The upload form:
  • <form method=post action="includes/upload.jsp?imgId=<%=iNumPhoto%>"
    name="upform" enctype="multipart/form-data">
    
    onchange="LimitAttach(this.form, this.form.uploadfile.value)">
    

    Where “iNumPhoto” is a parameter that i use when i need to overwrite an image (it’s set to -1 when the image is new), and “LimitAttach” is a JavaScript function that limits the types of file that can be submited trough my upload form.

  • “LimitAttach” function:
  • The Jsp file looks like this:
  • 
    
    <%@ page import="java.io.DataInputStream" %>
    <%@ page import="java.io.FileOutputStream" %>
    <%@ page import="java.util.Hashtable" %>
    
    <%
    String iNumPhoto = request.getParameter("imgId");
    String contentType = request.getContentType();
     if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
       DataInputStream in = new DataInputStream(request.getInputStream());
       int formDataLength = request.getContentLength();
       byte dataBytes[] = new byte[formDataLength];
       int byteRead = 0;
       int totalBytesRead = 0;
       while (totalBytesRead < formDataLength) {
           byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
           totalBytesRead += byteRead;
        }
       String file = new String(dataBytes);
       String saveFile = file.substring(file.indexOf("filename=\"") + 10);
       saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
       saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
       int lastIndex = contentType.lastIndexOf("=");
       String boundary = contentType.substring(lastIndex + 1, contentType.length());
       int pos;
       pos = file.indexOf("filename=\"");
       pos = file.indexOf("\n", pos) + 1;
       int boundaryLocation = file.indexOf(boundary, pos) - 4;
       int startPos = ((file.substring(0, pos)).getBytes()).length;
       int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
       FileOutputStream fileOut = new FileOutputStream(saveFile);
       int imageSize = endPos - startPos;
       byte[] imgBuffer = new byte[imageSize];
       byte[] width = new byte[4];
       // Calculate width from byte position 17 to 20 of PNG header
       System.arraycopy(dataBytes, startPos + 16, width, 0, 4);
       Integer myWidth = (width[0] * 16 * 3) + (width[1] * 16 * 2) + (width[2] * 16) + width[3];
       System.arraycopy(dataBytes, startPos, imgBuffer, 0, imgBuffer.length);
       Hashtable< Integer, Object> messageImages = message.getMessageImages();
       if (!iNumPhoto.equals("-1")) {
       Integer idPhoto = Integer.parseInt(iNumPhoto);
       MessageImage messageImage = (MessageImage) messageImages.get(idPhoto);
       if (!myWidth.equals(messageImage.getWidth())) {
       out.print(" The selected image has an invalid width! Please select a valid one! (width = "+myWidth+")");
                    out.print("");
                    //todo send error
                } else {
                    messageImages.remove(idPhoto);
                    messageImage.setWidth(myWidth);
                    messageImage.setData(imgBuffer);
                    messageImages.put(idPhoto, messageImage);
                    message.setMessageImages(messageImages);
                    out.print(" Image replaced! (width = "+myWidth+")");
                    out.print("");
                }
        } else {
             MessageImage newImage = new MessageImage();
             newImage.changeMandatoryValues(new String[]{"id", "messageId"}, new String[]{"-1", message.getId()});
            newImage.setWidth(myWidth);
           newImage.setData(imgBuffer);
           messageImages.put(-1, newImage);
           message.setMessageImages(messageImages);
    %>

    The tricky part was getting separated the byte-array containing the image, from all the data sent by the upload form (yes the form doesn’t send only the file). After that all easy, even figured out how to get the image width. I’m using a bean called “message”, and the “saving into the database” part is done by passing the byte-array to the bean where all the data-base related operations take place.

    Hot topic: pregnant “man”

    Posted on April 10th, 2008 in humour, people | 1 Comment »

    MALESHE! the real man!!!.

    MAN….my ass Vs. a real MAN!! :))

    All over the place they keep talking about the new pregnant “man”, but nobody is saying that the “mother” to be…. now claimbing that she/he is a man was a woman (lesbian). So if the poor woman was confused and decided to suddently become a “man” it’s not imperative to confuse the whole world.
    NO SHE IS NOT A MAN (dude) HE is and will be a woMAN, and the only way that a MAN could get pregnant(or look like pregnant) is from years and years of heavy beer drinking! :)

    Quote : “you know….i’ve learned that i’ve really been a dude all along, because the key difference betwen man and women is that women can have babies. If you can’t have babies … than you’re a MAN!”

    p. s. new South Park episode - “Eek-a-Penis!”- here

    Posting source code in WordPress

    Posted on April 10th, 2008 in programming | 1 Comment »

    ….Googled it!

    First atempt: Ended up here, tried [sourcecode language='css']…[/sourcecode] and got no result. (guess that this works only for wordpress.com users….no harm done)

    At a second try: got a plugin here (syntaxhighlighter Google Code project by Alex Gorbatchev). Copied it to my server into the wp-content/plugins, activated it from the wp-admin and… that’s it. It works like this: Place your code on the page and surround it with < pre > tag. Set name attribute to code and class attribute to one of the language aliases you wish to use. Works for: XML/HTML, C++ (cpp, c, c++), C# (c#, c-sharp, csharp), CSS (css), Delphi/Pascal (delphi, pascal), Java (java), Java Script(js, jscript, javascript), PHP (php), Python (py, python), Ruby (rb, ruby, rails, ror) , Sql (sql), VB (vb, vb.net ).
    After playing around a bit with the style my first try looked like this:

    if($you_can_see_this)
                echo "syntaxhighlighter works!";
    

    So from now on i will post pieces of code that trigger my attention.

    W3C Has Published HTML 5

    Posted on April 9th, 2008 in programming | No Comments »

    January 22nd 2008: W3C published a working draft for HTML 5. The HTML 5 working group includes AOL, Apple, Google, IBM, Microsoft, Mozilla, Nokia, Opera and many hundred other vendors.

    Some of the new features in HTML 5 are functions for embedding audio, video and graphics, client-side data storage, and interactive documents. Other features are new page elements like <header>, <section>, <footer>, and <figure>.

    HTML 5 improves interoperability and reduce development costs by making precise rules on how to handle all HTML elements, and how to recover from errors.

    See full HTML 5 Reference

    Terry Gilliam’s "Fear and Loathing in Las Vegas"

    Posted on April 8th, 2008 in movies | No Comments »

    Go Johnny go!!!!

    Raoul Duke: When I came to, the general back-alley ambience of the suite was so rotten, so incredibly foul. How long had I been lying there? All these signs of violence. What had happened? There was evidence in this room of excessive consumption of almost every type of drug known to civilized man since 1544 AD. What kind of addict would need all these coconut husks and crushed honeydew rinds? Would the presence of junkies account for all these uneaten french fries? These puddles of glazed ketchup on the bureau? Maybe so. But then why all this booze? And these crude pornographic photos smeared with mustard that had dried to a hard yellow crust? These were not the hoofprints of your average God-fearing junky. It was too savage. Too aggressive.

    Raoul Duke: Few people understand the psychology of dealing with a highway traffic cop. A normal speeder will panic and immediately pull over to the side. This is wrong. It arouses contempt in the cop heart. Make the bastard chase you. He will follow. But he won’t know what to make of your blinker signal that says you are about to turn right. This is to let him know you’re pulling off for a proper place to talk. It will take him a moment to realize that he’s about to make a 180 degree turn at speed, but you will be ready for it. Brace for the g’s, and fast heel-toe work.

    Raoul Duke: We had two bags of grass, seventy-five pellets of mescaline, five sheets of high-powered blotter acid, a saltshaker half-full of cocaine, and a whole galaxy of multi-colored uppers, downers, laughers, screamers… Also, a quart of tequila, a quart of rum, a case of beer, a pint of raw ether, and two dozen amyls. Not that we needed all that for the trip, but once you get into locked a serious drug collection, the tendency is to push it as far as you can. The only thing that really worried me was the ether. There is nothing in the world more helpless and irresponsible and depraved than a man in the depths of an ether binge, and I knew we’d get into that rotten stuff pretty soon.

    …Don’t fuck with me now, man, I am Ahab.!

    2008 Dodge Challenger

    Posted on April 8th, 2008 in cars | No Comments »


    Revealed in 2006 as a concept and introduced as a production model at the 2008 Chicago Auto Show, the new muscle car, inspired by the 70’s model, will launch from 0-60 mph in 4.9 seconds and cover the quarter-mile in 13.3 seconds.Under the hood, the Challenger will feature Dodge’s 6.1-liter overhead valve Hemi V8 and puts out 425 horsepower at 6200 rpm and 420 lb.-ft. of torque at 4800 rpm.

    The 2008 Challenger SRT8 will be offered in three colors: Brilliant Black Crystal Pearl Coat, Bright Silver Metallic, and Hemi Orange. Exterior features will include high-intensity discharge headlights, dual functional hood scoops, “carbon fiber-like” dual racing stripes, and a flat black rear lip spoiler.

    The 2008 Dodge Challenger SRT8 goes on sale this Spring with a price of $37,995!

    ….Now that’s a car!!

    ACELASI gust amar la fiecare reclama.

    Posted on April 8th, 2008 in enervari, pub | 1 Comment »

    Reteta: se iau 10 spoturi publicitare “random” difuzate zilele astea pe canalele TV romanesti. Se asculta cu voumul la minim (mute:) ).[totul pare ok.... iti dai seama care e tinta creatorilor spoturilor....de multe ori prea expliciti...]

    Pasul 2 : A se repeta experienta cu volumul pe “normal”. NU! nu e o gluma. Textele acelea sunt chiar reale! da… la una din 2 reclame se aude “acelasi/aceeasi”. “Acelasi gust” “acelasi pret” “acelasi ambalaj” “aceeasi aroma” “acelasi orice”. Chiar nu se schimba nimic?

    blue sunday[....]

    Posted on April 6th, 2008 in music | 1 Comment »

    ….

    fiat lanseaza "noul" 500 in Romania

    Posted on April 5th, 2008 in Events, cars | No Comments »

    now…

    Cei de la Fiat s’au dovedit mai atenti cu “mandra piata auto romaneasca” in ultima vreme, intensificand promovarea modelelor noi. Drept urmare soseste(dupa aproximativ 6 luni) noul model Fiat 500. Inginerii Fiat s’au intrecut pe ei insisi readucand la viata un model din anii 60, si au facut’o intr’un stil tipic italian. Masina este bine construita , pe platforma Fiat Panda, are propulsoare diverse iar designul este de invidiat(declarata cea mai frumoasa masina a anului in Europa).

    then…
    Fiat 500 este o masina frumoasa(cum se poate spune despre putine)… poate prea frumoasa pentru gusturile romanilor(care pentru cei 11500€ si’ar putea lua un “Bemve” din 2000 cu doar 100 000 km) si de aceea planul de a vinde 250 unitati pe piata romaneasca este unul destul de ambitios.

    new age documentary…

    Posted on April 5th, 2008 in enervari | No Comments »

    In ultima vreme combinatia fatala = un documentar pe un subiect nu foarte interesant + un scenariu/reconstituire (mai mult inchipuit/inflorit) de regizori si impersonat de actori de mana a 7a. Sa fie o strategie de atragere a maselor …. de umplere a pretiosului spatiu de emisie…. eu schimb tot mai frecvent canalul de pe posturile binecunoscute care erau pline de showuri destul de captivante odata.

    ….quality over quantity!?