Home  | My Account  |  Membership
WorldDeveloper.org
Forum Details
Topics
Posts
Categories
 
577 member(s)
718,905 hit(s)
14 categories
51 topics
26 messages
0 online
Author Topics Replies Views Last Updated
hostj2me
43 topic(s)
23 post(s)
HostJ2ME.com Search Proxy 8 11321 August 26, 2009 4:36 PM

Provides search results for the OSM client by aggregating results from Google, Bing, Wikipedia, and Yahoo using the respective search APIs.

Example Usage:


SearchAgent agent = new SearchAgent();
Query query = new Query();
query.addHeader("user-agent","MySearchClient"));

query.setTerm("volvo xc60");
query.setTypes(FileRecord.TYPE_ALL);


List providers = new ArrayList();
providers.add("yahoo");
providers.add("live");
providers.add("google");
providers.add("googlevideo");
providers.add("wikipedia");

BasicUIListable results = agent.find(query,5*1000,100,providers.toArray(new String[0]));

for ( SearchResult record : results.items(pn,ps) )
{
System.out.println(record.getTitle());
}


Contact me if you need the full source code

hostj2me
43 topic(s)
23 post(s)
Midlet Icon Extractor 0 4079 January 21, 2009 5:13 PM

HostJ2ME.com uses the code below to extract application icons from Midlet jars and display them in the HostJ2ME.com midlet directory.


package com.astrientlabs.hostj2me.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import com.astrientlabs.files.AstrientFile;
import com.astrientlabs.util.Strings;

public class IconExtractor
{
private String MANIFEST = "META-INF/MANIFEST.MF";

public byte[] extract(String path) throws ZipException, IOException
{
return extract(new File(path));
}

public byte[] extract(File jarFile) throws ZipException, IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
ZipFile zipFile = new ZipFile(jarFile);
try
{
/*for ( Enumeration? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); )
{
System.out.println(e.nextElement().getName());
}*/

ZipEntry entry = zipFile.getEntry(MANIFEST);

InputStream is = zipFile.getInputStream(entry);
if ( is != null )
{
Properties props = new Properties();
props.load(is);

String iconFile = props.getProperty("MIDlet-Icon");
if ( Strings.isNull(iconFile) )
{
props.list(System.out);
String midlet1 = props.getProperty("MIDlet-1");
if ( !Strings.isNull(midlet1) )
{
String[] parts = midlet1.split(",");
if ( parts.length > 2 )
{
iconFile = parts[1].trim();
if ( iconFile.startsWith("/") )
{
iconFile = iconFile.substring(1);
}
}
}
}

if ( iconFile != null )
{
ZipEntry iconEntry = zipFile.getEntry(iconFile);

if ( iconEntry != null )
{
FileOutputStream fos = new FileOutputStream("/tmp/icon.png");
InputStream zis = zipFile.getInputStream(iconEntry);
int r = 0;
byte[] buffer = new byte[4*1024];
while( (r = zis.read(buffer)) != -1 )
{
baos.write(buffer,0,r);
fos.write(buffer,0,r);
}

fos.close();
zis.close();
}
}
}
}
finally
{
zipFile.close();
}

return baos.toByteArray();
}

public static void main(String[] args)
{

File jarFile = new File("/projects/workspace/cliqmobile/builds/cliqmobile.jar");
IconExtractor extractor = new IconExtractor();
try
{
byte[] data = extractor.extract(jarFile);
System.out.println(data.length + " " + AstrientFile.fileType(data));
}
catch (ZipException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

System.exit(0);
}
}

hostj2me
43 topic(s)
23 post(s)
Java Utility for perfrorming DNS Blacklist lookups. For more information on DNSBL see http://en.wikipedia.org/wiki/DNSBL 0 7732 January 16, 2009 5:43 PM


package com.astrientlabs.net.dns;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import com.astrientlabs.prefs.Preferences;

