Merge branch 'master' into test-https-connection

This commit is contained in:
Myk Melez 2014-10-24 08:27:02 -07:00
Родитель 13ec4dfbee a4d5911fba
Коммит d714b8acab
38 изменённых файлов: 5039 добавлений и 40 удалений

Просмотреть файл

@ -35,7 +35,7 @@ Classes.prototype.loadFileFromJar = function(jar, fileName) {
if (!(fileName in zip.directory))
return null;
var bytes = zip.read(fileName);
return bytes.buffer.slice(0, bytes.length);
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}
Classes.prototype.loadFile = function(fileName) {

Просмотреть файл

@ -1,17 +1,28 @@
SRCS=$(shell find ./cldc1.1.1 -name *.java) $(shell find ./vm -name *.java) $(shell find ./midp -name *.java)
CUSTOM_SRCS=$(shell find ./custom -name *.java)
JPP_DEFS=
JPP_SRCS=$(shell find . -name *.jpp)
JPP_DESTS=$(JPP_SRCS:.jpp=.java)
EXTRA=$(shell find . -name *.png) $(shell find . -name *.bin) $(shell find . -name *.xml)
VPATH=./cldc1.1.1 ./vm ./midp ./custom
classes.jar: $(SRCS) $(CUSTOM_SRCS)
classes.jar: $(SRCS) $(CUSTOM_SRCS) $(JPP_DESTS)
rm -rf build
mkdir build
javac -cp cldc1.1.1:vm:midp -source 1.3 -target 1.3 -d ./build $(SRCS) > /dev/null
javac -sourcepath custom -cp build -source 1.3 -target 1.3 -d ./build $(CUSTOM_SRCS) > /dev/null
cd build && jar cvf0 ../classes.jar *
jar uvf classes.jar $(EXTRA)
jar uvf0 classes.jar $(EXTRA)
rm -rf build
tools/Jpp.class: tools/Jpp.java
javac $^
# Preprocess all .jpp files to generate corresponding .java files.
$(JPP_DESTS): tools/Jpp.class $(JPP_SRCS)
$(foreach file,$(JPP_SRCS), java -classpath tools Jpp $(file) $(JPP_DEFS) -o $(file:.jpp=.java))
clean:
rm -f `find . -name "*.jar" -or -name "*~"`
rm -f $(JPP_DESTS)

Просмотреть файл

@ -0,0 +1,359 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import javax.microedition.location.*;
/**
* This class is an implementation of the <code>Landmark</code> class defined
* by the JSR-179 specification.
*/
// JAVADOC COMMENT ELIDED
public class LandmarkImpl {
// JAVADOC COMMENT ELIDED
int recordId = -1;
// JAVADOC COMMENT ELIDED
String storeName = null;
// JAVADOC COMMENT ELIDED
String name;
// JAVADOC COMMENT ELIDED
String description;
// JAVADOC COMMENT ELIDED
boolean isCoordinates = false;
// JAVADOC COMMENT ELIDED
double latitude;
// JAVADOC COMMENT ELIDED
double longitude;
// JAVADOC COMMENT ELIDED
float altitude;
// JAVADOC COMMENT ELIDED
float horizontalAccuracy;
// JAVADOC COMMENT ELIDED
float verticalAccuracy;
// JAVADOC COMMENT ELIDED
boolean isAddressInfo = false;
// JAVADOC COMMENT ELIDED
int numAddressInfoFields = 0;
// JAVADOC COMMENT ELIDED
String AddressInfo_EXTENSION = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_STREET = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_POSTAL_CODE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CITY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_STATE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTRY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTRY_CODE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_DISTRICT = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_NAME = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_FLOOR = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_ROOM = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_ZONE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CROSSING1 = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CROSSING2 = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_URL = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_PHONE_NUMBER = null;
// JAVADOC COMMENT ELIDED
public LandmarkImpl(String name, String description,
QualifiedCoordinates coordinates,
AddressInfo addressInfo) {
setName(name);
this.description = description;
setQualifiedCoordinates(coordinates);
setAddressInfo(addressInfo);
}
// JAVADOC COMMENT ELIDED
int getRecordId() {
return recordId;
}
// JAVADOC COMMENT ELIDED
void setRecordId(int recordId) {
this.recordId = recordId;
}
// JAVADOC COMMENT ELIDED
String getStoreName() {
return storeName;
}
// JAVADOC COMMENT ELIDED
void setStoreName(String storeName) {
this.storeName = storeName;
}
// JAVADOC COMMENT ELIDED
public String getName() {
return name;
}
// JAVADOC COMMENT ELIDED
public String getDescription() {
return description;
}
// JAVADOC COMMENT ELIDED
public QualifiedCoordinates getQualifiedCoordinates() {
if (isCoordinates) {
return new QualifiedCoordinates(latitude, longitude, altitude,
horizontalAccuracy, verticalAccuracy);
}
return null;
}
// JAVADOC COMMENT ELIDED
public AddressInfo getAddressInfo() {
if(isAddressInfo) {
AddressInfo address = new AddressInfo();
address.setField(AddressInfo.EXTENSION, AddressInfo_EXTENSION);
address.setField(AddressInfo.STREET, AddressInfo_STREET);
address.setField(AddressInfo.POSTAL_CODE, AddressInfo_POSTAL_CODE);
address.setField(AddressInfo.CITY, AddressInfo_CITY);
address.setField(AddressInfo.COUNTY, AddressInfo_COUNTY);
address.setField(AddressInfo.STATE, AddressInfo_STATE);
address.setField(AddressInfo.COUNTRY, AddressInfo_COUNTRY);
address.setField(AddressInfo.COUNTRY_CODE,
AddressInfo_COUNTRY_CODE);
address.setField(AddressInfo.DISTRICT, AddressInfo_DISTRICT);
address.setField(AddressInfo.BUILDING_NAME,
AddressInfo_BUILDING_NAME);
address.setField(AddressInfo.BUILDING_FLOOR,
AddressInfo_BUILDING_FLOOR);
address.setField(AddressInfo.BUILDING_ROOM,
AddressInfo_BUILDING_ROOM);
address.setField(AddressInfo.BUILDING_ZONE,
AddressInfo_BUILDING_ZONE);
address.setField(AddressInfo.CROSSING1, AddressInfo_CROSSING1);
address.setField(AddressInfo.CROSSING2, AddressInfo_CROSSING2);
address.setField(AddressInfo.URL, AddressInfo_URL);
address.setField(AddressInfo.PHONE_NUMBER,
AddressInfo_PHONE_NUMBER);
return address;
}
return null;
}
// JAVADOC COMMENT ELIDED
public void setName(String name) {
if (name == null) {
throw new NullPointerException();
}
this.name = name;
}
// JAVADOC COMMENT ELIDED
public void setDescription(String description) {
this.description = description;
}
// JAVADOC COMMENT ELIDED
public void setQualifiedCoordinates(QualifiedCoordinates coordinates) {
if (coordinates != null) {
latitude = coordinates.getLatitude();
longitude = coordinates.getLongitude();
altitude = coordinates.getAltitude();
horizontalAccuracy = coordinates.getHorizontalAccuracy();
verticalAccuracy = coordinates.getVerticalAccuracy();
isCoordinates = true;
} else {
latitude = 0;
longitude = 0;
altitude = 0;
horizontalAccuracy = 0;
verticalAccuracy = 0;
isCoordinates = false;
}
}
// JAVADOC COMMENT ELIDED
public void setAddressInfo(AddressInfo address) {
if (address != null) {
numAddressInfoFields = 0;
AddressInfo_EXTENSION = address.getField(AddressInfo.EXTENSION);
if(AddressInfo_EXTENSION != null) {
numAddressInfoFields++;
}
AddressInfo_STREET = address.getField(AddressInfo.STREET);
if(AddressInfo_STREET != null) {
numAddressInfoFields++;
}
AddressInfo_POSTAL_CODE = address.getField(AddressInfo.POSTAL_CODE);
if(AddressInfo_POSTAL_CODE != null) {
numAddressInfoFields++;
}
AddressInfo_CITY = address.getField(AddressInfo.CITY);
if(AddressInfo_CITY != null) {
numAddressInfoFields++;
}
AddressInfo_COUNTY = address.getField(AddressInfo.COUNTY);
if(AddressInfo_COUNTY != null) {
numAddressInfoFields++;
}
AddressInfo_STATE = address.getField(AddressInfo.STATE);
if(AddressInfo_STATE != null) {
numAddressInfoFields++;
}
AddressInfo_COUNTRY = address.getField(AddressInfo.COUNTRY);
if(AddressInfo_COUNTRY != null) {
numAddressInfoFields++;
}
AddressInfo_COUNTRY_CODE =
address.getField(AddressInfo.COUNTRY_CODE);
if(AddressInfo_COUNTRY_CODE != null) {
numAddressInfoFields++;
}
AddressInfo_DISTRICT = address.getField(AddressInfo.DISTRICT);
if(AddressInfo_DISTRICT != null) {
numAddressInfoFields++;
}
AddressInfo_BUILDING_NAME =
address.getField(AddressInfo.BUILDING_NAME);
if(AddressInfo_BUILDING_NAME != null) {
numAddressInfoFields++;
}
AddressInfo_BUILDING_FLOOR =
address.getField(AddressInfo.BUILDING_FLOOR);
if(AddressInfo_BUILDING_FLOOR != null) {
numAddressInfoFields++;
}
AddressInfo_BUILDING_ROOM =
address.getField(AddressInfo.BUILDING_ROOM);
if(AddressInfo_BUILDING_ROOM != null) {
numAddressInfoFields++;
}
AddressInfo_BUILDING_ZONE =
address.getField(AddressInfo.BUILDING_ZONE);
if(AddressInfo_BUILDING_ZONE != null) {
numAddressInfoFields++;
}
AddressInfo_CROSSING1 = address.getField(AddressInfo.CROSSING1);
if(AddressInfo_CROSSING1 != null) {
numAddressInfoFields++;
}
AddressInfo_CROSSING2 = address.getField(AddressInfo.CROSSING2);
if(AddressInfo_CROSSING2 != null) {
numAddressInfoFields++;
}
AddressInfo_URL = address.getField(AddressInfo.URL);
if(AddressInfo_URL != null) {
numAddressInfoFields++;
}
AddressInfo_PHONE_NUMBER =
address.getField(AddressInfo.PHONE_NUMBER);
if(AddressInfo_PHONE_NUMBER != null) {
numAddressInfoFields++;
}
isAddressInfo = true;
} else {
AddressInfo_EXTENSION = null;
AddressInfo_STREET = null;
AddressInfo_POSTAL_CODE = null;
AddressInfo_CITY = null;
AddressInfo_COUNTY = null;
AddressInfo_STATE = null;
AddressInfo_COUNTRY = null;
AddressInfo_COUNTRY_CODE = null;
AddressInfo_DISTRICT = null;
AddressInfo_BUILDING_NAME = null;
AddressInfo_BUILDING_FLOOR = null;
AddressInfo_BUILDING_ROOM = null;
AddressInfo_BUILDING_ZONE = null;
AddressInfo_CROSSING1 = null;
AddressInfo_CROSSING2 = null;
AddressInfo_URL = null;
AddressInfo_PHONE_NUMBER = null;
numAddressInfoFields = 0;
isAddressInfo = false;
}
}
// JAVADOC COMMENT ELIDED
String asString() {
String coordinates;
if (isCoordinates) {
coordinates = "Lat: " + latitude +
" Lon: " + longitude;
} else {
coordinates = "null";
}
return "Landmark: { storeName = " + storeName +
" recordId = " + recordId +
" name = " + name +
" description = " + description +
" coordinates = " + coordinates +
" addressInfo = " + getAddressInfo() + " }";
}
// JAVADOC COMMENT ELIDED
public boolean equals(Object o) {
if (!(o instanceof LandmarkImpl)) {
return false;
}
if (this == o) {
return true;
}
LandmarkImpl lm = (LandmarkImpl)o;
boolean idEquals = recordId == lm.recordId;
boolean storeEquals = ((storeName == null) && (lm.storeName == null)) ||
((storeName != null) && storeName.equals(lm.storeName));
return idEquals && storeEquals;
}
/**
* Returns a proper hash code for using in Hashtable.
* @return hash code value for this instance
*/
public int hashCode() {
return recordId;
}
// JAVADOC COMMENT ELIDED
static {
initNativeClass();
}
// JAVADOC COMMENT ELIDED
private native static void initNativeClass();
}

Просмотреть файл

@ -0,0 +1,35 @@
/*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
/**
* Event listener for events delivered from native layer
*/
class LocationEventListener {
LocationEventListener() {
}
}

Просмотреть файл

@ -0,0 +1,158 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import javax.microedition.location.*;
/**
* This class is an implementation of the <code>Location</code> class defined
* by the JSR-179 specification.
*/
// JAVADOC COMMENT ELIDED
public class LocationImpl extends Location {
// JAVADOC COMMENT ELIDED
private static final String MIMETYPE_NMEA_STRING =
"application/X-jsr179-location-nmea";
// JAVADOC COMMENT ELIDED
private static final String MIMETYPE_LIF_STRING =
"application/X-jsr179-location-lif";
// JAVADOC COMMENT ELIDED
private static final String MIMETYPE_PLAIN_STRING = "text/plain";
// JAVADOC COMMENT ELIDED
private boolean isValid;
// JAVADOC COMMENT ELIDED
private long timestamp;
// JAVADOC COMMENT ELIDED
private QualifiedCoordinates coordinates;
// JAVADOC COMMENT ELIDED
private float speed;
// JAVADOC COMMENT ELIDED
private float course;
// JAVADOC COMMENT ELIDED
private int method;
// JAVADOC COMMENT ELIDED
private AddressInfo address;
// JAVADOC COMMENT ELIDED
String extraInfoNMEA;
// JAVADOC COMMENT ELIDED
String extraInfoLIF;
// JAVADOC COMMENT ELIDED
String extraInfoPlain;
// JAVADOC COMMENT ELIDED
String extraInfoOther;
// JAVADOC COMMENT ELIDED
String extraInfoOtherMIMEType;
// JAVADOC COMMENT ELIDED
LocationImpl(QualifiedCoordinates coordinates, float speed,
float course, int method, AddressInfo address,
boolean isValid) {
this.isValid = isValid;
this.timestamp = System.currentTimeMillis();
this.coordinates = coordinates;
this.speed = speed;
this.course = course;
this.method = method;
this.address = address;
}
// JAVADOC COMMENT ELIDED
public boolean isValid() {
return isValid;
}
// JAVADOC COMMENT ELIDED
public void setValid(boolean isValid) {
this.isValid = isValid;
}
// JAVADOC COMMENT ELIDED
public long getTimestamp() {
return timestamp;
}
// JAVADOC COMMENT ELIDED
public void setTimestamp(long timestamp) {
if (timestamp == 0) {
this.timestamp = System.currentTimeMillis();
} else {
this.timestamp = timestamp;
}
}
// JAVADOC COMMENT ELIDED
public void setTimestamp() {
timestamp = System.currentTimeMillis();
}
// JAVADOC COMMENT ELIDED
public QualifiedCoordinates getQualifiedCoordinates() {
return coordinates;
}
// JAVADOC COMMENT ELIDED
public float getSpeed() {
return speed;
}
// JAVADOC COMMENT ELIDED
public float getCourse() {
return course;
}
// JAVADOC COMMENT ELIDED
public int getLocationMethod() {
return method;
}
// JAVADOC COMMENT ELIDED
public AddressInfo getAddressInfo() {
return address;
}
// JAVADOC COMMENT ELIDED
public String getExtraInfo(String mimetype) {
if (mimetype == null) {
return null;
}
if (mimetype.equalsIgnoreCase(MIMETYPE_NMEA_STRING)) {
return extraInfoNMEA;
}
if (mimetype.equalsIgnoreCase(MIMETYPE_LIF_STRING)) {
return extraInfoLIF;
}
if (mimetype.equalsIgnoreCase(MIMETYPE_PLAIN_STRING)) {
return extraInfoPlain;
}
if (mimetype.equalsIgnoreCase(extraInfoOtherMIMEType)) {
return extraInfoOther;
}
return null;
}
}

Просмотреть файл

@ -0,0 +1,37 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
/**
* Implementation of atan2 math function.
*/
public class LocationMath {
private LocationMath() {};
// JAVADOC COMMENT ELIDED
public static native double atan2(double x, double y);
}

Просмотреть файл

@ -0,0 +1,352 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import java.util.*;
import java.io.*;
import javax.microedition.location.*;
/**
* This class is an implementation of the persistent storage to store landmarks.
*/
// JAVADOC COMMENT ELIDED
public class LocationPersistentStorage {
private static LocationPersistentStorage storage = null;
public static LocationPersistentStorage getInstance() {
if(storage == null) {
storage = new LocationPersistentStorage();
}
return storage;
}
// JAVADOC COMMENT ELIDED
private LocationPersistentStorage() {
}
// JAVADOC COMMENT ELIDED
public static synchronized void addStoreName(String storeName)
throws IOException {
try {
createLandmarkStore(storeName);
} catch (IllegalArgumentException e) {
throw new IOException(e.getMessage());
}
}
// JAVADOC COMMENT ELIDED
public static synchronized void removeStoreName(String storeName)
throws IOException {
// cannot delete default LandmarkStore
if(storeName == null) {
throw new
NullPointerException("the default store can't be deleted");
}
// remove file with landmarks
removeLandmarkStore(storeName);
}
// JAVADOC COMMENT ELIDED
public static synchronized String[] listStoreNames()
throws IOException {
Vector vectStores = new Vector();
String storeName;
int hndl = openLandmarkStoreList();
do {
storeName = landmarkStoreGetNext(hndl);
if ((storeName != null) && (storeName.length()>0)) {
vectStores.addElement(storeName);
} else {
closeLandmarkStoreList(hndl);
storeName = null;
}
} while(storeName != null);
String[] arrStores = null;
if(vectStores.size()>0) {
arrStores = new String[vectStores.size()];
vectStores.copyInto(arrStores);
}
return arrStores;
}
// JAVADOC COMMENT ELIDED
public static synchronized Vector getCategories(String storeName)
throws IOException {
Vector categories = new Vector();
int listHandle;
String category;
listHandle = openCategoryList(storeName);
if (listHandle != 0) {
try {
while ((category = categoryGetNext(listHandle)) != null) {
if (category.length() == 0) {
break;
}
categories.addElement(category);
}
} finally {
closeCategoryList(listHandle);
}
}
return categories;
}
// JAVADOC COMMENT ELIDED
public static synchronized void addCategory(String categoryName, String storeName)
throws IOException, IllegalArgumentException {
addCategoryImpl(storeName, categoryName);
}
// JAVADOC COMMENT ELIDED
public static synchronized void deleteCategory(String categoryName,
String storeName) throws IOException{
deleteCategoryImpl(storeName, categoryName);
}
// JAVADOC COMMENT ELIDED
public static synchronized void addLandmark(String storeName,
LandmarkImpl landmark, String category)
throws IOException, IllegalArgumentException {
try {
if ((landmark.getRecordId()) > -1 &&
(landmarkStoresEqual(landmark.getStoreName(),storeName))) {
try {
updateLandmark(storeName, landmark);
} catch (LandmarkException ex) {
landmark.setRecordId(-1);
}
if ((landmark.getRecordId() > -1) && (category != null)) {
addLandmarkToCategoryImpl(storeName, landmark.getRecordId(),
category);
return;
}
}
} catch (IllegalArgumentException e) {
// if it is happened, the landmark is deleted from store.
// Just continue to add Landmark
}
landmark.setRecordId(
addLandmarkToStoreImpl(storeName, landmark, category));
landmark.setStoreName(storeName);
}
// JAVADOC COMMENT ELIDED
public static synchronized void deleteLandmark(String storeName,
LandmarkImpl lm) throws IOException, LandmarkException {
if (landmarkStoresEqual(lm.getStoreName(), storeName) &&
(lm.getRecordId() > -1)) {
deleteLandmarkFromStoreImpl(storeName, lm.getRecordId());
} else {
throw new LandmarkException("This landmark belongs to a " +
"different store: " + lm.getStoreName());
}
}
// JAVADOC COMMENT ELIDED
public static Enumeration getLandmarksEnumeration(String storeName,
String category, String name,
double minLatitude,
double maxLatitude, double minLongitude,
double maxLongitude) throws IOException {
Vector landmarks = new Vector();
int landmarkID = 0;
int listHandle;
listHandle = openLandmarkList(storeName, category);
if (listHandle != 0) {
try {
boolean val = true;
do {
LandmarkImpl landmark = new LandmarkImpl("", null,
null, null);
landmarkID = landmarkGetNext(listHandle, landmark);
if (landmarkID != -1) {
/* Landmark name can not be NULL */
if (landmark.getName() == null) {
landmark.setName("");
}
if (name != null) {
if (!name.equals(landmark.getName())) {
continue;
}
}
if (landmark.getQualifiedCoordinates() != null) {
double lat = landmark.getQualifiedCoordinates().
getLatitude();
double lon = landmark.getQualifiedCoordinates().
getLongitude();
if (minLongitude > maxLongitude) {
val = (minLatitude <= lat) && (maxLatitude >= lat)
&& ((minLongitude < lon) || (maxLongitude > lon));
} else {
val = (minLatitude <= lat) && (minLongitude <= lon) &&
(maxLongitude >= lon) && (maxLatitude >= lat);
}
}
if (val) {
landmark.setRecordId(landmarkID);
landmark.setStoreName(storeName);
landmarks.addElement(landmark);
}
}
} while (landmarkID != -1);
} finally {
closeLandmarkList(listHandle);
}
Enumeration en = landmarks.elements();
if (en.hasMoreElements()) {
return en;
}
}
return null;
}
// JAVADOC COMMENT ELIDED
public static void removeLandmarkFromCategory(String storeName,
LandmarkImpl lm, String category) throws IOException {
if ((lm.getRecordId() > -1) &&
(landmarkStoresEqual(lm.getStoreName(),storeName))) {
deleteLandmarkFromCategoryImpl(
storeName, lm.getRecordId(), category);
}
}
// JAVADOC COMMENT ELIDED
public static synchronized void updateLandmark(String storeName,
LandmarkImpl landmark) throws IOException, LandmarkException {
if ((landmark.getRecordId() > -1) &&
(landmarkStoresEqual(landmark.getStoreName(), storeName))) {
try {
updateLandmarkImpl(storeName, landmark.getRecordId(),
landmark);
} catch (IllegalArgumentException ex) {
throw new LandmarkException(ex.getMessage());
}
return;
} else {
throw new LandmarkException(
"Landmark does not belong to this store");
}
}
// JAVADOC COMMENT ELIDED
private static boolean landmarkStoresEqual(String name1, String name2) {
if (((name1 == null) && (name2 == null)) ||
((name1 != null) && (name2 != null) && (name1.equals(name2)))) {
return true;
}
return false;
}
// JAVADOC COMMENT ELIDED
private static native void createLandmarkStore(String name)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void removeLandmarkStore(String name)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native int openLandmarkStoreList()
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void closeLandmarkStoreList(int listHandle)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native String landmarkStoreGetNext(int listHandle)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native int openCategoryList(String name)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void closeCategoryList(int listHandle)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native String categoryGetNext(int listHandle)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void addCategoryImpl(String storeName,
String categoryName)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void deleteCategoryImpl(String storeName,
String categoryName)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void addLandmarkToCategoryImpl(String storeName,
int landmarkID, String categoryName)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native int addLandmarkToStoreImpl(String storeName,
LandmarkImpl landmark, String categoryName)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void deleteLandmarkFromStoreImpl(String storeName,
int landmarkID)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native int openLandmarkList(String storeName,
String categoryName)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void closeLandmarkList(int listHandle)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native int landmarkGetNext(int listHandle,
LandmarkImpl landmark)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void deleteLandmarkFromCategoryImpl(String storeName,
int landmarkID, String category)
throws IOException;
// JAVADOC COMMENT ELIDED
private static native void updateLandmarkImpl(String storeName,
int landmarkID, LandmarkImpl landmark)
throws IOException;
}

Просмотреть файл

@ -0,0 +1,541 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import com.sun.j2me.log.Logging;
import com.sun.j2me.security.LocationPermission;
import java.util.Vector;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import com.sun.j2me.main.Configuration;
/**
* This class is an implementation of the <code>LocationProvider</code> class
* defined by the JSR-179 specification.
*/
// JAVADOC COMMENT ELIDED
public abstract class LocationProviderImpl extends LocationProvider {
// JAVADOC COMMENT ELIDED
protected LocationListener locationListener;
// JAVADOC COMMENT ELIDED
protected Criteria criteria = new Criteria();
// JAVADOC COMMENT ELIDED
private LocationThread locationThread = null;
// JAVADOC COMMENT ELIDED
private StateThread stateThread = null;
// JAVADOC COMMENT ELIDED
private int locationQueries = 0;
// JAVADOC COMMENT ELIDED
private boolean resetRequested = false;
// JAVADOC COMMENT ELIDED
private static final String SEPARATOR = ",";
// JAVADOC COMMENT ELIDED
public boolean matchesCriteria(Criteria criteria) {
return compareCriterias(criteria, this.criteria);
}
// JAVADOC COMMENT ELIDED
static boolean compareCriterias(Criteria c1, Criteria c2) {
if (!c1.isAllowedToCost() && c2.isAllowedToCost()) {
return false;
}
if (c1.isSpeedAndCourseRequired() && !c2.isSpeedAndCourseRequired()) {
return false;
}
if (c1.isAltitudeRequired() && !c2.isAltitudeRequired()) {
return false;
}
if (c1.isAddressInfoRequired() && !c2.isAddressInfoRequired()) {
return false;
}
if (c1.getHorizontalAccuracy() != Criteria.NO_REQUIREMENT &&
c1.getHorizontalAccuracy() < c2.getHorizontalAccuracy()) {
return false;
}
if (c1.getVerticalAccuracy() != Criteria.NO_REQUIREMENT &&
c1.getVerticalAccuracy() < c2.getVerticalAccuracy()) {
return false;
}
if (c1.getPreferredResponseTime() != Criteria.NO_REQUIREMENT &&
c1.getPreferredResponseTime() < c2.getPreferredResponseTime()) {
return false;
}
if (c1.getPreferredPowerConsumption() != Criteria.NO_REQUIREMENT
&& c1.getPreferredPowerConsumption() <
c2.getPreferredPowerConsumption()) {
return false;
}
return true;
}
static LocationProviderImpl getBestProvider(Criteria c, Vector v) {
for (int i=0; i<v.size(); i++) {
LocationProviderImpl p = (LocationProviderImpl)v.elementAt(i);
Criteria cr = p.criteria;
if ((cr.isAllowedToCost() == c.isAllowedToCost()) &&
(cr.getPreferredPowerConsumption() == c.getPreferredPowerConsumption()) ) {
return p;
}
}
for (int i=0; i<v.size(); i++) {
LocationProviderImpl p = (LocationProviderImpl)v.elementAt(i);
Criteria cr = p.criteria;
}
return null;
}
// JAVADOC COMMENT ELIDED
public abstract int getDefaultInterval();
// JAVADOC COMMENT ELIDED
public abstract int getDefaultMaxAge();
// JAVADOC COMMENT ELIDED
public abstract int getDefaultTimeout();
// JAVADOC COMMENT ELIDED
public abstract int getResponseTime();
// JAVADOC COMMENT ELIDED
public abstract int getStateInterval();
// JAVADOC COMMENT ELIDED
abstract LocationImpl getLastLocation();
// JAVADOC COMMENT ELIDED
public static synchronized Location getLastKnownLocation() {
return PlatformLocationProvider.getLastKnownLocation();
}
// JAVADOC COMMENT ELIDED
public void reset() {
if (locationQueries > 0) {
resetRequested = true;
int attemptCount = Integer
.parseInt(Configuration
.getProperty("com.sun.j2me.location.ResetTimeout"))
* 10;
while (locationQueries > 0 && attemptCount-- > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// nothing to do
}
}
resetRequested = false;
}
}
// JAVADOC COMMENT ELIDED
public Location getLocation(int timeout)
throws LocationException, InterruptedException {
Util.checkForPermission(LocationPermission.LOCATION, false);
if (timeout == 0 || timeout < -1) {
throw new IllegalArgumentException("Illegal timeout value");
}
LocationImpl location = getLocationImpl(timeout);
return location;
}
// JAVADOC COMMENT ELIDED
protected LocationImpl getLocationImpl(int timeout)
throws LocationException, InterruptedException {
long startTime;
long endTime;
LocationImpl newLocation = null;
if (getState() == OUT_OF_SERVICE) {
throw new LocationException("Provider is out of service");
}
try {
if (timeout == -1) {
timeout = getDefaultTimeout();
}
startTime = System.currentTimeMillis();
endTime = startTime + (long)timeout * 1000;
locationQueries++;
while (!resetRequested && System.currentTimeMillis() < endTime) {
if (getState() == AVAILABLE) {
newLocation = updateLocation(endTime -
System.currentTimeMillis());
if (resetRequested) {
break;
}
if (newLocation != null) {
return newLocation;
}
} else {
Thread.sleep((long)getStateInterval() * 1000);
}
long delay = Math.min((long)getResponseTime() * 1000,
endTime - System.currentTimeMillis());
if (delay <= 0) {
break;
}
while (!resetRequested && delay > 0) {
Thread.sleep(100);
delay -= 100;
}
}
if (!resetRequested) {
if (getState() == TEMPORARILY_UNAVAILABLE) {
throw new LocationException("Provider is temporarily unavailable");
}
// try one last time
newLocation = updateLocation((long)getResponseTime() * 1000);
if (!resetRequested) {
if (newLocation != null) {
return newLocation;
}
throw new LocationException("Could not acquire location");
}
}
} finally {
locationQueries--;
}
throw new InterruptedException("Location query was interrupted");
}
// JAVADOC COMMENT ELIDED
protected abstract LocationImpl updateLocation(long timeout)
throws LocationException;
// JAVADOC COMMENT ELIDED
protected abstract void setUpdateInterval(int interval);
// JAVADOC COMMENT ELIDED
public static LocationProviderImpl getInstanceImpl(Criteria criteria)
throws LocationException {
Vector vectProviders = new Vector();
LocationProviderImpl found = null;
new LocationEventListener();
if (criteria == null) {
criteria = new Criteria();
}
String listProviders = PlatformLocationProvider.
getListOfLocationProviders();
if(listProviders == null || ((listProviders = listProviders.trim()).equals(""))) {
throw new LocationException("All providers are out of service");
}
String providerName = null;
try {
providerName = PlatformLocationProvider.getBestProviderByCriteria(criteria);
if (providerName != null) {
try {
return new PlatformLocationProvider(providerName);
} catch (IllegalAccessException ex) {
throw new LocationException("can not create Location Provider " + providerName);
}
}
return null;
} catch (IllegalAccessException ex) {
/* Direct creation from criteria is Unsupported */
/* try to create in Java */
}
/* parsing the list of providers */
while (listProviders.length() > 0) {
int posSpace = listProviders.indexOf(SEPARATOR);
String newProviderName;
if (posSpace == -1) { // last provider name
newProviderName = listProviders;
listProviders = "";
} else { // not last name
newProviderName = listProviders.substring(0, posSpace);
listProviders = listProviders.substring(posSpace + 1);
}
try {
Criteria cr = PlatformLocationProvider.getProviderInfo(newProviderName);
if (compareCriterias(criteria, cr)) {
LocationProviderImpl providerInstance = new
PlatformLocationProvider(newProviderName);
vectProviders.addElement(providerInstance);
}
} catch (IllegalAccessException e) {
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Illegal access to provider");
}
}
}
// loop over all providers and set the ones that match the criteria
// in their proper state, to give the one available preference over
// the unavailable one
LocationProviderImpl provider;
while (vectProviders.size()>0 &&
(provider = getBestProvider(criteria, vectProviders)) != null) {
int state = provider.getState();
if (state == AVAILABLE) {
return provider;
}
if (state == TEMPORARILY_UNAVAILABLE && found == null) {
found = provider;
}
vectProviders.removeElement(provider);
}
if (found != null) {
return found;
}
return null;
}
// JAVADOC COMMENT ELIDED
public LocationListener getLocationListener() {
return locationListener;
}
// JAVADOC COMMENT ELIDED
public void setLocationListener(LocationListener listener,
int interval, int timeout, int maxAge)
throws IllegalArgumentException, SecurityException {
if (listener != null)
Util.checkForPermission(LocationPermission.LOCATION, true);
if (interval < -1 ||
(interval != -1 && (timeout > interval || maxAge > interval ||
timeout < 1 && timeout != -1 ||
maxAge < 1 && maxAge != -1))) {
if (listener != null) {
throw new IllegalArgumentException("Timeout value is invalid");
}
}
// stop the current locationThread and stateThread
if (locationThread != null) {
locationThread.terminate();
try { // wait for thread to die
locationThread.join();
} catch (InterruptedException e) { // do nothing
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
locationThread = null;
}
if (stateThread != null) {
stateThread.terminate();
try { // wait for thread to die
stateThread.join();
} catch (InterruptedException e) { // do nothing
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
stateThread = null;
}
if (listener == null) {
locationListener = null;
setUpdateInterval(0);
return;
}
if (interval == -1) {
interval = getDefaultInterval();
maxAge = getDefaultMaxAge();
timeout = getDefaultInterval()/2;
}
if (maxAge == -1) {
maxAge = getDefaultMaxAge();
}
if (timeout == -1) {
timeout = getDefaultInterval()/2;
}
this.locationListener = listener;
// Start the location thread when interval > 0
if (interval > 0) {
setUpdateInterval(interval);
locationThread = new LocationThread(this, listener, interval,
timeout, maxAge);
locationThread.start();
}
// Start the state update thread
stateThread = new StateThread(this, listener);
stateThread.start();
}
}
/**
* Class LocationThread provides location updates through location listener.
*/
class LocationThread extends Thread {
/** Location provider listener is registered to. */
private LocationProviderImpl provider;
/** Current location listener. */
private LocationListener listener;
/** Current interval for location sampling. */
private int interval;
/** Current timeout for sampling. */
private int timeout;
/** Current limit for old samples. */
private int maxAge;
/** Flag indicating if the thread should terminate. */
private boolean terminated = false;
// JAVADOC COMMENT ELIDED
LocationThread(LocationProviderImpl provider, LocationListener listener,
int interval, int timeout, int maxAge) {
this.provider = provider;
this.listener = listener;
this.interval = interval;
this.timeout = timeout;
this.maxAge = maxAge;
}
/**
* Terminates the thread.
*/
void terminate() {
terminated = true;
synchronized (this) {
notify();
}
}
// JAVADOC COMMENT ELIDED
public void run() {
int responseTime = Math.min(provider.getResponseTime(), interval);
long lastUpdate = System.currentTimeMillis() - (long)interval * 1000;
try {
while (!terminated) {
Location location = provider.getLastLocation();
if (location == null || System.currentTimeMillis() +
(long)responseTime * 1000 -
location.getTimestamp() > maxAge) {
// need to update location
try {
location =
provider.getLocationImpl(responseTime + timeout);
} catch (LocationException e) {
// couldn't get location, send the invalid one
location = new LocationImpl(null, 0, 0, 0,
null, false);
} catch (InterruptedException e) {
// reset() was called on the provider
// should the thread terminate? most probably not
}
}
long delay = lastUpdate + (long)interval * 1000 -
System.currentTimeMillis();
if (delay > 0) {
synchronized (this) {
wait(delay); // wait for the right timing
}
}
if (terminated) { // thread was stopped
break;
}
// send the new location to location listener
lastUpdate = System.currentTimeMillis();
listener.locationUpdated(provider, location);
delay = (long)(interval - responseTime) * 1000;
if (delay > 0) {
synchronized (this) {
wait(delay);
}
}
}
} catch (InterruptedException e) {
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
}
}
/**
* Class StateThread checks the current provider state every
* <code>interval</code> seconds and sends the state update
* when state is changed.
*/
class StateThread extends Thread {
/** Current location provider. */
private LocationProviderImpl provider;
/** Current location listener. */
private LocationListener listener;
/** Flag indicating if the thread should terminate. */
private boolean terminated = false;
// JAVADOC COMMENT ELIDED
StateThread(LocationProviderImpl provider, LocationListener listener) {
this.provider = provider;
this.listener = listener;
}
/**
* Terminates the thread.
*/
void terminate() {
terminated = true;
synchronized (this) {
notify();
}
}
// JAVADOC COMMENT ELIDED
public void run() {
// get the current provider state
int interval = provider.getStateInterval() * 1000;
int state = provider.getState();
try {
while (!terminated) {
synchronized (this) {
// wait before querying the current state
wait(interval);
}
if (terminated) { // thread was stopped
break;
}
// check the new provider state
int newState = provider.getState();
if (newState != state) { // state was changed
state = newState;
// send the state update
listener.providerStateChanged(provider, state);
}
}
} catch (InterruptedException e) {
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
}
}

Просмотреть файл

@ -0,0 +1,118 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import javax.microedition.location.LocationException;
import javax.microedition.location.Orientation;
/**
* This is a starting point of Orientation Provider implementation
*/
public class OrientationProvider {
/** The handler of Orientation Provider */
private static int provider = 0;
private OrientationProvider(){
}
public static OrientationProvider getInstance()
throws LocationException {
new LocationEventListener();
/* Call open() one time to prepare or start Orientation device */
if (provider == 0) {
provider = open();
}
if (provider == 0) {
throw new LocationException("Orientation retrieval not supported");
}
return new OrientationProvider();
}
public Orientation getOrientation() {
Orientation orientation = null;
boolean status;
OrientationInfo orientationInfo = new OrientationInfo();
if (getOrientation0(provider, orientationInfo))
orientation = orientationInfo.getOrientation();
return orientation;
}
private static native int open();
private native boolean getOrientation0(int provider, OrientationInfo orientationInfo);
}
/**
* The class contains information about Orientation
*/
class OrientationInfo {
/** Angle off the horizon. */
private float azimuth;
/** Sample uses magnetic north. */
private boolean isMagnetic;
/** Pitch direction. */
private float pitch;
/** Roll direction. */
private float roll;
/**
* Init class info in the native code
*/
static {
initNativeClass();
}
/**
* Default constructor
*/
OrientationInfo() {
azimuth = 0;
isMagnetic = false;
pitch = 0;
roll = 0;
}
/**
* Initializes native file handler.
*/
private static native void initNativeClass();
public Orientation getOrientation(){
return new Orientation(azimuth, isMagnetic, pitch, roll);
}
public String toString(){
return "OrientationInfo (azimuth = " + azimuth
+ ", isMagnetic = " + isMagnetic
+ ", pitch = " + pitch
+ ", roll = " + roll + ")";
}
}

Просмотреть файл

@ -0,0 +1,555 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import javax.microedition.location.AddressInfo;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.QualifiedCoordinates;
import javax.microedition.location.Criteria;
/**
* Implementation of Location Provider.
*/
public class PlatformLocationProvider extends LocationProviderImpl {
/** The name of Location Provider */
private String providerName;
/** The handler of Location Provider */
private int provider;
/** max size of Location Info in bytes */
private final static int MAX_LOCATION_BUFEER_SIZE = 1000;
/** Input buffer for retrieve Location Info */
private static byte[] lastKnownLocationBuffer =
new byte[MAX_LOCATION_BUFEER_SIZE];
/** Location Provider properties */
LocationProviderInfo providerInfo = new LocationProviderInfo();
/**
* Set of I3test variables
*/
/** I3Test variable - provider state */
private int i3testProviderState = 0; /* undefined by default */
/** I3Test location - last location */
private LocationImpl i3testLocation = null; /* undefined by default */
private static LocationImpl lastLocation = null;
// JAVADOC COMMENT ELIDED
public PlatformLocationProvider(String name) throws IllegalAccessException {
/* open connection to the provider */
provider = open(name);
if (provider == 0) {
throw new IllegalAccessException("Provider " + name +
" is not supported");
}
/* create and fill criteria */
if (getCriteria(name, providerInfo)) {
criteria.setHorizontalAccuracy(providerInfo.horizontalAccuracy);
criteria.setVerticalAccuracy(providerInfo.verticalAccuracy);
criteria.setPreferredResponseTime(providerInfo.averageResponseTime);
criteria.setPreferredPowerConsumption(
providerInfo.powerConsumption);
criteria.setCostAllowed(providerInfo.incurCost);
criteria.setSpeedAndCourseRequired(
providerInfo.canReportSpeedCource);
criteria.setAltitudeRequired(providerInfo.canReportAltitude);
criteria.setAddressInfoRequired(providerInfo.canReportAddressInfo);
}
}
static native boolean getBestProviderByCriteriaImpl(CriteriaImpl criteria);
// JAVADOC COMMENT ELIDED
static protected String getBestProviderByCriteria(Criteria criteria)
throws IllegalAccessException {
CriteriaImpl criteriaImpl = new CriteriaImpl(criteria);
if (!getBestProviderByCriteriaImpl(criteriaImpl)) {
throw new IllegalAccessException("function not supported");
}
if (criteriaImpl.providerName != null) {
if (criteriaImpl.providerName.trim().equals("")) {
return null;
}
}
return criteriaImpl.providerName;
}
// JAVADOC COMMENT ELIDED
static protected Criteria getProviderInfo(String name) {
LocationProviderInfo providerInfo = new LocationProviderInfo();
Criteria criteria = new Criteria();
/* create and fill criteria */
if (getCriteria(name, providerInfo)) {
criteria.setHorizontalAccuracy(providerInfo.horizontalAccuracy);
criteria.setVerticalAccuracy(providerInfo.verticalAccuracy);
criteria.setPreferredResponseTime(providerInfo.averageResponseTime);
criteria.setPreferredPowerConsumption(
providerInfo.powerConsumption);
criteria.setCostAllowed(providerInfo.incurCost);
criteria.setSpeedAndCourseRequired(
providerInfo.canReportSpeedCource);
criteria.setAltitudeRequired(providerInfo.canReportAltitude);
criteria.setAddressInfoRequired(providerInfo.canReportAddressInfo);
}
return criteria;
}
// JAVADOC COMMENT ELIDED
protected void setUpdateInterval(int interval) {
setUpdateIntervalImpl(provider, interval);
}
// JAVADOC COMMENT ELIDED
protected LocationImpl updateLocation(long timeout)
throws LocationException {
LocationImpl location = null;
/* request location update */
long startTimestamp = System.currentTimeMillis();
if (i3testLocation == null) {
if (waitForNewLocation(provider, timeout)) {
/* get location and calculate timestamp */
long endTimestamp = System.currentTimeMillis();
long timestamp =
endTimestamp - providerInfo.averageResponseTime;
if (timestamp < startTimestamp) {
timestamp = endTimestamp;
}
location = getNewLocationImpl(timestamp);
if (location != null && location.isValid()) {
if (ProximityNotifier.getInstance() != null &&
ProximityNotifier.getInstance().proximityThread != null) {
synchronized(ProximityNotifier.getInstance().proximityThread) {
ProximityNotifier.getInstance().proximityThread.notify();
}
}
}
}
} else {
location = i3testLocation;
}
return location;
}
// JAVADOC COMMENT ELIDED
synchronized public LocationImpl getLastLocation() {
LocationInfo locationInfo = new LocationInfo();
LocationImpl location = null;
if (getLastLocationImpl(provider, locationInfo)) {
location = locationInfo2Location(locationInfo);
lastLocation = location;
}
return location;
}
// JAVADOC COMMENT ELIDED
private static LocationImpl locationInfo2Location(LocationInfo locationInfo) {
QualifiedCoordinates coordinates = new QualifiedCoordinates(
locationInfo.latitude, locationInfo.longitude,
locationInfo.altitude, locationInfo.horizontalAccuracy,
locationInfo.verticalAccuracy);
AddressInfo address = new AddressInfo();
if (locationInfo.isAddressInfo) {
if (locationInfo.AddressInfo_EXTENSION != null) {
address.setField(AddressInfo.EXTENSION,
locationInfo.AddressInfo_EXTENSION);
}
if (locationInfo.AddressInfo_STREET != null) {
address.setField(AddressInfo.STREET,
locationInfo.AddressInfo_STREET);
}
if (locationInfo.AddressInfo_POSTAL_CODE != null) {
address.setField(AddressInfo.POSTAL_CODE,
locationInfo.AddressInfo_POSTAL_CODE);
}
if (locationInfo.AddressInfo_CITY != null) {
address.setField(AddressInfo.CITY,
locationInfo.AddressInfo_CITY);
}
if (locationInfo.AddressInfo_COUNTY != null) {
address.setField(AddressInfo.COUNTY,
locationInfo.AddressInfo_COUNTY);
}
if (locationInfo.AddressInfo_STATE != null) {
address.setField(AddressInfo.STATE,
locationInfo.AddressInfo_STATE);
}
if (locationInfo.AddressInfo_COUNTRY != null) {
address.setField(AddressInfo.COUNTRY,
locationInfo.AddressInfo_COUNTRY);
}
if (locationInfo.AddressInfo_COUNTRY_CODE != null) {
address.setField(AddressInfo.COUNTRY_CODE,
locationInfo.AddressInfo_COUNTRY_CODE);
}
if (locationInfo.AddressInfo_DISTRICT != null) {
address.setField(AddressInfo.DISTRICT,
locationInfo.AddressInfo_DISTRICT);
}
if (locationInfo.AddressInfo_BUILDING_NAME != null) {
address.setField(AddressInfo.BUILDING_NAME,
locationInfo.AddressInfo_BUILDING_NAME);
}
if (locationInfo.AddressInfo_BUILDING_FLOOR != null) {
address.setField(AddressInfo.BUILDING_FLOOR,
locationInfo.AddressInfo_BUILDING_FLOOR);
}
if (locationInfo.AddressInfo_BUILDING_ROOM != null) {
address.setField(AddressInfo.BUILDING_ROOM,
locationInfo.AddressInfo_BUILDING_ROOM);
}
if (locationInfo.AddressInfo_BUILDING_ZONE != null) {
address.setField(AddressInfo.BUILDING_ZONE,
locationInfo.AddressInfo_BUILDING_ZONE);
}
if (locationInfo.AddressInfo_CROSSING1 != null) {
address.setField(AddressInfo.CROSSING1,
locationInfo.AddressInfo_CROSSING1);
}
if (locationInfo.AddressInfo_CROSSING2 != null) {
address.setField(AddressInfo.CROSSING2,
locationInfo.AddressInfo_CROSSING2);
}
if (locationInfo.AddressInfo_URL != null) {
address.setField(AddressInfo.URL,
locationInfo.AddressInfo_URL);
}
if (locationInfo.AddressInfo_PHONE_NUMBER != null) {
address.setField(AddressInfo.PHONE_NUMBER,
locationInfo.AddressInfo_PHONE_NUMBER);
}
}
LocationImpl location = new LocationImpl(coordinates, locationInfo.speed,
locationInfo.course, locationInfo.method, address,
locationInfo.isValid);
location.extraInfoNMEA = locationInfo.extraInfoNMEA;
location.extraInfoLIF = locationInfo.extraInfoLIF;
location.extraInfoPlain = locationInfo.extraInfoPlain;
location.extraInfoOther = locationInfo.extraInfoOther;
location.extraInfoOtherMIMEType = locationInfo.extraInfoOtherMIMEType;
location.setTimestamp(locationInfo.timestamp);
return location;
}
// JAVADOC COMMENT ELIDED
private native boolean getLastLocationImpl(int provider,
LocationInfo locationInfo);
// JAVADOC COMMENT ELIDED
synchronized public static Location getLastKnownLocation() {
return lastLocation;
}
// JAVADOC COMMENT ELIDED
public int getDefaultInterval() {
return (providerInfo.defaultInterval >= 1000) ?
(providerInfo.defaultInterval / 1000) : 1;
}
// JAVADOC COMMENT ELIDED
public int getDefaultMaxAge() {
return (providerInfo.defaultMaxAge >= 1000) ?
(providerInfo.defaultMaxAge / 1000) : 1;
}
// JAVADOC COMMENT ELIDED
public int getDefaultTimeout() {
return (providerInfo.defaultTimeout >= 1000) ?
(providerInfo.defaultTimeout / 1000) : 1;
}
// JAVADOC COMMENT ELIDED
public int getResponseTime() {
return (providerInfo.averageResponseTime >= 1000) ?
(providerInfo.averageResponseTime / 1000) : 1;
}
// JAVADOC COMMENT ELIDED
public int getStateInterval() {
return (providerInfo.defaultStateInterval >= 1000) ?
(providerInfo.defaultStateInterval / 1000) : 1;
}
// JAVADOC COMMENT ELIDED
public int getState() {
/* I3Test use only */
if (i3testProviderState != 0) {
return i3testProviderState;
}
/* Real mode */
return getStateImpl(provider);
}
// JAVADOC COMMENT ELIDED
LocationImpl getNewLocationImpl(long timestamp) {
if (receiveNewLocationImpl(provider, timestamp)) {
return getLastLocation();
}
return null;
}
// JAVADOC COMMENT ELIDED
private native boolean receiveNewLocationImpl(int provider, long timestamp);
// JAVADOC COMMENT ELIDED
public void reset() {
resetImpl(provider);
super.reset();
}
// JAVADOC COMMENT ELIDED
static native String getListOfLocationProviders();
// JAVADOC COMMENT ELIDED
private native int open(String name);
// JAVADOC COMMENT ELIDED
private native void setUpdateIntervalImpl(int provider, int interval);
// JAVADOC COMMENT ELIDED
private native static boolean getCriteria(String name,
LocationProviderInfo criteria);
// JAVADOC COMMENT ELIDED
private native int getStateImpl(int provider);
// JAVADOC COMMENT ELIDED
private native boolean waitForNewLocation(int provider, long timeout);
// JAVADOC COMMENT ELIDED
private native void resetImpl(int provider);
// native finalizer
// #ifdef ENABLE_CDC [
protected native void finalize();
// #else ][
private native void finalize();
// #endif ]
/**
* Set of I3test helper functions
*/
/**
* Set provider state.
* I3test use only !!!
*
* @param newState new state of Location Provider
*/
void i3test_setState(int newState) {
i3testProviderState = newState;
}
/**
* Set Last Location
* I3test use only !!!
*
* @param location
*/
void i3test_setLocation(LocationImpl location) {
i3testLocation = location;
}
}
/**
* The class contains information about Platform Location Provider
*/
class LocationProviderInfo {
// JAVADOC COMMENT ELIDED
boolean incurCost;
// JAVADOC COMMENT ELIDED
boolean canReportAltitude;
// JAVADOC COMMENT ELIDED
boolean canReportAddressInfo;
// JAVADOC COMMENT ELIDED
boolean canReportSpeedCource;
// JAVADOC COMMENT ELIDED
int powerConsumption;
// JAVADOC COMMENT ELIDED
int horizontalAccuracy;
// JAVADOC COMMENT ELIDED
int verticalAccuracy;
// JAVADOC COMMENT ELIDED
int defaultTimeout;
// JAVADOC COMMENT ELIDED
int defaultMaxAge;
// JAVADOC COMMENT ELIDED
int defaultInterval;
// JAVADOC COMMENT ELIDED
int averageResponseTime;
// JAVADOC COMMENT ELIDED
int defaultStateInterval;
/**
* Init class info in the native code
*/
static {
initNativeClass();
}
/**
* Initializes native file handler.
*/
private native static void initNativeClass();
};
/**
* The class contains Criteria Fields
*/
class CriteriaImpl {
// JAVADOC COMMENT ELIDED
String providerName;
// JAVADOC COMMENT ELIDED
boolean costAllowed;
// JAVADOC COMMENT ELIDED
boolean altitudeRequired;
// JAVADOC COMMENT ELIDED
boolean addressInfoRequired;
// JAVADOC COMMENT ELIDED
boolean speedCourceRequired;
// JAVADOC COMMENT ELIDED
int powerConsumption;
// JAVADOC COMMENT ELIDED
int horizontalAccuracy;
// JAVADOC COMMENT ELIDED
int verticalAccuracy;
// JAVADOC COMMENT ELIDED
int responseTime;
/**
* Init class info in the native code
*/
static {
initNativeClass();
}
CriteriaImpl(Criteria criteria) {
providerName = null;
costAllowed = criteria.isAllowedToCost();
altitudeRequired = criteria.isAltitudeRequired();
addressInfoRequired = criteria.isAddressInfoRequired();
speedCourceRequired = criteria.isSpeedAndCourseRequired();
powerConsumption = criteria.getPreferredPowerConsumption();
horizontalAccuracy = criteria.getHorizontalAccuracy();
verticalAccuracy = criteria.getVerticalAccuracy() ;
responseTime = criteria.getPreferredResponseTime();
}
/**
* Initializes native file handler.
*/
private native static void initNativeClass();
};
/**
* The class contains information about Platform Location
*/
class LocationInfo {
// JAVADOC COMMENT ELIDED
boolean isValid;
// JAVADOC COMMENT ELIDED
long timestamp;
// JAVADOC COMMENT ELIDED
double latitude;
// JAVADOC COMMENT ELIDED
double longitude;
// JAVADOC COMMENT ELIDED
float altitude;
// JAVADOC COMMENT ELIDED
float horizontalAccuracy;
// JAVADOC COMMENT ELIDED
float verticalAccuracy;
// JAVADOC COMMENT ELIDED
float speed;
// JAVADOC COMMENT ELIDED
float course;
// JAVADOC COMMENT ELIDED
int method;
// JAVADOC COMMENT ELIDED
boolean isAddressInfo = false;
// JAVADOC COMMENT ELIDED
String AddressInfo_EXTENSION = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_STREET = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_POSTAL_CODE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CITY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_STATE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTRY = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_COUNTRY_CODE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_DISTRICT = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_NAME = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_FLOOR = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_ROOM = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_BUILDING_ZONE = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CROSSING1 = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_CROSSING2 = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_URL = null;
// JAVADOC COMMENT ELIDED
String AddressInfo_PHONE_NUMBER = null;
// JAVADOC COMMENT ELIDED
String extraInfoNMEA;
// JAVADOC COMMENT ELIDED
String extraInfoLIF;
// JAVADOC COMMENT ELIDED
String extraInfoPlain;
// JAVADOC COMMENT ELIDED
String extraInfoOther;
// JAVADOC COMMENT ELIDED
String extraInfoOtherMIMEType = null;
/**
* Init class info in the native code
*/
static {
initNativeClass();
}
/**
* Initializes native file handler.
*/
private native static void initNativeClass();
}

Просмотреть файл

@ -0,0 +1,437 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import com.sun.j2me.log.Logging;
import java.util.Vector;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.ProximityListener;
import javax.microedition.location.QualifiedCoordinates;
/**
* Asynchronous thread for periodic location
* event handling.
*/
public class ProximityNotifier {
/**
* Instance of the proximity notifier. If the application does not
* use proximity notification, this class will not be instantiated.
*/
static ProximityNotifier Instance = null;
/** Array of registered listeners. */
Vector proximityListeners = new Vector();
/** Thread for proximity notifications. */
ProximityThread proximityThread = null;
/** Current thread performing monitoring state updating. */
StateMonitorThread stateThread = null;
/** Dedicated provider for delivering proximity data. */
LocationProviderImpl proximityProvider = null;
/**
* Gets a handle to proximity notifier.
* @return current proximity notifier handle
*/
public static ProximityNotifier getInstance() {
if (Instance == null) {
Instance = new ProximityNotifier();
}
return Instance;
}
/**
* Constructor.
*/
private ProximityNotifier() {
}
/**
* This class wraps proximity listeners and adds additional information.
*/
static class ProximityListenerDecorator {
/** Location proximity listener. */
private ProximityListener listener;
/** Coordinates to monitor. */
private Coordinates coordinates;
/** Radius for proximity check. */
private float proximityRadius;
// JAVADOC COMMENT ELIDED
ProximityListenerDecorator(ProximityListener listener,
Coordinates coordinates,
float proximityRadius) {
this.listener = listener;
this.coordinates = coordinates;
this.proximityRadius = proximityRadius;
}
// JAVADOC COMMENT ELIDED
public void proximityEvent(Location location) {
// Nothing to notify if an invalid location
if (!location.isValid()) {
return;
}
QualifiedCoordinates qCoord = location.getQualifiedCoordinates();
float distance = coordinates.distance(qCoord);
float hAccuracy = qCoord.getHorizontalAccuracy();
if (Float.isNaN(hAccuracy)) {
hAccuracy = 0.0F;
}
/*
* Perform a stricter test for proximity. The looser test for
* proximity would be distance + hAccuracy but that would
* mean that we might be notifying for a location that's not
* within the requested radius.
*/
if (distance - hAccuracy <= proximityRadius) {
// listener should be removed *before* notifying,
// because it can be re-registered in the user code
Instance.removeProximityListener(listener);
listener.proximityEvent(coordinates, location);
}
}
/**
* Monitor state change dispatcher.
*
* @param isMonitoringActive is trur if monitoring is enabled
*/
public void monitoringStateChanged(boolean isMonitoringActive) {
listener.monitoringStateChanged(isMonitoringActive);
}
}
// JAVADOC COMMENT ELIDED
public void addProximityListener(ProximityListener listener,
Coordinates coordinates,
float proximityRadius) {
synchronized (proximityListeners) {
proximityListeners.addElement(
new ProximityListenerDecorator(listener, coordinates,
proximityRadius));
}
synchronized (this) {
if (proximityProvider == null) {
try {
proximityProvider =
LocationProviderImpl.getInstanceImpl(null);
} catch (LocationException e) {
// nothing to do
}
}
if (proximityThread == null) {
proximityThread = new ProximityThread();
proximityThread.start();
} else {
synchronized (proximityThread) {
proximityThread.notify();
}
}
if (stateThread == null) {
stateThread = new StateMonitorThread();
stateThread.start();
} else {
synchronized (stateThread) {
stateThread.notify();
}
}
}
}
// JAVADOC COMMENT ELIDED
public void removeProximityListener(ProximityListener listener) {
ProximityListenerDecorator[] listeners;
synchronized (proximityListeners) {
listeners =
new ProximityListenerDecorator[proximityListeners.size()];
proximityListeners.copyInto(listeners);
}
for (int i = 0; i < listeners.length; i++) {
if (listeners[i].listener == listener) {
synchronized (proximityListeners) {
proximityListeners.removeElement(listeners[i]);
}
}
}
// check if it was the last listener
if (proximityListeners.isEmpty()) {
synchronized (this) {
if (proximityThread != null) {
proximityThread.terminate();
if (Thread.currentThread() != proximityThread) {
try { // wait for thread to die
proximityThread.join();
} catch (InterruptedException e) { // do nothing
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
}
proximityThread = null;
}
if (stateThread != null) {
stateThread.terminate();
try { // wait for thread to die
stateThread.join();
} catch (InterruptedException e) { // do nothing
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
stateThread = null;
}
// dedicated provider is no longer needed
proximityProvider = null;
}
}
}
/**
* Dispatches a proximity event.
*
* @param location location that triggered the proximity event
*/
void fireProximityEvent(Location location) {
// prevents concurent modification in which the event code modifies
// the vector by invoking remove/add during event execution
ProximityListenerDecorator[] listeners;
synchronized (proximityListeners) {
listeners =
new ProximityListenerDecorator[proximityListeners.size()];
proximityListeners.copyInto(listeners);
}
if (listeners.length > 0) {
for (int i = 0; i < listeners.length; i++) {
listeners[i].proximityEvent(location);
}
}
}
/**
* Dispatches a monitor stat changed event.
*
* @param isMonitoringActive is true if monitoring is enabled
*/
void fireMonitoringStateChanged(boolean isMonitoringActive) {
// prevents concurent modification in which the event code modifies
// the vector by invoking remove/add during event execution
ProximityListenerDecorator[] listeners;
synchronized (proximityListeners) {
listeners =
new ProximityListenerDecorator[proximityListeners.size()];
proximityListeners.copyInto(listeners);
}
for (int i = 0; i < listeners.length; i++) {
listeners[i].monitoringStateChanged(isMonitoringActive);
}
}
/**
* Returns a vector of proximity listeners.
*
* @return the vector of registered proximity listeners
*/
Vector getListeners() {
return proximityListeners;
}
/**
* The recommended time interval for proximity update events.
*
* @return the default interval of the dedicated provider
*/
int getProximityInterval() {
if (proximityProvider != null) {
return proximityProvider.getDefaultInterval();
}
return 10;
}
/**
* The recommended time interval for querying monitoring state.
*
* @return time interval in seconds
*/
int getStateInterval() {
if (proximityProvider != null) {
return proximityProvider.getStateInterval();
}
return 10;
}
/**
* Retrieves location from the dedicated provider.
*
* @return location to be used for proximity detection.
*/
Location getLocation() {
Location location = null;
try {
if (proximityProvider == null) {
proximityProvider = LocationProviderImpl.getInstanceImpl(null);
}
location = proximityProvider.getLocationImpl(-1);
} catch (LocationException e) {
//nothing to do
} catch (InterruptedException e) {
//nothing to do
}
return location;
}
/**
* Checks if the monitoring is active.
*
* @return true if monitoring is active, false otherwise
*/
boolean getMonitoringState() {
return proximityProvider != null &&
proximityProvider.getState() == LocationProvider.AVAILABLE;
}
}
/**
* Class ProximityThread sends proximity notifications
* when the proximity is detected.
*/
class ProximityThread extends Thread {
/** Flag indicating if the thread should terminate. */
private boolean terminated = false;
/**
* Constructor.
*/
ProximityThread() {
}
/**
* Terminates the thread.
*/
void terminate() {
terminated = true;
synchronized (this) {
notify();
}
}
/**
* Runs the proximity notifier logic.
*/
public void run() {
ProximityNotifier notifier = ProximityNotifier.getInstance();
// time interval for updating location
int interval = notifier.getProximityInterval();
Location l = notifier.getLocation();
try {
while (!terminated) {
if (l != null) {
notifier.fireProximityEvent(l);
}
if (terminated) { // the thread was stopped
break;
}
long startWait = System.currentTimeMillis();
synchronized (this) {
wait((long)interval * 1000);
}
l = LocationProviderImpl.getLastKnownLocation();
if (l == null || (l.getTimestamp() < startWait)) {
l = notifier.getLocation();
}
}
} catch (InterruptedException e) {
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
}
}
/**
* Class StateMonitorThread sends notifications when
* the state of monitor is changed.
*/
class StateMonitorThread extends Thread {
/** Flag indicating if the thread should terminate. */
private boolean terminated = false;
/**
* Constructor.
*/
StateMonitorThread() {
}
/**
* Terminates the thread.
*/
void terminate() {
terminated = true;
synchronized (this) {
notify();
}
}
/**
* Runs the proximity notifier logic.
*/
public void run() {
boolean state = true;
ProximityNotifier notifier = ProximityNotifier.getInstance();
// time interval for checking the state in seconds
int interval = notifier.getStateInterval();
try {
while (!terminated) {
boolean newState = notifier.getMonitoringState();
if (newState != state) {
state = newState;
notifier.fireMonitoringStateChanged(state);
}
if (terminated) { // the thread was stopped
break;
}
synchronized (this) {
wait((long)interval * 1000);
}
}
} catch (InterruptedException e) {
if (Logging.TRACE_ENABLED) {
Logging.trace(e, "Wrong thread exception.");
}
}
}
}

Просмотреть файл

@ -0,0 +1,67 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.location;
import com.sun.j2me.app.AppPackage;
import com.sun.j2me.security.Permission;
/**
* Set of static utility functions for simple repetitive operations.
*/
public class Util {
private Util() {};
// JAVADOC COMMENT ELIDED
public static void checkRange(double val, double minimum, double maximum,
String exceptionComment) {
if (val < minimum || val > maximum) {
throw new IllegalArgumentException(exceptionComment + val);
}
if (Double.isNaN(val)) {
throw new IllegalArgumentException(exceptionComment + "NaN");
}
}
// JAVADOC COMMENT ELIDED
public static void checkForPermission(Permission permission,
boolean ignoreInterruptedException) {
try {
AppPackage.getInstance().checkForPermission(permission);
} catch (InterruptedException ie) {
if (!ignoreInterruptedException) {
throw new SecurityException(
"Interrupted while trying to ask the user permission");
}
}
}
// JAVADOC COMMENT ELIDED
public static void checkForPermission(Permission permission) {
checkForPermission(permission, true);
}
}

Просмотреть файл

@ -0,0 +1,31 @@
/*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.log;
/**
* Intermediate class for logging facilities
*/
public class LogChannels extends com.sun.midp.log.LogChannels {
}

Просмотреть файл

@ -0,0 +1,31 @@
/*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.log;
/**
* Intermediate class for logging facilities
*/
public class Logging extends com.sun.midp.log.Logging {
}

Просмотреть файл

@ -0,0 +1,65 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.j2me.security;
/**
* Location and landmark store access permissions.
*/
public class LocationPermission extends Permission {
static public LocationPermission LOCATION = new LocationPermission(
"javax.microedition.location.Location", null);
static public LocationPermission ORIENTATION =
new LocationPermission(
"javax.microedition.location.Orientation", null);
static public LocationPermission LOCATION_PROXIMITY =
new LocationPermission(
"javax.microedition.location.ProximityListener", null);
static public LocationPermission LANDMARK_STORE_READ =
new LocationPermission(
"javax.microedition.location.LandmarkStore.read", null);
static public LocationPermission LANDMARK_STORE_WRITE =
new LocationPermission(
"javax.microedition.location.LandmarkStore.write", null);
static public LocationPermission LANDMARK_STORE_CATEGORY =
new LocationPermission(
"javax.microedition.location.LandmarkStore.category", null);
static public LocationPermission LANDMARK_STORE_MANAGE =
new LocationPermission(
"javax.microedition.location.LandmarkStore.management", null);
public LocationPermission(String name, String resource) {
super(name, resource);
}
}

Просмотреть файл

@ -0,0 +1,125 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class AddressInfo {
// JAVADOC COMMENT ELIDED
public static final int EXTENSION = 1;
// JAVADOC COMMENT ELIDED
public static final int STREET = 2;
// JAVADOC COMMENT ELIDED
public static final int POSTAL_CODE = 3;
// JAVADOC COMMENT ELIDED
public static final int CITY = 4;
// JAVADOC COMMENT ELIDED
public static final int COUNTY = 5;
// JAVADOC COMMENT ELIDED
public static final int STATE = 6;
// JAVADOC COMMENT ELIDED
public static final int COUNTRY = 7;
// JAVADOC COMMENT ELIDED
public static final int COUNTRY_CODE = 8;
// JAVADOC COMMENT ELIDED
public static final int DISTRICT = 9;
// JAVADOC COMMENT ELIDED
public static final int BUILDING_NAME = 10;
// JAVADOC COMMENT ELIDED
public static final int BUILDING_FLOOR = 11;
// JAVADOC COMMENT ELIDED
public static final int BUILDING_ROOM = 12;
// JAVADOC COMMENT ELIDED
public static final int BUILDING_ZONE = 13;
// JAVADOC COMMENT ELIDED
public static final int CROSSING1 = 14;
// JAVADOC COMMENT ELIDED
public static final int CROSSING2 = 15;
// JAVADOC COMMENT ELIDED
public static final int URL = 16;
// JAVADOC COMMENT ELIDED
public static final int PHONE_NUMBER = 17;
// JAVADOC COMMENT ELIDED
final static int DATA_SIZE = 17;
// JAVADOC COMMENT ELIDED
private String[] data = new String[DATA_SIZE];
// JAVADOC COMMENT ELIDED
public AddressInfo() {
}
// JAVADOC COMMENT ELIDED
AddressInfo(String[] data) {
this.data = data;
}
// JAVADOC COMMENT ELIDED
String[] getData() {
return data;
}
// JAVADOC COMMENT ELIDED
public String getField(int field) {
checkField(field);
return data[field - 1];
}
// JAVADOC COMMENT ELIDED
private void checkField(int field) {
if (field < 1 || field > data.length) {
throw new
IllegalArgumentException("Unsuported field attribute value: "
+ field);
}
}
// JAVADOC COMMENT ELIDED
public void setField(int field, String value) {
checkField(field);
data[field - 1] = value;
}
}

Просмотреть файл

@ -0,0 +1,380 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
import com.sun.j2me.location.*;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class Coordinates {
// JAVADOC COMMENT ELIDED
public static final int DD_MM_SS = 1;
// JAVADOC COMMENT ELIDED
public static final int DD_MM = 2;
// JAVADOC COMMENT ELIDED
private double latitude;
// JAVADOC COMMENT ELIDED
private double longitude;
// JAVADOC COMMENT ELIDED
private float altitude;
// JAVADOC COMMENT ELIDED
static final double EARTH_RADIUS = 6378137D;
// JAVADOC COMMENT ELIDED
static final double FLATTENING = 298.257223563D;
// JAVADOC COMMENT ELIDED
static final double DEG2RAD = 0.01745329252D;
// JAVADOC COMMENT ELIDED
private float azimuth;
// JAVADOC COMMENT ELIDED
private float distance;
// JAVADOC COMMENT ELIDED
public Coordinates(double latitude, double longitude, float altitude) {
setLatitude(latitude);
setLongitude(longitude);
this.altitude = altitude;
}
// JAVADOC COMMENT ELIDED
public double getLatitude() {
return latitude;
}
// JAVADOC COMMENT ELIDED
public double getLongitude() {
return longitude;
}
// JAVADOC COMMENT ELIDED
public float getAltitude() {
return altitude;
}
// JAVADOC COMMENT ELIDED
public void setAltitude(float altitude) {
this.altitude = altitude;
}
// JAVADOC COMMENT ELIDED
public void setLatitude(double latitude) {
Util.checkRange(latitude, -90, 90,
"Latitude out of range [-90.0, 90]: ");
this.latitude = latitude;
}
// JAVADOC COMMENT ELIDED
public void setLongitude(double longitude) {
Util.checkRange(longitude, -180, 180,
"Longitude out of range [-180.0, 180): ");
if (longitude == 180D) {
throw new IllegalArgumentException(
"Longitude out of range [-180.0, 180): " + longitude);
}
this.longitude = longitude;
}
// JAVADOC COMMENT ELIDED
public static double convert(String coordinate) {
if (coordinate == null) {
throw new NullPointerException("Null string specified");
}
// tokenize the coordianates to 2 or 3 elements
if (coordinate.startsWith("0") && (!coordinate.startsWith("0:"))) {
throw new IllegalArgumentException(
"A coordinate cannot start with a 0 with two digits");
}
double[] coordinates = new double[] { Double.NaN, Double.NaN, 0 };
int next = -1;
int current = 0;
do {
if (current > 2) {
throw new
IllegalArgumentException(
"Invalid coordinate format");
}
int position = next + 1;
next = coordinate.indexOf(':', position);
String currentText;
if (next > -1) {
currentText = coordinate.substring(position, next);
try {
coordinates[current] = Double.parseDouble(currentText);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Invalid coordinate format: " + e.getMessage());
}
// only the last coordinate may be a fracture
if ((long)coordinates[current] != coordinates[current]) {
throw new
IllegalArgumentException(
"Only the last coordinate may be a fracture: "
+ coordinate);
}
} else {
currentText = coordinate.substring(position,
coordinate.length());
try {
coordinates[current] = Double.parseDouble(currentText);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Invalid coordinate format: " + e.getMessage());
}
}
if (currentText.startsWith("+")) {
throw new
IllegalArgumentException(
"Coordinate should not use 'plus' sign :"
+ currentText);
}
if (current > 0) {
int pos = currentText.indexOf('.');
if (pos > -1) {
if (pos != 2 || currentText.length() < 4) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
if (current != 2) {
if (currentText.length() - pos > 6) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
} else {
if (currentText.length() - pos > 4) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
}
} else {
if (currentText.length() != 2) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
}
}
if (currentText.endsWith(".")) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
current++;
} while (next > -1);
// special case for 180 when the degrees is -180 and the
// minutes, seconds and decimal fractions are 0
if (coordinates[0] != -180D) {
Util.checkRange(coordinates[0], -179, 179,
"Degrees out of range [-179.0, 179]: ");
Util.checkRange(coordinates[1], 0, 60,
"Minutes out of range [0, 59]: ");
Util.checkRange(coordinates[2], 0, 60,
"Seconds out of range [0, 59]: ");
if (coordinates[1] == 60D) {
throw new IllegalArgumentException(
"Minutes out of range [0, 59]: 60");
}
if (coordinates[2] == 60D) {
throw new IllegalArgumentException(
"Seconds out of range [0, 59]: 60");
}
if (Double.isNaN(coordinates[1])) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
} else {
if (coordinates[1] != 0D || coordinates[2] != 0D) {
throw new IllegalArgumentException(
"Invalid coordinate format");
}
}
// convert the integer array to a numeric representation:
double value = coordinates[0];
if (!coordinate.startsWith("-")) {
value += coordinates[1] / 60 + coordinates[2] / 3600;
} else {
value -= coordinates[1] / 60 + coordinates[2] / 3600;
}
return value;
}
// JAVADOC COMMENT ELIDED
public static String convert(double coordinate, int outputType) {
if (coordinate == 180D || Double.isNaN(coordinate)) {
throw new IllegalArgumentException("Coordinate out of range");
}
Util.checkRange(coordinate, -180, 180,
"Coordinate out of range [-180.0, 180): ");
StringBuffer buffer = new StringBuffer();
if (coordinate < 0) {
buffer.append("-");
}
coordinate = Math.abs(coordinate);
int deg = (int)coordinate;
buffer.append(deg);
buffer.append(":");
double dMin = (coordinate - deg) * 60D;
if (outputType == DD_MM_SS) {
int min1 = (int)dMin;
if (min1 == 60) min1 = 59;
if (min1 < 10) {
buffer.append("0");
}
buffer.append(min1);
buffer.append(":");
double dSec = (dMin - min1) * 60D;
double sec1 = (double)(int)Math.floor(1000D * dSec + 0.5D) / 1000D;
if (sec1 >= 60) sec1 = 59.999;
if (sec1 < 10) {
buffer.append("0");
}
buffer.append(sec1);
} else {
if (outputType != DD_MM) {
throw new
IllegalArgumentException(
"outputType must be either DD_MM or DD_MM_SS, " +
"instead we got: " + outputType);
}
double min2 = (double)(int)Math.floor(100000D * dMin + 0.5D)
/ 100000D;
if (min2 >= 60) min2 = 59.99999;
if (min2 < 10) {
buffer.append("0");
}
buffer.append(min2);
}
return buffer.toString();
}
// JAVADOC COMMENT ELIDED
public float azimuthTo(Coordinates to) {
if (to == null) {
throw new NullPointerException("Null coordinates specified");
}
computeAzimuthAndDistance(latitude, longitude,
to.latitude, to.longitude);
return azimuth;
}
// JAVADOC COMMENT ELIDED
public float distance(Coordinates to) {
if (to == null) {
throw new NullPointerException("Null coordinates specified");
}
computeAzimuthAndDistance(latitude, longitude,
to.latitude, to.longitude);
return distance;
}
// JAVADOC COMMENT ELIDED
private void computeAzimuthAndDistance(double lat1, double long1,
double lat2, double long2) {
if ((lat1 == lat2) && (long1 == long2)) {
azimuth = 0;
distance = 0;
return;
}
double c = 0.0;
double d = 0.0;
double e = 0.0;
double y = 0.0;
double sa = 0.0;
double sx = 0.0;
double sy = 0.0;
double cx = 0.0;
double cy = 0.0;
double cz = 0.0;
double c2a = 0.0;
double f = 1.0D / FLATTENING; // Flattening factor
// Initial values
double eps = 0.5E-13; // Tolerence
double glon1 = long1 * DEG2RAD;
double glat1 = lat1 * DEG2RAD;
double glon2 = long2 * DEG2RAD;
double glat2 = lat2 * DEG2RAD;
double r = 1.0D - f;
double tu1 = r * Math.sin(glat1) / Math.cos(glat1);
double tu2 = r * Math.sin(glat2) / Math.cos(glat2);
double cu1 = 1 / Math.sqrt(1 + tu1 * tu1);
double su1 = cu1 * tu1;
double cu2 = 1 / Math.sqrt(1 + tu2 * tu2);
double s = cu1 * cu2;
double baz = s * tu2;
double faz = baz * tu1;
double x = glon2 - glon1;
// Iterate
do {
sx = Math.sin(x);
cx = Math.cos(x);
tu1 = cu2 * sx;
tu2 = baz - su1 * cu2 * cx;
sy = Math.sqrt(tu1 * tu1 + tu2 * tu2);
cy = s * cx + faz;
y = LocationMath.atan2(sy, cy);
sa = s * sx / sy;
c2a = -sa * sa + 1;
cz = faz + faz;
if (c2a > 0) {
cz = -cz / c2a + cy;
}
e = cz * cz * 2 - 1;
c = ((-3 * c2a + 4) * f + 4) * c2a * f / 16;
d = x;
x = ((e * cy * c + cz) * sy * c + y) * sa;
x = (1 - c) * x * f + glon2 - glon1;
} while (Math.abs(d - x) > eps);
// Finish up
faz = LocationMath.atan2(tu1, tu2);
azimuth = (float)(faz / DEG2RAD);
if (azimuth < 0) {
azimuth += 360;
}
if (lat1 == 90D) {
azimuth = 180F;
} else if (lat1 == -90D) {
azimuth = 0.0F;
}
x = Math.sqrt((1 / r / r - 1) * c2a + 1) + 1;
x = (x - 2) / x;
c = 1 - x;
c = (x * x / 4 + 1) / c;
d = (0.375 * x * x - 1) * x;
x = e * cy;
s = 1 - 2 * e;
distance = (float)(((((sy * sy * 4 - 3) * s * cz * d / 6 - x) * d / 4 +
cz) * sy * d + y) * c * EARTH_RADIUS * r);
}
}

Просмотреть файл

@ -0,0 +1,145 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class Criteria {
// JAVADOC COMMENT ELIDED
public static final int NO_REQUIREMENT = 0;
// JAVADOC COMMENT ELIDED
public static final int POWER_USAGE_LOW = 1;
// JAVADOC COMMENT ELIDED
public static final int POWER_USAGE_MEDIUM = 2;
// JAVADOC COMMENT ELIDED
public static final int POWER_USAGE_HIGH = 3;
// JAVADOC COMMENT ELIDED
private int preferredPowerConsumption = NO_REQUIREMENT;
// JAVADOC COMMENT ELIDED
private boolean allowedToCost = true;
// JAVADOC COMMENT ELIDED
private boolean speedAndCourseRequired = false;
// JAVADOC COMMENT ELIDED
private boolean altitudeRequired = false;
// JAVADOC COMMENT ELIDED
private boolean addressInfoRequired = false;
// JAVADOC COMMENT ELIDED
private int horizontalAccuracy = NO_REQUIREMENT;
// JAVADOC COMMENT ELIDED
private int verticalAccuracy = NO_REQUIREMENT;
// JAVADOC COMMENT ELIDED
private int preferredResponseTime = NO_REQUIREMENT;
// JAVADOC COMMENT ELIDED
public Criteria() {
}
// JAVADOC COMMENT ELIDED
public int getPreferredPowerConsumption() {
return preferredPowerConsumption;
}
// JAVADOC COMMENT ELIDED
public boolean isAllowedToCost() {
return allowedToCost;
}
// JAVADOC COMMENT ELIDED
public int getVerticalAccuracy() {
return verticalAccuracy;
}
// JAVADOC COMMENT ELIDED
public int getHorizontalAccuracy() {
return horizontalAccuracy;
}
// JAVADOC COMMENT ELIDED
public int getPreferredResponseTime() {
return preferredResponseTime;
}
// JAVADOC COMMENT ELIDED
public boolean isSpeedAndCourseRequired() {
return speedAndCourseRequired;
}
// JAVADOC COMMENT ELIDED
public boolean isAltitudeRequired() {
return altitudeRequired;
}
// JAVADOC COMMENT ELIDED
public boolean isAddressInfoRequired() {
return addressInfoRequired;
}
// JAVADOC COMMENT ELIDED
public void setHorizontalAccuracy(int accuracy) {
horizontalAccuracy = accuracy;
}
// JAVADOC COMMENT ELIDED
public void setVerticalAccuracy(int accuracy) {
verticalAccuracy = accuracy;
}
// JAVADOC COMMENT ELIDED
public void setPreferredResponseTime(int time) {
preferredResponseTime = time;
}
// JAVADOC COMMENT ELIDED
public void setPreferredPowerConsumption(int level) {
preferredPowerConsumption = level;
}
// JAVADOC COMMENT ELIDED
public void setCostAllowed(boolean costAllowed) {
allowedToCost = costAllowed;
}
// JAVADOC COMMENT ELIDED
public void setSpeedAndCourseRequired(boolean speedAndCourseRequired) {
this.speedAndCourseRequired = speedAndCourseRequired;
}
// JAVADOC COMMENT ELIDED
public void setAltitudeRequired(boolean altitudeRequired) {
this.altitudeRequired = altitudeRequired;
}
// JAVADOC COMMENT ELIDED
public void setAddressInfoRequired(boolean addressInfoRequired) {
this.addressInfoRequired = addressInfoRequired;
}
}

Просмотреть файл

@ -0,0 +1,120 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
import com.sun.j2me.location.LandmarkImpl;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class Landmark {
/** Landmark Implementation */
private LandmarkImpl landmarkImpl;
private String nameImpl;
private String descriptionImpl;
private QualifiedCoordinates coordinatesImpl;
private AddressInfo addressInfoImpl;
// JAVADOC COMMENT ELIDED
public Landmark(String name, String description,
QualifiedCoordinates coordinates,
AddressInfo addressInfo) {
landmarkImpl = null;
setName(name);
descriptionImpl = description;
coordinatesImpl = coordinates;
addressInfoImpl = addressInfo;
}
// JAVADOC COMMENT ELIDED
public String getName() {
return nameImpl;
}
// JAVADOC COMMENT ELIDED
public String getDescription() {
return descriptionImpl;
}
// JAVADOC COMMENT ELIDED
public QualifiedCoordinates getQualifiedCoordinates() {
return coordinatesImpl;
}
// JAVADOC COMMENT ELIDED
public AddressInfo getAddressInfo() {
return addressInfoImpl;
}
// JAVADOC COMMENT ELIDED
public void setName(String name) {
if (name == null) {
throw new NullPointerException();
}
nameImpl = name;
}
// JAVADOC COMMENT ELIDED
public void setDescription(String description) {
descriptionImpl = description;
}
// JAVADOC COMMENT ELIDED
public void setQualifiedCoordinates(QualifiedCoordinates coordinates) {
coordinatesImpl = coordinates;
}
// JAVADOC COMMENT ELIDED
public void setAddressInfo(AddressInfo addressInfo) {
addressInfoImpl = addressInfo;
}
// JAVADOC COMMENT ELIDED
Landmark(LandmarkImpl landmark) {
landmarkImpl = landmark;
nameImpl = landmark.getName();
descriptionImpl = landmark.getDescription();
coordinatesImpl = landmark.getQualifiedCoordinates();
addressInfoImpl = landmark.getAddressInfo();
}
// JAVADOC COMMENT ELIDED
LandmarkImpl getInstance() {
if (landmarkImpl == null) {
landmarkImpl = new LandmarkImpl(nameImpl, descriptionImpl,
coordinatesImpl, addressInfoImpl);
} else {
landmarkImpl.setName(nameImpl);
landmarkImpl.setDescription(descriptionImpl);
landmarkImpl.setQualifiedCoordinates(coordinatesImpl);
landmarkImpl.setAddressInfo(addressInfoImpl);
}
return landmarkImpl;
}
}

Просмотреть файл

@ -0,0 +1,44 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class LandmarkException extends Exception {
// JAVADOC COMMENT ELIDED
public LandmarkException() {
}
// JAVADOC COMMENT ELIDED
public LandmarkException(String s) {
super(s);
}
}

Просмотреть файл

@ -0,0 +1,315 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
import com.sun.j2me.location.LandmarkImpl;
import com.sun.j2me.location.LocationPersistentStorage;
import com.sun.j2me.location.Util;
import com.sun.j2me.main.Configuration;
import com.sun.j2me.security.LocationPermission;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class LandmarkStore {
/** LandmarkStore Create property */
private static final String CREATE_LANDMARKSTORE_SUPPORTED =
"com.sun.j2me.location.CreateLandmarkStoreSupported";
/** LandmarkStore Delete property */
private static final String DELETE_LANDMARKSTORE_SUPPORTED =
"com.sun.j2me.location.DeleteLandmarkStoreSupported";
/** Category Create property */
private static final String CREATE_CATEGORY_SUPPORTED =
"com.sun.j2me.location.CreateCategorySupported";
/** Category Delete property */
private static final String DELETE_CATEGORY_SUPPORTED =
"com.sun.j2me.location.DeleteCategorySupported";
/** The default instance of a store */
private static final LandmarkStore defaultStore = new LandmarkStore();
/** The name of the record store */
private String storeName;
/**
* Constructor is private to prevent user from instanciating this class.
*
* @param storeName name of landmark store
*/
private LandmarkStore(String storeName) {
this.storeName = storeName;
}
/**
* Prevent the user from instanciating this class
* creates default LandmarkStore if it is not exist
*/
private LandmarkStore() {
this.storeName = null;
}
// JAVADOC COMMENT ELIDED
public static synchronized LandmarkStore getInstance(String storeName) {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_READ);
LandmarkStore current = null;
try {
if (storeName == null) {
return defaultStore;
} else {
String[] storeNames =
LocationPersistentStorage.listStoreNames();
if (storeNames != null) {
for (int i = 0; i < storeNames.length; i++) {
if (storeNames[i].equals(storeName)) {
current = new LandmarkStore(storeName);
break;
}
}
}
}
} catch (IOException e) { // return null
}
return current;
}
// JAVADOC COMMENT ELIDED
public static void createLandmarkStore(String storeName)
throws IOException, LandmarkException {
if (Configuration.getProperty(CREATE_LANDMARKSTORE_SUPPORTED).
equals("true")) {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_MANAGE);
if (storeName == null) {
throw new NullPointerException("storeName can not be null");
}
// verify that the name is correct and store does not exist
int storeLen = storeName.length();
if (storeLen == 0) {
throw new IllegalArgumentException("The store: name has " +
"incorrect length");
}
if (getInstance(storeName) != null) {
throw new IllegalArgumentException("The store: " + storeName +
" already exists");
}
LocationPersistentStorage.addStoreName(storeName);
} else {
throw new LandmarkException(
"Implementation does not support " +
"creating new landmark stores");
}
}
// JAVADOC COMMENT ELIDED
public static void deleteLandmarkStore(String storeName)
throws IOException, LandmarkException {
if (Configuration.getProperty(DELETE_LANDMARKSTORE_SUPPORTED).
equals("true")) {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_MANAGE);
if (storeName == null) {
throw new NullPointerException();
}
LocationPersistentStorage.removeStoreName(storeName);
} else {
throw new LandmarkException(
"Implementation does not support " +
"deleting landmark stores");
}
}
// JAVADOC COMMENT ELIDED
public static String[] listLandmarkStores() throws IOException {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_READ);
return LocationPersistentStorage.listStoreNames();
}
// JAVADOC COMMENT ELIDED
public void addLandmark(Landmark landmark, String category)
throws IOException {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_WRITE);
if (landmark == null) { // NullPointerException should be caused
throw new NullPointerException("Landmark is null");
}
LocationPersistentStorage.addLandmark(storeName,
landmark.getInstance(), category);
}
// JAVADOC COMMENT ELIDED
public Enumeration getLandmarks(String category, String name)
throws IOException {
Enumeration en = LocationPersistentStorage.
getLandmarksEnumeration(storeName, category, name,
-90, 90, -180, 180);
if (en == null) {
return null;
}
Vector vecLandmarks = new Vector();
while (en.hasMoreElements()) {
vecLandmarks.addElement(
new Landmark((LandmarkImpl)en.nextElement()));
}
return vecLandmarks.elements();
}
// JAVADOC COMMENT ELIDED
public Enumeration getLandmarks() throws IOException {
return getLandmarks(null, null);
}
// JAVADOC COMMENT ELIDED
public Enumeration getLandmarks(String category, double minLatitude,
double maxLatitude, double minLongitude, double maxLongitude)
throws IOException {
if ((minLongitude == 180D) ||
(maxLongitude == 180D)) {
throw new IllegalArgumentException("Longtitude out of range " +
"must not equal 180");
}
if (minLatitude > maxLatitude) {
throw new IllegalArgumentException("Minimum latitude cannot be " +
"larger than the maximum latitude");
}
Util.checkRange(minLatitude, -90, 90,
"Latitude out of range [-90.0, 90]: ");
Util.checkRange(maxLatitude, -90, 90,
"Latitude out of range [-90.0, 90]: ");
Util.checkRange(maxLongitude, -180, 180,
"Longitude out of range [-180.0, 180]: ");
Util.checkRange(minLongitude, -180, 180,
"Longitude out of range [-180.0, 180]: ");
Enumeration en = LocationPersistentStorage.
getLandmarksEnumeration(storeName, category, null,
minLatitude, maxLatitude,
minLongitude, maxLongitude);
if (en == null) {
return null;
}
Vector vecLandmarks = new Vector();
while (en.hasMoreElements()) {
vecLandmarks.addElement(
new Landmark((LandmarkImpl)en.nextElement()));
}
return vecLandmarks.elements();
}
// JAVADOC COMMENT ELIDED
public void removeLandmarkFromCategory(Landmark lm, String category)
throws IOException {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_WRITE);
if (lm == null || category == null) {
throw new NullPointerException();
}
LocationPersistentStorage.removeLandmarkFromCategory(
storeName, lm.getInstance(), category);
}
// JAVADOC COMMENT ELIDED
public void updateLandmark(Landmark lm)
throws IOException, LandmarkException {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_WRITE);
if (lm == null) {
throw new NullPointerException();
}
LocationPersistentStorage.updateLandmark(
storeName, lm.getInstance());
}
// JAVADOC COMMENT ELIDED
public void deleteLandmark(Landmark lm)
throws IOException, LandmarkException {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_WRITE);
if (lm == null) {
throw new NullPointerException();
}
LocationPersistentStorage.deleteLandmark(
storeName, lm.getInstance());
}
// JAVADOC COMMENT ELIDED
public Enumeration getCategories() {
try {
return getCategoriesVector().elements();
} catch (IOException e) {
return new Vector().elements();
}
}
// JAVADOC COMMENT ELIDED
private Vector getCategoriesVector() throws IOException {
return LocationPersistentStorage.
getCategories(storeName);
}
// JAVADOC COMMENT ELIDED
public void addCategory(String categoryName)
throws LandmarkException, IOException {
if (Configuration.getProperty(CREATE_CATEGORY_SUPPORTED).
equals("true")) {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_CATEGORY);
if (categoryName == null) {
throw new NullPointerException("Category name is null");
}
// save categories into persistent storage
LocationPersistentStorage.
addCategory(categoryName, storeName);
} else {
throw new LandmarkException(
"Implementation does not support " +
"creating categories");
}
}
// JAVADOC COMMENT ELIDED
public void deleteCategory(String categoryName)
throws LandmarkException, IOException {
if (Configuration.getProperty(DELETE_CATEGORY_SUPPORTED).
equals("true")) {
Util.checkForPermission(LocationPermission.LANDMARK_STORE_CATEGORY);
if (categoryName == null) {
throw new NullPointerException();
}
LocationPersistentStorage.
deleteCategory(categoryName, storeName);
} else {
throw new LandmarkException(
"Implementation does not support " +
"deleting categories");
}
}
}

