Sentiment Analysis with OpenNLP - machine-learning

I found this description of implementing a Sentiment Analysis task with OpenNLP. In my case I am using the newest OPenNLP-version, i.e., version 1.8.0. In the following example, they use a Maximum Entropy Model. I am using the same input.txt (tweets.txt)
http://technobium.com/sentiment-analysis-using-opennlp-document-categorizer/
public class StartSentiment {
public static DoccatModel model = null;
public static String[] analyzedTexts = {"I hate Mondays!"/*, "Electricity outage, this is a nightmare"/*, "I love it"*/};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);
}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("bin/text.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "2");
tp.put(TrainingParameters.ITERATIONS_PARAM, "30");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text){
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(new String[]{text});
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
}
In my case no matter what input String I am using, I am only getting a positive estimation of the input string. Any idea what could be the reason?
Thanks

Related

Building Splittable DoFn (SDF) to list objects in GCS

I am trying to develop custom source for parallel GCS content scanning. The naive approach would be to loop through listObjects function calls:
while (...) {
Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken);
pageToken = objects.getNextPageToken();
...
}
The problem is performance for the tens of millions objects.
Instead of the single thread code we can add delimiter / and submit parallel processed for each prefix found:
...
Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken, "/");
for (String subPrefix : object.getPrefixes()) {
scanAsync(bucket, subPrefix);
}
...
Next idea was to try to wrap this logic in Splittable DoFn.
Choice of RestrictionTracker: I don't see how can be used any of exiting RestrictionTracker. So decided to write own. Restriction itself is basically list of prefixes to scan. tryClaim checks if there is more prefixes left and receive newly scanned to append them to current restriction. trySplit splits list of prefixes.
The problem that I faced that trySplit can be called before all subPrefixes are found. In this case current restriction may receive more work to do after it was splitted. And it seems that trySplit is being called until it returns a not null value for a given RestrictionTracker: after certain number of elements goes to the output or after 1 second via scheduler or when ProcessContext.resume() returned. This doesn't work in my case as new prefixes can be found at any time. And I can't checkpoint via return ProcessContext.resume() because if split was already done, possible work that left in current restriction will cause checkDone() function to fail.
Another problem that I suspect that I couldn't achieve parallel execution in DirectRunner. As trySplit was always called with fractionOfRemainder=0 and new RestrictionTracker was started only after current one completed its piece of work.
It would be also great to read more detailed explanation about Splittable DoFn components lifecycle. How parallel execution per element is achieved. And how and when state of RestrictionTracker can be modified.
UPD: Adding simplified code that should show intended implementation
#DoFn.BoundedPerElement
private static class ScannerDoFn extends DoFn<String, String> {
private transient GcsUtil gcsUtil;
#GetInitialRestriction
public ScannerRestriction getInitialRestriction(#Element String bucket) {
return ScannerRestriction.init(bucket);
}
#ProcessElement
public ProcessContinuation processElement(
ProcessContext c,
#Element String bucket,
RestrictionTracker<ScannerRestriction, ScannerPosition> tracker,
OutputReceiver<String> outputReceiver) {
if (gcsUtil == null) {
gcsUtil = c.getPipelineOptions().as(GcsOptions.class).getGcsUtil();
}
ScannerRestriction currentRestriction = tracker.currentRestriction();
ScannerPosition position = new ScannerPosition();
while (true) {
if (tracker.tryClaim(position)) {
if (position.completedCurrent) {
// position.clear();
// ideally I would to get checkpoint here before starting new work
return ProcessContinuation.resume();
}
try {
Objects objects = gcsUtil.listObjects(
currentRestriction.bucket,
position.currentPrefix,
position.currentPageToken,
"/");
if (objects.getItems() != null) {
for (StorageObject o : objects.getItems()) {
outputReceiver.output(o.getName());
}
}
if (objects.getPrefixes() != null) {
position.newPrefixes.addAll(objects.getPrefixes());
}
position.currentPageToken = objects.getNextPageToken();
if (position.currentPageToken == null) {
position.completedCurrent = true;
}
} catch (Throwable throwable) {
logger.error("Error during scan", throwable);
}
} else {
return ProcessContinuation.stop();
}
}
}
#NewTracker
public RestrictionTracker<ScannerRestriction, ScannerPosition> restrictionTracker(#Restriction ScannerRestriction restriction) {
return new ScannerRestrictionTracker(restriction);
}
#GetRestrictionCoder
public Coder<ScannerRestriction> getRestrictionCoder() {
return ScannerRestriction.getCoder();
}
}
public static class ScannerPosition {
private String currentPrefix;
private String currentPageToken;
private final List<String> newPrefixes;
private boolean completedCurrent;
public ScannerPosition() {
this.currentPrefix = null;
this.currentPageToken = null;
this.newPrefixes = Lists.newArrayList();
this.completedCurrent = false;
}
public void clear() {
this.currentPageToken = null;
this.currentPrefix = null;
this.completedCurrent = false;
}
}
private static class ScannerRestriction {
private final String bucket;
private final LinkedList<String> prefixes;
private ScannerRestriction(String bucket) {
this.bucket = bucket;
this.prefixes = Lists.newLinkedList();
}
public static ScannerRestriction init(String bucket) {
ScannerRestriction res = new ScannerRestriction(bucket);
res.prefixes.add("");
return res;
}
public ScannerRestriction empty() {
return new ScannerRestriction(bucket);
}
public boolean isEmpty() {
return prefixes.isEmpty();
}
public static Coder<ScannerRestriction> getCoder() {
return ScannerRestrictionCoder.INSTANCE;
}
private static class ScannerRestrictionCoder extends AtomicCoder<ScannerRestriction> {
private static final ScannerRestrictionCoder INSTANCE = new ScannerRestrictionCoder();
private final static Coder<List<String>> listCoder = ListCoder.of(StringUtf8Coder.of());
#Override
public void encode(ScannerRestriction value, OutputStream outStream) throws IOException {
NullableCoder.of(StringUtf8Coder.of()).encode(value.bucket, outStream);
listCoder.encode(value.prefixes, outStream);
}
#Override
public ScannerRestriction decode(InputStream inStream) throws IOException {
String bucket = NullableCoder.of(StringUtf8Coder.of()).decode(inStream);
List<String> prefixes = listCoder.decode(inStream);
ScannerRestriction res = new ScannerRestriction(bucket);
res.prefixes.addAll(prefixes);
return res;
}
}
}
private static class ScannerRestrictionTracker extends RestrictionTracker<ScannerRestriction, ScannerPosition> {
private ScannerRestriction restriction;
private ScannerPosition lastPosition = null;
ScannerRestrictionTracker(ScannerRestriction restriction) {
this.restriction = restriction;
}
#Override
public boolean tryClaim(ScannerPosition position) {
restriction.prefixes.addAll(position.newPrefixes);
position.newPrefixes.clear();
if (position.completedCurrent) {
// completed work for current prefix
assert lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix);
lastPosition = null;
return true; // return true but we would need to claim again if we need to get next prefix
} else if (lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix)) {
// proceed work for current prefix
lastPosition = position;
return true;
}
// looking for next prefix
assert position.currentPrefix == null;
assert lastPosition == null;
if (restriction.isEmpty()) {
// no work to do
return false;
}
position.currentPrefix = restriction.prefixes.poll();
lastPosition = position;
return true;
}
#Override
public ScannerRestriction currentRestriction() {
return restriction;
}
#Override
public SplitResult<ScannerRestriction> trySplit(double fractionOfRemainder) {
if (lastPosition == null && restriction.isEmpty()) {
// no work at all
return null;
}
if (lastPosition != null && restriction.isEmpty()) {
// work at the moment only at currently scanned prefix
return SplitResult.of(restriction, restriction.empty());
}
int size = restriction.prefixes.size();
int newSize = new Double(Math.round(fractionOfRemainder * size)).intValue();
if (newSize == 0) {
ScannerRestriction residual = restriction;
restriction = restriction.empty();
return SplitResult.of(restriction, residual);
}
ScannerRestriction residual = restriction.empty();
for (int i=newSize; i<=size; i++) {
residual.prefixes.add(restriction.prefixes.removeLast());
}
return SplitResult.of(restriction, residual);
}
#Override
public void checkDone() throws IllegalStateException {
if (lastPosition != null) {
throw new IllegalStateException("Called checkDone on not completed job");
}
}
#Override
public IsBounded isBounded() {
return IsBounded.UNBOUNDED;
}
}