public class DNSBL
{
private static String[] RECORD_TYPES = { "A", "TXT" };

private DirContext ictx;
private List lookupServices = new ArrayList();


public DNSBL() throws NamingException
{
StringBuilder dnsServers = new StringBuilder("");
List nameservers = sun.net.dns.ResolverConfiguration.open().nameservers();
for( Object dns : nameservers )
{
dnsServers.append("dns://").append(dns).append(" ");
}

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put("com.sun.jndi.dns.timeout.initial", Preferences.system.get("dns.timeout","4000"));
env.put("com.sun.jndi.dns.timeout.retries", Preferences.system.get("dns.retry","1"));
env.put(Context.PROVIDER_URL,Preferences.system.get("dns.url",dnsServers.toString()));

ictx = new InitialDirContext(env);
}

public void addLookupService(String service)
{
lookupServices.add(service);
}

public void check(String ip) throws DNSBLException
{
String[] parts = ip.split("\\.");
StringBuilder buffer = new StringBuilder();

for (int i = 0; i parts.length; i++)
{
buffer.insert(0, '.');
buffer.insert(0, parts[i]);
}

ip = buffer.toString();



Attribute attribute;
Attributes attributes;


String lookupHost;
for ( String service : lookupServices )
{
lookupHost = ip + service;
try
{
attributes = ictx.getAttributes(lookupHost, RECORD_TYPES);
attribute = attributes.get("TXT");

if ( attribute != null )
{
throw new DNSBLException(lookupHost + ": " + attribute.get());
}
}
catch (NameNotFoundException e)
{
//this is good
//LogWriter.system.log(getClass(),e);
}
catch (NamingException e)
{
//LogWriter.system.log(getClass(),e);
}
}
}


public static void main (String[] args)
{


try
{
DNSBL dnsBL = new DNSBL();

dnsBL.addLookupService("blackholes.easynet.nl");
dnsBL.addLookupService("cbl.abuseat.org");
dnsBL.addLookupService("proxies.blackholes.wirehub.net");
dnsBL.addLookupService("bl.spamcop.net");
dnsBL.addLookupService("sbl.spamhaus.org");
dnsBL.addLookupService("dnsbl.njabl.org");
dnsBL.addLookupService("list.dsbl.org");
dnsBL.addLookupService("multihop.dsbl.org");
dnsBL.addLookupService("cbl.abuseat.org");

try
{
dnsBL.check("201.223.47.44");
}
catch (DNSBLException se)
{
System.out.println(se.getMessage());
}

try
{
dnsBL.check("38.100.193.183");
}
catch (DNSBLException se)
{
System.out.println(se.getMessage());
}

try
{
dnsBL.check("189.94.149.137");
}
catch (DNSBLException se)
{
System.out.println(se.getMessage());
}

try
{
dnsBL.check("220.227.113.25");
}
catch (DNSBLException se)
{
System.out.println(se.getMessage());
}



}
catch (Exception e)
{
e.printStackTrace();
}

System.exit(0);
}
}
class DNSBLException extends Exception
{

public DNSBLException()
{
super();
}

public DNSBLException(String message, Throwable cause)
{
super(message, cause);
}

public DNSBLException(String message)
{
super(message);
}

public DNSBLException(Throwable cause)
{
super(cause);
}
}

hostj2me
43 topic(s)
23 post(s)
Line Wrapping Utility for Drawing Strings on a Canvas 1 14039 January 29, 2007 8:14 PM


/*
* Copyright (C) 2006 Astrient Labs, LLC Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Astrient Labs, LLC
* www.astrientlabs.com
* rashid@astrientlabs.com
* Rashid Mayes 2006
*/
package com.astrientlabs.text;

