Friday, October 28, 2011

Creating HTTP or HTTPS Connection programmatically in Java

I create a class HttpUtil

Usage example

HttpUtil http = new HttpUtil();
 

http.setDoOutput(true); 
http.setDoInput(true);
http.setContentType("application/x-www-form-urlencoded");
http.setAllowUserInteractions(false);
           
String response = http.request("www.mydomain.com/process.php", params, "POST");


System.out.println(response);

params should be a HashMap for example

HashMap<String, String> params = new HashMap<String, String> ();
params.put("username","ali");
params.put("password","somepassword");

Using Batik Rasterizer in Java

In this example will create a exporting server for Highchart in Java. Since the default example is in PHP, and I'm using Java and tomcat as my web server.

I convert the PHP exporting script example to Java servlet code.

public class ReportExporter extends HttpServlet {

    protected void doPost(HttpServletRequest request, 

                          HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext application = this.getServletContext();

        String type = request.getParameter("type");
        String svg = request.getParameter("svg");
        String filename = request.getParameter("filename");
       
        System.out.println("type: " + type);
        System.out.println("svg: " + svg);
        System.out.println("filename: " + filename);
        System.out.println("width: " + request.getParameter("width"));

        if (filename == null && filename.equals("")) {
            filename = "chart";
        }

        String typeString = "";
        String ext = "";
        String outFile = "";
        String width = null;
        String tempName = null;

        try {
            tempName = SecurityUtil.md5(String.valueOf(System
                    .currentTimeMillis()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (type.equals("image/png")) {
            typeString = "-m image/png";
            ext = "png";
        } else if (type.equals("image/jpeg")) {
            typeString = "-m image/jpeg";
            ext = "jpg";
        } else if (type.equals("application/pdf")) {
            typeString = "-m application/pdf";
            ext = "pdf";
        } else if (type.equals("image/svg+xml")) {
            ext = "svg";
        }

        outFile = "temp/" + tempName + "." + ext;
        if (!typeString.equals("")) {
            width = request.getParameter("width");
            if (width != null && !width.equals(""))
                width = "-w " + width;
        }

        // Generate temporary file
        File f = new File(application.getRealPath("/temp/" + tempName
                + ".svg"));
        IOUtil.writeToFile(f, svg);
       
        String batikPath = application.getRealPath("/WEB-INF/lib/batik-rasterizer.jar");
        String classPath = "-cp " + application.getRealPath("/WEB-INF/lib");
        String outFileFullPath = application.getRealPath(outFile);
        String tempFileFullPath = application.getRealPath("temp/"+tempName+".svg");
       
        try {
           
            // Convert SVG file into specified type
            SystemUtil.runCommand("java",classPath, "-jar",batikPath, typeString,"-d",outFileFullPath,width,tempFileFullPath);


            // Show the file to user as download
            response.setHeader("Content-disposition", "attachment; filename=" + filename + "." +ext);
            response.setHeader("Content-type", type);
           
            ServletOutputStream out = response.getOutputStream();
           
            IOUtil.fileToStream(new File(outFileFullPath), out);
           
            out.flush();
            out.close();
        } catch (Throwable e) {
            e.printStackTrace();
            response.getOutputStream().print("Error on exporting");
        }
    }
}


You will need these classes
SystemUtil
IOUtil

This example use Batik rasterizer. Please download it here. Then place it your web application folder
WEB-INF/lib/batik-rasterizer.jar
WEB-INF/lib/batik-slideshow.jar
WEB-INF/lib/batik-squiggle.jar
WEB-INF/lib/batik-svgpp.jar
WEB-INF/lib/batik-ttf2svg.jar
WEB-INF/lib/lib -> contains lib for batik (see batik distribution batik-version/lib)

Thursday, October 27, 2011

Reset programmatically in Blackberry device

Create a dummy application

    public class DummyApp extends Application{ 
     
        public static void main( String[] args ) 
        { 
            new DummyApp().enterEventDispatcher(); 
        } 
    } 

Compile the code into .cod file and place in your project
let's say MyProject/res/DummyApp

in your main program add this method

    private void reset() {
        try {
               byte[] codData = getResource("/DummyApp");
           
            int dummycodhandle = CodeModuleManager.createNewModule(codData.length, codData, codData.length);
     
                //Save the module
            int result = CodeModuleManager.saveNewModule(dummycodhandle, true);
            if (result != CodeModuleManager.CMM_OK && result != CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN)
            {
                //The cod file was not saved.
                throw new Exception("Failed to save dummy cod.");
            }
                          
           int dummycodhandle2=CodeModuleManager.getModuleHandle("DummyApp");
           ApplicationDescriptor[] desc = CodeModuleManager.getApplicationDescriptors(dummycodhandle2);

           ApplicationManager.getApplicationManager().runApplication( desc[0], false );

           // Make sure the application is already started, assume 5 seconds is enough     
           Thread.currentThread().sleep(5000);
          
           CodeModuleManager.deleteModuleEx(dummycodhandle2,true);
           CodeModuleManager.promptForResetIfRequired();
        }
        catch (Exception e) {
            e.printStackTrace();
    }
    }
   
    private byte[] getResource(String name)
    {
        DataBuffer db = new DataBuffer();
        byte[] data = new byte[1024];
        DataInputStream input = new DataInputStream(UiApplication.getUiApplication().getClass().getResourceAsStream(name));
       
          int len = 0;
            try{
               while ( -1 != (len = input.read(data)) )
               {
                   db.write(data, 0, len);
               }
            }catch(Throwable e)
            {
                e.printStackTrace();
            }
            return db.getArray();                  
    }

When you want to ask your device to restart, just call the method reset()

Monday, October 17, 2011

Get Latitude and Longitude based on provided data using Java

We can get Latitude and Longitude based on MCC, MNC, LAC, Cell ID


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * GetLocation provide mechanism to get location based on MCC, MNC, LAC, and Cell ID
 *
 * @author Ali Irawan
 * @version 1.0
 */
public class GetLocation {

    /**
     * Get location  based on MCC, MNC, LAC, and Cell ID
     *
     * @param mcc mobile country code
     * @param mnc mobile network code
     * @param lac location area code
     * @param cellId cell id
     * @param requestAddress true if want to get address
     * @return JSON String representation of position
     *      * @throws IOException
     */
    @SuppressWarnings("unused")
    public static String getLocation(String mcc, String mnc, String lac,
            String cellId, boolean requestAddress) throws IOException {

        final String data = "{\"cell_towers\": [{\"location_area_code\": \""
                + lac + "\", \"mobile_network_code\": \"" + mnc
                + "\", \"cell_id\": \"" + cellId
                + "\", \"mobile_country_code\": \"" + mcc
                + "\"}], \"version\": \"1.1.0\", \"request_address\": \""
                + requestAddress + "\"}";
        final String url = "https://www.google.com/loc/json";

        URL anUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) anUrl.openConnection();

        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/jsonrequest");

        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes());
        out.close();

        InputStream in = conn.getInputStream();

        StringBuilder builder = new StringBuilder();
        Reader reader = new InputStreamReader(in);
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            builder.append(String.valueOf(buf, 0, read));
        }
        in.close();
        conn.disconnect();

        return builder.toString();
    }
}


Example of use:

String location = GetLocation.getLocation("510", "89", "9250", "851", true);
       
System.out.println(location);

Output:

{
   "location":
      {  
         "latitude":-6.2452443,
         "longitude":106.7908857,
         "address": {
                "country":"Indonesia",
                "country_code":"ID",
                "region":"Jakarta Capital Region",
                "city":"Jakarta Capital Region",
                "street":"Jalan Gandaria Tengah 4",
                "postal_code":"12240"
             },
         "accuracy":713.0
       },
   "access_token":"2:C5RroEdSGjSfnq9X:7oAhDHrp_5xzgTeU"
}