Boolean method not retuning correct value

Ok so I think I'm being a noob because it's a new semester but the method "palindromeTest" always return's false even though the string is equal and the number is a palindrome. (A palindrome example is: (565) 677-6565) (also don't give me the answer outright I want to solve it on my own)
public class IjazZ_PhoneStringPalindrome
{
public static void main(String[] args) throws IOException
{
String phoneNumber;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a phone number in this format (###) ###-####: ");
phoneNumber = br.readLine();
phoneNumber = justNumbers(phoneNumber);
if (palindromeTest(phoneNumber))
{
System.out.println("This phone number is a palindrome!");
}
else
{
System.out.println("This phone number is not a palindrome!");
}
}
public static String justNumbers(String phoneNumber)
{
StringTokenizer st = new StringTokenizer(phoneNumber, " ()-");
StringBuffer number = new StringBuffer();
while(st.hasMoreTokens())
{
number.append(st.nextToken());
}
phoneNumber = number.toString();
return phoneNumber;
}
public static boolean palindromeTest(String pNumber)
{
StringBuffer reversedNumber = new StringBuffer(pNumber);
reversedNumber.reverse().toString();
if(pNumber.equals(reversedNumber))
{
return true;
}
else
{
return false;
}
}
}
You don't assign the value returned by reversedNumber.reverse().toString()to reversedNumber.
Do
String reversedNumberString = reversedNumber.reverse().toString();
And by the way, you can just return
return pNumber.equals(reversedNumber); - the if/else statement is unnecessary.

URL Read CodeName One

I'm relatively new to Codename One. I'm trying to read an URL and save the content on a String. I tried:
private String lectura = "";
private String escritura = "";
/*-------------------------------------------------------
* Methods
*-------------------------------------------------------
*/
public Bulbs(int i, char rtype){
type = rtype;
number = i;
status = readCNO(type, number);
}
public String giveStatus(){
status = readCNO(type, number);
return status;
}
public void turnBulbOn(){
writeCNO('B', number, 1);
}
public void turnBulbOff(){
writeCNO('B', number, 0);
}
public String readCNO(char type, int number){
ConnectionRequest r = new ConnectionRequest();
r.setUrl("http://192.168.1.3/arduino/R!" + type + "/" + Integer.toString(number));
r.setPost(false);
r.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
lectura = decodedData;
} catch (Exception ex)
{
ex.printStackTrace();
lectura = "NoBulb";
}
}
});
NetworkManager.getInstance().addToQueue(r);
return lectura;
}
public String writeCNO(char type, int number, int action){
ConnectionRequest r2 = new ConnectionRequest();
r2.setUrl("http://192.168.1.3/arduino/R!" + type + "/" + Integer.toString(number) + "/"+ action);
r2.setPost(false);
r2.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
escritura = decodedData;
} catch (Exception ex)
{
ex.printStackTrace();
escritura = "NoBulb";
}
}
});
NetworkManager.getInstance().addToQueue(r2);
return escritura;
}
However when I run it, the Console displays a bunch of errors like:
Duplicate entry in the queue: com.codename1.io.ConnectionRequest: com.codename1.io.ConnectionRequest#22b3c488
Help very appreciated!
David.
You are adding the exact same URL to the queue twice which Codename One detects as a probable mistake. If this is intentional just invoke setDuplicateSupported(true) on both connection requests.