import java.util.Enumeration;
import java.util.NoSuchElementException;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class LineEnumeration implements Enumeration
{
private Font font;

private String text;
private int width;
private int position;
private int length;
private int start = 0;

public LineEnumeration(Font font, String text, int width)
{
this.font = font;
this.text = text;
this.width = width;
this.length = text.length();
}

public boolean hasMoreElements()
{
return (position (length - 1));
}

public Object nextElement() throws NoSuchElementException
{
try
{
int next = next();

String s = text.substring(start, next);
start = next;

if (text.length() - 1 > start && (text.charAt(start) == ' '
|| text.charAt(start) == '\n'))
{
position++;
start++;
}

return s;
}
catch (IndexOutOfBoundsException e)
{
throw new NoSuchElementException(e.getMessage());
}
catch (Exception e)
{
throw new NoSuchElementException(e.getMessage());
}
}

private int next()
{
int i = position;
int lastBreak = -1;

for (; i length
&& font.stringWidth(text.substring(position, i)) = width; i++)
{
if (text.charAt(i) == ' ')
{
lastBreak = i;
}
else if (text.charAt(i) == '\n')
{
lastBreak = i;
break;
}
}

if (i == length)
{
position = i;
}
else if (lastBreak == position)
{
position++;
}
else if (lastBreak position)
{
position = i;
}
else
{
position = lastBreak;
}

return position;
}

public int writeTo(Graphics g, int startx, int starty, int maxY, Font font)
{
int fontHeight = font.getHeight() + 1;

while (hasMoreElements() && starty maxY)
{
g.drawString(String.valueOf(nextElement()).trim(),
startx, starty, Graphics.TOP | Graphics.LEFT);
starty += fontHeight;
}

return starty;
}

public void reset()
{
start = 0;
position = 0;
}
}

hostj2me
43 topic(s)
23 post(s)
Paging utility for displaying lists in web UI 0 2718 January 02, 2008 6:29 PM


/*
* Copyright (C) 2005 Astrient Labs, LLC Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Astrient Labs, LLC.
* www.astrientlabs.com
* rashid@astrientlabs.com
* Rashid Mayes 2005
*/
package com.astrientlabs.webui;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import com.astrientlabs.logging.LogWriter;


public class BasicUIListable extends LinkedList implements UIListable
{
/**
*
*/
private static final long serialVersionUID = -7369036906003073472L;
private int pageSize = 10;
private int pageNumber = -1;
private Random random = new Random();


public List getItems(int pageNumber)
{
int start = pageNumber * pageSize;
int end = start + pageSize;

return getItems(start,end);
}

public List items(int pageNumber, int pageSize)
{
int start = (pageNumber * pageSize);
int end = start + pageSize;

return getItems(start,end);
}


public List getItems(int start, int end)
{
try
{
if ( start > -1 && start size() )
{
if ( end > size() )
{
end = size();
}

return this.subList(start,end);
}
}
catch (Exception e)
{
LogWriter.system.log(getClass(),e);
}

return this.subList(0,0);//(List)EMPTY_LIST;
}


public void resetPageNumber()
{
pageNumber = -1;
}

public List next()
{
return getItems(++pageNumber);
}


public List current()
{
return ( pageNumber == -1 ) ? next() : getItems(pageNumber);
}


public List previous()
{
return getItems(--pageNumber);
}

/**
* Returns the pageNumber.
* @return int
*/
public int getPageNumber()
{
return pageNumber;
}

/**
* Returns the pageSize.
* @return int
*/
public int getPageSize()
{
return pageSize;
}

/**
* Sets the pageNumber.
* @param pageNumber The pageNumber to set
*/
public void setPageNumber(int pageNumber)
{
this.pageNumber = pageNumber;
}

/**
* Sets the pageSize.
* @param pageSize The pageSize to set
*/
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}


public int totalPages()
{
int size = size();
int pageSize = getPageSize();

int total = size / pageSize;
if ( (size % pageSize ) > 0 )
{
total++;
}

return total;
}

public int totalPages(int pageSize)
{
int size = size();

int total = size / pageSize;
if ( (size % pageSize ) > 0 )
{
total++;
}

return total;
}

/*
public synchronized void buildIndexes(Indexer indexer)
{
indexes.clear();


Object o;
Object index;
for ( Iterator iter = this.iterator(); iter.hasNext(); )
{
o = iter.next();
index = indexer.index(indexes,this);
}
}*/

/*
public static void main(String[] args)
{
BasicUIListable list = new BasicUIListable();
list.setPageSize(2);
for(int i = 0; i 5;list.add(String.valueOf(i++)));
for (String s : list)
{
System.out.println(s);
}

System.out.println("\n\n");
List l = list.getItems(2);
for (String s : l)
{
System.out.println(s);
}

System.exit(0);
}*/

