1 /**
2 * MicroEmulator
3 * Copyright (C) 2006-2007 Bartek Teodorczyk <barteo@barteo.net>
4 * Copyright (C) 2006-2007 Vlad Skarzhevskyy
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 * @version $Id: MIDletResourceLoader.java 1404 2007-10-15 19:40:48Z vlads $
21 */
22 package org.microemu.app.util;
23
24 import java.io.InputStream;
25
26 import org.microemu.Injected;
27 import org.microemu.log.Logger;
28 import org.microemu.util.ThreadUtils;
29
30 /**
31 * @author vlads
32 *
33 * Use MIDletResourceLoader to load resources.
34 * To solve resource resource loading paterns commonly used in MIDlet and not aceptable in Java SE application
35 * when System class is called to load resource
36 *
37 * j2me example:
38 *
39 * String.class.getResourceAsStream(resourceName)
40 *
41 */
42 public class MIDletResourceLoader {
43
44 //TODO make this configurable
45
46 public static boolean traceResourceLoading = false;
47
48 /**
49 * @deprecated find better solution to share variable
50 */
51 public static ClassLoader classLoader;
52
53 private static final String FQCN = Injected.class.getName();
54
55 public static InputStream getResourceAsStream(Class origClass, String resourceName) {
56 if (traceResourceLoading) {
57 Logger.debug("Loading MIDlet resource", resourceName);
58 }
59 if (classLoader != origClass.getClassLoader()) {
60 // showWarning
61 String callLocation = ThreadUtils.getCallLocation(FQCN);
62 if (callLocation != null) {
63 Logger.warn("attempt to load resource [" + resourceName + "] using System ClasslLoader from " + callLocation);
64 }
65 }
66 resourceName = resolveName(origClass, resourceName);
67
68 InputStream is = classLoader.getResourceAsStream(resourceName);
69 if (is == null) {
70 Logger.debug("Resource not found ", resourceName);
71 }
72 return is;
73 }
74
75 private static String resolveName(Class origClass, String name) {
76 if (name == null) {
77 return name;
78 }
79 if (!name.startsWith("/")) {
80 while (origClass.isArray()) {
81 origClass = origClass.getComponentType();
82 }
83 String baseName = origClass.getName();
84 int index = baseName.lastIndexOf('.');
85 if (index != -1) {
86 name = baseName.substring(0, index).replace('.', '/') + "/" +name;
87 }
88 } else {
89 name = name.substring(1);
90 }
91 return name;
92 }
93 }