Serve JAD files OTA with PHP

November 3, 2008 on 2:14 pm | In J2ME, PHP, Uncategorized | No Comments

Some handy code to dynamtically serve JAD files for OTA installation. The below script sets the appropriate headers types, also tidies up the JAD file removing stray characters which can cause issues and setting the correct file paths internally.

Place the PH script in a root directory as serveJAD.php. Place your JAR and JAD files in a subdirectory /J2ME

Call the script by serveJAD.php?format=J2ME&file={jad minus extension} or you can use the Apache rewrite below and call as /J2ME/file.jad

ie

serveJAD.php?format=J2ME&file=game

or with Apache rewrite

/J2ME/game.jad

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?
	$format   = $_GET["format"];
	$file     = $_GET["file"].".jad";
    header("Cache-Control: no-cache, must-revalidate,no-transform" );
    header("Pragma: no-cache" );
	header("Content-type: text/vnd.sun.j2me.app-descriptor");
	header("Content-Disposition: attachment; filename=".$file.";");
	$jad = file_get_contents("./".$format."/".$file);
	$lines = explode("\n",$jad);
	$final = "";
	foreach($lines as $line){
		$line = trim($line);
		if(strlen($line)>0){
			$keypair = explode(": ",$line);
			if($keypair[0]=='MIDlet-Jar-URL' || stristr($keypair[0],"RIM-COD-URL")){
				$url = trim($keypair[1]);
				if(!stristr($url,"http:")){
					$keypair[1] = "http://".$_SERVER["HTTP_HOST"]."/$format/".$url;
				}
			}else if($keypair[0]=='MIDlet-Jar-Size'){
				$keypair[1] =  filesize("./".$format."/".$_GET["file"].".jar");
			}
 
			$line = join(": ",$keypair);
			$l = trim($line);
			if(!empty($final))$final.="\n";
			$final.=$l;
		}
	}
	print($final);
?>


RewriteEngine On
RewriteRule /J2ME/(.*)\.jad /serveJAD.php?format=J2ME&file=$1

You can also use this to build automatic index pages, using this as dir.php?format=J2ME

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
	$format   = $_GET["format"];
	$scanthis = "./".$format;
 	$scanlisting = scandir($scanthis);
    $dirlisting = array();
    foreach($scanlisting as $key => $value){
		if(stristr($value,"jad")){
			$name = explode(".",$value);
			$dirlisting[$name[0]] = $name[0];
		}
	}
	ksort($dirlisting);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="apps.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Application listing</title>
</head>
<body>
<p>
<?php foreach($dirlisting as $name){
?>
<a href="/<?php print($format);?>/<?php print($name);?>.jad"><?php print($name);?></a><br />
<?php
}
?></p>
</body>
</html>
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Converting a Midlet to a COD file for OTA installation

February 14, 2008 on 12:01 pm | In RIM / Blackberry, Uncategorized | 3 Comments

God, RIM sucks. Thought I’d mention that. I hate Blackberries with passion. Really.

Now, if you are converting a Midlet to a COD file, you will need to use the infamous rapc tool provided with the RIM JDE ( in the bin directory if you are looking for it ) . Now, along with issues with multiple versions, bugs and what have you, one big pain is if you want the RIM version of the JAD file created for OTA installation, rapc doesn’t give you all the parameters if you use the -midlet paramater. If you DON’T use it, you get a nice JAD but the COD will not work.

So, to get around this, I created a small app to extract the RIM specfic information from the COD file generated by rapc.

Generated the COD using

rapc import="%jde%\lib\net_rim_api.jar" codename=%jar% -midlet jad=%jar%.jad %jar%.jar

where %jde% is your JDE path, %jar% is the name of your module.

Extract JAD information from a COD file

To run:

java -jar cod2jad.jar {cod file} {module name}

This will dump the extra information to stdout, so you can just append it to your JAD file with >>, ie

java -jar cod2jad.jar path.cod myapp >> path.jad

Remember, once you have done this, open the COD file in winzip ( or whatever ) and extract the seperate elements to your webserver. Once note, if you COD is only made of one module, this will probably fail ( sorry ).

Oh, and if you are using Netbeans components, and/or getting verification errors, try turning down your obfusication level in your project - rapc hates the splash screen and wait screen when obfusicated for some reason. The other option is to try including the net_rim_api.jar in your project ( but don’t include in the package ).

And even nicer of me, here is the source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.magnetmobile.tools.rim;
 
/**
 *
 * @author Sime when drunk ... yay drunk code
 */
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
public class Cod2Jad {
 