public E random()
{
return this.get(random.nextInt(this.size()));
}
}



edited by hostj2me 1/2/08 1:31 PM

hostj2me
43 topic(s)
23 post(s)
Detecting Soft Keys 0 3199 November 06, 2007 8:17 PM

Here is the pseudo code I use to determine the soft key assignments in most of my J2ME apps.


int KEY_SOFTKEY_LEFT = -6;
int KEY_SOFTKEY_RIGHT = -7;

if ( ...check needed )
{
try
{
Class.forName("com.siemens.mp.game.Light");
KEY_SOFTKEY_RIGHT = -4;
KEY_SOFTKEY_LEFT = -1;
}
catch (ClassNotFoundException ignore)
{
//ignore.printStackTrace();

try
{
Class.forName("com.mot.iden.customercare.CustomerCare");
KEY_SOFTKEY_RIGHT = -21;
KEY_SOFTKEY_LEFT = -20;
}
catch (ClassNotFoundException ignore2)
{
//ignore2.printStackTrace();

try
{
Class.forName("com.motorola.phonebook.PhoneBookRecord");
KEY_SOFTKEY_RIGHT = -22;
KEY_SOFTKEY_LEFT = -21;
}
catch (ClassNotFoundException ignore3)
{
if ( someCanvas.getKeyName(-21).equalsIgnoreCase("soft1") )
{
KEY_SOFTKEY_LEFT = -21;
}

if ( someCanvas.getKeyName(-22).equalsIgnoreCase("soft2") )
{
KEY_SOFTKEY_RIGHT = -22;
}
}
}
}
}

hostj2me
43 topic(s)
23 post(s)
MIDI Converter, Type 1 to Type 0 0 1930 September 14, 2007 7:46 PM


/*
* Copyright (C) 2006 Astrient Labs, LLC Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Astrient Labs, LLC
* www.astrientlabs.com
* rashid@astrientlabs.com
* Rashid Mayes 2005
*/
package com.astrientlabs.audio;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiFileFormat;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;