Understanding mahout classification output

I have trained mahout model for three categories Category_A,Category_B,Category_C using 20newsGroupExample , Now i want to classify my documents using this model. Can somebody help me to understand output i am getting from this model.
Here is my output
{0:-2813549.8786637094,1:-2651723.736745838,2:-2710651.7525975127}
According to output category of document is 1, But expected category is 2. Am i going right or something is missing in my code ?
public class NaiveBayesClassifierExample {
public static void loadClassifier(String strModelPath, Vector v)
throws IOException {
Configuration conf = new Configuration();
NaiveBayesModel model = NaiveBayesModel.materialize(new Path(strModelPath), conf);
AbstractNaiveBayesClassifier classifier = new StandardNaiveBayesClassifier(model);
Vector st = classifier.classifyFull(v);
System.out.println(st.asFormatString());
System.out.println(st.maxValueIndex());
st.asFormatString();
}
public static Vector createVect() throws IOException {
FeatureVectorEncoder encoder = new StaticWordValueEncoder("text");
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
String inputData=readData();
StringReader in = new StringReader(inputData);
TokenStream ts = analyzer.tokenStream("body", in);
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
Vector v1 = new RandomAccessSparseVector(100000);
while (ts.incrementToken()) {
char[] termBuffer = termAtt.buffer();
int termLen = termAtt.length();
String w = new String(termBuffer, 0, termLen);
encoder.addToVector(w, 1.0, v1);
}
v1.normalize();
return v1;
}
private static String readData() {
// TODO Auto-generated method stub
BufferedReader reader=null;
String line, results = "";
try{
reader = new BufferedReader(new FileReader("c:\\inputFile.txt"));
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return results;
}
public static void main(String[] args) throws IOException {
Vector v = createVect();
String mp = "E:\\Final_Model\\model";
loadClassifier(mp, v);
}
}

Blackberry not able to fetch Latitude and longitude

I need to get the users latitude and longitude to display data in increasing order of distance.
I am using 2 phones in 2 different countries to test the app. It works fine with a bb bold 9700 when used in south asia. But does not with a bb 9650 when used in nyc.
I tried using the bb gps api based classes and also google tower based gps classes.
Both don't seem to work in nyc with bb 9650.I used other location based apps like yelp etc which work perfectly.
Attaching both the codes
Phone GPS
public class GPS_Location
{
private String log;
double longi;
double lati;
public GPS_Location()
{
new LocationTracker();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask
{
private Timer timer;
private LocationProvider provider;
Criteria cr;
public LocationTracker()
{
timer = new Timer();
cr= new Criteria();
resetGPS();
timer.schedule(this, 0, 60000);
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
/*provider.setLocationListener(null, 0, 0, 0);
provider.reset();
provider = null;*/
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
//provider = LocationProvider.getInstance(null);
} catch(Exception e)
{
}
}
public void run()
{
System.out.println("********************");
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("********************latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("********************longitude ::"+longi);
CustomSession.getInstance().setLatitude(lati);
CustomSession.getInstance().setLongitude(longi);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}
cell tower google service
public class JsonGenerator {
public void locating() throws IOException{
byte[] postData = getGPSJsonObject().toString().getBytes();
JSONObject jsonObject = null;
HttpConnection gpsConnection;
DataOutputStream os;
DataInputStream dis;
String gpsString = retrunURLString("http://www.google.com/loc/json");
try {
gpsConnection = (HttpConnection) Connector.open(gpsString);
gpsConnection.setRequestMethod(HttpConnection.POST);
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
.valueOf(postData.length));
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_TYPE,
"application / requestJson");
os = gpsConnection.openDataOutputStream();
os.write(postData);
int rc = gpsConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
return;
}
dis = gpsConnection.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = dis.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
String jsonString = new String(data);
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject locationObject = jsonObject.getJSONObject("location");
if (locationObject.getDouble("latitude") != 0.0
&& locationObject.getDouble("longitude") != 0.0) {
System.out.println("Latitute is =================::::"+locationObject.getDouble("latitude"));
System.out.println("Llongitude is =================::::"+locationObject.getDouble("longitude"));
CustomSession.getInstance().setLatitude(locationObject.getDouble("latitude"));
CustomSession.getInstance().setLongitude(locationObject.getDouble("longitude"));
// Global.horizontal_accuracy = locationObject
// .getDouble("accuracy");
// Global.locAvailable = true;
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public JSONObject getGPSJsonObject() {
JSONObject jsonString = new JSONObject();
try {
jsonString.put("version", "1.1.0");
jsonString.put("host", "maps.google.com");
int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
.toHexString(x)));
jsonString.put("home_mobile_network_code", RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
int radio = RadioInfo.getNetworkType();
if(radio==RadioInfo.NETWORK_CDMA){
jsonString.put("radio_type", "cdma");
}
else{
jsonString.put("radio_type", "gsm");
}
jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
jsonString.put("request_address", true);
jsonString.put("address_language", "en_GB");
CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
.getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
Hashtable map = new Hashtable();
map.put("mobile_country_code", new Integer(Integer
.parseInt(cellInfo.mobileCountryCode)));
map.put("location_area_code",
new Integer(cellInfo.locationAreaCode));
map.put("signal_strength", new Integer(cellInfo.signalStrength));
map.put("cell_id", new Integer(cellInfo.cellID));
map.put("age", new Integer(0));
map.put("mobile_network_code", new Integer(
cellInfo.mobileNetworkCode));
JSONArray array = new JSONArray();
array.put(0, map);
jsonString.put("cell_towers", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
public static String retrunURLString(String url) {
String urlString = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// WIFI
urlString = url + ";interface=wifi";
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
ServiceRecord record = getWAP2ServiceRecord();
if (record != null
&& (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// WAP 2.0
urlString = url + ";deviceside=true;ConnectionUID="
+ record.getUid();
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// BES/MDS
urlString = url + ";deviceside=false";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Direct TCP/IP
urlString = url + ";deviceside=true";
} else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
// BIS
urlString = url + ";deviceside=false;ConnectionUID="
+ record.getUid();
}
}
return urlString;
}
protected static ServiceRecord getWAP2ServiceRecord() {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
for (int i = 0; i < records.length; i++) {
String cid = records[i].getCid().toLowerCase();
String uid = records[i].getUid().toLowerCase();
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
return null;
}
private class CellTower {
public String mobileCountryCode;
public int locationAreaCode;
public int signalStrength;
public int cellID;
public int age;
public int mobileNetworkCode;
private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
mobileCountryCode = mcc;
locationAreaCode = lac;
signalStrength = ss;
cellID = ci;
age = a;
mobileNetworkCode = mnc;
}
}
}
Ideally you should be using multiple fix methods (your Criteria) to gather GPS information. Using just the default will not work in all circumstances, so you need to have fallback options. Here are the Criteria, in preferred order, that I use in the States and seems to do well. You just have to loop through them until you have a set that works.
//Speed optimal
BlackBerryCriteria speed = new BlackBerryCriteria();
speed.setHorizontalAccuracy(50);
speed.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
speed.setCostAllowed(true);
speed.setPreferredResponseTime(10000);
//MS-Based
BlackBerryCriteria msBased = new BlackBerryCriteria();
msBased.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
msBased.setHorizontalAccuracy(50);
msBased.setVerticalAccuracy(50);
msBased.setCostAllowed(true);
msBased.setPreferredResponseTime(10000);
//Assisted mode
BlackBerryCriteria assisted = new BlackBerryCriteria();
assisted.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_HIGH);
assisted.setHorizontalAccuracy(50);
assisted.setVerticalAccuracy(50);
assisted.setCostAllowed(true);
assisted.setPreferredResponseTime(10000);
//Autonomous
BlackBerryCriteria autonomous = new BlackBerryCriteria();
autonomous.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
autonomous.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setCostAllowed(true);
autonomous.setPreferredResponseTime(180000);
//Cell site
BlackBerryCriteria cell = new BlackBerryCriteria();
cell.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_LOW);
cell.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setCostAllowed(true);
cell.setPreferredResponseTime(180000);

Resources