Просмотреть файл

@ -0,0 +1,107 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class Location {
// JAVADOC COMMENT ELIDED
public static final int MTE_SATELLITE = 0x00000001;
// JAVADOC COMMENT ELIDED
public static final int MTE_TIMEDIFFERENCE = 0x00000002;
// JAVADOC COMMENT ELIDED
public static final int MTE_TIMEOFARRIVAL = 0x00000004;
// JAVADOC COMMENT ELIDED
public static final int MTE_CELLID = 0x00000008;
// JAVADOC COMMENT ELIDED
public static final int MTE_SHORTRANGE = 0x00000010;
// JAVADOC COMMENT ELIDED
public static final int MTE_ANGLEOFARRIVAL = 0x00000020;
// JAVADOC COMMENT ELIDED
public static final int MTY_TERMINALBASED = 0x00010000;
// JAVADOC COMMENT ELIDED
public static final int MTY_NETWORKBASED = 0x00020000;
// JAVADOC COMMENT ELIDED
public static final int MTA_ASSISTED = 0x00040000;
// JAVADOC COMMENT ELIDED
public static final int MTA_UNASSISTED = 0x00080000;
// JAVADOC COMMENT ELIDED
protected Location() {
}
// JAVADOC COMMENT ELIDED
public boolean isValid() {
return false;
}
// JAVADOC COMMENT ELIDED
public long getTimestamp() {
return 0;
}
// JAVADOC COMMENT ELIDED
public QualifiedCoordinates getQualifiedCoordinates() {
return null;
}
// JAVADOC COMMENT ELIDED
public float getSpeed() {
return 0;
}
// JAVADOC COMMENT ELIDED
public float getCourse() {
return 0;
}
// JAVADOC COMMENT ELIDED
public int getLocationMethod() {
return 0;
}
// JAVADOC COMMENT ELIDED
public AddressInfo getAddressInfo() {
return null;
}
// JAVADOC COMMENT ELIDED
public String getExtraInfo(String mimetype) {
return null;
}
}