public class MidiConverter
{
public static boolean isType1(byte[] data) throws InvalidMidiDataException, IOException
{
return isType1(new ByteArrayInputStream(data));
}

public static boolean isType1(InputStream is) throws InvalidMidiDataException, IOException
{
MidiFileFormat format = MidiSystem.getMidiFileFormat(is);
return (format.getType() == 1);
}

public static byte[] convertToType(byte[] data, int maxTracks) throws InvalidMidiDataException, IOException
{
return convertToType0(new ByteArrayInputStream(data), maxTracks);
}

public static byte[] convertToType0(InputStream is, int maxTracks) throws InvalidMidiDataException, IOException
{
Sequence sequence = MidiSystem.getSequence(is);

Track[] tracks = sequence.getTracks();
Track first = tracks[0];
Track track;

for (int i = 1; i tracks.length; i++)
{
track = tracks[i];
if (i maxTracks)
for (int j = 0, stop = track.size(); j stop; first.add(track.get(j++)))
;
sequence.deleteTrack(track);
}

ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
MidiSystem.write(sequence, 0, os);

return os.toByteArray();
}

public static void main(String[] args)
{
try
{
RandomAccessFile raf = new RandomAccessFile(new File("G:/in.mid"), "r");
byte[] data = new byte[(int) raf.length()];
raf.readFully(data);

ByteArrayInputStream bais = new ByteArrayInputStream(data);

if (isType1(bais))
{
bais.reset();
data = convertToType0(bais, 8);

FileOutputStream fos = new FileOutputStream(new File("g:out.mid"));
fos.write(data);
fos.close(); // finally:)
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
}

hostj2me
43 topic(s)
23 post(s)
J2ME: E61 Key map file 1 4620 March 22, 2007 10:04 PM

32=
33=!
34="
35=#
38=&
39='
40=(
41=)
42=*
43=+
44=,;.
45=-
46=.:_
47=/
48=0
49=1
50=2
51=3
52=4
53=5
54=6
55=7
56=8
57=9
61==
63=?
64=@
95=_
97=a"
98=b8
99=c)
100=d+
101=e-
102=f4
103=g5
104=h6
105=i/
106=j#
107=k
108=l
109=m0
110=n9
111=o=
112=p?
113=q!
114=r1
115=s@
116=t2
117=u*
118=v7
119=w&
120=x(
121=y3
122=z'
mode=0

hostj2me
43 topic(s)
23 post(s)
BBC News | Technology | World Edition: Designing mobiles for the world 0 3524 May 29, 2007 2:45 PM

Click here to view complete article

BBC News speaks to Jan Chipchase, principal human behavioural researcher at Nokia Design.

hostj2me
43 topic(s)
23 post(s)
J2ME: How to tell if application was Push activated 1 2382 May 29, 2007 2:22 PM


private boolean isPushActivated()
{
String[] connections = PushRegistry.listConnections(true);
return ( connections != null && connections.length > 0 )
}


hostj2me
43 topic(s)
23 post(s)
J2ME: replaceAll for Strings 0 2278 May 28, 2007 8:25 PM


public static String replaceAll(String text, String old, String newString)
{
int next = text.indexOf(old);
if ( next == -1 )
{
return text;
}
else
{
StringBuffer buffer = new StringBuffer(text.substring(0,next));
buffer.append(newString);
int current = next+old.length(), stop = text.length();
for ( ; current stop && (next = text.indexOf(old,current)) != -1; )
{
buffer.append(text.substring(current, next));
buffer.append(newString);
current = next+old.length();
}

if ( current stop )
{
buffer.append(text.substring(current));
}

return buffer.toString();
}
}

hostj2me
43 topic(s)
23 post(s)
Unix: Show machine configuration 0 2182 May 09, 2007 4:41 PM

hostj2me
43 topic(s)
23 post(s)
J2ME: Split a string by character, StringTokenizer 0 2232 March 05, 2007 5:51 PM


public static Vector split(String s, char c)
{
Vector parts = new Vector();
if ( s != null )
{
int lastfound = 0;
int pos = 0;
while ( (lastfound = s.indexOf(c,pos)) != - 1 )
{
parts.addElement(s.substring(pos,lastfound));
pos = lastfound+1;
}
if ( pos < s.length() ) parts.addElement(s.substring(pos));
}

return parts;
}



edited by hostj2me 4/28/07 9:43 PM

hostj2me
43 topic(s)
23 post(s)
Venture Beat: Social capitalism 0 3803 April 09, 2007 7:12 PM

Click here to view complete article

Today is Good Friday.


Appropriate time, perhaps, to point out the latest column, by attorney Jay Parkhill, which looks at social capitalism, its two basic models, and why some companies in this area are likely to succeed while others are not.


hostj2me
43 topic(s)
23 post(s)
HostJ2ME.com Image proxy servlet source code 0 2165 April 02, 2007 4:34 AM


package com.astrientlabs.biz.web;

import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.astrientlabs.files.AstrientFile;
import com.astrientlabs.logging.LogWriter;
import com.astrientlabs.lpa.CachingFileStore;
import com.astrientlabs.misc.ApiKey;
import com.astrientlabs.util.Strings;
import com.astrientlabs.web.WebServlet;
import com.astrientlabs.webstats.StatRecorder;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.JPEGEncodeParam;

public class ImageProxyServlet extends WebServlet
{
/**
*
*/
private static final long serialVersionUID = -7462909049956679674L;

private static final CachingFileStore fileStore = new CachingFileStore("/tmp/j2me/imageproxy");
private static final long maxFileSize = 1024L * 1024L * 10;

public void _doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

URL u = null;
HttpURLConnection con = null;

try
{
StatRecorder.record(request);

String heightString = request.getParameter("h");
String widthString = request.getParameter("w");
String url = request.getParameter("u");
String format = Strings.ifNull(request.getParameter("f"), "JPEG");
//String auth = Strings.ifNull(request.getParameter("auth"), "public");

String apiKey = request.getParameter("key");
ApiKey.testValid(apiKey);

LogWriter.system.log(ImageProxyServlet.class, apiKey + " Requested file " + url);

u = new URL(url);

con = (HttpURLConnection) u.openConnection();

String id = "F" + u.getHost().hashCode() + "." + u.getPath().hashCode();

String path = fileStore.getLocation(id, "orig");
File f = new File(path);

if (con.getContentLength() != -1 && con.getContentLength() > maxFileSize)
{
response.sendError(HttpURLConnection.HTTP_ENTITY_TOO_LARGE, "requested resource is too large");
return;
}

if ( /*!Preferences.system.getBoolean("imgproxy.caching",false) ||*/ (!f.exists() || f.lastModified() con.getLastModified() || f.length() == 0 || con.getContentLength() != f.length()) )
{
LogWriter.system.log(ImageProxyServlet.class, "downloading updated image");
fileStore.invalidate(id, "orig");
fileStore.add(id, "orig", new byte[0]);

InputStream is = u.openStream();
FileOutputStream fos = new FileOutputStream(f);
try
{
int r;
int read = 0;
byte[] buffer = new byte[4*1024];
while ((r = is.read(buffer)) != -1)
{
fos.write(buffer, 0, r);
read += r;
if (read > maxFileSize)
{
response.sendError(HttpURLConnection.HTTP_ENTITY_TOO_LARGE, "requested resource is too large");
return;
}
}
fos.flush();
}
finally
{
if (is != null)
is.close();
try
{
fos.close();
}
catch (Exception e)
{
}
}
}

String newFilePath = format.toUpperCase().hashCode() + "." + heightString + "." + widthString;

path = fileStore.getLocation(id, newFilePath);
File newFile = new File(path);

if (!newFile.exists() || newFile.lastModified() f.lastModified() || newFile.length() == 0)
{
fileStore.invalidate(id, newFilePath);

FileSeekableStream stream = new FileSeekableStream(f);
RenderedOp image = JAI.create("stream", stream);

scale(image, format, path, widthString, heightString);
image.dispose();
}

try
{
response.setContentType(AstrientFile.fileType(new FileSeekableStream(newFile)));
}
catch (Exception e)
{
LogWriter.system.log(ImageProxyServlet.class, e);
}

fileStore.writeTo(response.getOutputStream(), id, newFilePath);
}
catch (Exception e)
{
LogWriter.system.log(ImageProxyServlet.class, e);
response.sendError(HttpURLConnection.HTTP_NO_CONTENT, e.getMessage());
}
finally
{
if ( con != null )
{
try
{
con.disconnect();
}
catch (Exception ignored)
{

}
}
}
}

public void scale(RenderedOp image, String format, String location, String widthString, String heightString)
{
int width = (widthString == null) ? image.getWidth() : Integer.parseInt(widthString);
int height = (heightString == null) ? image.getHeight() : Integer.parseInt(heightString);

try
{
/*boolean landscape = (image.getWidth() > image.getHeight());
if (landscape && (height > width))
{
int tmpi = height;
height = width;
width = tmpi;
}*/

double cw = width / (1.0 * image.getWidth());
double ch = height / (1.0 * image.getHeight());

double scale;
if (cw ch)
{
scale = cw;
}
else
{
scale = ch;
}

if (scale > 1.0)
scale = 1.0;

Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BICUBIC);
ParameterBlock params = new ParameterBlock();
params.addSource(image);
params.add(new Float(scale));
params.add(new Float(scale));
params.add(0.0F);
params.add(0.0F);
params.add(interp);

RenderedOp image1 = JAI.create("scale", params);

if (format.equalsIgnoreCase("JPEG"))
{
JPEGEncodeParam param = new JPEGEncodeParam();
param.setQuality(1.2F);
RenderedOp op = JAI.create("filestore", image1, location, format, param);
op.dispose();
}
else
{
RenderedOp op = JAI.create("filestore", image1, location, format);
op.dispose();
}

}
finally
{
}
}
}

©2008 WorldDeveloper.org - PO Box 310575 Miami, FL 33231

WorldDeveloper.org is a managed social network for application developers around the world.