    public static void main(String args[])throws NoSuchAlgorithmException {
 
        FileInputStream fis = null;
        try {
            int count = 0;
            if (args.length != 2) {
                System.out.println("usage: {path to COD} {Module name}");
                System.exit(-1);
            }
            Hashtable htSizes = new Hashtable();
            Hashtable htJarContents = new Hashtable();
            fis = new FileInputStream(args[0]);
 
 
            BufferedInputStream bis = new BufferedInputStream(fis);
            ZipInputStream zis = new ZipInputStream(bis);
            ZipEntry ze = null;
            while ((ze = zis.getNextEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
 
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1) {
                    size = ((Integer) htSizes.get(ze.getName())).intValue();
                }
                byte[] b = new byte[(int) size];
                int rb = 0;
                int chunk = 0;
                while (((int) size - rb) > 0) {
                    chunk = zis.read(b, rb, (int) size - rb);
                    if (chunk == -1) {
                        break;
                    }
                    rb += chunk;
                }
                htJarContents.put(ze.getName(), b);
                process(ze, count, b);
                count++;
            }
 
            System.out.println("RIM-COD-Module-Name:" + args[1]);
            System.out.println("RIM-COD-Module-Dependencies: net_rim_cldc");
            System.out.println("RIM-COD-Creation-Time: 1202924527");
 
            zis.close();
            bis.close();
            fis.close();
        } catch (IOException ex) {
            System.out.println("Could not access file "+args[0]);
            System.exit(-1);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(Cod2Jad.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 
    private static void process(Object obj, int count,byte[] data) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
        ZipEntry entry = (ZipEntry) obj;
        String name = entry.getName();
        long size = entry.getSize();
        long compressedSize = entry.getCompressedSize();
 
        String output = "RIM-COD-URL" + (count > 0 ? ("-" + count) : "") + ": " + name;
        System.out.println(output);
 
        output = "RIM-COD-Size" + (count > 0 ? ("-" + count) : "") + ": " + compressedSize;
        System.out.println(output);
 
        output = "RIM-COD-SHA1" + (count > 0 ? ("-" + count) : "") + ": ";
        output +=  SHA1(data, true);
        System.out.println(output);
    }
 
    private static String convertToHex(byte[] data, boolean spaced) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i <
                data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9)) {
                    buf.append((char) ('0' + halfbyte));
                } else {
                    buf.append((char) ('a' + (halfbyte - 10)));
                }
 
                halfbyte = data[i] & 0x0F;
            } while (two_halfs++ < 1);
 
            if (spaced) {
                buf.append(' ');
            }
        }
 
        return buf.toString();
    }
 
    public static String SHA1(byte[] data, boolean spaced)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md =
                MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(data, 0, data.length);
        sha1hash =
                md.digest();
        return convertToHex(sha1hash, spaced);
    }
}
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Java based Google Sitemap generator

October 21, 2007 on 5:18 pm | In Java | 3 Comments

Very basic sitemap generator written in Java. Also useful for creating a dump of the URLs in your site ( pipe output to file )

Dowload here

This is still in beta form, but does work. Add your comments or request on this post.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Drawing filled polygons in J2ME

May 11, 2007 on 10:13 am | In J2ME, Java, Useful stuff | No Comments

Check this sourceforge project for a really useful class.

http://sourceforge.net/projects/jmicropolygon/

Works really well on most of the phones we have tried it one. Once you have this class you can then do filled and stroked thick lines in J2ME.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Find the point at which 2 lines intersect

May 11, 2007 on 10:07 am | In Java, Useful stuff | No Comments

Given two lines ( defined as 2 x,y coordinates in an array ), this will return the x,y position at which the two lines intersect. If they do not intersect, it will return null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public Coordinate intersects(Coordinate[] coA,Coordinate[] coB ) {
 
        double x11 = coA[0].getX();
        double y11 = coA[0].getY();
        double x12 = coA[1].getX();
        double y12 = coA[1].getY();
        double x21 = coB[0].getX();
        double y21 = coB[0].getY();
        double x22 = coB[1].getX();
        double y22 = coB[1].getY();
 
        double dx1 = x12 - x11;
        double dy1 = y12 - y11;
        double dx2 = x22 - x21;
        double dy2 = y22 - y21;
        double det = (dx2*dy1-dy2*dx1);
 
        Coordinate coReturn = null;
 
        if (det != 0.0) {
            double mu = ((x11 - x21)*dy1 - (y11 - y21)*dx1)/det;
            if (mu >= 0.0  &&  mu <= 1.0) {
                coReturn = new Coordinate();
                coReturn.setX((int)(x21 + mu*dx2 + 0.5));
                coReturn.setY((int)(y21 + mu*dy2 + 0.5));
            }
        }    
        return coReturn;
}
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]
Next Page »

Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds. Valid XHTML and CSS. ^Top^