Просмотреть файл

@ -0,0 +1,44 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class LocationException extends Exception {
// JAVADOC COMMENT ELIDED
public LocationException() {
}
// JAVADOC COMMENT ELIDED
public LocationException(String s) {
super(s);
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This interface is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public interface LocationListener {
// JAVADOC COMMENT ELIDED
public void locationUpdated(LocationProvider provider, Location location);
// JAVADOC COMMENT ELIDED
public void providerStateChanged(LocationProvider provider, int newState);
}

Просмотреть файл

@ -0,0 +1,117 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
import com.sun.j2me.location.LocationProviderImpl;
import com.sun.j2me.location.ProximityNotifier;
import com.sun.j2me.location.Util;
import com.sun.j2me.main.Configuration;
import com.sun.j2me.security.LocationPermission;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public abstract class LocationProvider {
/** Proximity support property */
private static final String PROXIMITY_SUPPORTED =
"com.sun.j2me.location.ProximitySupported";
// JAVADOC COMMENT ELIDED
public static final int AVAILABLE = 1;
// JAVADOC COMMENT ELIDED
public static final int TEMPORARILY_UNAVAILABLE = 2;
// JAVADOC COMMENT ELIDED
public static final int OUT_OF_SERVICE = 3;
// JAVADOC COMMENT ELIDED
protected LocationProvider() {
}
// JAVADOC COMMENT ELIDED
public abstract int getState();
// JAVADOC COMMENT ELIDED
public static LocationProvider getInstance(Criteria criteria)
throws LocationException {
return LocationProviderImpl.getInstanceImpl(criteria);
}
// JAVADOC COMMENT ELIDED
public abstract Location getLocation(int timeout)
throws LocationException, InterruptedException;
// JAVADOC COMMENT ELIDED
public abstract void setLocationListener(LocationListener listener,
int interval, int timeout,
int maxAge);
// JAVADOC COMMENT ELIDED
public abstract void reset();
// JAVADOC COMMENT ELIDED
public static Location getLastKnownLocation() {
Util.checkForPermission(LocationPermission.LOCATION, false);
return LocationProviderImpl.getLastKnownLocation();
}
// JAVADOC COMMENT ELIDED
public static void addProximityListener(ProximityListener listener,
Coordinates coordinates, float proximityRadius)
throws LocationException {
String proximitySupported =
Configuration.getProperty(PROXIMITY_SUPPORTED);
if (proximitySupported.equals("true")) {
Util.checkForPermission(LocationPermission.LOCATION_PROXIMITY, false);
if (listener == null || coordinates == null) {
throw new NullPointerException();
}
if (proximityRadius <= 0.0F || Float.isNaN(proximityRadius)) {
throw new IllegalArgumentException(
"Illegal proximityRadius: " + proximityRadius);
}
ProximityNotifier.getInstance().addProximityListener(listener,
coordinates, proximityRadius);
} else {
throw new LocationException(
"Proximity monitoring is not supported");
}
}
// JAVADOC COMMENT ELIDED
public static void removeProximityListener(ProximityListener listener) {
if (listener == null) {
throw new NullPointerException("Proximity listener is null");
}
ProximityNotifier.getInstance().removeProximityListener(listener);
}
}

Просмотреть файл

@ -0,0 +1,85 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
import com.sun.j2me.location.OrientationProvider;
import com.sun.j2me.location.Util;
import com.sun.j2me.security.LocationPermission;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class Orientation {
/** Angle off the horizon. */
private float azimuth;
/** Sample uses magnetic north. */
private boolean isMagnetic;
/** Pitch direction. */
private float pitch;
/** Roll direction. */
private float roll;
// JAVADOC COMMENT ELIDED
public Orientation(float azimuth, boolean isMagnetic,
float pitch, float roll) {
this.azimuth = azimuth;
this.isMagnetic = isMagnetic;
this.pitch = pitch;
this.roll = roll;
}
// JAVADOC COMMENT ELIDED
public float getCompassAzimuth() {
return azimuth;
}
// JAVADOC COMMENT ELIDED
public boolean isOrientationMagnetic() {
return isMagnetic;
}
// JAVADOC COMMENT ELIDED
public float getPitch() {
return pitch;
}
// JAVADOC COMMENT ELIDED
public float getRoll() {
return roll;
}
// JAVADOC COMMENT ELIDED
public static Orientation getOrientation() throws LocationException {
Util.checkForPermission(LocationPermission.ORIENTATION);
OrientationProvider provider = OrientationProvider.getInstance();
if (provider != null) {
return provider.getOrientation();
}
return null;
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This interface is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public interface ProximityListener {
// JAVADOC COMMENT ELIDED
public void monitoringStateChanged(boolean isMonitoringActive);
// JAVADOC COMMENT ELIDED
public void proximityEvent(Coordinates coordinates, Location location);
}

Просмотреть файл

@ -0,0 +1,78 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.location;
/**
* This class is defined by the JSR-179 specification
* <em>Location API for J2ME for J2ME&trade;.</em>
*/
// JAVADOC COMMENT ELIDED
public class QualifiedCoordinates extends Coordinates {
/** Horizontal accuracy. */
private float horizontalAccuracy;
/** Vertical accuracy. */
private float verticalAccuracy;
// JAVADOC COMMENT ELIDED
public QualifiedCoordinates(double latitude, double longitude,
float altitude, float horizontalAccuracy,
float verticalAccuracy) {
super(latitude, longitude, altitude);
setHorizontalAccuracy(horizontalAccuracy);
setVerticalAccuracy(verticalAccuracy);
}
// JAVADOC COMMENT ELIDED
public float getHorizontalAccuracy() {
return horizontalAccuracy;
}
// JAVADOC COMMENT ELIDED
public float getVerticalAccuracy() {
return verticalAccuracy;
}
// JAVADOC COMMENT ELIDED
public void setHorizontalAccuracy(float horizontalAccuracy) {
if (horizontalAccuracy < 0) {
throw new
IllegalArgumentException("Horizontal accuracy has to be "
+ "larger than 0, it was set to: "
+ horizontalAccuracy);
}
this.horizontalAccuracy = horizontalAccuracy;
}
// JAVADOC COMMENT ELIDED
public void setVerticalAccuracy(float verticalAccuracy) {
if (verticalAccuracy < 0) {
throw new IllegalArgumentException(
"Vertical accuracy has to be larger than 0, it was set to: "
+ verticalAccuracy);
}
this.verticalAccuracy = verticalAccuracy;
}
}

398
java/tools/Jpp.java Normal file
Просмотреть файл

@ -0,0 +1,398 @@
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
import java.io.*;
/**
* A simple Java preprocessor. It process the following kind of directives
* in Java code:
* \/\* #ifdef <LABEL> \*\/
* \/\* #ifndef <LABEL> \*\/
* \/\* #else \*\/
* \/\* #endif \*\/
* The directives have to be embedded in a comment.
*/
public class Jpp {
FileInputStream input;
FileOutputStream output;
static String IFDEF = "#ifdef";
static String IFNDEF = "#ifndef";
static String ELSE = "#else";
static String ENDIF = "#endif";
String labels[];
int nLabels = 0;
boolean space = true;
boolean trace = false;
public static void main(String [] args) {
if (args.length < 1)
prUsage();
String input = null;
String labels[] = new String[256];
String destDir = null, destFile = null;
int n = 0;
boolean space = true;
boolean trace = false;
int i = 0;
while (i < args.length) {
if (args[i].startsWith("-D")) {
labels[n++] = args[i].substring(2);
} else if (args[i].equals("-d")) {
if (i == args.length)
prUsage();
i++;
destDir = args[i];
} else if (args[i].equals("-o")) {
if (i == args.length)
prUsage();
i++;
destFile = args[i];
} else if (args[i].equals("-nospace")) {
space = false;
} else if (args[i].equals("-trace")) {
trace = true;
} else {
if (args[i].endsWith(".jpp"))
input = args[i];
}
i++;
}
if (input == null)
prUsage();
if (destDir != null && destFile != null)
prUsage();
Jpp jpp = new Jpp();
jpp.process(input, labels, n, destDir, destFile, space, trace);
}
static void prUsage() {
System.err.println(
"java Jpp <input>.jpp -D<label1> ... -D<labeln> " +
"[-d <output directory>] [-o <output file>] [-nospace] [-trace]");
System.exit(-1);
}
void process(String inFile, String labels[], int nLabels, String destDir,
String destFile, boolean space, boolean trace) {
this.labels = labels;
this.nLabels = nLabels;
this.space = space;
this.trace = trace;
String outFile;
String separator = System.getProperty("file.separator");
if (destFile != null) {
try {
int idx = destFile.lastIndexOf(separator);
if (idx != -1) {
String dir = destFile.substring(0, idx);
File f = new File(dir);
f.mkdirs();
}
} catch (Exception e) {
System.err.println(e);
}
outFile = destFile;
} else if (destDir != null) {
int idx = inFile.lastIndexOf(separator);
if (idx != -1)
outFile = inFile.substring(idx+1, inFile.length()-3) + "java";
else
outFile = inFile.substring(0, inFile.length()-3) + "java";
outFile = destDir + separator + outFile;
} else
outFile = inFile.substring(0, inFile.length()-3) + "java";
(new File(outFile)).getParentFile().mkdirs();
try {
input = new FileInputStream(inFile);
} catch (IOException e) {
System.err.println("Cannot open input file: " + inFile + ":\n" + e);
System.exit(-1);
}
try {
output = new FileOutputStream(outFile);
} catch (IOException e) {
System.err.println("Cannot create output file: " + outFile +
":\n" + e);
System.exit(-1);
}
try {
processCode(true, false, null, 0);
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
boolean processCode(boolean include, boolean endif,
String token, int level)
throws IOException {
byte bary[] = new byte[1024];
int b;
int commentCount = 0;
int idx = 0;
int bidx[] = new int[1];
byte cr[] = new byte[1];
while (true) {
b = input.read();
if (b < 0)
break;
if ((b == '/' || b == '*') && commentCount == 1) {
bary[idx++] = (byte)b;
// Found the comment block.
bidx[0] = idx;
cr[0] = -1;
String tk = getToken(bary, bidx, cr);
if (tk == null)
break;
idx = bidx[0];
if (tk.equals(IFDEF) || tk.equals(IFNDEF)) {
bidx[0] = idx;
cr[0] = -1;
String tk2 = getToken(bary, bidx, cr);
if (tk2 == null)
break;
idx = bidx[0];
skipComments(b == '/', cr[0]);
boolean elseFound;
boolean incl;
if (trace)
trace(tk, tk2, level+1);
if (include) {
if ((tk.equals(IFDEF) && isDefined(tk2)) ||
(tk.equals(IFNDEF) && !isDefined(tk2))) {
incl = true;
} else {
incl = false;
}
elseFound = processCode(incl, true, tk2, level+1);
if (elseFound)
elseFound = processCode(!incl, true, tk2, level+1);
} else {
elseFound = processCode(false, true, tk2, level+1);
if (elseFound)
elseFound = processCode(false, true, tk2, level+1);
}
if (elseFound)
throw new IOException("Unmatched #else");
idx = 0;
} else if (tk.equals(ELSE)) {
if (trace)
trace(tk, "for " + token, level);
if (!endif)
throw new IOException("Unmatched #else");
skipComments(b == '/', cr[0]);
idx = 0;
return true;
} else if (tk.equals(ENDIF)) {
if (trace)
trace(tk, "for " + token, level);
if (!endif)
throw new IOException("Unmatched #endif");
skipComments(b == '/', cr[0]);
idx = 0;
return false;
} else {
// No match.
// Write the code if it should be included.
// Otherwise, only write the CR to maintain
// the line numbers.
if (include)
output.write(bary, 0, idx);
else if (space)
replaceCR(bary, 0, idx);
idx = 0;
}
commentCount = 0;
} else if (b == '/') {
commentCount = 1;
bary[idx++] = (byte)b;
} else {
if (commentCount != 0) {
// Write the code if it should be included.
// Otherwise, only write the CR to maintain
// the line numbers.
if (include)
output.write(bary, 0, idx);
else if (space)
replaceCR(bary, 0, idx);
idx = 0;
commentCount = 0;
}
if (include)
output.write(b);
else if (space && (b == 10 || b == 13))
output.write(b);
}
}
if (endif)
throw new IOException("Missing #endif");
return false;
}
void skipComments(boolean slash, byte cr) throws IOException {
int b;
// Handle double slash type of comments.
if (slash) {
if (cr != -1) {
if (space)
output.write(cr);
return;
}
while (true) {
b = input.read();
if (b < 0)
break;
if (b == 10 || b == 13) {
if (space)
output.write(b);
break;
}
}
return;
}
int commentCount = 0;
while (true) {
b = input.read();
if (b < 0)
throw new IOException("Incomplete comments block");
if (b == '*') {
commentCount = 1;
} else if (b == '/' && commentCount == 1) {
commentCount = 0;
break;
} else {
if (space && (b == 10 || b == 13))
output.write(b);
commentCount = 0;
}
}
}
/**
* Parse the characters to only write te CR's.
*/
void replaceCR(byte b[], int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
if (space && (b[off+i] == 10 || b[off+i] == 13))
output.write(b[off+i]);
}
}
/**
* Extract the next token.
*/
byte token[] = new byte[1024];
String getToken(byte bary[], int idx[], byte cr[]) throws IOException {
int b;
int i = 0;
// Discard the leading spaces.
do {
b = input.read();
if (b < 0)
break;
bary[idx[0]++] = (byte)b;
} while (b == ' ' || b == '\t' || b == '*' || b == '/' ||
b == 10 || b == 13);
while (true) {
if (b == ' ' || b == '\t' || b == 10 || b == 13) {
if (cr != null && (b == 10 || b == 13))
cr[0] = (byte)b;
break;
} else
token[i++] = (byte)b;
b = input.read();
if (b < 0)
break;
bary[idx[0]++] = (byte)b;
}
if (i == 0)
return null;
return new String(token, 0, i);
}
/**
* Check if the label is defined.
*/
boolean isDefined(String label) {
for (int i = 0; i < nLabels; i++) {
if (label.equals(labels[i]))
return true;
}
if (System.getProperty(label) != null)
return true;
return false;
}
void trace(String tk1, String tk2, int level) {
for (; level > 0; level--)
System.out.print(" ");
System.out.println(tk1 + " " + tk2);
}
}

Просмотреть файл

@ -361,6 +361,55 @@
c.restore();
}
/**
* create the outline of an elliptical arc
* covering the specified rectangle.
* @param x the x-coordinate of the center of the ellipse.
* @param y y-coordinate of the center of the ellipse.
* @param rw the horizontal radius of the arc.
* @param rh the vertical radius of the arc.
* @param arcStart the beginning angle
* @param arcEnd the ending angle
* @param closed if true, draw a closed arc sector.
*/
function createEllipticalArc(c, x, y, rw, rh, arcStart, arcEnd, closed) {
c.save();
c.translate(x, y);
if (closed) {
c.moveTo(0, 0);
}
// draw circle arc which will be stretched into an oval arc
c.scale(1, rh / rw);
c.arc(0, 0, rw, arcStart, arcEnd, false);
if (closed) {
c.lineTo(0, 0);
}
c.restore();
}
/**
* Create a round rectangle path.
* @param x the x coordinate of the rectangle
* @param y the y coordinate of the rectangle
* @param width the width of the rectangle
* @param height the height of the rectangle
* @param arcWidth the horizontal diameter of the arc at the four corners
* @param arcHeight the vertical diameter of the arc at the four corners
*/
function createRoundRect(c, x, y, width, height, arcWidth, arcHeight) {
var rw = arcWidth / 2;
var rh = arcHeight / 2;
c.moveTo(x + rw, y);
c.lineTo(x + width - rw, y);
createEllipticalArc(c, x + width - rw, y + rh, rw, rh, 1.5 * Math.PI, 2 * Math.PI, false);
c.lineTo(x + width, y + height - rh);
createEllipticalArc(c, x + width - rw, y + height - rh, rw, rh, 0, 0.5 * Math.PI, false);
c.lineTo(x + rw, y + height);
createEllipticalArc(c, x + rw, y + height - rh, rw, rh, 0.5 * Math.PI, Math.PI, false);
c.lineTo(x, y + rh);
createEllipticalArc(c, x + rw, y + rh, rw, rh, Math.PI, 1.5 * Math.PI, false);
}
/**
* Like withPixel, but ignores alpha channel, setting the alpha value to 1.
* Useful when you suspect that the caller is specifying the alpha channel
@ -609,6 +658,9 @@
});
Native.create("javax/microedition/lcdui/Graphics.drawRect.(IIII)V", function(ctx, x, y, w, h) {
if (w < 0 || h < 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withClip(g, c, x, y, function(x, y) {
@ -621,7 +673,28 @@
});
});
Native.create("javax/microedition/lcdui/Graphics.drawRoundRect.(IIIIII)V", function(ctx, x, y, w, h, arcWidth, arcHeight) {
if (w < 0 || h < 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withClip(g, c, x, y, function(x, y) {
withPixel(g, c, function() {
withSize(w, h, function(w, h) {
c.beginPath();
createRoundRect(c, x, y, w, h, arcWidth, arcHeight);
c.stroke();
});
});
});
});
});
Native.create("javax/microedition/lcdui/Graphics.fillRect.(IIII)V", function(ctx, x, y, w, h) {
if (w <= 0 || h <= 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withClip(g, c, x, y, function(x, y) {
@ -635,13 +708,17 @@
});
Native.create("javax/microedition/lcdui/Graphics.fillRoundRect.(IIIIII)V", function(ctx, x, y, w, h, arcWidth, arcHeight) {
if (w <= 0 || h <= 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withClip(g, c, x, y, function(x, y) {
withPixel(g, c, function() {
withSize(w, h, function(w, h) {
// TODO implement rounding
c.fillRect(x, y, w, h);
c.beginPath();
createRoundRect(c, x, y, w, h, arcWidth, arcHeight);
c.fill();
});
});
});
@ -649,34 +726,34 @@
});
Native.create("javax/microedition/lcdui/Graphics.drawArc.(IIIIII)V", function(ctx, x, y, width, height, startAngle, arcAngle) {
if (width < 0 || height < 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withPixel(g, c, function() {
// TODO need to use bezierCurveTo to implement this properly,
// but this works as a rough hack for now
var radius = Math.ceil(Math.max(height, width) / 2);
var startRad = startAngle * 0.0175;
var arcRad = arcAngle * 0.0175;
var endRad = -startAngle * 0.0175;
var startRad = endRad - arcAngle * 0.0175;
c.beginPath();
c.moveTo(x + radius, y);
c.arc(x, y, radius, startRad, arcRad);
createEllipticalArc(c, x, y, width / 2, height / 2, startRad, endRad, false);
c.stroke();
});
});
});
Native.create("javax/microedition/lcdui/Graphics.fillArc.(IIIIII)V", function(ctx, x, y, width, height, startAngle, arcAngle) {
if (width <= 0 || height <= 0) {
return;
}
var g = this;
withGraphics(g, function(c) {
withPixel(g, c, function() {
// TODO need to use bezierCurveTo to implement this properly,
// but this works as a rough hack for now
var radius = Math.ceil(Math.max(height, width) / 2);
var startRad = startAngle * 0.0175;
var arcRad = arcAngle * 0.0175;
var endRad = -startAngle * 0.0175;
var startRad = endRad - arcAngle * 0.0175;
c.beginPath();
c.moveTo(x + radius, y);
c.arc(x, y, radius, startRad, arcRad);
c.moveTo(x, y);
createEllipticalArc(c, x, y, width / 2, height / 2, startRad, endRad, true);
c.moveTo(x, y);
c.fill();
});
});

Просмотреть файл

@ -224,6 +224,15 @@ Native.create("com/sun/midp/security/Permissions.loadGroupPermissions.(Ljava/lan
return list;
});
Native.create("com/sun/midp/main/CldcPlatformRequest.dispatchPlatformRequest.(Ljava/lang/String;)Z", function(ctx, request) {
request = util.fromJavaString(request);
if (request.startsWith("http://") || request.startsWith("https://")) {
window.open(request);
} else {
console.warn("com/sun/midp/main/CldcPlatformRequest.dispatchPlatformRequest.(Ljava/lang/String;)Z not implemented for: " + request);
}
});
Native.create("com/sun/midp/main/CommandState.restoreCommandState.(Lcom/sun/midp/main/CommandState;)V", function(ctx, state) {
var suiteId = (MIDP.midletClassName === "internal") ? -1 : 1;
state.class.getField("I.suiteId.I").set(state, suiteId);
@ -849,18 +858,14 @@ function(ctx, obj) {
MIDP.localizedStrings = new Map();
Native.create("com/sun/midp/l10n/LocalizedStringsBase.getContent.(I)Ljava/lang/String;", function(ctx, id) {
var classInfo = CLASSES.getClass("com/sun/midp/i18n/ResourceConstants");
var key;
classInfo.fields.forEach(function(field) {
if (classInfo.constant_pool[field.constantValue].integer === id)
key = field.name;
});
if (!key) {
throw new JavaException("java/io/IOException");
}
if (MIDP.localizedStrings.size === 0) {
// First build up a mapping of field names to field IDs
var classInfo = CLASSES.getClass("com/sun/midp/i18n/ResourceConstants");
var constantsMap = new Map();
classInfo.fields.forEach(function(field) {
constantsMap.set(field.name, classInfo.constant_pool[field.constantValue].integer);
});
var data = CLASSES.loadFileFromJar("java/classes.jar", "assets/0/en-US.xml");
if (!data)
throw new JavaException("java/io/IOException");
@ -871,11 +876,13 @@ Native.create("com/sun/midp/l10n/LocalizedStringsBase.getContent.(I)Ljava/lang/S
for (var n = 0; n < entries.length; ++n) {
var attrs = entries[n].attributes;
MIDP.localizedStrings.set(attrs.Key.value, attrs.Value.value);
// map the key value to a field ID
var id = constantsMap.get(attrs.Key.value);
MIDP.localizedStrings.set(id, attrs.Value.value);
}
}
var value = MIDP.localizedStrings.get(key);
var value = MIDP.localizedStrings.get(id);
if (!value) {
throw new JavaException("java/lang/IllegalStateException");

Просмотреть файл

@ -30,6 +30,10 @@ class HelloGraphics extends Canvas implements Runnable {
} else {
g.drawString("World", getWidth() / 4 * 3, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
g.setColor(0xFF, 0, 0);
g.drawRoundRect(0, 0, getWidth() / 4, getHeight() / 4, getWidth() / 8, getHeight() / 8);
g.setColor(0xFF, 0, 0xFF);
g.fillRoundRect(10, 10, getWidth() / 8, getHeight() / 10, getWidth() / 16, getHeight() / 20);
}
public void run() {

Просмотреть файл

@ -97,17 +97,23 @@ public class RunTests extends MIDlet {
}
public void startApp() {
String arg0 = getAppProperty("arg-0");
String arg = getAppProperty("arg-0");
if (arg0 != null && arg0.length() > 0) {
if (arg != null && arg.length() > 0) {
Vector v = new Vector();
for (int i = 0; i < Testlets.list.length; i++) {
v.addElement(Testlets.list[i]);
for (int n = 0; n < Testlets.list.length; ++n) {
v.addElement(Testlets.list[n]);
}
if (v.contains(arg0)) {
runTest(arg0);
} else {
System.err.println("can't find test " + arg0);
int i = 0;
while (arg != null && arg.length() > 0) {
if (v.contains(arg)) {
runTest(arg);
} else {
System.err.println("can't find test " + arg);
}
arg = getAppProperty("arg-" + ++i);
}
} else {
for (int n = 0; n < Testlets.list.length; ++n) {

Просмотреть файл

@ -19,6 +19,8 @@ var gfxTests = [
{ name: "gfx/DrawRegionTest", maxDifferent: 0 },
{ name: "gfx/ImageRenderingTest", maxDifferent: 266 },
{ name: "gfx/FillRectTest", maxDifferent: 0 },
{ name: "gfx/DrawAndFillRoundRectTest", maxDifferent: 2000 },
{ name: "gfx/DrawAndFillArcTest", maxDifferent: 2000 },
{ name: "gfx/DrawStringTest", maxDifferent: 345 },
{ name: "gfx/DrawRedStringTest", maxDifferent: 513 },
{ name: "gfx/TextBoxTest", maxDifferent: 4677 },

Просмотреть файл

@ -0,0 +1,35 @@
package gfx;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class DrawAndFillArcTest extends MIDlet {
private Command quitCommand;
private Display display;
class TestCanvas extends Canvas {
protected void paint(Graphics g) {
g.setColor(255, 0, 0);
g.drawArc(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), 90, 300);
g.setColor(0, 0, 255);
g.fillArc(getWidth() / 2, 200, 200, 80, 10, 170);
System.out.println("PAINTED");
}
}
public DrawAndFillArcTest() {
display = Display.getDisplay(this);
}
public void startApp() {
TestCanvas test = new TestCanvas();
display.setCurrent(test);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Двоичные данные
tests/gfx/DrawAndFillArcTest.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.5 KiB

Просмотреть файл

@ -0,0 +1,35 @@
package gfx;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class DrawAndFillRoundRectTest extends MIDlet {
private Command quitCommand;
private Display display;
class TestCanvas extends Canvas {
protected void paint(Graphics g) {
g.setColor(255, 0, 0);
g.drawRoundRect(0, 0, getWidth(), getHeight(), getWidth() / 2, getHeight() / 2);
g.setColor(0, 0, 255);
g.fillRoundRect(20, 30, 200, 80, 100, 80);
System.out.println("PAINTED");
}
}
public DrawAndFillRoundRectTest() {
display = Display.getDisplay(this);
}
public void startApp() {
TestCanvas test = new TestCanvas();
display.setCurrent(test);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Двоичные данные
tests/gfx/DrawAndFillRoundRectTest.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 7.7 KiB