Blog Archive

Showing posts with label How To's. Show all posts
Showing posts with label How To's. Show all posts

Friday, February 20, 2015

Tutorial: How to transfer binary files (pdf,images etc) in json


This is a common scenario in most of today web apps.
Today's web applications heavily rely on json for client server communication. Because json is a totally text based standard it goes very well until we need to send anything which is not text, like pdf files and images. And it is not a good idea that you implement a separate module to transfer binary files, it will defeat the whole purpose of using json.
I my self struggled a lot to find a good solution for this. And I didn't found a strait forward and simple tutorial to handle binary files with json.
So I decided to write one. Please share your comments and suggestions so I can Improve it.

Theory:
As json only supports text so we have to convert binary file (pdf, image etc) in to a string. And then we can easily add it to a json field.

Code Example: In my example I am using java for server end but you can use your own tools and languages, Theory will remain same.

I am assuming that you are familiar with jsp-servlet development thats why I am leaving out unnecessary implementation details of J2EE application.

Required jar Files : commons-codec-1.5.jar

Server End:

//Servlet

public class GetPdfServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response )
{
doGet(request,response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response )
{
PrintWriter pw = null;
try{
pw = response.getWriter();

ByteArrayOutputStream ba= loadPdf(“myFile.pdf”);

//Converting byte[] to base64 string
//NOTE: Always remember to encode your base 64 string in utf8 format other wise you may always get problems on browser.
String pdfBase64String = org.apache.commons.codec.binary.StringUtils.newStringUtf8(org.apache.commons.codec.binary.Base64.encodeBase64(ba.toByteArray()));
//wrting json response to browser
pw.println("{");
pw.println("\"successful\": true,");
pw.println("\"pdf\": \""+pdfBase64String+"\"");
pw.println("}");
return;
}catch(Exception ex)
{
pw.println("{");
pw.println("\"successful\": false,");
pw.println("\"message\": \""+ex.getMessage()+"\",");
pw.println("}");
return;
}
}

private ByteArrayOutputStream loadPdf(String fileName)
{
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
}
} catch (IOException ex) {
ex.printStackTrace();
}
return bos;
}
}


Client End :

index.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<script type="text/javascript" src="/js/loadPdf.js"></script>
</head>
<body>
<div id='dataFormContainer'>
</div>
<form>
<input type='button' value='getPDF' onClick='getPdf()'>
</form>
</body>
</html>

LoadPdf.js

function getPdf()
{
var ax = getXMLHttpRequest();
ax.open('POST', "[your servlet url]",true);
ax.onreadystatechange=function()
{
if(ax.readyState==4 && ax.status==200)
{
var dataFormContainer = document.getElementById("dataFormContainer");
var response = eval("("+ax.responseText+")");
if(response.successful)
{
var url = "data:application/pdf;base64,"+response.pdf;
var _iFrame = document.createElement('iframe');
_iFrame.setAttribute('src', url);
dataFormContainer.appendChild(_iFrame);
}
}
}
ax.send();
}

NOTE: Always remember to encode your base 64 string in utf8 format at server end other wise you may always get problems on browser.

Wednesday, December 29, 2010

How To Write A C Program To Disable USB Devices

In this Post I will Teach U How To Make A Program Which Disable Ur All USB Ports.

Which U use To insert PEndrvie/Flashdrive

Using C\C++ Langauge.

First of all you need a 32 bit compiler for that.
For this example you can use microsoft Visual C++ compiler or
BloodShed's Dev C++ which is a free compiler for c and C++.
You can download Dev-C++ from following link:
http://www.blooodshed.net/download.html

So lets write the code. The following code will disable all usb ports of your computer.

BlockUSB.c

#include<stdio.h>

void main()
{
system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 4 \/f");
}

Compile and run above code. And then insert your usb pendrive, pendrive will not gonna be work.

To Re-Enable Usb Ports Compile and run following code.
UnBlockUsb.c

#include<stdio.h>

void main()
{
system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 3 \/f");
}

Thursday, May 6, 2010

How to use mouse in turbo c program.

This is very interesting to know how to use mouse in your turbo c program. In windows programs mouse support is inbuilt to program. But Turbo c is a 16 bit dos environment ide. So how can you do so in a dos application. We know that Turbo c is itself a dos based program. And it uses mouse,
so it is possible to use mouse in dos application.
You can use mouse in your turbo c program through issue a interrupt 0x33 which is mouse interrupt number in x86 architecture.
int86() function defined in dos.h is used to raise interrupts. But we also need to access and modify CPU registers like ax,bx etc. So there is a union called REGS in dos.h by which we can access CPU registers.
So by the use of this function int86() and union REGS you can write program to use mouse.

Following is an example of turbo c using mouse.

Try this and use mouse in your application. good luck!!!

#include<stdio.h>
#include<dos.h>
#define INTIALIZE 1
#define BUTTON_PRESS 5
#define LEFT_BUTTON_PRESS 0
#define RIGHT_BUTTON_PRESS 1
#define BUTTON_PRESSED 1

//unions to acces cpu registers
union REGS output,input;
void main()
{
//Setting value to intialize mouse device.
input.x.ax=INTIALIZE;
//int86 function function used to raise a interrupt.
//0x33 is mouse interrupt number.
int86(0x33,&input,&output);
printf("Press left mouse button to exit...");
//loop untile left mouse button is pressed
while(output.x.bx != BUTTON_PRESSED)
{
//setting register value to check for button press
input.x.ax=BUTTON_PRESS;
//setting register value to check for left mouse button press
input.x.bx=LEFT_BUTTON_PRESS;
//raising interrupt to check for mouse button press
int86(0x33,&input,&output);
}

}

How to print value of a register to screen.

How many times you thought to print result stored in a register to print on screen. This is rather difficult but there is no built in feature to print value stored in a register to screen(like printf("%d") in c).
So i have wrote a code to print result on screen. You can put this code in a separate
subroutine and you can call it any where in your program.

Basic Concept:
You know that only array of ASCII values can be print on screen by interrupt 21h.
I have just converted a number into ASCII string to print it.

So following is the code I wrote.



data segment
numberToBePrint dw 9870
charArray db 10 DUP('$')
ends
stack segment
ends
code segment
start:
mov ax,data
mov ds,ax
;setting ax register to ziro
sub ax,ax
;assigning number to be print on screen

mov ax,numberToBePrint


;first loop
Reapet:
mov cx,10
;divide ax by 10, remainder of divide will store in dx
div cx

;assigning address of first block of charArray to di register
mov di,offset charArray

mov cl,[di]
;assigning remainder in first block of char array
mov [di],dl
;changing numeric number into its ascii equivalent.
;by adding 48 to its value, 48 is ascii code of 0
add [di],48

;second loop
Reapet1:
;increment di to point to next block of array.
inc di
;logic for swaping array element to next block
mov bl,[di]
mov [di],cl
mov cl,bl
;if current block contains 0 then get out from loop
cmp cl,'$'
jnz Reapet1

;clearing remainder from dx
sub dx,dx
;checking ax for 0, if ax is 0 then get out from loop
cmp ax,0
jnz Reapet

;printing char array on the screen

mov dx, offset charArray
;9 is the interrupt service number used for screen display
mov ah,9
;calling dos for printing characters starting from location stored in dx
int 21h

;waiting for a key press.
mov ah,1
int 21h
mov ah,1
int 21h

;exit from program
mov ax,4c00h
int 21h
end start
ends