code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.file;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Tests for {@link GpxTrackWriter}.
*
* @author Rodrigo Damazio
*/
public class GpxTrackWriterTest extends TrackFormatWriterTest {
public void testXmlOutput() throws Exception {
TrackFormatWriter writer = new GpxTrackWriter(getContext());
String result = writeTrack(writer);
Document doc = parseXmlDocument(result);
Element gpxTag = getChildElement(doc, "gpx");
Element trackTag = getChildElement(gpxTag, "trk");
assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name"));
assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc"));
List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2);
List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2);
assertTagMatchesLocation(segPointTags.get(0), "0", "0", "1970-01-01T00:00:00Z", "0");
assertTagMatchesLocation(segPointTags.get(1), "1", "-1", "1970-01-01T00:01:40Z", "10");
segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2);
assertTagMatchesLocation(segPointTags.get(0), "2", "-2", "1970-01-01T00:03:20Z", "20");
assertTagMatchesLocation(segPointTags.get(1), "3", "-3", "1970-01-01T00:05:00Z", "30");
List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2);
Element wptTag = waypointTags.get(0);
assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name"));
assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc"));
assertTagMatchesLocation(wptTag, "1", "-1", "1970-01-01T00:01:40Z", "10");
wptTag = waypointTags.get(1);
assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name"));
assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc"));
assertTagMatchesLocation(wptTag, "2", "-2", "1970-01-01T00:03:20Z", "20");
}
/**
* Asserts that the given tag describes a location.
*
* @param tag the tag
* @param latitude the location's latitude
* @param longitude the location's longitude
* @param time the location's time
* @param elevation the location's elevation
*/
private void assertTagMatchesLocation(
Element tag, String latitude, String longitude, String time, String elevation) {
assertEquals(latitude, tag.getAttribute("lat"));
assertEquals(longitude, tag.getAttribute("lon"));
assertEquals(time, getChildTextValue(tag, "time"));
assertEquals(elevation, getChildTextValue(tag, "ele"));
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.docs;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient.WorksheetEntry;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.wireless.gdata.data.Entry;
import android.test.AndroidTestCase;
/**
* Tests {@link SendDocsUtils}.
*
* @author Jimmy Shih
*/
public class SendDocsUtilsTest extends AndroidTestCase {
private static final long TIME = 1288721514000L;
/**
* Tests {@link SendDocsUtils#getEntryId(Entry)} with a valid id.
*/
public void testGetEntryId_valid() {
Entry entry = new Entry();
entry.setId("https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123");
assertEquals("123", SendDocsUtils.getEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getEntryId(Entry)} with an invalid id.
*/
public void testGetEntryId_invalid() {
Entry entry = new Entry();
entry.setId("123");
assertEquals(null, SendDocsUtils.getEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} with a valid id.
*/
public void testGetNewSpreadsheetId_valid_id() {
assertEquals("123", SendDocsUtils.getNewSpreadsheetId(
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an open
* tag, <id>.
*/
public void testGetNewSpreadsheetId_no_open_tag() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
"https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an end tag,
* </id>.
*/
public void testGetNewSpreadsheetId_no_end_tag() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without the url
* prefix,
* https://docs.google.com/feeds/documents/private/full/spreadsheet%3A.
*/
public void testGetNewSpreadsheetId_no_prefix() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId("<id>123</id>"));
}
/**
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
* valid entry.
*/
public void testGetWorksheetEntryId_valid() {
WorksheetEntry entry = new WorksheetEntry();
entry.setId("/123");
assertEquals("123", SendDocsUtils.getWorksheetEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
* invalid entry.
*/
public void testGetWorksheetEntryId_invalid() {
WorksheetEntry entry = new WorksheetEntry();
entry.setId("123");
assertEquals(null, SendDocsUtils.getWorksheetEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)} with metric units.
*/
public void testGetRowContent_metric() throws Exception {
Track track = getTrack();
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
+ "<gsx:distance><![CDATA[20.00]]></gsx:distance>"
+ "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>"
+ "<gsx:averagespeed><![CDATA[14,400.00]]></gsx:averagespeed>"
+ "<gsx:averagemovingspeed><![CDATA[18,000.00]]>" + "</gsx:averagemovingspeed>"
+ "<gsx:maxspeed><![CDATA[5,400.00]]></gsx:maxspeed>"
+ "<gsx:speedunit><![CDATA[km/h]]></gsx:speedunit>"
+ "<gsx:elevationgain><![CDATA[6,000]]></gsx:elevationgain>"
+ "<gsx:minelevation><![CDATA[-500]]></gsx:minelevation>"
+ "<gsx:maxelevation><![CDATA[550]]></gsx:maxelevation>"
+ "<gsx:elevationunit><![CDATA[m]]></gsx:elevationunit>" + "<gsx:map>"
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
+ "</entry>";
assertEquals(expectedData, SendDocsUtils.getRowContent(track, true, getContext()));
}
/**
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)} with imperial units.
*/
public void testGetRowContent_imperial() throws Exception {
Track track = getTrack();
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
+ "<gsx:distance><![CDATA[12.43]]></gsx:distance>"
+ "<gsx:distanceunit><![CDATA[mi]]></gsx:distanceunit>"
+ "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>"
+ "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>"
+ "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>"
+ "<gsx:speedunit><![CDATA[mi/h]]></gsx:speedunit>"
+ "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>"
+ "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>"
+ "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>"
+ "<gsx:elevationunit><![CDATA[ft]]></gsx:elevationunit>" + "<gsx:map>"
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
+ "</entry>";
assertEquals(expectedData, SendDocsUtils.getRowContent(track, false, getContext()));
}
/**
* Gets a track for testing {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)}.
*/
private Track getTrack() {
TripStatistics stats = new TripStatistics();
stats.setStartTime(TIME);
stats.setTotalTime(5000);
stats.setMovingTime(4000);
stats.setTotalDistance(20000);
stats.setMaxSpeed(1500);
stats.setTotalElevationGain(6000);
stats.setMinElevation(-500);
stats.setMaxElevation(550);
Track track = new Track();
track.setName("trackName");
track.setDescription("trackDescription");
track.setMapId("trackMapId");
track.setStatistics(stats);
return track;
}
/**
* Tests {@link SendDocsUtils#appendTag(StringBuilder, String, String)} with
* repeated calls.
*/
public void testAppendTag() {
StringBuilder stringBuilder = new StringBuilder();
SendDocsUtils.appendTag(stringBuilder, "name1", "value1");
assertEquals("<gsx:name1><![CDATA[value1]]></gsx:name1>", stringBuilder.toString());
SendDocsUtils.appendTag(stringBuilder, "name2", "value2");
assertEquals(
"<gsx:name1><![CDATA[value1]]></gsx:name1><gsx:name2><![CDATA[value2]]></gsx:name2>",
stringBuilder.toString());
}
/**
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with metric units.
*/
public void testGetDistance_metric() {
assertEquals("1.22", SendDocsUtils.getDistance(1222.3, true));
}
/**
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with imperial
* units.
*/
public void testGetDistance_imperial() {
assertEquals("0.76", SendDocsUtils.getDistance(1222.3, false));
}
/**
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with metric units.
*/
public void testGetSpeed_metric() {
assertEquals("15.55", SendDocsUtils.getSpeed(4.32, true));
}
/**
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with imperial units.
*/
public void testGetSpeed_imperial() {
assertEquals("9.66", SendDocsUtils.getSpeed(4.32, false));
}
/**
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with metric
* units.
*/
public void testGetElevation_metric() {
assertEquals("3", SendDocsUtils.getElevation(3.456, true));
}
/**
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with imperial
* units.
*/
public void testGetElevation_imperial() {
assertEquals("11", SendDocsUtils.getElevation(3.456, false));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
/**
* Tests for {@link PreferenceBackupHelper}.
*
* @author Rodrigo Damazio
*/
public class PreferenceBackupHelperTest extends TestCase {
private Map<String, ?> preferenceValues;
private SharedPreferences preferences;
private PreferenceBackupHelper preferenceBackupHelper;
/**
* Mock shared preferences editor which does not persist state.
*/
private class MockPreferenceEditor implements SharedPreferences.Editor {
private Map<String, Object> newPreferences = new HashMap<String, Object>(preferenceValues);
@Override
public Editor clear() {
newPreferences.clear();
return this;
}
@Override
public boolean commit() {
apply();
return true;
}
@Override
public void apply() {
preferenceValues = newPreferences;
}
@Override
public Editor putBoolean(String key, boolean value) {
return put(key, value);
}
@Override
public Editor putFloat(String key, float value) {
return put(key, value);
}
@Override
public Editor putInt(String key, int value) {
return put(key, value);
}
@Override
public Editor putLong(String key, long value) {
return put(key, value);
}
@Override
public Editor putString(String key, String value) {
return put(key, value);
}
public Editor putStringSet(String key, Set<String> value) {
return put(key, value);
}
private <T> Editor put(String key, T value) {
newPreferences.put(key, value);
return this;
}
@Override
public Editor remove(String key) {
newPreferences.remove(key);
return this;
}
}
/**
* Mock shared preferences which does not persist state.
*/
private class MockPreferences implements SharedPreferences {
@Override
public boolean contains(String key) {
return preferenceValues.containsKey(key);
}
@Override
public Editor edit() {
return new MockPreferenceEditor();
}
@Override
public Map<String, ?> getAll() {
return preferenceValues;
}
@Override
public boolean getBoolean(String key, boolean defValue) {
return get(key, defValue);
}
@Override
public float getFloat(String key, float defValue) {
return get(key, defValue);
}
@Override
public int getInt(String key, int defValue) {
return get(key, defValue);
}
@Override
public long getLong(String key, long defValue) {
return get(key, defValue);
}
@Override
public String getString(String key, String defValue) {
return get(key, defValue);
}
public Set<String> getStringSet(String key, Set<String> defValue) {
return get(key, defValue);
}
@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
private <T> T get(String key, T defValue) {
Object value = preferenceValues.get(key);
if (value == null) return defValue;
return (T) value;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
preferenceValues = new HashMap<String, Object>();
preferences = new MockPreferences();
preferenceBackupHelper = new PreferenceBackupHelper();
}
public void testExportImportPreferences() throws Exception {
// Populate with some initial values
Editor editor = preferences.edit();
editor.clear();
editor.putBoolean("bool1", true);
editor.putBoolean("bool2", false);
editor.putFloat("flt1", 3.14f);
editor.putInt("int1", 42);
editor.putLong("long1", 123456789L);
editor.putString("str1", "lolcat");
editor.apply();
// Export it
byte[] exported = preferenceBackupHelper.exportPreferences(preferences);
// Mess with the previous values
editor = preferences.edit();
editor.clear();
editor.putString("str2", "Shouldn't be there after restore");
editor.putBoolean("bool2", true);
editor.apply();
// Import it back
preferenceBackupHelper.importPreferences(exported, preferences);
assertFalse(preferences.contains("str2"));
assertTrue(preferences.getBoolean("bool1", false));
assertFalse(preferences.getBoolean("bool2", true));
assertEquals(3.14f, preferences.getFloat("flt1", 0.0f));
assertEquals(42, preferences.getInt("int1", 0));
assertEquals(123456789L, preferences.getLong("long1", 0));
assertEquals("lolcat", preferences.getString("str1", ""));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.database.MatrixCursor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
/**
* Tests for {@link DatabaseDumper}.
*
* @author Rodrigo Damazio
*/
public class DatabaseDumperTest extends TestCase {
/**
* This class is the same as {@link MatrixCursor}, except this class
* implements {@link #getBlob} ({@link MatrixCursor} leaves it
* unimplemented).
*/
private class BlobAwareMatrixCursor extends MatrixCursor {
public BlobAwareMatrixCursor(String[] columnNames) {
super(columnNames);
}
@Override public byte[] getBlob(int columnIndex) {
return getString(columnIndex).getBytes();
}
}
private static final String[] COLUMN_NAMES = {
"intCol", "longCol", "floatCol", "doubleCol", "stringCol", "boolCol", "blobCol"
};
private static final byte[] COLUMN_TYPES = {
ContentTypeIds.INT_TYPE_ID, ContentTypeIds.LONG_TYPE_ID,
ContentTypeIds.FLOAT_TYPE_ID, ContentTypeIds.DOUBLE_TYPE_ID,
ContentTypeIds.STRING_TYPE_ID, ContentTypeIds.BOOLEAN_TYPE_ID,
ContentTypeIds.BLOB_TYPE_ID
};
private static final String[][] FAKE_DATA = {
{ "42", "123456789", "3.1415", "2.72", "lolcat", "1", "blob" },
{ null, "123456789", "3.1415", "2.72", "lolcat", "1", "blob" },
{ "42", null, "3.1415", "2.72", "lolcat", "1", "blob" },
{ "42", "123456789", null, "2.72", "lolcat", "1", "blob" },
{ "42", "123456789", "3.1415", null, "lolcat", "1", "blob" },
{ "42", "123456789", "3.1415", "2.72", null, "1", "blob" },
{ "42", "123456789", "3.1415", "2.72", "lolcat", null, "blob" },
{ "42", "123456789", "3.1415", "2.72", "lolcat", "1", null },
};
private static final long[] EXPECTED_FIELD_SETS = {
0x7F, 0x7E, 0x7D, 0x7B, 0x77, 0x6F, 0x5F, 0x3F
};
private BlobAwareMatrixCursor cursor;
@Override
protected void setUp() throws Exception {
super.setUp();
// Add fake data to the cursor
cursor = new BlobAwareMatrixCursor(COLUMN_NAMES);
for (String[] row : FAKE_DATA) {
cursor.addRow(row);
}
}
public void testWriteAllRows_noNulls() throws Exception {
testWriteAllRows(false);
}
public void testWriteAllRows_withNulls() throws Exception {
testWriteAllRows(true);
}
private void testWriteAllRows(boolean hasNullFields) throws Exception {
// Dump it
DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, hasNullFields);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outStream );
dumper.writeAllRows(cursor, writer);
// Read the results
byte[] result = outStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
DataInputStream reader = new DataInputStream(inputStream);
// Verify the header
assertHeader(reader);
// Verify the number of rows
assertEquals(FAKE_DATA.length, reader.readInt());
// Row 0 -- everything populated
assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 1 -- no int
assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong());
if (hasNullFields) reader.readInt();
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 2 -- no long
assertEquals(EXPECTED_FIELD_SETS[2], reader.readLong());
assertEquals(42, reader.readInt());
if (hasNullFields) reader.readLong();
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 3 -- no float
assertEquals(EXPECTED_FIELD_SETS[3], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
if (hasNullFields) reader.readFloat();
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 4 -- no double
assertEquals(EXPECTED_FIELD_SETS[4], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
if (hasNullFields) reader.readDouble();
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 5 -- no string
assertEquals(EXPECTED_FIELD_SETS[5], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
if (hasNullFields) reader.readUTF();
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 6 -- no boolean
assertEquals(EXPECTED_FIELD_SETS[6], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
if (hasNullFields) reader.readBoolean();
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 7 -- no blob
assertEquals(EXPECTED_FIELD_SETS[7], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
if (hasNullFields) {
int length = reader.readInt();
readBlob(reader, length);
}
}
public void testFewerRows() throws Exception {
// Dump only the first two rows
DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, false);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outStream);
dumper.writeHeaders(cursor, 2, writer);
cursor.moveToFirst();
dumper.writeOneRow(cursor, writer);
cursor.moveToNext();
dumper.writeOneRow(cursor, writer);
// Read the results
byte[] result = outStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
DataInputStream reader = new DataInputStream(inputStream);
// Verify the header
assertHeader(reader);
// Verify the number of rows
assertEquals(2, reader.readInt());
// Row 0
assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 1
assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong());
// Null field not read
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
}
private void assertHeader(DataInputStream reader) throws IOException {
assertEquals(COLUMN_NAMES.length, reader.readInt());
for (int i = 0; i < COLUMN_NAMES.length; i++) {
assertEquals(COLUMN_NAMES[i], reader.readUTF());
assertEquals(COLUMN_TYPES[i], reader.readByte());
}
}
private String readBlob(InputStream reader, int length) throws Exception {
if (length == 0) {
return "";
}
byte[] blob = new byte[length];
assertEquals(length, reader.read(blob));
return new String(blob);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.content.ContentValues;
import android.net.Uri;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests for {@link DatabaseImporter}.
*
* @author Rodrigo Damazio
*/
public class DatabaseImporterTest extends TestCase {
private static final Uri DESTINATION_URI = Uri.parse("http://www.google.com/");
private static final int TEST_BULK_SIZE = 10;
private ArrayList<ContentValues> insertedValues;
private class TestableDatabaseImporter extends DatabaseImporter {
public TestableDatabaseImporter(boolean readNullFields) {
super(DESTINATION_URI, null, readNullFields, TEST_BULK_SIZE);
}
@Override
protected void doBulkInsert(ContentValues[] values) {
insertedValues.ensureCapacity(insertedValues.size() + values.length);
// We need to make a copy of the values since the objects are re-used
for (ContentValues contentValues : values) {
insertedValues.add(new ContentValues(contentValues));
}
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
insertedValues = new ArrayList<ContentValues>();
}
public void testImportAllRows() throws Exception {
testImportAllRows(false);
}
public void testImportAllRows_readNullFields() throws Exception {
testImportAllRows(true);
}
private void testImportAllRows(boolean readNullFields) throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(2);
// Add a row with all fields present
writer.writeLong(0x7F);
writer.writeInt(42);
writer.writeBoolean(true);
writer.writeUTF("lolcat");
writer.writeFloat(3.1415f);
writer.writeDouble(2.72);
writer.writeLong(123456789L);
writer.writeInt(4);
writer.writeBytes("blob");
// Add a row with some missing fields
writer.writeLong(0x15);
writer.writeInt(42);
if (readNullFields) writer.writeBoolean(false);
writer.writeUTF("lolcat");
if (readNullFields) writer.writeFloat(0.0f);
writer.writeDouble(2.72);
if (readNullFields) writer.writeLong(0L);
if (readNullFields) writer.writeInt(0); // empty blob
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(readNullFields);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertEquals(2, insertedValues.size());
// Verify the first row
ContentValues value = insertedValues.get(0);
assertEquals(value.toString(), 7, value.size());
assertValue(42, "col1", value);
assertValue(true, "col2", value);
assertValue("lolcat", "col3", value);
assertValue(3.1415f, "col4", value);
assertValue(2.72, "col5", value);
assertValue(123456789L, "col6", value);
assertBlobValue("blob", "col7", value);
// Verify the second row
value = insertedValues.get(1);
assertEquals(value.toString(), 3, value.size());
assertValue(42, "col1", value);
assertValue("lolcat", "col3", value);
assertValue(2.72, "col5", value);
}
public void testImportAllRows_noRows() throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(0);
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(false);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertTrue(insertedValues.isEmpty());
}
public void testImportAllRows_emptyRows() throws Exception {
testImportAllRowsWithEmptyRows(false);
}
public void testImportAllRows_emptyRowsWithNulls() throws Exception {
testImportAllRowsWithEmptyRows(true);
}
private void testImportAllRowsWithEmptyRows(boolean readNullFields) throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(3);
// Add 2 rows with no fields
for (int i = 0; i < 2; i++) {
writer.writeLong(0);
if (readNullFields) {
writer.writeInt(0);
writer.writeBoolean(false);
writer.writeUTF("");
writer.writeFloat(0.0f);
writer.writeDouble(0.0);
writer.writeLong(0L);
writer.writeInt(0); // empty blob
}
}
// Add a row with some missing fields
writer.writeLong(0x15);
writer.writeInt(42);
if (readNullFields) writer.writeBoolean(false);
writer.writeUTF("lolcat");
if (readNullFields) writer.writeFloat(0.0f);
writer.writeDouble(2.72);
if (readNullFields) writer.writeLong(0L);
if (readNullFields) writer.writeInt(0); // empty blob
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(readNullFields);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertEquals(insertedValues.toString(), 3, insertedValues.size());
ContentValues value = insertedValues.get(0);
assertEquals(value.toString(), 0, value.size());
value = insertedValues.get(1);
assertEquals(value.toString(), 0, value.size());
// Verify the third row (only one with values)
value = insertedValues.get(2);
assertEquals(value.toString(), 3, value.size());
assertFalse(value.containsKey("col2"));
assertFalse(value.containsKey("col4"));
assertFalse(value.containsKey("col6"));
assertValue(42, "col1", value);
assertValue("lolcat", "col3", value);
assertValue(2.72, "col5", value);
}
public void testImportAllRows_bulks() throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
// Add the header
writer.writeInt(2);
writer.writeUTF("col1");
writer.writeByte(ContentTypeIds.INT_TYPE_ID);
writer.writeUTF("col2");
writer.writeByte(ContentTypeIds.STRING_TYPE_ID);
// Add lots of rows (so the insertions are split in multiple bulks)
int numRows = TEST_BULK_SIZE * 5 / 2;
writer.writeInt(numRows);
for (int i = 0; i < numRows; i++) {
writer.writeLong(3);
writer.writeInt(i);
writer.writeUTF(Integer.toString(i * 2));
}
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(false);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
// Verify the rows
assertEquals(numRows, insertedValues.size());
for (int i = 0; i < numRows; i++) {
ContentValues value = insertedValues.get(i);
assertEquals(value.toString(), 2, value.size());
assertValue(i, "col1", value);
assertValue(Integer.toString(i * 2), "col2", value);
}
}
private void writeFullHeader(DataOutputStream writer) throws IOException {
// Add the header
writer.writeInt(7);
writer.writeUTF("col1");
writer.writeByte(ContentTypeIds.INT_TYPE_ID);
writer.writeUTF("col2");
writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID);
writer.writeUTF("col3");
writer.writeByte(ContentTypeIds.STRING_TYPE_ID);
writer.writeUTF("col4");
writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID);
writer.writeUTF("col5");
writer.writeByte(ContentTypeIds.DOUBLE_TYPE_ID);
writer.writeUTF("col6");
writer.writeByte(ContentTypeIds.LONG_TYPE_ID);
writer.writeUTF("col7");
writer.writeByte(ContentTypeIds.BLOB_TYPE_ID);
}
private <T> void assertValue(T expectedValue, String name, ContentValues values) {
@SuppressWarnings("unchecked")
T value = (T) values.get(name);
assertNotNull(value);
assertEquals(expectedValue, value);
}
private void assertBlobValue(String expectedValue, String name, ContentValues values ){
byte[] blob = values.getAsByteArray(name);
assertEquals(expectedValue, new String(blob));
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.fusiontables;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.location.Location;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests {@link SendFusionTablesUtils}.
*
* @author Jimmy Shih
*/
public class SendFusionTablesUtilsTest extends TestCase {
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null track.
*/
public void testGetMapUrl_null_track() {
assertEquals(null, SendFusionTablesUtils.getMapUrl(null));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null table id.
*/
public void testGetMapUrl_null_table_id() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
track.setStatistics(stats);
track.setTableId(null);
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null stats.
*/
public void testGetMapUrl_null_stats() {
Track track = new Track();
track.setStatistics(null);
track.setTableId("123");
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with a valid track.
*/
public void testGetMapUrl_valid_track() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
track.setStatistics(stats);
track.setTableId("123");
assertEquals(
"https://www.google.com/fusiontables/embedviz?"
+ "viz=MAP&q=select+col0,+col1,+col2,+col3+from+123+&h=false&lat=7.500000&lng=75.000000"
+ "&z=15&t=1&l=col2", SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* no value.
*/
public void testFormatSqlValues_no_value() {
assertEquals("()", SendFusionTablesUtils.formatSqlValues());
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* an empty string.
*/
public void testFormatSqlValues_empty_string() {
assertEquals("(\'\')", SendFusionTablesUtils.formatSqlValues(""));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* one value.
*/
public void testFormatSqlValues_one_value() {
assertEquals("(\'first\')", SendFusionTablesUtils.formatSqlValues("first"));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* two values.
*/
public void testFormatSqlValues_two_values() {
assertEquals(
"(\'first\',\'second\')", SendFusionTablesUtils.formatSqlValues("first", "second"));
}
/**
* Tests {@link SendFusionTablesUtils#escapeSqlString(String)} with a value
* containing several single quotes.
*/
public void testEscapeSqValuel() {
String value = "let's'";
assertEquals("let''s''", SendFusionTablesUtils.escapeSqlString(value));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a null
* point.
*/
public void testGetKmlPoint_null_point() {
assertEquals(
"<Point><coordinates></coordinates></Point>", SendFusionTablesUtils.getKmlPoint(null));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a valid
* point.
*/
public void testGetKmlPoint_valid_point() {
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
assertEquals("<Point><coordinates>10.1,20.2,30.3</coordinates></Point>",
SendFusionTablesUtils.getKmlPoint(location));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with a null
* locations.
*/
public void testKmlLineString_null_locations() {
assertEquals("<LineString><coordinates></coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(null));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with no
* location.
*/
public void testKmlLineString_no_location() {
ArrayList<Location> locations = new ArrayList<Location>();
assertEquals("<LineString><coordinates></coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with one
* location.
*/
public void testKmlLineString_one_location() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
locations.add(location);
assertEquals("<LineString><coordinates>10.1,20.2,30.3</coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with two
* locations.
*/
public void testKmlLineString_two_locations() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location1 = new Location("test");
location1.setLongitude(10.1);
location1.setLatitude(20.2);
location1.setAltitude(30.3);
locations.add(location1);
Location location2 = new Location("test");
location2.setLongitude(1.1);
location2.setLatitude(2.2);
location2.removeAltitude();
locations.add(location2);
assertEquals("<LineString><coordinates>10.1,20.2,30.3 1.1,2.2</coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
* with no altitude.
*/
public void testAppendLocation_no_altitude() {
StringBuilder builder = new StringBuilder();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.removeAltitude();
SendFusionTablesUtils.appendLocation(location, builder);
assertEquals("10.1,20.2", builder.toString());
}
/**
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
* with altitude.
*/
public void testAppendLocation_has_altitude() {
StringBuilder builder = new StringBuilder();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
SendFusionTablesUtils.appendLocation(location, builder);
assertEquals("10.1,20.2,30.3", builder.toString());
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a null
* inputstream.
*/
public void testGetTableId_null() {
assertEquals(null, SendFusionTablesUtils.getTableId(null));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
* inputstream containing no data.
*/
public void testGetTableId_no_data() {
InputStream inputStream = new ByteArrayInputStream(new byte[0]);
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an empty
* inputstream.
*/
public void testGetTableId_empty() {
String string = "";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an one
* line inputstream.
*/
public void testGetTableId_one_line() {
String string = "tableid";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
* inputstream not containing "tableid".
*/
public void testGetTableId_no_table_id() {
String string = "error\n123";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a valid
* inputstream.
*/
public void testGetTableId() {
String string = "tableid\n123";
InputStream inputStream = null;
inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals("123", SendFusionTablesUtils.getTableId(inputStream));
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.fusiontables;
import com.google.android.apps.mytracks.io.docs.SendDocsActivity;
import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest;
import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity;
import android.test.AndroidTestCase;
/**
* Tests the {@link SendFusionTablesActivity}.
*
* @author Youtao Liu
*/
public class SendFusionTablesActivityTest extends AndroidTestCase {
private SendFusionTablesActivity sendFusionTablesActivity;
private SendRequest sendRequest;
@Override
protected void setUp() throws Exception {
super.setUp();
sendRequest = new SendRequest(1L, true, false, true);
sendFusionTablesActivity = new SendFusionTablesActivity();
}
/**
* Tests the method
* {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets
* the flags of "sendDocs" and "cancel" to false and false.
*/
public void testGetNextClass_notCancelNotSendDocs() {
sendRequest.setSendDocs(false);
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false);
assertEquals(UploadResultActivity.class, next);
}
/**
* Tests the method
* {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets
* the flags of "sendDocs" and "cancel" to true and false.
*/
public void testGetNextClass_notCancelSendDocs() {
sendRequest.setSendDocs(true);
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false);
assertEquals(SendDocsActivity.class, next);
}
/**
* Tests the method
* {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets
* the flags of "sendDocs" and "cancel" to true and true.
*/
public void testGetNextClass_cancelSendDocs() {
sendRequest.setSendDocs(true);
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true);
assertEquals(UploadResultActivity.class, next);
}
/**
* Tests the method
* {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets
* the flags of "sendDocs" and "cancel" to false and true.
*/
public void testGetNextClass_cancelNotSendDocs() {
sendRequest.setSendDocs(false);
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true);
assertEquals(UploadResultActivity.class, next);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.maps;
import com.google.android.apps.mytracks.io.docs.SendDocsActivity;
import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity;
import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest;
import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity;
import android.test.AndroidTestCase;
/**
* Tests the {@link SendMapsActivity}.
*
* @author Youtao Liu
*/
public class SendMapsActivityTest extends AndroidTestCase {
private SendMapsActivity sendMapsActivity;
private SendRequest sendRequest;
@Override
protected void setUp() throws Exception {
super.setUp();
sendRequest = new SendRequest(1L, true, false, true);
sendMapsActivity = new SendMapsActivity();
}
/**
* Tests the method
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
* of "sendFusionTables","sendDocs" and "cancel" to true, true and false.
*/
public void testGetNextClass_notCancelSendFusionTables() {
sendRequest.setSendFusionTables(true);
sendRequest.setSendDocs(true);
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
assertEquals(SendFusionTablesActivity.class, next);
}
/**
* Tests the method
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
* of "sendFusionTables","sendDocs" and "cancel" to false, true and false.
*/
public void testGetNextClass_notCancelSendDocs() {
sendRequest.setSendFusionTables(false);
sendRequest.setSendDocs(true);
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
assertEquals(SendDocsActivity.class, next);
}
/**
* Tests the method
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
* of "sendFusionTables","sendDocs" and "cancel" to false, false and false.
*/
public void testGetNextClass_notCancelNotSend() {
sendRequest.setSendFusionTables(false);
sendRequest.setSendDocs(false);
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
assertEquals(UploadResultActivity.class, next);
}
/**
* Tests the method
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
* of "sendFusionTables","sendDocs" and "cancel" to true, true and true.
*/
public void testGetNextClass_cancelSendDocs() {
sendRequest.setSendFusionTables(true);
sendRequest.setSendDocs(true);
Class<?> next = sendMapsActivity.getNextClass(sendRequest, true);
assertEquals(UploadResultActivity.class, next);
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.maps;
import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata;
import com.google.android.maps.mytracks.R;
import android.content.Intent;
import android.test.AndroidTestCase;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Tests the {@link ChooseMapActivity}.
*
* @author Youtao Liu
*/
public class ChooseMapActivityTest extends AndroidTestCase {
private static final String MAP_ID = "mapid";
private static final String MAP_TITLE = "title";
private static final String MAP_DESC = "desc";
private ArrayList<String> mapIds = new ArrayList<String>();
private ArrayList<MapsMapMetadata> mapDatas = new ArrayList<MapsMapMetadata>();
private boolean errorDialogShown = false;
private boolean progressDialogRemoved = false;
/**
* Creates a class to override some methods of {@link ChooseMapActivity} to
* makes it testable.
*
* @author youtaol
*/
public class ChooseMapActivityMock extends ChooseMapActivity {
/**
* By overriding this method, avoids to start next activity.
*/
@Override
public void startActivity(Intent intent) {}
/**
* By overriding this method, avoids to show an error dialog and set the
* show flag to true.
*/
@Override
public void showErrorDialog() {
errorDialogShown = true;
}
/**
* By overriding this method, avoids to show an error dialog and set the
* show flag to true.
*/
@Override
public void removeProgressDialog() {
progressDialogRemoved = true;
}
}
/**
* Tests the method
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
* . An alert dialog should be shown when there is no map.
*
* @throws InterruptedException
*/
public void testOnAsyncTaskCompleted_fail() {
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
errorDialogShown = false;
progressDialogRemoved = false;
chooseMapActivityMock.onAsyncTaskCompleted(false, null, null);
assertTrue(progressDialogRemoved);
assertTrue(errorDialogShown);
}
/**
* Tests the method
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
* . Check the logic when there is only map.
*/
public void testOnAsyncTaskCompleted_success_oneMap() {
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
chooseMapActivityMock.arrayAdapter = new ArrayAdapter<ChooseMapActivity.ListItem>(getContext(),
R.layout.choose_map_item);
simulateMaps(1);
chooseMapActivityMock.onAsyncTaskCompleted(true, mapIds, mapDatas);
assertEquals(1, chooseMapActivityMock.arrayAdapter.getCount());
assertEquals(MAP_ID + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapId());
assertEquals(MAP_TITLE + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapData()
.getTitle());
assertEquals(MAP_DESC + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapData()
.getDescription());
}
/**
* Tests the method
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
* . Check the logic when there are 10 maps.
*/
public void testOnAsyncTaskCompleted_success_twoMaps() {
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
chooseMapActivityMock.arrayAdapter = new ArrayAdapter<ChooseMapActivity.ListItem>(getContext(),
R.layout.choose_map_item);
simulateMaps(10);
chooseMapActivityMock.onAsyncTaskCompleted(true, mapIds, mapDatas);
assertEquals(10, chooseMapActivityMock.arrayAdapter.getCount());
assertEquals(MAP_ID + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapId());
assertEquals(MAP_TITLE + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapData()
.getTitle());
assertEquals(MAP_DESC + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapData()
.getDescription());
}
/**
* Simulates map data for the test.
*
* @param number of data should be simulated.
*/
private void simulateMaps(int number) {
mapIds = new ArrayList<String>();
mapDatas = new ArrayList<MapsMapMetadata>();
for (int i = 0; i < number; i++) {
mapIds.add(MAP_ID + i);
MapsMapMetadata metaData = new MapsMapMetadata();
metaData.setTitle(MAP_TITLE + i);
metaData.setDescription(MAP_DESC + i);
metaData.setSearchable(true);
mapDatas.add(metaData);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.maps;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.gdata.maps.MapsFeature;
import com.google.android.maps.GeoPoint;
import android.location.Location;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests {@link SendMapsUtils}.
*
* @author Jimmy Shih
*/
public class SendMapsUtilsTest extends TestCase {
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null track.
*/
public void testGetMapUrl_null_track() {
assertEquals(null, SendMapsUtils.getMapUrl(null));
}
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null map id.
*/
public void testGetMapUrl_null_map_id() {
Track track = new Track();
track.setMapId(null);
assertEquals(null, SendMapsUtils.getMapUrl(track));
}
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with a valid track.
*/
public void testGetMapUrl_valid_track() {
Track track = new Track();
track.setMapId("123");
assertEquals("https://maps.google.com/maps/ms?msa=0&msid=123", SendMapsUtils.getMapUrl(track));
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with a title.
*/
public void testBuildMapsMarkerFeature_with_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
"name", "this\nmap\ndescription", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("name", mapFeature.getTitle());
assertEquals("this<br>map<br>description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with an empty title.
*/
public void testBuildMapsMarkerFeature_empty_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
"", "description", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals("description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with a null title.
*/
public void testBuildMapsMarkerFeature_null_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
null, "description", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals("description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
* title.
*/
public void testBuildMapsLineFeature_with_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("name", locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("name", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with an
* empty title.
*/
public void testBuildMapsLineFeature_empty_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("", locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
* null title.
*/
public void testBuildMapsLineFeature_null_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature(null, locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#getGeoPoint(Location)}.
*/
public void testGeoPoint() {
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
GeoPoint geoPoint = SendMapsUtils.getGeoPoint(location);
assertEquals(50000000, geoPoint.getLatitudeE6());
assertEquals(100000000, geoPoint.getLongitudeE6());
}
} | Java |
/*
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Test for the DoubleBuffer class.
*
* @author Sandor Dornbush
*/
public class DoubleBufferTest extends TestCase {
/**
* Tests that the constructor leaves the buffer in a valid state.
*/
public void testConstructor() {
DoubleBuffer buffer = new DoubleBuffer(10);
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Simple test with 10 of the same values.
*/
public void testBasic() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 9; i++) {
buffer.setNext(1.0);
assertFalse(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
buffer.setNext(1);
assertTrue(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests with 5 entries of -10 and 5 entries of 10.
*/
public void testSplit() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 5; i++) {
buffer.setNext(-10);
assertFalse(buffer.isFull());
assertEquals(-10.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(-10.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
for (int i = 1; i < 5; i++) {
buffer.setNext(10);
assertFalse(buffer.isFull());
double expectedAverage = ((i * 10.0) - 50.0) / (i + 5);
assertEquals(buffer.toString(),
expectedAverage, buffer.getAverage(), 0.01);
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(expectedAverage, averageAndVariance[0]);
}
buffer.setNext(10);
assertTrue(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(100.0, averageAndVariance[1]);
}
/**
* Tests that reset leaves the buffer in a valid state.
*/
public void testReset() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 100; i++) {
buffer.setNext(i);
}
assertTrue(buffer.isFull());
buffer.reset();
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests that if a lot of items are inserted the smoothing and looping works.
*/
public void testLoop() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 1000; i++) {
buffer.setNext(i);
assertEquals(i >= 9, buffer.isFull());
if (i > 10) {
assertEquals(i - 4.5, buffer.getAverage());
}
}
}
}
| Java |
// Copyright 2009 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.stats;
import com.google.android.apps.mytracks.Constants;
import android.location.Location;
import junit.framework.TestCase;
/**
* Test the the function of the TripStatisticsBuilder class.
*
* @author Sandor Dornbush
*/
public class TripStatisticsBuilderTest extends TestCase {
private TripStatisticsBuilder builder = null;
@Override
protected void setUp() throws Exception {
super.setUp();
builder = new TripStatisticsBuilder(System.currentTimeMillis());
}
public void testAddLocationSimple() throws Exception {
builder = new TripStatisticsBuilder(1000);
TripStatistics stats = builder.getStatistics();
assertEquals(0.0, builder.getSmoothedElevation());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation());
assertEquals(0.0, stats.getMaxSpeed());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade());
assertEquals(0.0, stats.getTotalElevationGain());
assertEquals(0, stats.getMovingTime());
assertEquals(0.0, stats.getTotalDistance());
for (int i = 0; i < 100; i++) {
Location l = new Location("test");
l.setAccuracy(1.0f);
l.setLongitude(45.0);
// Going up by 5 meters each time.
l.setAltitude(i);
// Moving by .1% of a degree latitude.
l.setLatitude(i * .001);
l.setSpeed(11.1f);
// Each time slice is 10 seconds.
long time = 1000 + 10000 * i;
l.setTime(time);
boolean moving = builder.addLocation(l, time);
assertEquals((i != 0), moving);
stats = builder.getStatistics();
assertEquals(10000 * i, stats.getTotalTime());
assertEquals(10000 * i, stats.getMovingTime());
assertEquals(i, builder.getSmoothedElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, stats.getMinElevation());
assertEquals(i, stats.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i, stats.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(11.1f, stats.getMaxSpeed(), 0.1);
}
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(0.009, stats.getMinGrade(), 0.0001);
assertEquals(0.009, stats.getMaxGrade(), 0.0001);
}
// 1 degree = 111 km
// 1 timeslice = 0.001 degree = 111 m
assertEquals(111.0 * i, stats.getTotalDistance(), 100);
}
}
/**
* Test that elevation works if the user is stable.
*/
public void testElevationSimple() throws Exception {
for (double elevation = 0; elevation < 1000; elevation += 10) {
builder = new TripStatisticsBuilder(System.currentTimeMillis());
for (int j = 0; j < 100; j++) {
assertEquals(0.0, builder.updateElevation(elevation));
assertEquals(elevation, builder.getSmoothedElevation());
TripStatistics data = builder.getStatistics();
assertEquals(elevation, data.getMinElevation());
assertEquals(elevation, data.getMaxElevation());
assertEquals(0.0, data.getTotalElevationGain());
}
}
}
public void testElevationGain() throws Exception {
for (double i = 0; i < 1000; i++) {
double expectedGain;
if (i < (Constants.ELEVATION_SMOOTHING_FACTOR - 1)) {
expectedGain = 0;
} else if (i < Constants.ELEVATION_SMOOTHING_FACTOR) {
expectedGain = 0.5;
} else {
expectedGain = 1.0;
}
assertEquals(expectedGain,
builder.updateElevation(i));
assertEquals(i, builder.getSmoothedElevation(), 20);
TripStatistics data = builder.getStatistics();
assertEquals(0.0, data.getMinElevation(), 0.0);
assertEquals(i, data.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
}
}
public void testGradeSimple() throws Exception {
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, 100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(1.0, builder.getStatistics().getMinGrade());
}
}
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, -100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(-1.0, builder.getStatistics().getMinGrade());
}
}
}
public void testGradeIgnoreShort() throws Exception {
for (double i = 0; i < 100; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(1, 100);
assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade());
assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade());
}
}
public void testUpdateSpeedIncludeZero() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 0.0, i, 4.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
}
}
public void testUpdateSpeedIngoreErrorCode() {
builder.updateSpeed(12345000, 128.0, 12344000, 0.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeedIngoreLargeAcceleration() {
builder.updateSpeed(12345000, 100.0, 12344000, 1.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeed() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 4.0, i, 4.0);
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(4.0, builder.getStatistics().getMaxSpeed());
}
}
}
}
| Java |
/**
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
import java.util.Random;
/**
* This class test the ExtremityMonitor class.
*
* @author Sandor Dornbush
*/
public class ExtremityMonitorTest extends TestCase {
public ExtremityMonitorTest(String name) {
super(name);
}
public void testInitialize() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
}
public void testSimple() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
assertFalse(monitor.update(1));
assertFalse(monitor.update(0.5));
}
/**
* Throws a bunch of random numbers between [0,1] at the monitor.
*/
public void testRandom() {
ExtremityMonitor monitor = new ExtremityMonitor();
Random random = new Random(42);
for (int i = 0; i < 1000; i++) {
monitor.update(random.nextDouble());
}
assertTrue(monitor.getMin() < 0.1);
assertTrue(monitor.getMax() < 1.0);
assertTrue(monitor.getMin() >= 0.0);
assertTrue(monitor.getMax() > 0.9);
}
public void testReset() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
monitor.reset();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Tests for {@link TripStatistics}.
* This only tests non-trivial pieces of that class.
*
* @author Rodrigo Damazio
*/
public class TripStatisticsTest extends TestCase {
private TripStatistics statistics;
@Override
protected void setUp() throws Exception {
super.setUp();
statistics = new TripStatistics();
}
public void testSetBounds() {
// This is not a trivial setter, conversion happens in it
statistics.setBounds(12345, -34567, 56789, -98765);
assertEquals(12345, statistics.getLeft());
assertEquals(-34567, statistics.getTop());
assertEquals(56789, statistics.getRight());
assertEquals(-98765, statistics.getBottom());
}
public void testMerge() {
TripStatistics statistics2 = new TripStatistics();
statistics.setStartTime(1000L); // Resulting start time
statistics.setStopTime(2500L);
statistics2.setStartTime(3000L);
statistics2.setStopTime(4000L); // Resulting stop time
statistics.setTotalTime(1500L);
statistics2.setTotalTime(1000L); // Result: 1500+1000
statistics.setMovingTime(700L);
statistics2.setMovingTime(600L); // Result: 700+600
statistics.setTotalDistance(750.0);
statistics2.setTotalDistance(350.0); // Result: 750+350
statistics.setTotalElevationGain(50.0);
statistics2.setTotalElevationGain(850.0); // Result: 850+50
statistics.setMaxSpeed(60.0); // Resulting max speed
statistics2.setMaxSpeed(30.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0); // Resulting min elevation
statistics2.setMaxElevation(3575.0); // Resulting max elevation
statistics2.setMinElevation(2800.0);
statistics.setMaxGrade(15.0);
statistics.setMinGrade(-25.0); // Resulting min grade
statistics2.setMaxGrade(35.0); // Resulting max grade
statistics2.setMinGrade(0.0);
// Resulting bounds: -10000, 35000, 30000, -40000
statistics.setBounds(-10000, 20000, 30000, -40000);
statistics2.setBounds(-5000, 35000, 0, 20000);
statistics.merge(statistics2);
assertEquals(1000L, statistics.getStartTime());
assertEquals(4000L, statistics.getStopTime());
assertEquals(2500L, statistics.getTotalTime());
assertEquals(1300L, statistics.getMovingTime());
assertEquals(1100.0, statistics.getTotalDistance());
assertEquals(900.0, statistics.getTotalElevationGain());
assertEquals(60.0, statistics.getMaxSpeed());
assertEquals(-10000, statistics.getLeft());
assertEquals(30000, statistics.getRight());
assertEquals(35000, statistics.getTop());
assertEquals(-40000, statistics.getBottom());
assertEquals(1200.0, statistics.getMinElevation());
assertEquals(3575.0, statistics.getMaxElevation());
assertEquals(-25.0, statistics.getMinGrade());
assertEquals(35.0, statistics.getMaxGrade());
}
public void testGetAverageSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setTotalTime(50000); // in milliseconds
assertEquals(20.0, statistics.getAverageSpeed());
}
public void testGetAverageMovingSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setMovingTime(20000); // in milliseconds
assertEquals(50.0, statistics.getAverageMovingSpeed());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences prefs;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(11, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should still be incremental.
locationIterator = new FixedSizeLocationIterator(21, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
String metricUnitsKey = context.getString(R.string.metric_units_key);
String speedKey = context.getString(R.string.report_speed_key);
prefs.edit()
.putBoolean(metricUnitsKey, true)
.putBoolean(speedKey, true)
.apply();
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(speedKey, false)
.apply();
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(prefs, speedKey);
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(metricUnitsKey, false)
.apply();
listener.onSharedPreferenceChanged(prefs, metricUnitsKey);
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A unit test for {@link MyTracksProviderUtilsImpl}.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
private Context context;
private MyTracksProviderUtils providerUtils;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
}
public void testLocationIterator_noPoints() {
testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_customFactory() {
final Location location = new Location("test_location");
final AtomicInteger counter = new AtomicInteger();
testIterator(1, 15, 4, false, new LocationFactory() {
@Override
public Location createLocation() {
counter.incrementAndGet();
return location;
}
});
// Make sure we were called exactly as many times as we had track points.
assertEquals(15, counter.get());
}
public void testLocationIterator_nullFactory() {
try {
testIterator(1, 15, 4, false, null);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected.
}
}
public void testLocationIterator_noBatchAscending() {
testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_noBatchDescending() {
testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchAscending() {
testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchDescending() {
testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_largeTrack() {
testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
private List<Location> testIterator(long trackId, int numPoints, int batchSize,
boolean descending, LocationFactory locationFactory) {
long lastPointId = initializeTrack(trackId, numPoints);
((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize);
List<Location> locations = new ArrayList<Location>(numPoints);
LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory);
try {
while (it.hasNext()) {
Location loc = it.next();
assertNotNull(loc);
locations.add(loc);
// Make sure the IDs are returned in the right order.
assertEquals(descending ? lastPointId - locations.size() + 1
: lastPointId - numPoints + locations.size(), it.getLocationId());
}
assertEquals(numPoints, locations.size());
} finally {
it.close();
}
return locations;
}
private long initializeTrack(long id, int numPoints) {
Track track = new Track();
track.setId(id);
track.setName("Test: " + id);
track.setNumberOfPoints(numPoints);
providerUtils.insertTrack(track);
track = providerUtils.getTrack(id);
assertNotNull(track);
Location[] locations = new Location[numPoints];
for (int i = 0; i < numPoints; ++i) {
Location loc = new Location("test");
loc.setLatitude(37.0 + (double) i / 10000.0);
loc.setLongitude(57.0 - (double) i / 10000.0);
loc.setAccuracy((float) i / 100.0f);
loc.setAltitude(i * 2.5);
locations[i] = loc;
}
providerUtils.bulkInsertTrackPoints(locations, numPoints, id);
// Load all inserted locations.
long lastPointId = -1;
int counter = 0;
LocationIterator it = providerUtils.getLocationIterator(id, -1, false,
MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
try {
while (it.hasNext()) {
it.next();
lastPointId = it.getLocationId();
counter++;
}
} finally {
it.close();
}
assertTrue(numPoints == 0 || lastPointId > 0);
assertEquals(numPoints, track.getNumberOfPoints());
assertEquals(numPoints, counter);
return lastPointId;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType;
import android.os.Parcel;
import android.test.AndroidTestCase;
/**
* Tests for the WaypointCreationRequest class.
* {@link WaypointCreationRequest}
*
* @author Sandor Dornbush
*/
public class WaypointCreationRequestTest extends AndroidTestCase {
public void testTypeParceling() {
WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER;
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertNull(copy.getName());
assertNull(copy.getDescription());
assertNull(copy.getIconUrl());
}
public void testAllAttributesParceling() {
WaypointCreationRequest original =
new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png");
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertEquals("name", copy.getName());
assertEquals("description", copy.getDescription());
assertEquals("img.png", copy.getIconUrl());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult;
import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.content.ContentUris;
import android.location.Location;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@link SearchEngine}.
* These are not meant to be quality tests, but instead feature-by-feature tests
* (in other words, they don't test the mixing of different score boostings, just
* each boosting separately)
*
* @author Rodrigo Damazio
*/
public class SearchEngineTest extends AndroidTestCase {
private static final Location HERE = new Location("gps");
private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP
private MyTracksProviderUtils providerUtils;
private SearchEngine engine;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
MockContext context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
engine = new SearchEngine(providerUtils);
}
@Override
protected void tearDown() throws Exception {
providerUtils.deleteAllTracks();
super.tearDown();
}
private long insertTrack(String title, String description, String category, double distance, long hoursAgo) {
Track track = new Track();
track.setName(title);
track.setDescription(description);
track.setCategory(category);
TripStatistics stats = track.getStatistics();
if (hoursAgo > 0) {
// Started twice hoursAgo, so the average time is hoursAgo.
stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2);
stats.setStopTime(NOW);
}
int latitude = (int) ((HERE.getLatitude() + distance) * 1E6);
int longitude = (int) ((HERE.getLongitude() + distance) * 1E6);
stats.setBounds(latitude, longitude, latitude, longitude);
Uri uri = providerUtils.insertTrack(track);
return ContentUris.parseId(uri);
}
private long insertTrack(String title, String description, String category) {
return insertTrack(title, description, category, 0, -1);
}
private long insertTrack(String title, double distance) {
return insertTrack(title, "", "", distance, -1);
}
private long insertTrack(String title, long hoursAgo) {
return insertTrack(title, "", "", 0.0, hoursAgo);
}
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
Waypoint waypoint = new Waypoint();
waypoint.setName(title);
waypoint.setDescription(description);
waypoint.setCategory(category);
waypoint.setTrackId(trackId);
Location location = new Location(HERE);
location.setLatitude(location.getLatitude() + distance);
location.setLongitude(location.getLongitude() + distance);
if (hoursAgo >= 0) {
location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
}
waypoint.setLocation(location);
Uri uri = providerUtils.insertWaypoint(waypoint);
return ContentUris.parseId(uri);
}
private long insertWaypoint(String title, String description, String category) {
return insertWaypoint(title, description, category, 0.0, -1, -1);
}
private long insertWaypoint(String title, double distance) {
return insertWaypoint(title, "", "", distance, -1, -1);
}
private long insertWaypoint(String title, long hoursAgo) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, -1);
}
private long insertWaypoint(String title, long hoursAgo, long trackId) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId);
}
public void testSearchText() {
// Insert 7 tracks (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertTrack("bb", "cc", "dd");
long descriptionMatchId = insertTrack("bb", "aa", "cc");
long categoryMatchId = insertTrack("bb", "cc", "aa");
long titleMatchId = insertTrack("aa", "bb", "cc");
long titleCategoryMatchId = insertTrack("aa", "bb", "ca");
long titleDescriptionMatchId = insertTrack("aa", "ba", "cc");
long allMatchId = insertTrack("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertTrackResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchWaypointText() {
// Insert 7 waypoints (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertWaypoint("bb", "cc", "dd");
long descriptionMatchId = insertWaypoint("bb", "aa", "cc");
long categoryMatchId = insertWaypoint("bb", "cc", "aa");
long titleMatchId = insertWaypoint("aa", "bb", "cc");
long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca");
long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc");
long allMatchId = insertWaypoint("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertWaypointResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchMixedText() {
// Insert 5 entries (purposefully out of result order):
// - one waypoint which will match by description
// - one waypoint which won't match
// - one waypoint which will match by title
// - one track which won't match
// - one track which will match by title
long descriptionWaypointId = insertWaypoint("bb", "aa", "cc");
insertWaypoint("bb", "cc", "dd");
long titleWaypointId = insertWaypoint("aa", "bb", "cc");
insertTrack("bb", "cc", "dd");
long trackId = insertTrack("aa", "bb", "cc");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertEquals(results.toString(), 3, results.size());
assertTrackResult(trackId, results.get(0));
assertWaypointResult(titleWaypointId, results.get(1));
assertWaypointResult(descriptionWaypointId, results.get(2));
}
public void testSearchTrackDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertTrack("aa", 0.3);
long nearId = insertTrack("ab", 0.1);
long farId = insertTrack("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertTrackResults(results, nearId, farId, farFarAwayId);
}
public void testSearchWaypointDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertWaypoint("aa", 0.3);
long nearId = insertWaypoint("ab", 0.1);
long farId = insertWaypoint("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertWaypointResults(results, nearId, farId, farFarAwayId);
}
public void testSearchTrackRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertTrack("aa", 3);
long recentId = insertTrack("ab", 1);
long oldId = insertTrack("ac", 2);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertTrackResults(results, recentId, oldId, oldestId);
}
public void testSearchWaypointRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertWaypoint("aa", 2);
long recentId = insertWaypoint("ab", 0);
long oldId = insertWaypoint("ac", 1);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertWaypointResults(results, recentId, oldId, oldestId);
}
public void testSearchCurrentTrack() {
// All results match text, but one of them is the current track.
long currentId = insertTrack("ab", 1);
long otherId = insertTrack("aa", 1);
SearchQuery query = new SearchQuery("a", null, currentId, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Current track should be demoted.
assertTrackResults(results, otherId, currentId);
}
public void testSearchCurrentTrackWaypoint() {
// All results match text, but one of them is in the current track.
long otherId = insertWaypoint("aa", 1, 456);
long currentId = insertWaypoint("ab", 1, 123);
SearchQuery query = new SearchQuery("a", null, 123, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Waypoint in current track should be promoted.
assertWaypointResults(results, currentId, otherId);
}
private void assertTrackResult(long trackId, ScoredResult result) {
assertNotNull("Not a track", result.track);
assertNull("Ambiguous result", result.waypoint);
assertEquals(trackId, result.track.getId());
}
private void assertTrackResults(List<ScoredResult> results, long... trackIds) {
String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results;
assertEquals(results.size(), trackIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.track);
assertNull(errMsg, result.waypoint);
assertEquals(errMsg, trackIds[i], result.track.getId());
}
}
private void assertWaypointResult(long waypointId, ScoredResult result) {
assertNotNull("Not a waypoint", result.waypoint);
assertNull("Ambiguous result", result.track);
assertEquals(waypointId, result.waypoint.getId());
}
private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) {
String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results;
assertEquals(results.size(), waypointIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.waypoint);
assertNull(errMsg, result.track);
assertEquals(errMsg, waypointIds[i], result.waypoint.getId());
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import android.util.Pair;
/**
* Tests for {@link DescriptionGeneratorImpl}.
*
* @author Jimmy Shih
*/
public class DescriptionGeneratorImplTest extends AndroidTestCase {
private DescriptionGeneratorImpl descriptionGenerator;
@Override
protected void setUp() throws Exception {
descriptionGenerator = new DescriptionGeneratorImpl(getContext());
}
/**
* Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track,
* java.util.Vector, java.util.Vector)}.
*/
public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
track.setStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
+ " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Min pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: 11/2/2010 11:11 AM<br>"
+ "Activity type: hiking<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null));
}
/**
* Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(Waypoint)}.
*/
public void testGenerateWaypointDescription() {
Waypoint waypoint = new Waypoint();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
waypoint.setStatistics(stats);
String expected = "Total distance: 20.00 km (12.4 mi)\n"
+ "Total time: 10:00\n"
+ "Moving time: 05:00\n"
+ "Average speed: 120.00 km/h (74.6 mi/h)\n"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)\n"
+ "Max speed: 360.00 km/h (223.7 mi/h)\n"
+ "Average pace: 0.50 min/km (0.8 min/mi)\n"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)\n"
+ "Min pace: 0.17 min/km (0.3 min/mi)\n"
+ "Max elevation: 550 m (1804 ft)\n"
+ "Min elevation: -500 m (-1640 ft)\n"
+ "Elevation gain: 6000 m (19685 ft)\n"
+ "Max grade: 42 %\n"
+ "Min grade: 11 %\n"
+ "Recorded: 11/2/2010 11:11 AM\n";
assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint));
}
/**
* Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder,
* int, String)}.
*/
public void testWriteDistance() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>");
assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int,
* String)}.
*/
public void testWriteTime() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>");
assertEquals("Total time: 00:01<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder,
* int, String)}.
*/
public void testWriteSpeed() {
StringBuilder builder = new StringBuilder();
Pair<Double, Double> speed = descriptionGenerator.writeSpeed(
1.1, builder, R.string.description_average_speed, "\n");
assertEquals(3.96, speed.first);
assertEquals(3.96 * UnitConversions.KM_TO_MI, speed.second);
assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder,
* int, String)}.
*/
public void testWriteElevation() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>");
assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int,
* String)}.
*/
public void testWritePace() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writePace(
new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n");
assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)}.
*/
public void testWriteGrade() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 4 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with a NaN.
*/
public void testWriteGrade_nan() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with an infinite number.
*/
public void testWriteGrade_infinite() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(
Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)}.
*/
public void testGetPace() {
assertEquals(12.0, descriptionGenerator.getPace(5));
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed.
*/
public void testGetPace_zero() {
assertEquals(0.0, descriptionGenerator.getPace(0));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import junit.framework.TestCase;
/**
* A unit test for {@link ChartsExtendedEncoder}.
*
* @author Bartlomiej Niechwiej
*/
public class ChartsExtendedEncoderTest extends TestCase {
public void testGetEncodedValue_validArguments() {
// Valid arguments.
assertEquals("AK", ChartsExtendedEncoder.getEncodedValue(10));
assertEquals("JO", ChartsExtendedEncoder.getEncodedValue(590));
assertEquals("AA", ChartsExtendedEncoder.getEncodedValue(0));
// 64^2 = 4096.
assertEquals("..", ChartsExtendedEncoder.getEncodedValue(4095));
}
public void testGetEncodedValue_invalidArguments() {
// Invalid arguments.
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(4096));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(1234564096));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-10));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-12324435));
}
public void testGetSeparator() {
assertEquals(",", ChartsExtendedEncoder.getSeparator());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.Constants;
import android.os.Environment;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
/**
* Tests for {@link FileUtils}.
*
* @author Rodrigo Damazio
*/
public class FileUtilsTest extends TestCase {
private FileUtils fileUtils;
private Set<String> existingFiles;
@Override
protected void setUp() throws Exception {
super.setUp();
existingFiles = new HashSet<String>();
fileUtils = new FileUtils() {
@Override
protected boolean fileExists(File directory, String fullName) {
return existingFiles.contains(fullName);
}
};
}
public void testBuildExternalDirectoryPath() {
String expectedName = Environment.getExternalStorageDirectory()
+ File.separator
+ Constants.SDCARD_TOP_DIR
+ File.separator
+ "a"
+ File.separator
+ "b"
+ File.separator
+ "c";
String dirName = fileUtils.buildExternalDirectoryPath("a", "b", "c");
assertEquals(expectedName, dirName);
}
/**
* Tests sanitize filename.
*/
public void testSanitizeFileName() {
String name = "Swim\10ming-^across:/the/ pacific (ocean).";
String expected = "Swim_ming-^across_the_ pacific (ocean)_";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Tests characters in other languages, like Chinese and Russian, are allowed.
*/
public void testSanitizeFileName_i18n() {
String name = "您好-привет";
String expected = "您好-привет";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Tests special FAT32 characters are allowed.
*/
public void testSanitizeFileName_special_characters() {
String name = "$%'-_@~`!(){}^#&+,;=[] ";
String expected = "$%'-_@~`!(){}^#&+,;=[] ";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Testing collapsing multiple underscores characters.
*/
public void testSanitizeFileName_collapse() {
String name = "hello//there";
String expected = "hello_there";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
public void testTruncateFileName() {
File directory = new File("/dir1/dir2/");
String suffix = ".gpx";
char[] name = new char[FileUtils.MAX_FAT32_PATH_LENGTH];
for (int i = 0; i < name.length; i++) {
name[i] = 'a';
}
String nameString = new String(name);
String truncated = fileUtils.truncateFileName(directory, nameString, suffix);
for (int i = 0; i < truncated.length(); i++) {
assertEquals('a', truncated.charAt(i));
}
assertEquals(FileUtils.MAX_FAT32_PATH_LENGTH,
new File(directory, truncated + suffix).getPath().length());
}
public void testBuildUniqueFileName_someExist() {
existingFiles = new HashSet<String>();
existingFiles.add("Filename.ext");
existingFiles.add("Filename(1).ext");
existingFiles.add("Filename(2).ext");
existingFiles.add("Filename(3).ext");
existingFiles.add("Filename(4).ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(5).ext", filename);
}
public void testBuildUniqueFileName_oneExists() {
existingFiles.add("Filename.ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(1).ext", filename);
}
public void testBuildUniqueFileName_noneExists() {
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename.ext", filename);
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import java.util.Vector;
import junit.framework.TestCase;
/**
* Tests for the Chart URL generator.
*
* @author Sandor Dornbush
*/
public class ChartURLGeneratorTest extends TestCase {
public void testgetChartUrl() {
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
Track t = new Track();
TripStatistics stats = t.getStatistics();
stats.setMinElevation(0);
stats.setMaxElevation(2000);
stats.setTotalDistance(100);
distances.add(0.0);
elevations.add(10.0);
distances.add(10.0);
elevations.add(300.0);
distances.add(20.0);
elevations.add(800.0);
distances.add(50.0);
elevations.add(1900.0);
distances.add(75.0);
elevations.add(1200.0);
distances.add(90.0);
elevations.add(700.0);
distances.add(100.0);
elevations.add(70.0);
String chart = ChartURLGenerator.getChartUrl(distances,
elevations,
t,
"Title",
true);
assertEquals(
"http://chart.apis.google.com/chart?&chs=600x350&cht=lxy&"
+ "chtt=Title&chxt=x,y&chxr=0,0,0,0|1,0.0,2100.0,300&chco=009A00&"
+ "chm=B,00AA00,0,0,0&chg=100000,14.285714285714286,1,0&"
+ "chd=e:AAGZMzf.v.5l..,ATJJYY55kkVVCI",
chart);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import android.test.AndroidTestCase;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* Tests for {@link StringUtils}.
*
* @author Rodrigo Damazio
*/
public class StringUtilsTest extends AndroidTestCase {
/**
* Tests {@link StringUtils#formatDateTime(android.content.Context, long)}.
*/
public void testFormatTime() {
// Unix time 0 in UTC is "4:00 PM" in Pacific Standard time zone.
// This test can break if run on a different time zone or with a different
// time format preference.
assertEquals("4:00 PM", StringUtils.formatTime(getContext(), 0L));
}
/**
* Tests {@link StringUtils#formatDateTime(android.content.Context, long)}.
*/
public void testFormatDateTime() {
// Unix time 0 in UTC is "12/31/1969 4:00 PM" in Pacific Standard time zone.
// This test can break if run on a different time zone or with a different
// date/time format preference.
assertEquals("12/31/1969 4:00 PM", StringUtils.formatDateTime(getContext(), 0L));
}
/**
* Tests {@link StringUtils#formatDateTimeIso8601(long)}.
*/
public void testFormatDateTimeIso8601() {
assertEquals("1970-01-01T00:00:12.345Z", StringUtils.formatDateTimeIso8601(12345));
}
/**
* Tests {@link StringUtils#formatElapsedTime(long)}.
*/
public void testformatElapsedTime() {
// 1 second
assertEquals("00:01", StringUtils.formatElapsedTime(1000));
// 10 seconds
assertEquals("00:10", StringUtils.formatElapsedTime(10000));
// 1 minute
assertEquals("01:00", StringUtils.formatElapsedTime(60000));
// 10 minutes
assertEquals("10:00", StringUtils.formatElapsedTime(600000));
// 1 hour
assertEquals("1:00:00", StringUtils.formatElapsedTime(3600000));
// 10 hours
assertEquals("10:00:00", StringUtils.formatElapsedTime(36000000));
// 100 hours
assertEquals("100:00:00", StringUtils.formatElapsedTime(360000000));
}
/**
* Tests {@link StringUtils#formatElapsedTimeWithHour(long)}.
*/
public void testformatElapsedTimeWithHour() {
// 1 second
assertEquals("0:00:01", StringUtils.formatElapsedTimeWithHour(1000));
// 10 seconds
assertEquals("0:00:10", StringUtils.formatElapsedTimeWithHour(10000));
// 1 minute
assertEquals("0:01:00", StringUtils.formatElapsedTimeWithHour(60000));
// 10 minutes
assertEquals("0:10:00", StringUtils.formatElapsedTimeWithHour(600000));
// 1 hour
assertEquals("1:00:00", StringUtils.formatElapsedTimeWithHour(3600000));
// 10 hours
assertEquals("10:00:00", StringUtils.formatElapsedTimeWithHour(36000000));
// 100 hours
assertEquals("100:00:00", StringUtils.formatElapsedTimeWithHour(360000000));
}
/**
* Tests {@link StringUtils#formatDistance(android.content.Context, double,
* boolean)}.
*/
public void testFormatDistance() {
// A large number in metric
assertEquals("5.00 km", StringUtils.formatDistance(getContext(), 5000, true));
// A large number in imperial
assertEquals("3.11 mi", StringUtils.formatDistance(getContext(), 5000, false));
// A small number in metric
assertEquals("100.00 m", StringUtils.formatDistance(getContext(), 100, true));
// A small number in imperial
assertEquals("328.08 ft", StringUtils.formatDistance(getContext(), 100, false));
}
/**
* Tests {@link StringUtils#formatSpeed(android.content.Context, double,
* boolean, boolean)}.
*/
public void testFormatSpeed() {
// Speed in metric
assertEquals("36.00 km/h", StringUtils.formatSpeed(getContext(), 10, true, true));
// Speed in imperial
assertEquals("22.37 mi/h", StringUtils.formatSpeed(getContext(), 10, false, true));
// Pace in metric
assertEquals("1.67 min/km", StringUtils.formatSpeed(getContext(), 10, true, false));
// Pace in imperial
assertEquals("2.68 min/mi", StringUtils.formatSpeed(getContext(), 10, false, false));
// zero pace
assertEquals("0.00 min/km", StringUtils.formatSpeed(getContext(), 0, true, false));
assertEquals("0.00 min/mi", StringUtils.formatSpeed(getContext(), 0, false, false));
// speed is NaN
assertEquals("-", StringUtils.formatSpeed(getContext(), Double.NaN, true, true));
// speed is infinite
assertEquals("-", StringUtils.formatSpeed(getContext(), Double.NEGATIVE_INFINITY, true, true));
}
/**
* Tests {@link StringUtils#formatTimeDistance(android.content.Context, long, double, boolean)}.
*/
public void testFormatTimeDistance() {
assertEquals("00:10 5.00 km", StringUtils.formatTimeDistance(getContext(), 10000, 5000, true));
}
/**
* Tests {@link StringUtils#formatCData(String)}.
*/
public void testFormatCData() {
assertEquals("<![CDATA[hello]]>", StringUtils.formatCData("hello"));
assertEquals("<![CDATA[hello]]]]><![CDATA[>there]]>", StringUtils.formatCData("hello]]>there"));
}
/**
* Tests {@link StringUtils#getTime(String)}.
*/
public void testGetTime() {
assertGetTime("2010-05-04T03:02:01", 2010, 5, 4, 3, 2, 1, 0);
assertGetTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0);
}
/**
* Tests {@link StringUtils#getTime(String)} with fractional seconds.
*/
public void testGetTime_fractional() {
assertGetTime("2010-05-04T03:02:01.3", 2010, 5, 4, 3, 2, 1, 300);
assertGetTime("2010-05-04T03:02:01.35", 2010, 5, 4, 3, 2, 1, 350);
assertGetTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352);
assertGetTime("2010-05-04T03:02:01.3525Z", 2010, 5, 4, 3, 2, 1, 352);
}
/**
* Tests {@link StringUtils#getTime(String)} with time zone.
*/
public void testGetTime_timezone() {
assertGetTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0);
assertGetTime("2010-05-04T03:02:01+00:00", 2010, 5, 4, 3, 2, 1, 0);
assertGetTime("2010-05-04T03:02:01-00:00", 2010, 5, 4, 3, 2, 1, 0);
assertGetTime("2010-05-04T03:02:01+01:00", 2010, 5, 4, 2, 2, 1, 0);
assertGetTime("2010-05-04T03:02:01+10:30", 2010, 5, 3, 16, 32, 1, 0);
assertGetTime("2010-05-04T03:02:01-09:30", 2010, 5, 4, 12, 32, 1, 0);
assertGetTime("2010-05-04T03:02:01-05:00", 2010, 5, 4, 8, 2, 1, 0);
}
/**
* Tests {@link StringUtils#getTime(String)} with fractional seconds and time
* zone.
*/
public void testGetTime_fractionalAndTimezone() {
assertGetTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352);
assertGetTime("2010-05-04T03:02:01.47+00:00", 2010, 5, 4, 3, 2, 1, 470);
assertGetTime("2010-05-04T03:02:01.5791+03:00", 2010, 5, 4, 0, 2, 1, 579);
assertGetTime("2010-05-04T03:02:01.8-05:30", 2010, 5, 4, 8, 32, 1, 800);
}
/**
* Asserts the {@link StringUtils#getTime(String)} returns the expected
* values.
*
* @param xmlDateTime the xml date time string
* @param year the expected year
* @param month the expected month
* @param day the expected day
* @param hour the expected hour
* @param minute the expected minute
* @param second the expected second
* @param millisecond the expected milliseconds
*/
private void assertGetTime(String xmlDateTime, int year, int month, int day, int hour, int minute,
int second, int millisecond) {
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(year, month - 1, day, hour, minute, second);
calendar.set(GregorianCalendar.MILLISECOND, millisecond);
assertEquals(calendar.getTimeInMillis(), StringUtils.getTime(xmlDateTime));
}
/**
* Tests {@link StringUtils#getTimeParts(long)} with a positive number.
*/
public void testGetTimeParts_postive() {
int parts[] = StringUtils.getTimeParts(61000);
assertEquals(1, parts[0]);
assertEquals(1, parts[1]);
assertEquals(0, parts[2]);
}
/**
* Tests {@link StringUtils#getTimeParts(long)} with a negative number.
*/
public void testGetTimeParts_negative() {
int parts[] = StringUtils.getTimeParts(-61000);
assertEquals(-1, parts[0]);
assertEquals(-1, parts[1]);
assertEquals(0, parts[2]);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.graphics.Path;
import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*/
public class MapOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MockMyTracksOverlay myTracksOverlay;
private MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
// Set a TrackPathPainter with a MockPath.
myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
public Path newPath() {
return new MockPath();
}
});
mockView = null;
}
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(2, path.totalPoints);
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
// Same after drawing on canvas.
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
}
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
}
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 40; ++i) {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
// Shadow.
myTracksOverlay.draw(canvas, mockView, true);
// We don't expect to do anything if
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
// No shadow.
myTracksOverlay.draw(canvas, mockView, false);
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
assertEquals(100, path.totalPoints);
// TODO: Check the points from the path (and the segments).
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartView.Mode;
import com.google.android.maps.mytracks.R;
import android.test.ActivityInstrumentationTestCase2;
/**
* Tests the {@link ChartSettingsDialog}.
*
* @author Youtao Liu
*/
public class ChartSettingsDialogTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private ChartSettingsDialog chartSettingsDialog;
public ChartSettingsDialogTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
chartSettingsDialog = new ChartSettingsDialog(getActivity());
chartSettingsDialog.show();
}
/**
* Tests the {@link ChartSettingsDialog#setMode} and check the result by
* {@link ChartSettingsDialog#getMode}. Gets all modes of Mode, then set and
* get each mode.
*/
public void testSetMode() {
Mode[] modes = Mode.values();
for (Mode mode : modes) {
chartSettingsDialog.setMode(mode);
assertEquals(mode, chartSettingsDialog.getMode());
}
}
/**
* Tests the {@link ChartSettingsDialog#setDisplaySpeed}.
*/
public void testSetDisplaySpeed() {
chartSettingsDialog.setDisplaySpeed(true);
assertEquals(getActivity().getString(R.string.stat_speed),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
chartSettingsDialog.setDisplaySpeed(false);
assertEquals(getActivity().getString(R.string.stat_pace),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
}
/**
* Tests the {@link ChartSettingsDialog#setSeriesEnabled} and check the result
* by {@link ChartSettingsDialog#isSeriesEnabled}.
*/
public void testSetSeriesEnabled() {
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
chartSettingsDialog.setSeriesEnabled(i, true);
assertEquals(true, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(true, chartSettingsDialog.isSeriesEnabled(i));
chartSettingsDialog.setSeriesEnabled(i, false);
assertEquals(false, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(false, chartSettingsDialog.isSeriesEnabled(i));
}
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.jayway.android.robotium.solo.Solo;
import android.app.Instrumentation;
import android.location.Location;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ZoomControls;
/**
* Tests {@link ChartActivity}.
*
* @author Youtao Liu
*/
public class ChartActivityTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private Instrumentation instrumentation;
private ChartActivity chartActivity;
private Solo solo;
private View zoomIn;
private View zoomOut;
private int currentZoomLevel;
private final String LOCATION_PROVIDER = "gps";
private final double INITIAL_LONGTITUDE = 22;
private final double INITIAL_LATITUDE = 22;
private final double INITIAL_ALTITUDE = 22;
private final float INITIAL_ACCURACY = 5;
private final float INITIAL_SPEED = 10;
private final float INITIAL_BEARING = 3.0f;
// 10 is same with the default value in ChartView
private final int MAX_ZOOM_LEVEL = 10;
private final int MIN_ZOOM_LEVEL = 1;
// The ratio from meter/second to kilometer/hour, the conversion is 60 * 60 /
// 1000 = 3.6.
private final double METER_PER_SECOND_TO_KILOMETER_PER_HOUR = 3.6;
private final double KILOMETER_TO_METER = 1000.0;
private final double HOURS_PER_UNIT = 60;
public ChartActivityTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
chartActivity = getActivity();
}
/**
* Tests {@link ChartActivity#zoomIn()} and {@link ChartActivity#zoomOut()}.
*/
public void testZoomInAndZoomOut() {
currentZoomLevel = chartActivity.getChartView().getZoomLevel();
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ZoomControls zoomControls = (ZoomControls) chartActivity.findViewById(R.id.elevation_zoom);
zoomIn = zoomControls.getChildAt(0);
zoomOut = zoomControls.getChildAt(1);
// Invoke following two methods method to initial the display of
// ZoomControls.
zoomControls.setIsZoomInEnabled(chartActivity.getChartView().canZoomIn());
zoomControls.setIsZoomOutEnabled(chartActivity.getChartView().canZoomOut());
// Click zoomIn button to disable.
for (int i = currentZoomLevel; i > MIN_ZOOM_LEVEL; i--) {
zoomIn.performClick();
}
}
});
instrumentation.waitForIdleSync();
assertEquals(false, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Click to the second max zoom level
for (int i = MIN_ZOOM_LEVEL; i < MAX_ZOOM_LEVEL - 1; i++) {
zoomOut.performClick();
assertEquals(true, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
}
zoomOut.performClick();
}
});
instrumentation.waitForIdleSync();
assertEquals(true, zoomIn.isEnabled());
assertEquals(false, zoomOut.isEnabled());
}
/**
* There are two parts in this test. Tests
* {@link ChartActivity#OnCreateDialog()} which includes the logic to create
* {@link ChartSettingsDialog}.
*/
public void testCreateSettingDialog() {
solo = new Solo(instrumentation, chartActivity);
// Part1, tests {@link ChartActivity#onCreateOptionsMenu()}. Check if
// optional menu is created.
assertNull(chartActivity.getChartSettingsMenuItem());
sendKeys(KeyEvent.KEYCODE_MENU);
assertNotNull(chartActivity.getChartSettingsMenuItem());
// Part2, tests {@link ChartActivity#onOptionsItemSelected()}. Clicks on the
// "Chart settings", and then verify that the dialog contains the
// "By distance" text.
solo.clickOnText(chartActivity.getString(R.string.menu_chart_view_chart_settings));
instrumentation.waitForIdleSync();
assertTrue(solo.searchText(chartActivity.getString(R.string.chart_settings_by_distance)));
}
/**
* Tests the logic to get the incorrect values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorIncorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Input incorrect state.
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
}
/**
* Tests the logic to get the correct values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorCorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(20.0, point[3]);
assertEquals(20.0, point[4]);
assertEquals(20.0, point[5]);
}
/**
* Tests the logic to get the value of metric Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceMetric() {
// By distance.
chartActivity.getChartView().setMode(ChartView.Mode.BY_DISTANCE);
// Resets last location and writes first location.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second is a same location, just different time.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(0.0, point[0]);
// The third location is a new location, and use metric.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation3, false);
// Computes the distance between Latitude 22 and 23.
float[] results = new float[4];
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance1 = results[0];
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The fourth location is a new location, and use metric.
MyTracksLocation myTracksLocation4 = getMyTracksLocation();
myTracksLocation4.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation4, false);
// Computes the distance between Latitude 23 and 24.
Location.distanceBetween(myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(),
myTracksLocation4.getLatitude(), myTracksLocation4.getLongitude(), results);
double distance2 = results[0];
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the value of imperial Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
// The first is a same location, just different time.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second location is a new location, and use imperial.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation2, false);
/*
* Computes the distance between Latitude 22 and 23. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
float[] results = new float[4];
Location.distanceBetween(myTracksLocation1.getLatitude(), myTracksLocation1.getLongitude(),
myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(), results);
double distance1 = results[0] * UnitConversions.KM_TO_MI;
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The third location is a new location, and use imperial.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation3, false);
/*
* Computes the distance between Latitude 23 and 24. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance2 = results[0] * UnitConversions.KM_TO_MI;
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the values of time in {@link #fillDataPoint}.
*/
public void testFillDataPoint_time() {
// By time
chartActivity.getChartView().setMode(ChartView.Mode.BY_TIME);
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
long timeSpan = 222;
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setTime(myTracksLocation1.getTime() + timeSpan);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((double) timeSpan, point[0]);
}
/**
* Tests the logic to get the value of elevation in
* {@link ChartActivity#fillDataPoint} by one and two points.
*/
public void testFillDataPoint_elevation() {
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
/*
* At first, clear old points of elevation, so give true to the second
* parameter. Then only one value INITIALLONGTITUDE in buffer.
*/
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(INITIAL_ALTITUDE, point[1]);
/*
* Send another value to buffer, now there are two values, INITIALALTITUDE
* and INITIALALTITUDE * 2.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setAltitude(INITIAL_ALTITUDE * 2);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((INITIAL_ALTITUDE + INITIAL_ALTITUDE * 2) / 2.0, point[1]);
}
/**
* Tests the logic to get the value of speed in
* {@link ChartActivity#fillDataPoint}. In this test, firstly remove all
* points in memory, and then fill in two points one by one. The speed values
* of these points are 129, 130.
*/
public void testFillDataPoint_speed() {
// Set max speed to make the speed of points are valid.
chartActivity.setTrackMaxSpeed(200.0);
/*
* At first, clear old points of speed, so give true to the second
* parameter. It will not be filled in to the speed buffer.
*/
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
myTracksLocation1.setSpeed(129);
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[2]);
/*
* Tests the logic when both metricUnits and reportSpeed are true.This
* location will be filled into speed buffer.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
// Add a time span here to make sure the second point is valid, the value
// 222 here is doesn't matter.
myTracksLocation2.setTime(myTracksLocation1.getTime() + 222);
myTracksLocation2.setSpeed(130);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(130.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR, point[2]);
}
/**
* Tests the logic to compute speed when use Imperial.
*/
public void testFillDataPoint_speedImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(132);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(132.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR * UnitConversions.KM_TO_MI,
point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false.
*/
public void testFillDataPoint_pace_nonZeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(134);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(HOURS_PER_UNIT / (134.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR), point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false and average
* speed is zero.
*/
public void testFillDataPoint_pace_zeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(0);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(Double.NaN, point[2]);
}
/**
* Simulates a MyTracksLocation for test.
*
* @return a simulated location.
*/
private MyTracksLocation getMyTracksLocation() {
// Initial Location
Location loc = new Location(LOCATION_PROVIDER);
loc.setLongitude(INITIAL_LONGTITUDE);
loc.setLatitude(INITIAL_LATITUDE);
loc.setAltitude(INITIAL_ALTITUDE);
loc.setAccuracy(INITIAL_ACCURACY);
loc.setSpeed(INITIAL_SPEED);
loc.setTime(System.currentTimeMillis());
loc.setBearing(INITIAL_BEARING);
SensorDataSet sd = SensorDataSet.newBuilder().build();
MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd);
return myTracksLocation;
}
/**
* Helper method to test fillDataPoint.
*
* @param location location to fill
* @param operation a flag to do some operations
* @return data of this location
*/
private double[] fillDataPointTestHelper(Location location, boolean isNeedClear) {
if (isNeedClear) {
chartActivity.clearTrackPoints();
}
double[] point = new double[6];
chartActivity.fillDataPoint(location, point);
return point;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import java.io.File;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A unit test for {@link MyTracks} activity.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
private SharedPreferences sharedPreferences;
private TrackRecordingServiceConnection serviceConnection;
public MyTracksTest() {
super(MyTracks.class);
}
@Override
protected void tearDown() throws Exception {
clearSelectedAndRecordingTracks();
waitForIdle();
super.tearDown();
}
public void testInitialization_mainAction() {
// Make sure we can start MyTracks and the activity doesn't start recording.
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithNoData() {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithValidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("valid", ".gpx", getActivity().getFilesDir()));
// TODO: Add a valid GPX.
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testInitialization_viewActionWithInvalidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("invalid", ".gpx", getActivity().getFilesDir()));
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testRecording_startAndStop() throws Exception {
assertInitialized();
// Check if not recording.
clearSelectedAndRecordingTracks();
waitForIdle();
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Start a new track.
getActivity().startRecording();
serviceConnection.bindIfRunning();
long recordingTrackId = awaitRecordingStatus(5000, true);
assertTrue(recordingTrackId >= 0);
// Wait until we are done and make sure that selectedTrack = recordingTrack.
waitForIdle();
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(recordingTrackId, selectedTrackId);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Watch for MyTracksDetails activity.
ActivityMonitor monitor = getInstrumentation().addMonitor(
TrackDetail.class.getName(), null, false);
// Now, stop the track and make sure that it is still selected, but
// no longer recording.
getActivity().stopRecording();
// Check if we got back MyTracksDetails activity.
Activity activity = getInstrumentation().waitForMonitor(monitor);
assertTrue(activity instanceof TrackDetail);
// TODO: Update track name and other properties and test if they were
// properly saved.
// Simulate a click on Save button.
final Button save = (Button) activity.findViewById(R.id.track_detail_save);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
save.performClick();
}
});
// Check the remaining properties.
recordingTrackId = awaitRecordingStatus(5000, false);
assertEquals(-1, recordingTrackId);
assertEquals(recordingTrackId, getRecordingTrackId());
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
// Make sure this is the same track as the last recording track ID.
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
private void assertInitialized() {
assertNotNull(getActivity());
serviceConnection = new TrackRecordingServiceConnection(getActivity(), null);
}
/**
* Waits until the UI thread becomes idle.
*/
private void waitForIdle() throws InterruptedException {
// Note: We can't use getInstrumentation().waitForIdleSync() here.
final Object semaphore = new Object();
synchronized (semaphore) {
final AtomicBoolean isIdle = new AtomicBoolean();
getInstrumentation().waitForIdle(new Runnable() {
@Override
public void run() {
synchronized (semaphore) {
isIdle.set(true);
semaphore.notify();
}
}
});
while (!isIdle.get()) {
semaphore.wait();
}
}
}
/**
* Clears {selected,recording}TrackId in the {@link #getSharedPreferences()}.
*/
private void clearSelectedAndRecordingTracks() {
Editor editor = getSharedPreferences().edit();
editor.putLong(getActivity().getString(R.string.selected_track_key), -1);
editor.putLong(getActivity().getString(R.string.recording_track_key), -1);
editor.clear();
editor.apply();
}
/**
* Waits until the recording state changes to the given status.
*
* @param timeout the maximum time to wait, in milliseconds.
* @param isRecording the final status to await.
* @return the recording track ID.
*/
private long awaitRecordingStatus(long timeout, boolean isRecording)
throws TimeoutException, InterruptedException {
long startTime = System.nanoTime();
while (isRecording() != isRecording) {
if (System.nanoTime() - startTime > timeout * 1000000) {
throw new TimeoutException("Timeout while waiting for recording!");
}
Thread.sleep(20);
}
waitForIdle();
assertEquals(isRecording, isRecording());
return getRecordingTrackId();
}
private long getRecordingTrackId() {
return getSharedPreferences().getLong(getActivity().getString(R.string.recording_track_key), -1);
}
private SharedPreferences getSharedPreferences() {
if (sharedPreferences == null) {
sharedPreferences = getActivity().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
private boolean isRecording() {
return ServiceUtils.isRecording(getActivity(),
serviceConnection.getServiceIfBound(), getSharedPreferences());
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.testing;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import android.content.Context;
/**
* A fake factory for {@link MyTracksProviderUtils} which always returns a
* predefined instance.
*
* @author Rodrigo Damazio
*/
public class TestingProviderUtilsFactory extends Factory {
private MyTracksProviderUtils instance;
public TestingProviderUtilsFactory(MyTracksProviderUtils instance) {
this.instance = instance;
}
@Override
protected MyTracksProviderUtils newForContext(Context context) {
return instance;
}
public static Factory installWithInstance(MyTracksProviderUtils instance) {
Factory oldFactory = Factory.getInstance();
Factory factory = new TestingProviderUtilsFactory(instance);
MyTracksProviderUtils.Factory.overrideInstance(factory);
return oldFactory;
}
public static void restoreOldFactory(Factory factory) {
MyTracksProviderUtils.Factory.overrideInstance(factory);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
/**
* Tests for the AntPreference.
*
* @author Youtao Liu
*/
public class AntPreferenceTest extends AndroidTestCase {
public void testNotPaired() {
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 0;
}
};
assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired),
antPreference.getSummary());
}
public void testPaired() {
int persistInt = 1;
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 1;
}
};
assertEquals(
getContext().getString(R.string.settings_sensor_ant_paired, persistInt),
antPreference.getSummary());
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.test.AndroidTestCase;
import java.util.List;
/**
* Tests for the BootReceiver.
*
* @author Youtao Liu
*/
public class BootReceiverTest extends AndroidTestCase {
private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService";
/**
* Tests the behavior when receive notification which is the phone boot.
*/
public void testOnReceive_startService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BOOT_COMPLETED);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is started
assertTrue(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Tests the behavior when receive notification which is not the phone boot.
*/
public void testOnReceive_noStartService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BUG_REPORT);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is not started
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Checks if a service is started in a context.
*
* @param context the context for checking a service
* @param serviceName the service name to find if existed
*/
private boolean isServiceExisted(Context context, String serviceName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName componentName = serviceInfo.service;
if (componentName.getClassName().equals(serviceName)) {
return true;
}
}
return false;
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock class that intercepts {@code Path}'s and records calls to
* {@code #moveTo()} and {@code #lineTo()}.
*/
public class MockPath extends Path {
/** A list of disjoined path segments. */
public final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** The total number of points in this path. */
public int totalPoints;
private List<PointF> currentSegment;
@Override
public void lineTo(float x, float y) {
super.lineTo(x, y);
Assert.assertNotNull(currentSegment);
currentSegment.add(new PointF(x, y));
totalPoints++;
}
@Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
segments.add(currentSegment =
new ArrayList<PointF>(Arrays.asList(new PointF(x, y))));
totalPoints++;
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings;
import com.google.android.maps.mytracks.R;
import android.graphics.Paint.Style;
import android.test.AndroidTestCase;
/**
* @author Sandor Dornbush
*/
public class ChartValueSeriesTest extends AndroidTestCase {
private ChartValueSeries series;
@Override
protected void setUp() throws Exception {
series = new ChartValueSeries(getContext(),
R.color.elevation_fill,
R.color.elevation_border,
new ZoomSettings(5, new int[] {100}),
R.string.stat_elevation);
}
public void testInitialConditions() {
assertEquals(0, series.getInterval());
assertEquals(1, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(0, series.getMax());
assertEquals(0.0, series.getSpread());
assertEquals(Style.STROKE, series.getPaint().getStyle());
assertEquals(getContext().getString(R.string.stat_elevation),
series.getTitle());
assertTrue(series.isEnabled());
}
public void testEnabled() {
series.setEnabled(false);
assertFalse(series.isEnabled());
}
public void testSmallUpdates() {
series.update(0);
series.update(10);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(3, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(100, series.getMax());
assertEquals(100.0, series.getSpread());
}
public void testBigUpdates() {
series.update(0);
series.update(901);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(1000, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testNotZeroBasedUpdates() {
series.update(500);
series.update(1401);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(500, series.getMin());
assertEquals(1500, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testZoomSettings_invalidArgs() {
try {
new ZoomSettings(0, new int[] {10, 50, 100});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {1, 3, 2});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
}
public void testZoomSettings_minAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(10, settings.calculateInterval(0, 15));
assertEquals(10, settings.calculateInterval(0, 50));
assertEquals(50, settings.calculateInterval(0, 111));
assertEquals(50, settings.calculateInterval(0, 250));
assertEquals(100, settings.calculateInterval(0, 251));
assertEquals(100, settings.calculateInterval(0, 10000));
}
public void testZoomSettings_minNotAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(50, settings.calculateInterval(5, 55));
assertEquals(10, settings.calculateInterval(10, 60));
assertEquals(50, settings.calculateInterval(7, 250));
assertEquals(100, settings.calculateInterval(7, 257));
assertEquals(100, settings.calculateInterval(11, 10000));
// A regression test.
settings = new ZoomSettings(5, new int[] {5, 10, 20});
assertEquals(10, settings.calculateInterval(-37.14, -11.89));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import android.content.Context;
import android.graphics.Rect;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock version of {@code MapOverlay} that does not use
* {@class MapView}.
*/
public class MockMyTracksOverlay extends MapOverlay {
private Projection mockProjection;
public MockMyTracksOverlay(Context context) {
super(context);
mockProjection = new MockProjection();
}
@Override
public Projection getMapProjection(MapView mapView) {
return mockProjection;
}
@Override
public Rect getMapViewRect(MapView mapView) {
return new Rect(0, 0, 100, 100);
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
private int slowDefault;
private int normalDefault;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
// Get the default value
slowDefault = 9;
normalDefault = 15;
}
/**
* Tests the initialization of slowSpeed and normalSpeed in {@link
* DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)}.
*/
public void testConstructor() {
String[] slowSpeedsInShPre = { "0", "1", "99", "" };
int[] slowSpeedExpectations = { 0, 1, 99, slowDefault };
String[] normalSpeedsInShPre = { "0", "1", "99", "" };
int[] normalSpeedExpectations = { 0, 1, 99, normalDefault };
for (int i = 0; i < slowSpeedsInShPre.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), slowSpeedsInShPre[i]);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
normalSpeedsInShPre[i]);
sharedPreferencesEditor.commit();
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
assertEquals(slowSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_null_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not slowSpeed and not normalSpeed.
*/
public void testOnSharedPreferenceChanged_other_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is slowSpeed.
*/
public void testOnSharedPreferenceChanged_slowSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_slow_key));
assertEquals(slowSpeed + 2, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 2, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is normalSpeed.
*/
public void testOnSharedPreferenceChanged_normalSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 4));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 4));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowSpeed + 4, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 4, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of slowSpeed and normalSpeed in SharedPreference
* is "". In such situation, the default value should get returned.
*/
public void testOnSharedPreferenceChanged_emptyValue() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), "");
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key), "");
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowDefault, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalDefault, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase {
public void testSimpeColorTrackPathPainter() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new SingleColorTrackPathPainter(getContext());
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCase {
public void testDynamicSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new DynamicSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase {
public void testFixedSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new FixedSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
/**
* Tests for the MyTracks track path painter factory.
*
* @author Vangelis S.
*/
public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase {
public void testTrackPathPainterFactory() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
Context context = getContext();
SharedPreferences prefs = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
if (prefs == null) {
return;
}
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_none,
SingleColorTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_fixed,
DynamicSpeedTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_dynamic,
DynamicSpeedTrackPathPainter.class);
}
private <T> void testTrackPathPainterFactorySpecific(Context context, SharedPreferences prefs,
int track_color_mode, Class <?> c) {
prefs.edit().putString(context.getString(R.string.track_color_mode_key),
context.getString(track_color_mode)).apply();
int startLocationIdx = 0;
Boolean alwaysVisible = true;
TrackPathPainter painter = TrackPathPainterFactory.getTrackPathPainter(context);
myTracksOverlay.setTrackPathPainter(painter);
assertNotNull(painter);
assertTrue(c.isInstance(painter));
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
}
/**
* Tests the method {@link DynamicSpeedTrackPathDescriptor#getSpeedMargin()}
* with zero, normal and illegal value.
*/
public void testGetSpeedMargin() {
String[] actuals = { "0", "50", "99", "" };
// The default value of speedMargin is 25.
int[] expectations = { 0, 50, 99, 25 };
// Test
for (int i = 0; i < expectations.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(expectations[i],
dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences));
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_nullKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_otherKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
"trackColorModeDynamicVariation",
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
"trackColorModeDynamicVariation");
assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of speedMargin is "".
*/
public void testOnSharedPreferenceChanged_emptyValue() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "");
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_dynamic_speed_variation_key));
// The default value of speedMargin is 25.
assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
long trackId = -1;
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
* averageMovingSpeed.
*/
public void testIsDiffereceSignificant() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
double[] averageMovingSpeeds = { 0, 30, 30, 30 };
double[] newAverageMovingSpeed = { 20, 30,
// Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2),
// Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
boolean[] expectedValues = { true, false, false, true };
double[] expectedAverageMovingSpeed = { 20, 30, 30,
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
// Test
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant(
averageMovingSpeeds[i], newAverageMovingSpeed[i]));
assertEquals(expectedAverageMovingSpeed[i],
dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed());
}
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.MockMyTracksOverlay;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterTestCase extends AndroidTestCase {
protected Canvas canvas;
protected MockMyTracksOverlay myTracksOverlay;
protected MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
mockView = null;
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import android.graphics.Point;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock {@code Projection} that acts as the identity matrix.
*/
public class MockProjection implements Projection {
@Override
public Point toPixels(GeoPoint in, Point out) {
return out;
}
@Override
public float metersToEquatorPixels(float meters) {
return meters;
}
@Override
public GeoPoint fromPixels(int x, int y) {
return new GeoPoint(y, x);
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.testing.mocking.AndroidMock.expect;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.test.AndroidTestCase;
import java.io.File;
/**
* Tests {@link RemoveTempFilesService}.
*
* @author Sandor Dornbush
*/
public class RemoveTempFilesServiceTest extends AndroidTestCase {
private static final String DIR_NAME = "/tmp";
private static final String FILE_NAME = "foo";
private RemoveTempFilesService service;
@UsesMocks({ File.class, })
protected void setUp() throws Exception {
service = new RemoveTempFilesService();
};
/**
* Tests when the directory doesn't exists.
*/
public void test_noDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(false);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when the directory is empty.
*/
public void test_emptyDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[0]);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when there is a new file and it shouldn't get deleted.
*/
public void test_newFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
expect(file.lastModified()).andStubReturn(System.currentTimeMillis());
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
/**
* Tests when there is an old file and it should get deleted.
*/
public void test_oldFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
// qSet to one hour and 1 millisecond later than the current time
expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001);
expect(file.delete()).andStubReturn(true);
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(1, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import android.test.AndroidTestCase;
/**
* Tests for {@link StatusAnnouncerFactory}.
* These tests require Donut+ to run.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
public void testCreate() {
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
PeriodicTask task = factory.create(getContext());
assertTrue(task instanceof StatusAnnouncerTask);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.easymock.Capture;
/**
* Tests for {@link StatusAnnouncerTask}.
* WARNING: I'm not responsible if your eyes start bleeding while reading this
* code. You have been warned. It's still better than no test, though.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Use something other than our hardcoded value
private static final Locale DEFAULT_LOCALE = Locale.KOREAN;
private static final String ANNOUNCEMENT = "I can haz cheeseburger?";
private Locale oldDefaultLocale;
private StatusAnnouncerTask task;
private StatusAnnouncerTask mockTask;
private Capture<OnInitListener> initListenerCapture;
private Capture<PhoneStateListener> phoneListenerCapture;
private TextToSpeechDelegate ttsDelegate;
private TextToSpeechInterface tts;
/**
* Mockable interface that we delegate TTS calls to.
*/
interface TextToSpeechInterface {
int addEarcon(String earcon, String packagename, int resourceId);
int addEarcon(String earcon, String filename);
int addSpeech(String text, String packagename, int resourceId);
int addSpeech(String text, String filename);
boolean areDefaultsEnforced();
String getDefaultEngine();
Locale getLanguage();
int isLanguageAvailable(Locale loc);
boolean isSpeaking();
int playEarcon(String earcon, int queueMode,
HashMap<String, String> params);
int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params);
int setEngineByPackageName(String enginePackageName);
int setLanguage(Locale loc);
int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener);
int setPitch(float pitch);
int setSpeechRate(float speechRate);
void shutdown();
int speak(String text, int queueMode, HashMap<String, String> params);
int stop();
int synthesizeToFile(String text, HashMap<String, String> params,
String filename);
}
/**
* Subclass of {@link TextToSpeech} which delegates calls to the interface
* above.
* The logic here is stupid and the author is ashamed of having to write it
* like this, but basically the issue is that TextToSpeech cannot be mocked
* without running its constructor, its constructor runs async operations
* which call other methods (and then if the methods are part of a mock we'd
* have to set a behavior, but we can't 'cause the object hasn't been fully
* built yet).
* The logic is that calls made during the constructor (when tts is not yet
* set) will go up to the original class, but after tts is set we'll forward
* them all to the mock.
*/
private class TextToSpeechDelegate
extends TextToSpeech implements TextToSpeechInterface {
public TextToSpeechDelegate(Context context, OnInitListener listener) {
super(context, listener);
}
@Override
public int addEarcon(String earcon, String packagename, int resourceId) {
if (tts == null) {
return super.addEarcon(earcon, packagename, resourceId);
}
return tts.addEarcon(earcon, packagename, resourceId);
}
@Override
public int addEarcon(String earcon, String filename) {
if (tts == null) {
return super.addEarcon(earcon, filename);
}
return tts.addEarcon(earcon, filename);
}
@Override
public int addSpeech(String text, String packagename, int resourceId) {
if (tts == null) {
return super.addSpeech(text, packagename, resourceId);
}
return tts.addSpeech(text, packagename, resourceId);
}
@Override
public int addSpeech(String text, String filename) {
if (tts == null) {
return super.addSpeech(text, filename);
}
return tts.addSpeech(text, filename);
}
@Override
public Locale getLanguage() {
if (tts == null) {
return super.getLanguage();
}
return tts.getLanguage();
}
@Override
public int isLanguageAvailable(Locale loc) {
if (tts == null) {
return super.isLanguageAvailable(loc);
}
return tts.isLanguageAvailable(loc);
}
@Override
public boolean isSpeaking() {
if (tts == null) {
return super.isSpeaking();
}
return tts.isSpeaking();
}
@Override
public int playEarcon(String earcon, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playEarcon(earcon, queueMode, params);
}
return tts.playEarcon(earcon, queueMode, params);
}
@Override
public int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playSilence(durationInMs, queueMode, params);
}
return tts.playSilence(durationInMs, queueMode, params);
}
@Override
public int setLanguage(Locale loc) {
if (tts == null) {
return super.setLanguage(loc);
}
return tts.setLanguage(loc);
}
@Override
public int setOnUtteranceCompletedListener(
OnUtteranceCompletedListener listener) {
if (tts == null) {
return super.setOnUtteranceCompletedListener(listener);
}
return tts.setOnUtteranceCompletedListener(listener);
}
@Override
public int setPitch(float pitch) {
if (tts == null) {
return super.setPitch(pitch);
}
return tts.setPitch(pitch);
}
@Override
public int setSpeechRate(float speechRate) {
if (tts == null) {
return super.setSpeechRate(speechRate);
}
return tts.setSpeechRate(speechRate);
}
@Override
public void shutdown() {
if (tts == null) {
super.shutdown();
return;
}
tts.shutdown();
}
@Override
public int speak(
String text, int queueMode, HashMap<String, String> params) {
if (tts == null) {
return super.speak(text, queueMode, params);
}
return tts.speak(text, queueMode, params);
}
@Override
public int stop() {
if (tts == null) {
return super.stop();
}
return tts.stop();
}
@Override
public int synthesizeToFile(String text, HashMap<String, String> params,
String filename) {
if (tts == null) {
return super.synthesizeToFile(text, params, filename);
}
return tts.synthesizeToFile(text, params, filename);
}
}
@UsesMocks({
StatusAnnouncerTask.class,
StringUtils.class,
})
@Override
protected void setUp() throws Exception {
super.setUp();
oldDefaultLocale = Locale.getDefault();
Locale.setDefault(DEFAULT_LOCALE);
// Eww, the effort required just to mock TextToSpeech is insane
final AtomicBoolean listenerCalled = new AtomicBoolean();
OnInitListener blockingListener = new OnInitListener() {
@Override
public void onInit(int status) {
synchronized (this) {
listenerCalled.set(true);
notify();
}
}
};
ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener);
// Wait for all async operations done in the constructor to finish.
synchronized (blockingListener) {
while (!listenerCalled.get()) {
// Releases the synchronized lock until we're woken up.
blockingListener.wait();
}
}
// Phew, done, now we can start forwarding calls
tts = AndroidMock.createMock(TextToSpeechInterface.class);
initListenerCapture = new Capture<OnInitListener>();
phoneListenerCapture = new Capture<PhoneStateListener>();
// Create a partial forwarding mock
mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext());
task = new StatusAnnouncerTask(getContext()) {
@Override
protected TextToSpeech newTextToSpeech(Context ctx,
OnInitListener onInitListener) {
return mockTask.newTextToSpeech(ctx, onInitListener);
}
@Override
protected String getAnnouncement(TripStatistics stats) {
return mockTask.getAnnouncement(stats);
}
@Override
protected void listenToPhoneState(
PhoneStateListener listener, int events) {
mockTask.listenToPhoneState(listener, events);
}
};
}
@Override
protected void tearDown() {
Locale.setDefault(oldDefaultLocale);
}
public void testStart() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_languageNotSupported() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED);
expect(tts.setLanguage(Locale.ENGLISH))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_notReady() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.ERROR);
AndroidMock.verify(mockTask, tts);
}
public void testShutdown() {
// First, start
doStart();
AndroidMock.verify(mockTask);
AndroidMock.reset(mockTask);
// Then, shut down
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
mockTask.listenToPhoneState(
same(phoneListener), eq(PhoneStateListener.LISTEN_NONE));
tts.shutdown();
AndroidMock.replay(mockTask, tts);
task.shutdown();
AndroidMock.verify(mockTask, tts);
}
public void testRun() throws Exception {
// Expect service data calls
TripStatistics stats = new TripStatistics();
// Expect announcement building call
expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT);
// Put task in "ready" state
startTask(TextToSpeech.SUCCESS);
// Expect actual announcement call
expect(tts.speak(
eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH),
AndroidMock.<HashMap<String, String>>isNull()))
.andReturn(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(stats);
AndroidMock.verify(mockTask, tts);
}
public void testRun_notReady() throws Exception {
// Put task in "not ready" state
startTask(TextToSpeech.ERROR);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_duringCall() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_ringWhileSpeaking() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(true);
expect(tts.stop()).andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
// Update the state to ringing - this should stop the current announcement.
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
// Run the announcement - this should do nothing.
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_whileRinging() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noService() throws Exception {
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noStats() throws Exception {
// Expect service data calls
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero.
*/
public void testGetAnnounceTime_time_zero() {
long time = 0; // 0 seconds
assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one.
*/
public void testGetAnnounceTime_time_one() {
long time = 1 * 1000; // 1 second
assertEquals("0 minutes 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers with the hour unit.
*/
public void testGetAnnounceTime_singular_has_hour() {
long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second
assertEquals("1 hour 1 minute", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* with the hour unit.
*/
public void testGetAnnounceTime_plural_has_hour() {
long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds
assertEquals("2 hours 2 minutes", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers without the hour unit.
*/
public void testGetAnnounceTime_singular_no_hour() {
long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second
assertEquals("1 minute 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* without the hour unit.
*/
public void testGetAnnounceTime_plural_no_hour() {
long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds
assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time));
}
private void startTask(int state) {
AndroidMock.resetToNice(tts);
AndroidMock.replay(tts);
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
ttsInitListener.onInit(state);
AndroidMock.resetToDefault(tts);
}
private void doStart() {
mockTask.listenToPhoneState(capture(phoneListenerCapture),
eq(PhoneStateListener.LISTEN_CALL_STATE));
expect(mockTask.newTextToSpeech(
same(getContext()), capture(initListenerCapture)))
.andStubReturn(ttsDelegate);
AndroidMock.replay(mockTask);
task.start();
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Tests {@link DefaultTrackNameFactory}
*
* @author Matthew Simmons
*/
public class DefaultTrackNameFactoryTest extends AndroidTestCase {
private static final long TRACK_ID = 1L;
private static final long START_TIME = 1288213406000L;
public void testDefaultTrackName_date_local() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_local_value);
}
};
assertEquals(StringUtils.formatDateTime(getContext(), START_TIME),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_date_iso_8601() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_iso_8601_value);
}
};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
DefaultTrackNameFactory.ISO_8601_FORMAT);
assertEquals(simpleDateFormat.format(new Date(START_TIME)),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_number() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_number_value);
}
};
assertEquals(
"Track " + TRACK_ID, defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.IBinder;
import android.test.RenamingDelegatingContext;
import android.test.ServiceTestCase;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for the MyTracks track recording service.
*
* @author Bartlomiej Niechwiej
*
* TODO: The original class, ServiceTestCase, has a few limitations, e.g.
* it's not possible to properly shutdown the service, unless tearDown()
* is called, which prevents from testing multiple scenarios in a single
* test (see runFunctionTest for more details).
*/
public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> {
private Context context;
private MyTracksProviderUtils providerUtils;
private SharedPreferences sharedPreferences;
/*
* In order to support starting and binding to the service in the same
* unit test, we provide a workaround, as the original class doesn't allow
* to bind after the service has been previously started.
*/
private boolean bound;
private Intent serviceIntent;
public TrackRecordingServiceTest() {
super(TestRecordingService.class);
}
/**
* A context wrapper with the user provided {@link ContentResolver}.
*
* TODO: Move to test utils package.
*/
public static class MockContext extends ContextWrapper {
private final ContentResolver contentResolver;
public MockContext(ContentResolver contentResolver, Context base) {
super(base);
this.contentResolver = contentResolver;
}
@Override
public ContentResolver getContentResolver() {
return contentResolver;
}
}
@Override
protected IBinder bindService(Intent intent) {
if (getService() != null) {
if (bound) {
throw new IllegalStateException(
"Service: " + getService() + " is already bound");
}
bound = true;
serviceIntent = intent.cloneFilter();
return getService().onBind(intent);
} else {
return super.bindService(intent);
}
}
@Override
protected void shutdownService() {
if (bound) {
assertNotNull(getService());
getService().onUnbind(serviceIntent);
bound = false;
}
super.shutdownService();
}
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
// Disable auto resume by default.
updateAutoResumePrefs(0, -1);
// No recording track.
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), -1);
editor.apply();
}
@SmallTest
public void testStartable() {
startService(createStartIntent());
assertNotNull(getService());
}
@MediumTest
public void testBindable() {
IBinder service = bindService(createStartIntent());
assertNotNull(service);
}
@MediumTest
public void testResumeAfterReboot_shouldResume() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We expect to resume the previous track.
assertTrue(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(123, service.getRecordingTrackId());
}
// TODO: shutdownService() has a bug and doesn't set mServiceCreated
// to false, thus preventing from a second call to onCreate().
// Report the bug to Android team. Until then, the following tests
// and checks must be commented out.
//
// TODO: If fixed, remove "disabled" prefix from the test name.
@MediumTest
public void disabledTestResumeAfterReboot_simulateReboot() throws Exception {
updateAutoResumePrefs(0, 10);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Simulate recording a track.
long id = service.startNewTrack();
assertTrue(service.isRecording());
assertEquals(id, service.getRecordingTrackId());
shutdownService();
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
assertTrue(getService().isRecording());
}
@MediumTest
public void testResumeAfterReboot_noRecordingTrack() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), false);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it was stopped.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_expiredTrack() throws Exception {
// Insert a dummy track last updated 20 min ago.
createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it has expired.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_tooManyAttempts() throws Exception {
// Insert a dummy track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Set the number of attempts to max.
updateAutoResumePrefs(
TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because there were already
// too many attempts.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_noTracks() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
// Test if we start in no-recording mode by default.
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_oldTracks() throws Exception {
createDummyTrack(123, -1, false);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_orphanedRecordingTrack() throws Exception {
// Just set recording track to a bogus value.
setRecordingTrack(256);
// Make sure that the service will not start recording and will clear
// the bogus track.
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
/**
* Synchronous/waitable broadcast receiver to be used in testing.
*/
private class BlockingBroadcastReceiver extends BroadcastReceiver {
private static final long MAX_WAIT_TIME_MS = 10000;
private List<Intent> receivedIntents = new ArrayList<Intent>();
public List<Intent> getReceivedIntents() {
return receivedIntents;
}
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyTracksTest", "Got broadcast: " + intent);
synchronized (receivedIntents) {
receivedIntents.add(intent);
receivedIntents.notifyAll();
}
}
public boolean waitUntilReceived(int receiveCount) {
long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS;
synchronized (receivedIntents) {
while (receivedIntents.size() < receiveCount) {
try {
// Wait releases synchronized lock until it returns
receivedIntents.wait(500);
} catch (InterruptedException e) {
// Do nothing
}
if (System.currentTimeMillis() > deadline) {
return false;
}
}
}
return true;
}
}
@MediumTest
public void testStartNewTrack_noRecording() throws Exception {
// NOTICE: due to the way Android permissions work, if this fails,
// uninstall the test apk then retry - the test must be installed *after*
// My Tracks (go figure).
// Reference: http://code.google.com/p/android/issues/detail?id=5521
BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver();
String startAction = context.getString(R.string.track_started_broadcast_action);
context.registerReceiver(startReceiver, new IntentFilter(startAction));
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""),
track.getCategory());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Verify that the start broadcast was received.
assertTrue(startReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = startReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(startAction, broadcastIntent.getAction());
assertEquals(id, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(startReceiver);
}
@MediumTest
public void testStartNewTrack_alreadyRecording() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// Starting a new track when there is a recording should just return -1L.
long newTrack = service.startNewTrack();
assertEquals(-1L, newTrack);
assertEquals(123, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(123, service.getRecordingTrackId());
}
@MediumTest
public void testEndCurrentTrack_alreadyRecording() throws Exception {
// See comment above if this fails randomly.
BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver();
String stopAction = context.getString(R.string.track_stopped_broadcast_action);
context.registerReceiver(stopReceiver, new IntentFilter(stopAction));
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// End the current track.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
// Verify that the stop broadcast was received.
assertTrue(stopReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = stopReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(stopAction, broadcastIntent.getAction());
assertEquals(123, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(stopReceiver);
}
@MediumTest
public void testEndCurrentTrack_noRecording() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Ending the current track when there is no recording should not result in any error.
service.endCurrentTrack();
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testIntegration_completeRecordingSession() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
fullRecordingSession();
}
@MediumTest
public void testInsertStatisticsMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertStatisticsMarker_validLocation() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_statistics_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_statistics),
wpt.getName());
assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNotNull(wpt.getStatistics());
// TODO check the rest of the params.
// TODO: Check waypoint 2.
}
@MediumTest
public void testInsertWaypointMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertWaypointMarker_validWaypoint() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_waypoint_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_waypoint),
wpt.getName());
assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNull(wpt.getStatistics());
}
@MediumTest
public void testWithProperties_noAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, 1);
}
@MediumTest
public void testWithProperties_noMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, 5);
}
@MediumTest
public void testWithProperties_noMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, 2);
}
@MediumTest
public void testWithProperties_noSplitFreq() throws Exception {
functionalTest(R.string.split_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByDist() throws Exception {
functionalTest(R.string.split_frequency_key, 5);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByTime() throws Exception {
functionalTest(R.string.split_frequency_key, -2);
}
@MediumTest
public void testWithProperties_noMetricUnits() throws Exception {
functionalTest(R.string.metric_units_key, (Object) null);
}
@MediumTest
public void testWithProperties_metricUnitsEnabled() throws Exception {
functionalTest(R.string.metric_units_key, true);
}
@MediumTest
public void testWithProperties_metricUnitsDisabled() throws Exception {
functionalTest(R.string.metric_units_key, false);
}
@MediumTest
public void testWithProperties_noMinRecordingInterval() throws Exception {
functionalTest(R.string.min_recording_interval_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingInterval()
throws Exception {
functionalTest(R.string.min_recording_interval_key, 3);
}
@MediumTest
public void testWithProperties_noMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, 500);
}
@MediumTest
public void testWithProperties_noSensorType() throws Exception {
functionalTest(R.string.sensor_type_key, (Object) null);
}
@MediumTest
public void testWithProperties_zephyrSensorType() throws Exception {
functionalTest(R.string.sensor_type_key,
context.getString(R.string.sensor_type_value_zephyr));
}
private ITrackRecordingService bindAndGetService(Intent intent) {
ITrackRecordingService service = ITrackRecordingService.Stub.asInterface(
bindService(intent));
assertNotNull(service);
return service;
}
private Track createDummyTrack(long id, long stopTime, boolean isRecording) {
Track dummyTrack = new Track();
dummyTrack.setId(id);
dummyTrack.setName("Dummy Track");
TripStatistics tripStatistics = new TripStatistics();
tripStatistics.setStopTime(stopTime);
dummyTrack.setStatistics(tripStatistics);
addTrack(dummyTrack, isRecording);
return dummyTrack;
}
private void updateAutoResumePrefs(int attempts, int timeoutMins) {
Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(
R.string.auto_resume_track_current_retry_key), attempts);
editor.putInt(context.getString(
R.string.auto_resume_track_timeout_key), timeoutMins);
editor.apply();
}
private Intent createStartIntent() {
Intent startIntent = new Intent();
startIntent.setClass(context, TrackRecordingService.class);
return startIntent;
}
private void addTrack(Track track, boolean isRecording) {
assertTrue(track.getId() >= 0);
providerUtils.insertTrack(track);
assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId());
setRecordingTrack(isRecording ? track.getId() : -1);
}
private void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), id);
editor.apply();
}
// TODO: We support multiple values for readability, however this test's
// base class doesn't properly shutdown the service, so it's not possible
// to pass more than 1 value at a time.
private void functionalTest(int resourceId, Object ...values)
throws Exception {
final String key = context.getString(resourceId);
for (Object value : values) {
// Remove all properties and set the property for the given key.
Editor editor = sharedPreferences.edit();
editor.clear();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value == null) {
// Do nothing, as clear above has already removed this property.
}
editor.apply();
fullRecordingSession();
}
}
private void fullRecordingSession() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Start a track.
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Insert a few points, markers and statistics.
long startTime = System.currentTimeMillis();
for (int i = 0; i < 30; i++) {
Location loc = new Location("gps");
loc.setLongitude(35.0f + i / 10.0f);
loc.setLatitude(45.0f - i / 5.0f);
loc.setAccuracy(5);
loc.setSpeed(10);
loc.setTime(startTime + i * 10000);
loc.setBearing(3.0f);
service.recordLocation(loc);
if (i % 10 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
} else if (i % 7 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
}
}
// Stop the track. Validate if it has correct data.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
TripStatistics tripStatistics = track.getStatistics();
assertNotNull(tripStatistics);
assertTrue(tripStatistics.getStartTime() > 0);
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
| Java |
// Copyright 2012 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.services;
import android.app.Notification;
import android.app.Service;
import android.test.ServiceTestCase;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}.
* {@link ServiceTestCase} throws a null pointer exception when the service
* calls {@link Service#startForeground(int, android.app.Notification)} and
* {@link Service#stopForeground(boolean)}.
* <p>
* See http://code.google.com/p/android/issues/detail?id=12122
* <p>
* Wrap these two methods in wrappers and override them.
*
* @author Jimmy Shih
*/
public class TestRecordingService extends TrackRecordingService {
private static final String TAG = TestRecordingService.class.getSimpleName();
@Override
protected void startForegroundService(Notification notification) {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, true);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
@Override
protected void stopForegroundService() {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, false);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import java.util.Arrays;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class PolarMessageParserTest extends TestCase {
PolarMessageParser parser = new PolarMessageParser();
// A complete and valid Polar HxM packet
// FE08F701D1001104FE08F702D1001104
private final byte[] originalBuf =
{(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08,
(byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04};
private byte[] buf;
public void setUp() {
buf = Arrays.copyOf(originalBuf, originalBuf.length);
}
public void testIsValid() {
assertTrue(parser.isValid(buf));
}
public void testIsValid_invalidHeader() {
// Invalidate header.
buf[0] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidCheckbyte() {
// Invalidate checkbyte.
buf[2] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidSequence() {
// Invalidate sequence.
buf[3] = 0x11;
assertFalse(parser.isValid(buf));
}
public void testParseBuffer() {
buf[5] = 70;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(70, sds.getHeartRate().getValue());
}
public void testFindNextAlignment_offset() {
// The first 4 bytes are garbage
buf = new byte[originalBuf.length + 4];
buf[0] = 4;
buf[1] = 2;
buf[2] = 4;
buf[3] = 2;
// Then the valid message.
System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length);
assertEquals(4, parser.findNextAlignment(buf));
}
public void testFindNextAlignment_invalid() {
buf[0] = 0;
assertEquals(-1, parser.findNextAlignment(buf));
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager;
import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class SensorManagerFactoryTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
@Override
protected void setUp() throws Exception {
super.setUp();
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
}
@SmallTest
public void testDefaultSettings() throws Exception {
assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext()));
}
@SmallTest
public void testCreateZephyr() throws Exception {
assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr);
}
@SmallTest
public void testCreateAnt() throws Exception {
assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant);
}
@SmallTest
public void testCreateAntSRM() throws Exception {
assertClassForName(AntSrmBridgeSensorManager.class, R.string.sensor_type_value_srm_ant_bridge);
}
private void assertClassForName(Class<?> c, int i) {
sharedPreferences.edit()
.putString(getContext().getString(R.string.sensor_type_key),
getContext().getString(i))
.apply();
SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext());
assertNotNull(sm);
assertTrue(c.isInstance(sm));
SensorManagerFactory.getInstance().releaseSensorManager(sm);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntStartupMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0x12,
};
AntStartupMessage message = new AntStartupMessage(rawMessage);
assertEquals(0x12, message.getMessage());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Laszlo Molnar
*/
public class SensorEventCounterTest extends AndroidTestCase {
@SmallTest
public void testGetEventsPerMinute() {
SensorEventCounter sec = new SensorEventCounter();
assertEquals(0, sec.getEventsPerMinute(0, 0, 0));
assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500));
assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntMessageTest extends AndroidTestCase {
private static class TestAntMessage extends AntMessage {
public static short decodeShort(byte low, byte high) {
return AntMessage.decodeShort(low, high);
}
}
public void testDecode() {
assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
public class AntSensorManagerTest extends AndroidTestCase {
private class TestAntSensorManager extends AntSensorManager {
public TestAntSensorManager(Context context) {
super(context);
}
public byte messageId;
public byte[] messageData;
@Override
protected void setupAntSensorChannels() {}
@SuppressWarnings("deprecation")
@Override
public void handleMessage(byte[] rawMessage) {
super.handleMessage(rawMessage);
}
@SuppressWarnings("hiding")
@Override
public boolean handleMessage(byte messageId, byte[] messageData) {
this.messageId = messageId;
this.messageData = messageData;
return true;
}
}
private TestAntSensorManager sensorManager;
@Override
protected void setUp() throws Exception {
super.setUp();
sensorManager = new TestAntSensorManager(getContext());
}
public void testSimple() {
byte[] rawMessage = {
0x03, // length
0x12, // message id
0x11, 0x22, 0x33, // body
};
byte[] expectedBody = { 0x11, 0x22, 0x33 };
sensorManager.handleMessage(rawMessage);
assertEquals((byte) 0x12, sensorManager.messageId);
MoreAsserts.assertEquals(expectedBody, sensorManager.messageData);
}
public void testTooShort() {
byte[] rawMessage = {
0x53, // length
0x12 // message id
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
public void testLengthWrong() {
byte[] rawMessage = {
0x53, // length
0x12, // message id
0x34, // body
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntChannelIdMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0, // channel number
0x34, 0x12, // device number
(byte) 0xaa, // device type id
(byte) 0xbb, // transmission type
};
AntChannelIdMessage message = new AntChannelIdMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(0x1234, message.getDeviceNumber());
assertEquals((byte) 0xaa, message.getDeviceTypeId());
assertEquals((byte) 0xbb, message.getTransmissionType());
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntMesg;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class AntDirectSensorManagerTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
private AntSensorBase heartRateSensor;
private static final byte HEART_RATE_CHANNEL = 0;
private class MockAntDirectSensorManager extends AntDirectSensorManager {
public MockAntDirectSensorManager(Context context) {
super(context);
}
@Override
protected boolean setupChannel(AntSensorBase sensor, byte channel) {
if (channel == HEART_RATE_CHANNEL) {
heartRateSensor = sensor;
return true;
}
return false;
}
}
private AntDirectSensorManager manager;
public void setUp() {
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
manager = new MockAntDirectSensorManager(getContext());
}
@SmallTest
public void testBroadcastData() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
heartRateSensor.setDeviceNumber((short) 42);
byte[] buff = new byte[9];
buff[0] = HEART_RATE_CHANNEL;
buff[8] = (byte) 220;
manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff);
Sensor.SensorDataSet sds = manager.getSensorDataSet();
assertNotNull(sds);
assertTrue(sds.hasHeartRate());
assertEquals(Sensor.SensorState.SENDING,
sds.getHeartRate().getState());
assertEquals(220, sds.getHeartRate().getValue());
assertFalse(sds.hasCadence());
assertFalse(sds.hasPower());
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
}
@SmallTest
public void testChannelId() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
byte[] buff = new byte[9];
buff[1] = 43;
manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff);
assertEquals(43, heartRateSensor.getDeviceNumber());
assertEquals(43,
sharedPreferences.getInt(
getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1));
assertNull(manager.getSensorDataSet());
}
@SmallTest
public void testResponseEvent() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
manager.setHeartRate(210);
heartRateSensor.setDeviceNumber((short) 42);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
byte[] buff = new byte[3];
buff[0] = HEART_RATE_CHANNEL;
buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
buff[2] = 0; // code
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
heartRateSensor.setDeviceNumber((short) 0);
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState());
}
// TODO: Test timeout too.
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntDefine;
import com.dsi.ant.AntMesg;
import android.test.AndroidTestCase;
public class AntChannelResponseMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0,
AntMesg.MESG_EVENT_ID,
AntDefine.EVENT_RX_SEARCH_TIMEOUT
};
AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId());
assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode());
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class ZephyrMessageParserTest extends TestCase {
ZephyrMessageParser parser = new ZephyrMessageParser();
public void testIsValid() {
byte[] smallBuf = new byte[59];
assertFalse(parser.isValid(smallBuf));
// A complete and valid Zephyr HxM packet
byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 };
// Make buffer invalid
buf[0] = buf[58] = buf[59] = 0;
assertFalse(parser.isValid(buf));
buf[0] = 0x02;
assertFalse(parser.isValid(buf));
buf[58] = 0x1E;
assertFalse(parser.isValid(buf));
buf[59] = 0x03;
assertTrue(parser.isValid(buf));
}
public void testParseBuffer() {
byte[] buf = new byte[60];
// Heart Rate (-1 =^ 255 unsigned byte)
buf[12] = -1;
// Battery Level
buf[11] = 51;
// Cadence (=^ 255*16 strides/min)
buf[56] = -1;
buf[57] = 15;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getHeartRate().getValue());
assertTrue(sds.hasBatteryLevel());
assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING);
assertEquals(51, sds.getBatteryLevel().getValue());
assertTrue(sds.hasCadence());
assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getCadence().getValue());
}
public void testFindNextAlignment() {
byte[] buf = new byte[60];
assertEquals(-1, parser.findNextAlignment(buf));
buf[10] = 0x03;
buf[11] = 0x02;
assertEquals(10, parser.findNextAlignment(buf));
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.stats;
/**
* A helper class that tracks a minimum and a maximum of a variable.
*
* @author Sandor Dornbush
*/
public class ExtremityMonitor {
/**
* The smallest value seen so far.
*/
private double min;
/**
* The largest value seen so far.
*/
private double max;
public ExtremityMonitor() {
reset();
}
/**
* Updates the min and the max with the new value.
*
* @param value the new value for the monitor
* @return true if an extremity was found
*/
public boolean update(double value) {
boolean changed = false;
if (value < min) {
min = value;
changed = true;
}
if (value > max) {
max = value;
changed = true;
}
return changed;
}
/**
* Gets the minimum value seen.
*
* @return The minimum value passed into the update() function
*/
public double getMin() {
return min;
}
/**
* Gets the maximum value seen.
*
* @return The maximum value passed into the update() function
*/
public double getMax() {
return max;
}
/**
* Resets this object to it's initial state where the min and max are unknown.
*/
public void reset() {
min = Double.POSITIVE_INFINITY;
max = Double.NEGATIVE_INFINITY;
}
/**
* Sets the minimum and maximum values.
*/
public void set(double min, double max) {
this.min = min;
this.max = max;
}
/**
* Sets the minimum value.
*/
public void setMin(double min) {
this.min = min;
}
/**
* Sets the maximum value.
*/
public void setMax(double max) {
this.max = max;
}
public boolean hasData() {
return min != Double.POSITIVE_INFINITY
&& max != Double.NEGATIVE_INFINITY;
}
@Override
public String toString() {
return "Min: " + min + " Max: " + max;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.stats;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Statistical data about a trip.
* The data in this class should be filled out by TripStatisticsBuilder.
*
* TODO: hashCode and equals
*
* @author Rodrigo Damazio
*/
public class TripStatistics implements Parcelable {
/**
* The start time for the trip. This is system time which might not match gps
* time.
*/
private long startTime = -1L;
/**
* The stop time for the trip. This is the system time which might not match
* gps time.
*/
private long stopTime = -1L;
/**
* The total time that we believe the user was traveling in milliseconds.
*/
private long movingTime;
/**
* The total time of the trip in milliseconds.
* This is only updated when new points are received, so it may be stale.
*/
private long totalTime;
/**
* The total distance in meters that the user traveled on this trip.
*/
private double totalDistance;
/**
* The total elevation gained on this trip in meters.
*/
private double totalElevationGain;
/**
* The maximum speed in meters/second reported that we believe to be a valid
* speed.
*/
private double maxSpeed;
/**
* The min and max latitude values seen in this trip.
*/
private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor();
/**
* The min and max longitude values seen in this trip.
*/
private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor();
/**
* The min and max elevation seen on this trip in meters.
*/
private final ExtremityMonitor elevationExtremities = new ExtremityMonitor();
/**
* The minimum and maximum grade calculations on this trip.
*/
private final ExtremityMonitor gradeExtremities = new ExtremityMonitor();
/**
* Default constructor.
*/
public TripStatistics() {
}
/**
* Copy constructor.
*
* @param other another statistics data object to copy from
*/
public TripStatistics(TripStatistics other) {
this.maxSpeed = other.maxSpeed;
this.movingTime = other.movingTime;
this.startTime = other.startTime;
this.stopTime = other.stopTime;
this.totalDistance = other.totalDistance;
this.totalElevationGain = other.totalElevationGain;
this.totalTime = other.totalTime;
this.latitudeExtremities.set(other.latitudeExtremities.getMin(),
other.latitudeExtremities.getMax());
this.longitudeExtremities.set(other.longitudeExtremities.getMin(),
other.longitudeExtremities.getMax());
this.elevationExtremities.set(other.elevationExtremities.getMin(),
other.elevationExtremities.getMax());
this.gradeExtremities.set(other.gradeExtremities.getMin(),
other.gradeExtremities.getMax());
}
/**
* Combines these statistics with those from another object.
* This assumes that the time periods covered by each do not intersect.
*
* @param other the other waypoint
*/
public void merge(TripStatistics other) {
startTime = Math.min(startTime, other.startTime);
stopTime = Math.max(stopTime, other.stopTime);
totalTime += other.totalTime;
movingTime += other.movingTime;
totalDistance += other.totalDistance;
totalElevationGain += other.totalElevationGain;
maxSpeed = Math.max(maxSpeed, other.maxSpeed);
latitudeExtremities.update(other.latitudeExtremities.getMax());
latitudeExtremities.update(other.latitudeExtremities.getMin());
longitudeExtremities.update(other.longitudeExtremities.getMax());
longitudeExtremities.update(other.longitudeExtremities.getMin());
elevationExtremities.update(other.elevationExtremities.getMax());
elevationExtremities.update(other.elevationExtremities.getMin());
gradeExtremities.update(other.gradeExtremities.getMax());
gradeExtremities.update(other.gradeExtremities.getMin());
}
/**
* Gets the time that this track started.
*
* @return The number of milliseconds since epoch to the time when this track
* started
*/
public long getStartTime() {
return startTime;
}
/**
* Gets the time that this track stopped.
*
* @return The number of milliseconds since epoch to the time when this track
* stopped
*/
public long getStopTime() {
return stopTime;
}
/**
* Gets the total time that this track has been active.
* This statistic is only updated when a new point is added to the statistics,
* so it may be off. If you need to calculate the proper total time, use
* {@link #getStartTime} with the current time.
*
* @return The total number of milliseconds the track was active
*/
public long getTotalTime() {
return totalTime;
}
/**
* Gets the total distance the user traveled.
*
* @return The total distance traveled in meters
*/
public double getTotalDistance() {
return totalDistance;
}
/**
* Gets the the average speed the user traveled.
* This calculation only takes into account the displacement until the last
* point that was accounted for in statistics.
*
* @return The average speed in m/s
*/
public double getAverageSpeed() {
if (totalTime == 0L) {
return 0.0;
}
return totalDistance / ((double) totalTime / 1000.0);
}
/**
* Gets the the average speed the user traveled when they were actively
* moving.
*
* @return The average moving speed in m/s
*/
public double getAverageMovingSpeed() {
if (movingTime == 0L) {
return 0.0;
}
return totalDistance / ((double) movingTime / 1000.0);
}
/**
* Gets the the maximum speed for this track.
*
* @return The maximum speed in m/s
*/
public double getMaxSpeed() {
return maxSpeed;
}
/**
* Gets the moving time.
*
* @return The total number of milliseconds the user was moving
*/
public long getMovingTime() {
return movingTime;
}
/**
* Gets the total elevation gain for this trip. This is calculated as the sum
* of all positive differences in the smoothed elevation.
*
* @return The elevation gain in meters for this trip
*/
public double getTotalElevationGain() {
return totalElevationGain;
}
/**
* Returns the leftmost position (lowest longitude) of the track, in signed degrees.
*/
public double getLeftDegrees() {
return longitudeExtremities.getMin();
}
/**
* Returns the leftmost position (lowest longitude) of the track, in signed millions of degrees.
*/
public int getLeft() {
return (int) (longitudeExtremities.getMin() * 1E6);
}
/**
* Returns the rightmost position (highest longitude) of the track, in signed degrees.
*/
public double getRightDegrees() {
return longitudeExtremities.getMax();
}
/**
* Returns the rightmost position (highest longitude) of the track, in signed millions of degrees.
*/
public int getRight() {
return (int) (longitudeExtremities.getMax() * 1E6);
}
/**
* Returns the bottommost position (lowest latitude) of the track, in signed degrees.
*/
public double getBottomDegrees() {
return latitudeExtremities.getMin();
}
/**
* Returns the bottommost position (lowest latitude) of the track, in signed millions of degrees.
*/
public int getBottom() {
return (int) (latitudeExtremities.getMin() * 1E6);
}
/**
* Returns the topmost position (highest latitude) of the track, in signed degrees.
*/
public double getTopDegrees() {
return latitudeExtremities.getMax();
}
/**
* Returns the topmost position (highest latitude) of the track, in signed millions of degrees.
*/
public int getTop() {
return (int) (latitudeExtremities.getMax() * 1E6);
}
/**
* Returns the mean position (center latitude) of the track, in signed degrees.
*/
public double getMeanLatitude() {
return (getBottomDegrees() + getTopDegrees()) / 2.0;
}
/**
* Returns the mean position (center longitude) of the track, in signed degrees.
*/
public double getMeanLongitude() {
return (getLeftDegrees() + getRightDegrees()) / 2.0;
}
/**
* Gets the minimum elevation seen on this trip. This is calculated from the
* smoothed elevation so this can actually be more than the current elevation.
*
* @return The smallest elevation reading for this trip in meters
*/
public double getMinElevation() {
return elevationExtremities.getMin();
}
/**
* Gets the maximum elevation seen on this trip. This is calculated from the
* smoothed elevation so this can actually be less than the current elevation.
*
* @return The largest elevation reading for this trip in meters
*/
public double getMaxElevation() {
return elevationExtremities.getMax();
}
/**
* Gets the maximum grade for this trip.
*
* @return The maximum grade for this trip as a fraction
*/
public double getMaxGrade() {
return gradeExtremities.getMax();
}
/**
* Gets the minimum grade for this trip.
*
* @return The minimum grade for this trip as a fraction
*/
public double getMinGrade() {
return gradeExtremities.getMin();
}
// Setters - to be used when restoring state or loading from the DB
/**
* Sets the start time for this trip.
*
* @param startTime the start time, in milliseconds since the epoch
*/
public void setStartTime(long startTime) {
this.startTime = startTime;
}
/**
* Sets the stop time for this trip.
*
* @param stopTime the stop time, in milliseconds since the epoch
*/
public void setStopTime(long stopTime) {
this.stopTime = stopTime;
}
/**
* Sets the total moving time.
*
* @param movingTime the moving time in milliseconds
*/
public void setMovingTime(long movingTime) {
this.movingTime = movingTime;
}
/**
* Sets the total trip time.
*
* @param totalTime the total trip time in milliseconds
*/
public void setTotalTime(long totalTime) {
this.totalTime = totalTime;
}
/**
* Sets the total trip distance.
*
* @param totalDistance the trip distance in meters
*/
public void setTotalDistance(double totalDistance) {
this.totalDistance = totalDistance;
}
/**
* Sets the total elevation variation during the trip.
*
* @param totalElevationGain the elevation variation in meters
*/
public void setTotalElevationGain(double totalElevationGain) {
this.totalElevationGain = totalElevationGain;
}
/**
* Sets the maximum speed reached during the trip.
*
* @param maxSpeed the maximum speed in meters per second
*/
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
/**
* Sets the minimum elevation reached during the trip.
*
* @param elevation the minimum elevation in meters
*/
public void setMinElevation(double elevation) {
elevationExtremities.setMin(elevation);
}
/**
* Sets the maximum elevation reached during the trip.
*
* @param elevation the maximum elevation in meters
*/
public void setMaxElevation(double elevation) {
elevationExtremities.setMax(elevation);
}
/**
* Sets the minimum grade obtained during the trip.
*
* @param grade the grade as a fraction (-1.0 would mean vertical downwards)
*/
public void setMinGrade(double grade) {
gradeExtremities.setMin(grade);
}
/**
* Sets the maximum grade obtained during the trip).
*
* @param grade the grade as a fraction (1.0 would mean vertical upwards)
*/
public void setMaxGrade(double grade) {
gradeExtremities.setMax(grade);
}
/**
* Sets the bounding box for this trip.
* The unit for all parameters is signed decimal degrees (degrees * 1E6).
*
* @param leftE6 the westmost longitude reached
* @param topE6 the northmost latitude reached
* @param rightE6 the eastmost longitude reached
* @param bottomE6 the southmost latitude reached
*/
public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) {
latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6);
longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6);
}
// Data manipulation methods
/**
* Adds to the current total distance.
*
* @param distance the distance to add in meters
*/
void addTotalDistance(double distance) {
totalDistance += distance;
}
/**
* Adds to the total elevation variation.
*
* @param gain the elevation variation in meters
*/
void addTotalElevationGain(double gain) {
totalElevationGain += gain;
}
/**
* Adds to the total moving time of the trip.
*
* @param time the time in milliseconds
*/
void addMovingTime(long time) {
movingTime += time;
}
/**
* Accounts for a new latitude value for the bounding box.
*
* @param latitude the latitude value in signed decimal degrees
*/
void updateLatitudeExtremities(double latitude) {
latitudeExtremities.update(latitude);
}
/**
* Accounts for a new longitude value for the bounding box.
*
* @param longitude the longitude value in signed decimal degrees
*/
void updateLongitudeExtremities(double longitude) {
longitudeExtremities.update(longitude);
}
/**
* Accounts for a new elevation value for the bounding box.
*
* @param elevation the elevation value in meters
*/
void updateElevationExtremities(double elevation) {
elevationExtremities.update(elevation);
}
/**
* Accounts for a new grade value.
*
* @param grade the grade value as a fraction
*/
void updateGradeExtremities(double grade) {
gradeExtremities.update(grade);
}
// String conversion
@Override
public String toString() {
return "TripStatistics { Start Time: " + getStartTime()
+ "; Total Time: " + getTotalTime()
+ "; Moving Time: " + getMovingTime()
+ "; Total Distance: " + getTotalDistance()
+ "; Elevation Gain: " + getTotalElevationGain()
+ "; Min Elevation: " + getMinElevation()
+ "; Max Elevation: " + getMaxElevation()
+ "; Average Speed: " + getAverageMovingSpeed()
+ "; Min Grade: " + getMinGrade()
+ "; Max Grade: " + getMaxGrade()
+ "}";
}
// Parcelable interface and creator
/**
* Creator of statistics data from parcels.
*/
public static class Creator
implements Parcelable.Creator<TripStatistics> {
@Override
public TripStatistics createFromParcel(Parcel source) {
TripStatistics data = new TripStatistics();
data.startTime = source.readLong();
data.movingTime = source.readLong();
data.totalTime = source.readLong();
data.totalDistance = source.readDouble();
data.totalElevationGain = source.readDouble();
data.maxSpeed = source.readDouble();
double minLat = source.readDouble();
double maxLat = source.readDouble();
data.latitudeExtremities.set(minLat, maxLat);
double minLong = source.readDouble();
double maxLong = source.readDouble();
data.longitudeExtremities.set(minLong, maxLong);
double minElev = source.readDouble();
double maxElev = source.readDouble();
data.elevationExtremities.set(minElev, maxElev);
double minGrade = source.readDouble();
double maxGrade = source.readDouble();
data.gradeExtremities.set(minGrade, maxGrade);
return data;
}
@Override
public TripStatistics[] newArray(int size) {
return new TripStatistics[size];
}
}
/**
* Creator of {@link TripStatistics} from parcels.
*/
public static final Creator CREATOR = new Creator();
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(startTime);
dest.writeLong(movingTime);
dest.writeLong(totalTime);
dest.writeDouble(totalDistance);
dest.writeDouble(totalElevationGain);
dest.writeDouble(maxSpeed);
dest.writeDouble(latitudeExtremities.getMin());
dest.writeDouble(latitudeExtremities.getMax());
dest.writeDouble(longitudeExtremities.getMin());
dest.writeDouble(longitudeExtremities.getMax());
dest.writeDouble(elevationExtremities.getMin());
dest.writeDouble(elevationExtremities.getMax());
dest.writeDouble(gradeExtremities.getMin());
dest.writeDouble(gradeExtremities.getMax());
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.location.Location;
/**
* This class extends the standard Android location with extra information.
*
* @author Sandor Dornbush
*/
public class MyTracksLocation extends Location {
private Sensor.SensorDataSet sensorDataSet = null;
/**
* The id of this location from the provider.
*/
private int id = -1;
public MyTracksLocation(Location location, Sensor.SensorDataSet sd) {
super(location);
this.sensorDataSet = sd;
}
public MyTracksLocation(String provider) {
super(provider);
}
public Sensor.SensorDataSet getSensorDataSet() {
return sensorDataSet;
}
public void setSensorData(Sensor.SensorDataSet sensorData) {
this.sensorDataSet = sensorData;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void reset() {
super.reset();
sensorDataSet = null;
id = -1;
}
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Defines the URI for the tracks provider and the available column names
* and content types.
*
* @author Leif Hendrik Wilden
*/
public interface TracksColumns extends BaseColumns {
public static final Uri CONTENT_URI =
Uri.parse("content://com.google.android.maps.mytracks/tracks");
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.google.track";
public static final String CONTENT_ITEMTYPE =
"vnd.android.cursor.item/vnd.google.track";
public static final String DEFAULT_SORT_ORDER = "_id";
/* All columns */
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String CATEGORY = "category";
public static final String STARTID = "startid";
public static final String STOPID = "stopid";
public static final String STARTTIME = "starttime";
public static final String STOPTIME = "stoptime";
public static final String NUMPOINTS = "numpoints";
public static final String TOTALDISTANCE = "totaldistance";
public static final String TOTALTIME = "totaltime";
public static final String MOVINGTIME = "movingtime";
public static final String AVGSPEED = "avgspeed";
public static final String AVGMOVINGSPEED = "avgmovingspeed";
public static final String MAXSPEED = "maxspeed";
public static final String MINELEVATION = "minelevation";
public static final String MAXELEVATION = "maxelevation";
public static final String ELEVATIONGAIN = "elevationgain";
public static final String MINGRADE = "mingrade";
public static final String MAXGRADE = "maxgrade";
public static final String MINLAT = "minlat";
public static final String MAXLAT = "maxlat";
public static final String MINLON = "minlon";
public static final String MAXLON = "maxlon";
public static final String MAPID = "mapid";
public static final String TABLEID = "tableid";
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A request for the service to create a waypoint at the current location.
*
* @author Sandor Dornbush
*/
public class WaypointCreationRequest implements Parcelable {
public static enum WaypointType {
MARKER,
STATISTICS;
}
private WaypointType type;
private String name;
private String description;
private String iconUrl;
public final static WaypointCreationRequest DEFAULT_MARKER =
new WaypointCreationRequest(WaypointType.MARKER);
public final static WaypointCreationRequest DEFAULT_STATISTICS =
new WaypointCreationRequest(WaypointType.STATISTICS);
private WaypointCreationRequest(WaypointType type) {
this.type = type;
}
public WaypointCreationRequest(WaypointType type, String name,
String description, String iconUrl) {
this.type = type;
this.name = name;
this.description = description;
this.iconUrl = iconUrl;
}
public static class Creator implements Parcelable.Creator<WaypointCreationRequest> {
@Override
public WaypointCreationRequest createFromParcel(Parcel source) {
int i = source.readInt();
if (i > WaypointType.values().length) {
throw new IllegalArgumentException("Could not find waypoint type: " + i);
}
WaypointCreationRequest request = new WaypointCreationRequest(WaypointType.values()[i]);
request.description = source.readString();
request.iconUrl = source.readString();
request.name = source.readString();
return request;
}
public WaypointCreationRequest[] newArray(int size) {
return new WaypointCreationRequest[size];
}
}
public static final Creator CREATOR = new Creator();
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int arg1) {
parcel.writeInt(type.ordinal());
parcel.writeString(description);
parcel.writeString(iconUrl);
parcel.writeString(name);
}
public WaypointType getType() {
return type;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
} | Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A way point. It has a location, meta data such as name, description,
* category, and icon, plus it can store track statistics for a "sub-track".
*
* TODO: hashCode and equals
*
* @author Leif Hendrik Wilden
* @author Rodrigo Damazio
*/
public final class Waypoint implements Parcelable {
/**
* Creator for a Waypoint object
*/
public static class Creator implements Parcelable.Creator<Waypoint> {
public Waypoint createFromParcel(Parcel source) {
ClassLoader classLoader = getClass().getClassLoader();
Waypoint waypoint = new Waypoint();
waypoint.id = source.readLong();
waypoint.name = source.readString();
waypoint.description = source.readString();
waypoint.category = source.readString();
waypoint.icon = source.readString();
waypoint.trackId = source.readLong();
waypoint.type = source.readInt();
waypoint.startId = source.readLong();
waypoint.stopId = source.readLong();
byte hasStats = source.readByte();
if (hasStats > 0) {
waypoint.stats = source.readParcelable(classLoader);
}
byte hasLocation = source.readByte();
if (hasLocation > 0) {
waypoint.location = source.readParcelable(classLoader);
}
return waypoint;
}
public Waypoint[] newArray(int size) {
return new Waypoint[size];
}
}
public static final Creator CREATOR = new Creator();
public static final int TYPE_WAYPOINT = 0;
public static final int TYPE_STATISTICS = 1;
private long id = -1;
private String name = "";
private String description = "";
private String category = "";
private String icon = "";
private long trackId = -1;
private int type = 0;
private Location location;
/** Start track point id */
private long startId = -1;
/** Stop track point id */
private long stopId = -1;
private TripStatistics stats;
/** The length of the track, without smoothing. */
private double length;
/** The total duration of the track (not from the last waypoint) */
private long duration;
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(category);
dest.writeString(icon);
dest.writeLong(trackId);
dest.writeInt(type);
dest.writeLong(startId);
dest.writeLong(stopId);
dest.writeByte(stats == null ? (byte) 0 : (byte) 1);
if (stats != null) {
dest.writeParcelable(stats, 0);
}
dest.writeByte(location == null ? (byte) 0 : (byte) 1);
if (location != null) {
dest.writeParcelable(location, 0);
}
}
// Getters and setters:
//---------------------
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Location getLocation() {
return location;
}
public void setTrackId(long trackId) {
this.trackId = trackId;
}
public int describeContents() {
return 0;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTrackId() {
return trackId;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getStartId() {
return startId;
}
public void setStartId(long startId) {
this.startId = startId;
}
public long getStopId() {
return stopId;
}
public void setStopId(long stopId) {
this.stopId = stopId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setLocation(Location location) {
this.location = location;
}
public TripStatistics getStatistics() {
return stats;
}
public void setStatistics(TripStatistics stats) {
this.stats = stats;
}
// WARNING: These fields are used for internal state keeping. You probably
// want to look at getStatistics instead.
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import java.util.Iterator;
import java.util.List;
/**
* Utility to access data from the mytracks content provider.
*
* @author Rodrigo Damazio
*/
public interface MyTracksProviderUtils {
/**
* Authority (first part of URI) for the MyTracks content provider:
*/
public static final String AUTHORITY = "com.google.android.maps.mytracks";
/**
* Deletes all tracks (including track points) from the provider.
*/
void deleteAllTracks();
/**
* Deletes a track with the given track id.
*
* @param trackId the unique track id
*/
void deleteTrack(long trackId);
/**
* Deletes a way point with the given way point id.
* This will also correct the next statistics way point after the deleted one
* to reflect the deletion.
* The generator is needed to stitch together statistics waypoints.
*
* @param waypointId the unique way point id
* @param descriptionGenerator the class to generate descriptions
*/
void deleteWaypoint(long waypointId,
DescriptionGenerator descriptionGenerator);
/**
* Finds the next statistics waypoint after the given waypoint.
*
* @param waypoint a given waypoint
* @return the next statistics waypoint, or null if none found.
*/
Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint);
/**
* Updates the waypoint in the provider.
*
* @param waypoint
* @return true if successful
*/
boolean updateWaypoint(Waypoint waypoint);
/**
* Finds the last recorded location from the location provider.
*
* @return the last location, or null if no locations available
*/
Location getLastLocation();
/**
* Finds the first recorded waypoint for a given track from the location
* provider.
* This is a special waypoint that holds the stats for current segment.
*
* @param trackId the id of the track the waypoint belongs to
* @return the first waypoint, or null if no waypoints available
*/
Waypoint getFirstWaypoint(long trackId);
/**
* Finds the given waypoint from the location provider.
*
* @param waypointId
* @return the waypoint, or null if it does not exist
*/
Waypoint getWaypoint(long waypointId);
/**
* Finds the last recorded location id from the track points provider.
*
* @param trackId find last location on this track
* @return the location id, or -1 if no locations available
*/
long getLastLocationId(long trackId);
/**
* Finds the id of the 1st waypoint for a given track.
* The 1st waypoint is special as it contains the stats for the current
* segment.
*
* @param trackId find last location on this track
* @return the waypoint id, or -1 if no waypoints are available
*/
long getFirstWaypointId(long trackId);
/**
* Finds the id of the 1st waypoint for a given track.
* The 1st waypoint is special as it contains the stats for the current
* segment.
*
* @param trackId find last location on this track
* @return the waypoint id, or -1 if no waypoints are available
*/
long getLastWaypointId(long trackId);
/**
* Finds the last recorded track from the track provider.
*
* @return the last track, or null if no tracks available
*/
Track getLastTrack();
/**
* Finds the last recorded track id from the tracks provider.
*
* @return the track id, or -1 if no tracks available
*/
long getLastTrackId();
/**
* Finds a location by given unique id.
*
* @param id the desired id
* @return a Location object, or null if not found
*/
Location getLocation(long id);
/**
* Creates a cursor over the locations in the track points provider which
* iterates over a given range of unique ids.
* Caller owns the returned cursor and is responsible for closing it.
*
* @param trackId the id of the track for which to get the points
* @param minTrackPointId the minimum id for the track points
* @param maxLocations maximum number of locations retrieved
* @param descending if true the results will be returned in descending id
* order (latest location first)
* @return A cursor over the selected range of locations
*/
Cursor getLocationsCursor(long trackId, long minTrackPointId,
int maxLocations, boolean descending);
/**
* Creates a cursor over the waypoints of a track.
* Caller owns the returned cursor and is responsible for closing it.
*
* @param trackId the id of the track for which to get the points
* @param minWaypointId the minimum id for the track points
* @param maxWaypoints the maximum number of waypoints to return
* @return A cursor over the selected range of locations
*/
Cursor getWaypointsCursor(long trackId, long minWaypointId,
int maxWaypoints);
/**
* Creates a cursor over waypoints with the given selection.
* Caller owns the returned cursor and is responsible for closing it.
*
* @param selection a given selection
* @param selectionArgs arguments for the given selection
* @param order the order in which to return results
* @param maxWaypoints the maximum number of waypoints to return
* @return a cursor of the selected waypoints
*/
Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints);
/**
* Finds a track by given unique track id.
* Note that the returned track object does not have any track points attached.
* Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load
* the track points.
*
* @param id desired unique track id
* @return a Track object, or null if not found
*/
Track getTrack(long id);
/**
* Retrieves all tracks without track points. If no tracks exist, an empty
* list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)}
* to load the track points.
*
* @return a list of all the recorded tracks
*/
List<Track> getAllTracks();
/**
* Creates a cursor over the tracks provider with a given selection.
* Caller owns the returned cursor and is responsible for closing it.
*
* @param selection a given selection
* @param selectionArgs parameters for the given selection
* @param order the order to return results in
* @return a cursor of the selected tracks
*/
Cursor getTracksCursor(String selection, String[] selectionArgs, String order);
/**
* Inserts a track in the tracks provider.
* Note: This does not insert any track points.
* Use {@link #insertTrackPoint(Location, long)} to insert them.
*
* @param track the track to insert
* @return the content provider URI for the inserted track
*/
Uri insertTrack(Track track);
/**
* Inserts a track point in the tracks provider.
*
* @param location the location to insert
* @return the content provider URI for the inserted track point
*/
Uri insertTrackPoint(Location location, long trackId);
/**
* Inserts multiple track points in a single operation.
*
* @param locations an array of locations to insert
* @param length the number of locations (from the beginning of the array)
* to actually insert, or -1 for all of them
* @param trackId the ID of the track to insert the points into
* @return the number of points inserted
*/
int bulkInsertTrackPoints(Location[] locations, int length, long trackId);
/**
* Inserts a waypoint in the provider.
*
* @param waypoint the waypoint to insert
* @return the content provider URI for the inserted track
*/
Uri insertWaypoint(Waypoint waypoint);
/**
* Tests if a track with given id exists.
*
* @param id the unique id
* @return true if track exists
*/
boolean trackExists(long id);
/**
* Updates a track in the content provider.
* Note: This will not update any track points.
*
* @param track a given track
*/
void updateTrack(Track track);
/**
* Creates a Track object from a given cursor.
*
* @param cursor a cursor pointing at a db or provider with tracks
* @return a new Track object
*/
Track createTrack(Cursor cursor);
/**
* Creates the ContentValues for a given Track object.
*
* Note: If the track has an id<0 the id column will not be filled.
*
* @param track a given track object
* @return a filled in ContentValues object
*/
ContentValues createContentValues(Track track);
/**
* Creates a location object from a given cursor.
*
* @param cursor a cursor pointing at a db or provider with locations
* @return a new location object
*/
Location createLocation(Cursor cursor);
/**
* Fill a location object with values from a given cursor.
*
* @param cursor a cursor pointing at a db or provider with locations
* @param location a location object to be overwritten
*/
void fillLocation(Cursor cursor, Location location);
/**
* Creates a waypoint object from a given cursor.
*
* @param cursor a cursor pointing at a db or provider with waypoints.
* @return a new waypoint object
*/
Waypoint createWaypoint(Cursor cursor);
/**
* A lightweight wrapper around the original {@link Cursor} with a method to clean up.
*/
interface LocationIterator extends Iterator<Location> {
/**
* Returns ID of the most recently retrieved track point through a call to {@link #next()}.
*
* @return the ID of the most recent track point ID.
*/
long getLocationId();
/**
* Should be called in case the underlying iterator hasn't reached the last record.
* Calling it if it has reached the last record is a no-op.
*/
void close();
}
/**
* A factory for creating new {@class Location}s.
*/
interface LocationFactory {
/**
* Creates a new {@link Location} object to be populated from the underlying database record.
* It's up to the implementing class to decide whether to create a new instance or reuse
* existing to optimize for speed.
*
* @return a {@link Location} to be populated from the database.
*/
Location createLocation();
}
/**
* The default {@class Location}s factory, which creates a new location of 'gps' type.
*/
LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() {
@Override
public Location createLocation() {
return new Location("gps");
}
};
/**
* A location factory which uses two location instances (one for the current location,
* and one for the previous), useful when we need to keep the last location.
*/
public class DoubleBufferedLocationFactory implements LocationFactory {
private final Location locs[] = new MyTracksLocation[] {
new MyTracksLocation("gps"),
new MyTracksLocation("gps")
};
private int lastLoc = 0;
@Override
public Location createLocation() {
lastLoc = (lastLoc + 1) % locs.length;
return locs[lastLoc];
}
}
/**
* Creates a new read-only iterator over all track points for the given track. It provides
* a lightweight way of iterating over long tracks without failing due to the underlying cursor
* limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws
* {@class UnsupportedOperationException}.
*
* Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so,
* the iterator calls {@link LocationFactory#createLocation()} and populates it with information
* retrieved from the record.
*
* When done with iteration, you must call {@link LocationIterator#close()} to make sure that all
* resources are properly deallocated.
*
* Example use:
* <code>
* ...
* LocationIterator it = providerUtils.getLocationIterator(
* 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
* try {
* for (Location loc : it) {
* ... // Do something useful with the location.
* }
* } finally {
* it.close();
* }
* ...
* </code>
*
* @param trackId the ID of a track to retrieve locations for.
* @param startTrackPointId the ID of the first track point to load, or -1 to start from
* the first point.
* @param descending if true the results will be returned in descending ID
* order (latest location first).
* @param locationFactory the factory for creating new locations.
*
* @return the read-only iterator over the given track's points.
*/
LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending,
LocationFactory locationFactory);
/**
* A factory which can produce instances of {@link MyTracksProviderUtils},
* and can be overridden in tests (a.k.a. poor man's guice).
*/
public static class Factory {
private static Factory instance = new Factory();
/**
* Creates and returns an instance of {@link MyTracksProviderUtils} which
* uses the given context to access its data.
*/
public static MyTracksProviderUtils get(Context context) {
return instance.newForContext(context);
}
/**
* Returns the global instance of this factory.
*/
public static Factory getInstance() {
return instance;
}
/**
* Overrides the global instance for this factory, to be used for testing.
* If used, don't forget to set it back to the original value after the
* test is run.
*/
public static void overrideInstance(Factory factory) {
instance = factory;
}
/**
* Creates an instance of {@link MyTracksProviderUtils}.
*/
protected MyTracksProviderUtils newForContext(Context context) {
return new MyTracksProviderUtilsImpl(context.getContentResolver());
}
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Defines the URI for the tracks provider and the available column names
* and content types.
*
* @author Leif Hendrik Wilden
*/
public interface WaypointsColumns extends BaseColumns {
public static final Uri CONTENT_URI =
Uri.parse("content://com.google.android.maps.mytracks/waypoints");
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.google.waypoint";
public static final String CONTENT_ITEMTYPE =
"vnd.android.cursor.item/vnd.google.waypoint";
public static final String DEFAULT_SORT_ORDER = "_id";
/* All columns */
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String CATEGORY = "category";
public static final String ICON = "icon";
public static final String TRACKID = "trackid";
public static final String TYPE = "type";
public static final String LENGTH = "length";
public static final String DURATION = "duration";
public static final String STARTTIME = "starttime";
public static final String STARTID = "startid";
public static final String STOPID = "stopid";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String ALTITUDE = "elevation";
public static final String BEARING = "bearing";
public static final String TIME = "time";
public static final String ACCURACY = "accuracy";
public static final String SPEED = "speed";
public static final String TOTALDISTANCE = "totaldistance";
public static final String TOTALTIME = "totaltime";
public static final String MOVINGTIME = "movingtime";
public static final String AVGSPEED = "avgspeed";
public static final String AVGMOVINGSPEED = "avgmovingspeed";
public static final String MAXSPEED = "maxspeed";
public static final String MINELEVATION = "minelevation";
public static final String MAXELEVATION = "maxelevation";
public static final String ELEVATIONGAIN = "elevationgain";
public static final String MINGRADE = "mingrade";
public static final String MAXGRADE = "maxgrade";
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Defines the URI for the track points provider and the available column names
* and content types.
*
* @author Leif Hendrik Wilden
*/
public interface TrackPointsColumns extends BaseColumns {
public static final Uri CONTENT_URI =
Uri.parse("content://com.google.android.maps.mytracks/trackpoints");
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.google.trackpoint";
public static final String CONTENT_ITEMTYPE =
"vnd.android.cursor.item/vnd.google.trackpoint";
public static final String DEFAULT_SORT_ORDER = "_id";
/* All columns */
public static final String TRACKID = "trackid";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String ALTITUDE = "elevation";
public static final String BEARING = "bearing";
public static final String TIME = "time";
public static final String ACCURACY = "accuracy";
public static final String SPEED = "speed";
public static final String SENSOR = "sensor";
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* A class representing a (GPS) Track.
*
* TODO: hashCode and equals
*
* @author Leif Hendrik Wilden
* @author Rodrigo Damazio
*/
public class Track implements Parcelable {
/**
* Creator for a Track object.
*/
public static class Creator implements Parcelable.Creator<Track> {
public Track createFromParcel(Parcel source) {
ClassLoader classLoader = getClass().getClassLoader();
Track track = new Track();
track.id = source.readLong();
track.name = source.readString();
track.description = source.readString();
track.mapId = source.readString();
track.category = source.readString();
track.startId = source.readLong();
track.stopId = source.readLong();
track.stats = source.readParcelable(classLoader);
track.numberOfPoints = source.readInt();
for (int i = 0; i < track.numberOfPoints; ++i) {
Location loc = source.readParcelable(classLoader);
track.locations.add(loc);
}
track.tableId = source.readString();
return track;
}
public Track[] newArray(int size) {
return new Track[size];
}
}
public static final Creator CREATOR = new Creator();
/**
* The track points (which may not have been loaded).
*/
private ArrayList<Location> locations = new ArrayList<Location>();
/**
* The number of location points (present even if the points themselves were
* not loaded).
*/
private int numberOfPoints = 0;
private long id = -1;
private String name = "";
private String description = "";
private String mapId = "";
private String tableId = "";
private long startId = -1;
private long stopId = -1;
private String category = "";
private TripStatistics stats = new TripStatistics();
public Track() {
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(mapId);
dest.writeString(category);
dest.writeLong(startId);
dest.writeLong(stopId);
dest.writeParcelable(stats, 0);
dest.writeInt(numberOfPoints);
for (int i = 0; i < numberOfPoints; ++i) {
dest.writeParcelable(locations.get(i), 0);
}
dest.writeString(tableId);
}
// Getters and setters:
//---------------------
public int describeContents() {
return 0;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getStartId() {
return startId;
}
public void setStartId(long startId) {
this.startId = startId;
}
public long getStopId() {
return stopId;
}
public void setStopId(long stopId) {
this.stopId = stopId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMapId() {
return mapId;
}
public void setMapId(String mapId) {
this.mapId = mapId;
}
public String getTableId() {
return tableId;
}
public void setTableId(String tableId) {
this.tableId = tableId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getNumberOfPoints() {
return numberOfPoints;
}
public void setNumberOfPoints(int numberOfPoints) {
this.numberOfPoints = numberOfPoints;
}
public void addLocation(Location l) {
locations.add(l);
}
public ArrayList<Location> getLocations() {
return locations;
}
public void setLocations(ArrayList<Location> locations) {
this.locations = locations;
}
public TripStatistics getStatistics() {
return stats;
}
public void setStatistics(TripStatistics stats) {
this.stats = stats;
}
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.protobuf.InvalidProtocolBufferException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Helper class providing easy access to locations and tracks in the
* MyTracksProvider. All static members.
*
* @author Leif Hendrik Wilden
*/
public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
private final ContentResolver contentResolver;
private int defaultCursorBatchSize = 2000;
public MyTracksProviderUtilsImpl(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
/**
* Creates the ContentValues for a given location object.
*
* @param location a given location
* @param trackId the id of the track it belongs to
* @return a filled in ContentValues object
*/
private static ContentValues createContentValues(
Location location, long trackId) {
ContentValues values = new ContentValues();
values.put(TrackPointsColumns.TRACKID, trackId);
values.put(TrackPointsColumns.LATITUDE,
(int) (location.getLatitude() * 1E6));
values.put(TrackPointsColumns.LONGITUDE,
(int) (location.getLongitude() * 1E6));
// This is an ugly hack for Samsung phones that don't properly populate the
// time field.
values.put(TrackPointsColumns.TIME,
(location.getTime() == 0)
? System.currentTimeMillis()
: location.getTime());
if (location.hasAltitude()) {
values.put(TrackPointsColumns.ALTITUDE, location.getAltitude());
}
if (location.hasBearing()) {
values.put(TrackPointsColumns.BEARING, location.getBearing());
}
if (location.hasAccuracy()) {
values.put(TrackPointsColumns.ACCURACY, location.getAccuracy());
}
if (location.hasSpeed()) {
values.put(TrackPointsColumns.SPEED, location.getSpeed());
}
if (location instanceof MyTracksLocation) {
MyTracksLocation mtLocation = (MyTracksLocation) location;
if (mtLocation.getSensorDataSet() != null) {
values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray());
}
}
return values;
}
@Override
public ContentValues createContentValues(Track track) {
ContentValues values = new ContentValues();
TripStatistics stats = track.getStatistics();
// Values id < 0 indicate no id is available:
if (track.getId() >= 0) {
values.put(TracksColumns._ID, track.getId());
}
values.put(TracksColumns.NAME, track.getName());
values.put(TracksColumns.DESCRIPTION, track.getDescription());
values.put(TracksColumns.MAPID, track.getMapId());
values.put(TracksColumns.TABLEID, track.getTableId());
values.put(TracksColumns.CATEGORY, track.getCategory());
values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints());
values.put(TracksColumns.STARTID, track.getStartId());
values.put(TracksColumns.STARTTIME, stats.getStartTime());
values.put(TracksColumns.STOPTIME, stats.getStopTime());
values.put(TracksColumns.STOPID, track.getStopId());
values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance());
values.put(TracksColumns.TOTALTIME, stats.getTotalTime());
values.put(TracksColumns.MOVINGTIME, stats.getMovingTime());
values.put(TracksColumns.MAXLAT, stats.getTop());
values.put(TracksColumns.MINLAT, stats.getBottom());
values.put(TracksColumns.MAXLON, stats.getRight());
values.put(TracksColumns.MINLON, stats.getLeft());
values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed());
values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed());
values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed());
values.put(TracksColumns.MINELEVATION, stats.getMinElevation());
values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation());
values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain());
values.put(TracksColumns.MINGRADE, stats.getMinGrade());
values.put(TracksColumns.MAXGRADE, stats.getMaxGrade());
return values;
}
private static ContentValues createContentValues(Waypoint waypoint) {
ContentValues values = new ContentValues();
// Values id < 0 indicate no id is available:
if (waypoint.getId() >= 0) {
values.put(WaypointsColumns._ID, waypoint.getId());
}
values.put(WaypointsColumns.NAME, waypoint.getName());
values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription());
values.put(WaypointsColumns.CATEGORY, waypoint.getCategory());
values.put(WaypointsColumns.ICON, waypoint.getIcon());
values.put(WaypointsColumns.TRACKID, waypoint.getTrackId());
values.put(WaypointsColumns.TYPE, waypoint.getType());
values.put(WaypointsColumns.LENGTH, waypoint.getLength());
values.put(WaypointsColumns.DURATION, waypoint.getDuration());
values.put(WaypointsColumns.STARTID, waypoint.getStartId());
values.put(WaypointsColumns.STOPID, waypoint.getStopId());
TripStatistics stats = waypoint.getStatistics();
if (stats != null) {
values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance());
values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime());
values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime());
values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed());
values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed());
values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed());
values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation());
values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation());
values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain());
values.put(WaypointsColumns.MINGRADE, stats.getMinGrade());
values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade());
values.put(WaypointsColumns.STARTTIME, stats.getStartTime());
}
Location location = waypoint.getLocation();
if (location != null) {
values.put(WaypointsColumns.LATITUDE,
(int) (location.getLatitude() * 1E6));
values.put(WaypointsColumns.LONGITUDE,
(int) (location.getLongitude() * 1E6));
values.put(WaypointsColumns.TIME, location.getTime());
if (location.hasAltitude()) {
values.put(WaypointsColumns.ALTITUDE, location.getAltitude());
}
if (location.hasBearing()) {
values.put(WaypointsColumns.BEARING, location.getBearing());
}
if (location.hasAccuracy()) {
values.put(WaypointsColumns.ACCURACY, location.getAccuracy());
}
if (location.hasSpeed()) {
values.put(WaypointsColumns.SPEED, location.getSpeed());
}
}
return values;
}
@Override
public Location createLocation(Cursor cursor) {
Location location = new MyTracksLocation("");
fillLocation(cursor, location);
return location;
}
/**
* A cache of track column indices.
*/
private static class CachedTrackColumnIndices {
public final int idxId;
public final int idxLatitude;
public final int idxLongitude;
public final int idxAltitude;
public final int idxTime;
public final int idxBearing;
public final int idxAccuracy;
public final int idxSpeed;
public final int idxSensor;
public CachedTrackColumnIndices(Cursor cursor) {
idxId = cursor.getColumnIndex(TrackPointsColumns._ID);
idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE);
idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE);
idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE);
idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME);
idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING);
idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY);
idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED);
idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR);
}
}
private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices,
Location location) {
location.reset();
if (!cursor.isNull(columnIndices.idxLatitude)) {
location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6);
}
if (!cursor.isNull(columnIndices.idxLongitude)) {
location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6);
}
if (!cursor.isNull(columnIndices.idxAltitude)) {
location.setAltitude(cursor.getFloat(columnIndices.idxAltitude));
}
if (!cursor.isNull(columnIndices.idxTime)) {
location.setTime(cursor.getLong(columnIndices.idxTime));
}
if (!cursor.isNull(columnIndices.idxBearing)) {
location.setBearing(cursor.getFloat(columnIndices.idxBearing));
}
if (!cursor.isNull(columnIndices.idxSpeed)) {
location.setSpeed(cursor.getFloat(columnIndices.idxSpeed));
}
if (!cursor.isNull(columnIndices.idxAccuracy)) {
location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy));
}
if (location instanceof MyTracksLocation &&
!cursor.isNull(columnIndices.idxSensor)) {
MyTracksLocation mtLocation = (MyTracksLocation) location;
// TODO get the right buffer.
Sensor.SensorDataSet sensorData;
try {
sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor));
mtLocation.setSensorData(sensorData);
} catch (InvalidProtocolBufferException e) {
Log.w(TAG, "Failed to parse sensor data.", e);
}
}
}
@Override
public void fillLocation(Cursor cursor, Location location) {
CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor);
fillLocation(cursor, columnIndicies, location);
}
@Override
public Track createTrack(Cursor cursor) {
int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID);
int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME);
int idxDescription =
cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION);
int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID);
int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID);
int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY);
int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID);
int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME);
int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME);
int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID);
int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS);
int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT);
int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT);
int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON);
int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON);
int idxTotalDistance =
cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE);
int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME);
int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME);
int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED);
int idxMinElevation =
cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION);
int idxMaxElevation =
cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION);
int idxElevationGain =
cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN);
int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE);
int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE);
Track track = new Track();
TripStatistics stats = track.getStatistics();
if (!cursor.isNull(idxId)) {
track.setId(cursor.getLong(idxId));
}
if (!cursor.isNull(idxName)) {
track.setName(cursor.getString(idxName));
}
if (!cursor.isNull(idxDescription)) {
track.setDescription(cursor.getString(idxDescription));
}
if (!cursor.isNull(idxMapId)) {
track.setMapId(cursor.getString(idxMapId));
}
if (!cursor.isNull(idxTableId)) {
track.setTableId(cursor.getString(idxTableId));
}
if (!cursor.isNull(idxCategory)) {
track.setCategory(cursor.getString(idxCategory));
}
if (!cursor.isNull(idxStartId)) {
track.setStartId(cursor.getInt(idxStartId));
}
if (!cursor.isNull(idxStartTime)) {
stats.setStartTime(cursor.getLong(idxStartTime));
}
if (!cursor.isNull(idxStopTime)) {
stats.setStopTime(cursor.getLong(idxStopTime));
}
if (!cursor.isNull(idxStopId)) {
track.setStopId(cursor.getInt(idxStopId));
}
if (!cursor.isNull(idxNumPoints)) {
track.setNumberOfPoints(cursor.getInt(idxNumPoints));
}
if (!cursor.isNull(idxTotalDistance)) {
stats.setTotalDistance(cursor.getFloat(idxTotalDistance));
}
if (!cursor.isNull(idxTotalTime)) {
stats.setTotalTime(cursor.getLong(idxTotalTime));
}
if (!cursor.isNull(idxMovingTime)) {
stats.setMovingTime(cursor.getLong(idxMovingTime));
}
if (!cursor.isNull(idxMaxlat)
&& !cursor.isNull(idxMinlat)
&& !cursor.isNull(idxMaxlon)
&& !cursor.isNull(idxMinlon)) {
int top = cursor.getInt(idxMaxlat);
int bottom = cursor.getInt(idxMinlat);
int right = cursor.getInt(idxMaxlon);
int left = cursor.getInt(idxMinlon);
stats.setBounds(left, top, right, bottom);
}
if (!cursor.isNull(idxMaxSpeed)) {
stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed));
}
if (!cursor.isNull(idxMinElevation)) {
stats.setMinElevation(cursor.getFloat(idxMinElevation));
}
if (!cursor.isNull(idxMaxElevation)) {
stats.setMaxElevation(cursor.getFloat(idxMaxElevation));
}
if (!cursor.isNull(idxElevationGain)) {
stats.setTotalElevationGain(cursor.getFloat(idxElevationGain));
}
if (!cursor.isNull(idxMinGrade)) {
stats.setMinGrade(cursor.getFloat(idxMinGrade));
}
if (!cursor.isNull(idxMaxGrade)) {
stats.setMaxGrade(cursor.getFloat(idxMaxGrade));
}
return track;
}
@Override
public Waypoint createWaypoint(Cursor cursor) {
int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID);
int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME);
int idxDescription =
cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION);
int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY);
int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON);
int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID);
int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE);
int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH);
int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION);
int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME);
int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID);
int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID);
int idxTotalDistance =
cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE);
int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME);
int idxMovingTime =
cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME);
int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED);
int idxMinElevation =
cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION);
int idxMaxElevation =
cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION);
int idxElevationGain =
cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN);
int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE);
int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE);
int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE);
int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE);
int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE);
int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME);
int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING);
int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY);
int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED);
Waypoint waypoint = new Waypoint();
if (!cursor.isNull(idxId)) {
waypoint.setId(cursor.getLong(idxId));
}
if (!cursor.isNull(idxName)) {
waypoint.setName(cursor.getString(idxName));
}
if (!cursor.isNull(idxDescription)) {
waypoint.setDescription(cursor.getString(idxDescription));
}
if (!cursor.isNull(idxCategory)) {
waypoint.setCategory(cursor.getString(idxCategory));
}
if (!cursor.isNull(idxIcon)) {
waypoint.setIcon(cursor.getString(idxIcon));
}
if (!cursor.isNull(idxTrackId)) {
waypoint.setTrackId(cursor.getLong(idxTrackId));
}
if (!cursor.isNull(idxType)) {
waypoint.setType(cursor.getInt(idxType));
}
if (!cursor.isNull(idxLength)) {
waypoint.setLength(cursor.getDouble(idxLength));
}
if (!cursor.isNull(idxDuration)) {
waypoint.setDuration(cursor.getLong(idxDuration));
}
if (!cursor.isNull(idxStartId)) {
waypoint.setStartId(cursor.getLong(idxStartId));
}
if (!cursor.isNull(idxStopId)) {
waypoint.setStopId(cursor.getLong(idxStopId));
}
TripStatistics stats = new TripStatistics();
boolean hasStats = false;
if (!cursor.isNull(idxStartTime)) {
stats.setStartTime(cursor.getLong(idxStartTime));
hasStats = true;
}
if (!cursor.isNull(idxTotalDistance)) {
stats.setTotalDistance(cursor.getFloat(idxTotalDistance));
hasStats = true;
}
if (!cursor.isNull(idxTotalTime)) {
stats.setTotalTime(cursor.getLong(idxTotalTime));
hasStats = true;
}
if (!cursor.isNull(idxMovingTime)) {
stats.setMovingTime(cursor.getLong(idxMovingTime));
hasStats = true;
}
if (!cursor.isNull(idxMaxSpeed)) {
stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed));
hasStats = true;
}
if (!cursor.isNull(idxMinElevation)) {
stats.setMinElevation(cursor.getFloat(idxMinElevation));
hasStats = true;
}
if (!cursor.isNull(idxMaxElevation)) {
stats.setMaxElevation(cursor.getFloat(idxMaxElevation));
hasStats = true;
}
if (!cursor.isNull(idxElevationGain)) {
stats.setTotalElevationGain(cursor.getFloat(idxElevationGain));
hasStats = true;
}
if (!cursor.isNull(idxMinGrade)) {
stats.setMinGrade(cursor.getFloat(idxMinGrade));
hasStats = true;
}
if (!cursor.isNull(idxMaxGrade)) {
stats.setMaxGrade(cursor.getFloat(idxMaxGrade));
hasStats = true;
}
if (hasStats) {
waypoint.setStatistics(stats);
}
Location location = new Location("");
if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) {
location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6);
location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6);
}
if (!cursor.isNull(idxAltitude)) {
location.setAltitude(cursor.getFloat(idxAltitude));
}
if (!cursor.isNull(idxTime)) {
location.setTime(cursor.getLong(idxTime));
}
if (!cursor.isNull(idxBearing)) {
location.setBearing(cursor.getFloat(idxBearing));
}
if (!cursor.isNull(idxSpeed)) {
location.setSpeed(cursor.getFloat(idxSpeed));
}
if (!cursor.isNull(idxAccuracy)) {
location.setAccuracy(cursor.getFloat(idxAccuracy));
}
waypoint.setLocation(location);
return waypoint;
}
@Override
public void deleteAllTracks() {
contentResolver.delete(TracksColumns.CONTENT_URI, null, null);
contentResolver.delete(TrackPointsColumns.CONTENT_URI,
null, null);
contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null);
}
@Override
public void deleteTrack(long trackId) {
Track track = getTrack(trackId);
if (track != null) {
contentResolver.delete(TrackPointsColumns.CONTENT_URI,
"_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(),
null);
}
contentResolver.delete(WaypointsColumns.CONTENT_URI,
WaypointsColumns.TRACKID + "=" + trackId, null);
contentResolver.delete(
TracksColumns.CONTENT_URI, "_id=" + trackId, null);
}
@Override
public void deleteWaypoint(long waypointId,
DescriptionGenerator descriptionGenerator) {
final Waypoint deletedWaypoint = getWaypoint(waypointId);
if (deletedWaypoint != null
&& deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) {
final Waypoint nextWaypoint =
getNextStatisticsWaypointAfter(deletedWaypoint);
if (nextWaypoint != null) {
Log.d(TAG, "Correcting marker " + nextWaypoint.getId()
+ " after deleted marker " + deletedWaypoint.getId());
nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics());
nextWaypoint.setDescription(
descriptionGenerator.generateWaypointDescription(nextWaypoint));
if (!updateWaypoint(nextWaypoint)) {
Log.w(TAG, "Update of marker was unsuccessful.");
}
} else {
Log.d(TAG, "No statistics marker after the deleted one was found.");
}
}
contentResolver.delete(
WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null);
}
@Override
public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) {
final String selection = WaypointsColumns._ID + ">" + waypoint.getId()
+ " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId()
+ " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS;
final String sortOrder = WaypointsColumns._ID + " LIMIT 1";
Cursor cursor = null;
try {
cursor = contentResolver.query(
WaypointsColumns.CONTENT_URI,
null /*projection*/,
selection,
null /*selectionArgs*/,
sortOrder);
if (cursor != null && cursor.moveToFirst()) {
return createWaypoint(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught unexpected exception.", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@Override
public boolean updateWaypoint(Waypoint waypoint) {
try {
final int rows = contentResolver.update(
WaypointsColumns.CONTENT_URI,
createContentValues(waypoint),
"_id=" + waypoint.getId(),
null /*selectionArgs*/);
return rows == 1;
} catch (RuntimeException e) {
Log.e(TAG, "Caught unexpected exception.", e);
}
return false;
}
/**
* Finds a locations from the provider by the given selection.
*
* @param select a selection argument that identifies a unique location
* @return the fist location matching, or null if not found
*/
private Location findLocationBy(String select) {
Cursor cursor = null;
try {
cursor = contentResolver.query(
TrackPointsColumns.CONTENT_URI, null, select, null, null);
if (cursor != null && cursor.moveToNext()) {
return createLocation(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpeceted exception.", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
/**
* Finds a track from the provider by the given selection.
*
* @param select a selection argument that identifies a unique track
* @return the first track matching, or null if not found
*/
private Track findTrackBy(String select) {
Cursor cursor = null;
try {
cursor = contentResolver.query(
TracksColumns.CONTENT_URI, null, select, null, null);
if (cursor != null && cursor.moveToNext()) {
return createTrack(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught unexpected exception.", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@Override
public Location getLastLocation() {
return findLocationBy("_id=(select max(_id) from trackpoints)");
}
@Override
public Waypoint getFirstWaypoint(long trackId) {
if (trackId < 0) {
return null;
}
Cursor cursor = contentResolver.query(
WaypointsColumns.CONTENT_URI,
null /*projection*/,
"trackid=" + trackId,
null /*selectionArgs*/,
"_id LIMIT 1");
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return createWaypoint(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
cursor.close();
}
}
return null;
}
@Override
public Waypoint getWaypoint(long waypointId) {
if (waypointId < 0) {
return null;
}
Cursor cursor = contentResolver.query(
WaypointsColumns.CONTENT_URI,
null /*projection*/,
"_id=" + waypointId,
null /*selectionArgs*/,
null /*sortOrder*/);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return createWaypoint(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
cursor.close();
}
}
return null;
}
@Override
public long getLastLocationId(long trackId) {
if (trackId < 0) {
return -1;
}
final String[] projection = {"_id"};
Cursor cursor = contentResolver.query(
TrackPointsColumns.CONTENT_URI,
projection,
"_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")",
null /*selectionArgs*/,
null /*sortOrder*/);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(
cursor.getColumnIndexOrThrow(TrackPointsColumns._ID));
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
cursor.close();
}
}
return -1;
}
@Override
public long getFirstWaypointId(long trackId) {
if (trackId < 0) {
return -1;
}
final String[] projection = {"_id"};
Cursor cursor = contentResolver.query(
WaypointsColumns.CONTENT_URI,
projection,
"trackid=" + trackId,
null /*selectionArgs*/,
"_id LIMIT 1" /*sortOrder*/);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(
cursor.getColumnIndexOrThrow(WaypointsColumns._ID));
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
cursor.close();
}
}
return -1;
}
@Override
public long getLastWaypointId(long trackId) {
if (trackId < 0) {
return -1;
}
final String[] projection = {"_id"};
Cursor cursor = contentResolver.query(
WaypointsColumns.CONTENT_URI,
projection,
WaypointsColumns.TRACKID + "=" + trackId,
null /*selectionArgs*/,
"_id DESC LIMIT 1" /*sortOrder*/);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(
cursor.getColumnIndexOrThrow(WaypointsColumns._ID));
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
cursor.close();
}
}
return -1;
}
@Override
public Track getLastTrack() {
Cursor cursor = null;
try {
cursor = contentResolver.query(
TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)",
null, null);
if (cursor != null && cursor.moveToNext()) {
return createTrack(cursor);
}
} catch (RuntimeException e) {
Log.w(TAG, "Caught an unexpected exception.", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@Override
public long getLastTrackId() {
String[] proj = { TracksColumns._ID };
Cursor cursor = contentResolver.query(
TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)",
null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(
cursor.getColumnIndexOrThrow(TracksColumns._ID));
}
} finally {
cursor.close();
}
}
return -1;
}
@Override
public Location getLocation(long id) {
if (id < 0) {
return null;
}
String selection = TrackPointsColumns._ID + "=" + id;
return findLocationBy(selection);
}
@Override
public Cursor getLocationsCursor(long trackId, long minTrackPointId,
int maxLocations, boolean descending) {
if (trackId < 0) {
return null;
}
String selection;
if (minTrackPointId >= 0) {
selection = String.format("%s=%d AND %s%s%d",
TrackPointsColumns.TRACKID, trackId, TrackPointsColumns._ID,
descending ? "<=" : ">=", minTrackPointId);
} else {
selection = String.format("%s=%d", TrackPointsColumns.TRACKID, trackId);
}
String sortOrder = "_id " + (descending ? "DESC" : "ASC");
if (maxLocations > 0) {
sortOrder += " LIMIT " + maxLocations;
}
return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, null, sortOrder);
}
@Override
public Cursor getWaypointsCursor(long trackId, long minWaypointId,
int maxWaypoints) {
if (trackId < 0) {
return null;
}
String selection;
String[] selectionArgs;
if (minWaypointId > 0) {
selection = String.format("%s = ? AND %s >= ?",
WaypointsColumns.TRACKID,
WaypointsColumns._ID);
selectionArgs = new String[] {
Long.toString(trackId),
Long.toString(minWaypointId)
};
} else {
selection = String.format("%s=?", WaypointsColumns.TRACKID);
selectionArgs = new String[] { Long.toString(trackId) };
}
return getWaypointsCursor(selection, selectionArgs, null, maxWaypoints);
}
@Override
public Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints) {
if (order == null) {
order = "_id ASC";
}
if (maxWaypoints > 0) {
order += " LIMIT " + maxWaypoints;
}
return contentResolver.query(
WaypointsColumns.CONTENT_URI, null, selection, selectionArgs, order);
}
@Override
public Track getTrack(long id) {
if (id < 0) {
return null;
}
String select = TracksColumns._ID + "=" + id;
return findTrackBy(select);
}
@Override
public List<Track> getAllTracks() {
Cursor cursor = getTracksCursor(null, null, TracksColumns._ID);
ArrayList<Track> tracks = new ArrayList<Track>();
if (cursor != null) {
tracks.ensureCapacity(cursor.getCount());
if (cursor.moveToFirst()) {
do {
tracks.add(createTrack(cursor));
} while(cursor.moveToNext());
}
cursor.close();
}
return tracks;
}
@Override
public Cursor getTracksCursor(String selection, String[] selectionArgs, String order) {
return contentResolver.query(
TracksColumns.CONTENT_URI, null, selection, selectionArgs, order);
}
@Override
public Uri insertTrack(Track track) {
Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack");
return contentResolver.insert(TracksColumns.CONTENT_URI,
createContentValues(track));
}
@Override
public Uri insertTrackPoint(Location location, long trackId) {
Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint");
return contentResolver.insert(TrackPointsColumns.CONTENT_URI,
createContentValues(location, trackId));
}
@Override
public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) {
if (length == -1) { length = locations.length; }
ContentValues[] values = new ContentValues[length];
for (int i = 0; i < length; i++) {
values[i] = createContentValues(locations[i], trackId);
}
return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values);
}
@Override
public Uri insertWaypoint(Waypoint waypoint) {
Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint");
waypoint.setId(-1);
return contentResolver.insert(WaypointsColumns.CONTENT_URI,
createContentValues(waypoint));
}
@Override
public boolean trackExists(long id) {
if (id < 0) {
return false;
}
Cursor cursor = null;
try {
final String[] projection = { TracksColumns._ID };
cursor = contentResolver.query(
TracksColumns.CONTENT_URI,
projection,
TracksColumns._ID + "=" + id/*selection*/,
null/*selectionArgs*/,
null/*sortOrder*/);
if (cursor != null && cursor.moveToNext()) {
return true;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return false;
}
@Override
public void updateTrack(Track track) {
Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack");
contentResolver.update(TracksColumns.CONTENT_URI,
createContentValues(track), "_id=" + track.getId(), null);
}
@Override
public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId,
final boolean descending, final LocationFactory locationFactory) {
if (locationFactory == null) {
throw new IllegalArgumentException("Expecting non-null locationFactory");
}
return new LocationIterator() {
private long lastTrackPointId = startTrackPointId;
private Cursor cursor = getCursor(startTrackPointId);
private final CachedTrackColumnIndices columnIndices = cursor != null ?
new CachedTrackColumnIndices(cursor) : null;
private Cursor getCursor(long trackPointId) {
return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending);
}
private boolean advanceCursorToNextBatch() {
long pointId = lastTrackPointId + (descending ? -1 : 1);
Log.d(TAG, "Advancing cursor point ID: " + pointId);
cursor.close();
cursor = getCursor(pointId);
return cursor != null;
}
@Override
public long getLocationId() {
return lastTrackPointId;
}
@Override
public boolean hasNext() {
if (cursor == null) {
return false;
}
if (cursor.isAfterLast()) {
return false;
}
if (cursor.isLast()) {
// If the current batch size was less that max, we can safely return, otherwise
// we need to advance to the next batch.
return cursor.getCount() == defaultCursorBatchSize &&
advanceCursorToNextBatch() && !cursor.isAfterLast();
}
return true;
}
@Override
public Location next() {
if (cursor == null ||
!(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) {
throw new NoSuchElementException();
}
lastTrackPointId = cursor.getLong(columnIndices.idxId);
Location location = locationFactory.createLocation();
fillLocation(cursor, columnIndices, location);
return location;
}
@Override
public void close() {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// @VisibleForTesting
void setDefaultCursorBatchSize(int defaultCursorBatchSize) {
this.defaultCursorBatchSize = defaultCursorBatchSize;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import java.util.Vector;
/**
* An interface for an object that can generate descriptions of track and
* waypoint.
*
* @author Sandor Dornbush
*/
public interface DescriptionGenerator {
/**
* Generates a track description.
*
* @param track the track
* @param distances a vector of distances to generate the elevation chart
* @param elevations a vector of elevations to generate the elevation chart
*/
public String generateTrackDescription(
Track track, Vector<Double> distances, Vector<Double> elevations);
/**
* Generate a waypoint description.
*
* @param waypoint the waypoint
*/
public String generateWaypointDescription(Waypoint waypoint);
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.lib;
/**
* Constants for the My Tracks common library.
* These constants should ideally not be used by third-party applications.
*
* @author Rodrigo Damazio
*/
public class MyTracksLibConstants {
public static final String TAG = "MyTracksLib";
private MyTracksLibConstants() {}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.samples.api;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* A receiver to receive MyTracks notifications.
*
* @author Jimmy Shih
*/
public class MyTracksReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
long trackId = intent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L);
Toast.makeText(context, action + " " + trackId, Toast.LENGTH_LONG).show();
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.samples.api;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.services.ITrackRecordingService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Calendar;
import java.util.List;
/**
* An activity to access MyTracks content provider and service.
*
* Note you must first install MyTracks before installing this app.
*
* You also need to enable third party application access inside MyTracks
* MyTracks -> menu -> Settings -> Sharing -> Allow access
*
* @author Jimmy Shih
*/
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
// utils to access the MyTracks content provider
private MyTracksProviderUtils myTracksProviderUtils;
// display output from the MyTracks content provider
private TextView outputTextView;
// MyTracks service
private ITrackRecordingService myTracksService;
// intent to access the MyTracks service
private Intent intent;
// connection to the MyTracks service
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
myTracksService = ITrackRecordingService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName className) {
myTracksService = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// for the MyTracks content provider
myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
outputTextView = (TextView) findViewById(R.id.output);
Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button);
addWaypointsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Track> tracks = myTracksProviderUtils.getAllTracks();
Calendar now = Calendar.getInstance();
for (Track track : tracks) {
Waypoint waypoint = new Waypoint();
waypoint.setTrackId(track.getId());
waypoint.setName(now.getTime().toLocaleString());
waypoint.setDescription(now.getTime().toLocaleString());
myTracksProviderUtils.insertWaypoint(waypoint);
}
}
});
// for the MyTracks service
intent = new Intent();
ComponentName componentName = new ComponentName(
getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class));
intent.setComponent(componentName);
Button startRecordingButton = (Button) findViewById(R.id.start_recording_button);
startRecordingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (myTracksService != null) {
try {
myTracksService.startNewTrack();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException", e);
}
}
}
});
Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button);
stopRecordingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (myTracksService != null) {
try {
myTracksService.endCurrentTrack();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException", e);
}
}
}
});
}
@Override
protected void onStart() {
super.onStart();
// use the MyTracks content provider to get all the tracks
List<Track> tracks = myTracksProviderUtils.getAllTracks();
for (Track track : tracks) {
outputTextView.append(track.getId() + " ");
}
// start and bind the MyTracks service
startService(intent);
bindService(intent, serviceConnection, 0);
}
@Override
protected void onStop() {
super.onStop();
// unbind and stop the MyTracks service
if (myTracksService != null) {
unbindService(serviceConnection);
}
stopService(intent);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import java.io.Serializable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.*;
import javax.swing.JLabel;
import javax.swing.Timer;
/**
*
* @author Robert Alvarado
*/
public class Reloj extends JLabel {
private Timer timer;
int tiempo = 0;
int tiempo2 = 0;
int tiempo3 = 0;
private String MSegundo = "00";
private String Segundo = "0";
private String Minuto = "0";
String Texto = "00:00:00";
public void actualizacion(final JLabel L) {
timer = new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
tiempo++;
MSegundo = Integer.toString(tiempo);
if (tiempo == 59) {
tiempo2++;
tiempo = 0;
Segundo = Integer.toString(tiempo2);
if (tiempo2 == 59) {
tiempo3++;
tiempo2 = 0;
Minuto = Integer.toString(tiempo3);
}
}
if (Integer.parseInt(Minuto) <= 9) {
Texto = "0" + Minuto + ":";
} else {
Texto = Minuto + ":";
}
if (Integer.parseInt(Segundo) <= 9) {
Texto = Texto + "0" + Segundo + ":";
} else {
Texto = Texto + Segundo + ":";
}
if (Integer.parseInt(MSegundo) <= 9) {
Texto = Texto + "0" + MSegundo;
} else {
Texto = Texto + MSegundo;
}
L.setText(Texto);
}
});
}
public void Parar() {
timer.stop();
}
public void Iniciar(){
timer.start();
}
public void Reiniciar(JLabel L){
this.Minuto = "0";
this.Segundo = "0";
this.MSegundo = "0";
tiempo = 0;
tiempo2 = 0;
tiempo3 = 0;
Texto = "00:00:00";
L.setText(Texto);
}
}
| Java |
package bean;
import java.io.Serializable;
import java.sql.*;
import java.util.ResourceBundle;
public class Conexion implements Serializable {
// La descripcion del driver de la BD
private static String driver;
// La direccion URL de la BD
private static String url;
// El nombre de la BD
private static String nombreBd;
// EL login del usuario para conectarse al servidor de BD
private static String usuario;
// EL password del usuario para conectarse al servidor de BD
private static String password;
// El nombre del archivo de properties, donde se encuentran los datos para la conexión con la Base de Datos
private static String archivoProperties;
private static Connection conexion;
/**
* Metodo utilizado para establecer los valores necesarios para la conexion con la Base de Datos
*/
public static void establecerPropiedadesConexion(String driver, String url, String nombreBd, String usuario, String password){
Conexion.driver= driver;
Conexion.url=url;
Conexion.nombreBd=nombreBd;
Conexion.usuario=usuario;
Conexion.password= password;
}
/**
* Metodo que se encarga de leer los valores valores necesarios para la conexion con la Base de Datos,
* de un archivo de configuracion .properties
*/
public static void establecerPropiedadesConexion(String archivoProperties, String driver, String url, String nombreBd, String usuario, String password){
//Obtenemos de un archivo de configuracion .properties los valores de conexion a la Base de Datos
ResourceBundle bundle =ResourceBundle.getBundle(archivoProperties);
//Obtenemos las propiedades del archivo de configuracion
Conexion.driver= bundle.getString(driver);
Conexion.url=bundle.getString(url);
Conexion.nombreBd=bundle.getString(nombreBd);
Conexion.usuario=bundle.getString(usuario);
Conexion.password= bundle.getString(password);
}
/**
* @return driver
*/
public static String getDriver() {
return driver;
}
/**
* @param driver
*/
public static void setDriver(String driver) {
Conexion.driver = driver;
}
/**
* @return url
*/
public static String getUrl() {
return url;
}
/**
* @param url
*/
public static void setUrl(String url) {
Conexion.url = url;
}
/**
* @return bd
*/
public static String getNombreBd() {
return nombreBd;
}
/**
* @param bd
*/
public static void setNombreBd(String nombreBd) {
Conexion.nombreBd = nombreBd;
}
/**
* @return usuario
*/
public static String getUsuario() {
return usuario;
}
/**
* @param usuario
*/
public static void setUsuario(String usuario) {
Conexion.usuario = usuario;
}
/**
* @return password
*/
public static String getPassword() {
return password;
}
/**
* @param password
*/
public static void setPassword(String password) {
Conexion.password = password;
}
/**
* Metodo utilizado para Obtener una conexion a BD
* @return Un objeto tipo Connection que representa una conexion a la BD
*/
private static Connection getConexion() {
try{
if (conexion == null || conexion.isClosed()) {
// Cargo el driver en memoria
Class.forName(driver);
// Establezco la conexion
conexion=DriverManager.getConnection(url+nombreBd,usuario,password);
}
}
catch(SQLException e){
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conexion;
}
/** * Metodo consultar
* @param String tiraSQL
* @return ResultSet
*/
public static ResultSet consultar(String tiraSQL) {
getConexion();
ResultSet resultado = null;
try {
Statement sentencia= conexion.createStatement();
resultado = sentencia.executeQuery(tiraSQL);
}
catch(Exception e) {
e.printStackTrace();
}
try {
conexion.close();
}
catch( SQLException e ) {
e.printStackTrace();
}
return resultado;
}
/** * Metodo ejecutar
* @param String TiraSQL
* @return boolean
*/
public static boolean ejecutar(String tiraSQL) {
getConexion();
boolean ok = false;
try {
Statement sentencia = conexion.createStatement();
int i = sentencia.executeUpdate(tiraSQL);
if (i > 0) {
ok = true;
}
sentencia.close ();
}
catch(Exception e) {
e.printStackTrace();
}
try {
conexion.close();
}
catch( SQLException e ) {
e.printStackTrace();
}
return ok;
}
} | Java |
/*
* ActiveSliderUI.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JSlider;
import javax.swing.plaf.basic.BasicSliderUI;
public class ActiveSliderUI extends BasicSliderUI
{
private Image thumbImage = null;
private Image thumbPressedImage = null;
private Image[] backgroundImages = null;
private JSlider parentSlider = null;
private Dimension thumbDim = null;
private int newThumbHeight = -1;
private int thumbXOffset = 0;
private int thumbYOffset = 0;
private boolean hideThumb = false;
public ActiveSliderUI(JSlider slider)
{
super(slider);
parentSlider = slider;
}
public void setThumbImage(Image img)
{
thumbImage = img;
thumbDim = new Dimension(thumbImage.getWidth(null), thumbImage.getHeight(null));
}
public void setThumbPressedImage(Image img)
{
thumbPressedImage = img;
}
protected Dimension getThumbSize()
{
return thumbDim;
}
public void forceThumbHeight(int h)
{
newThumbHeight = h;
}
public void setThumbXOffset(int x)
{
thumbXOffset = x;
}
public void setThumbYOffset(int y)
{
thumbYOffset = y;
}
public void setHideThumb(boolean hide)
{
hideThumb = hide;
}
public void setBackgroundImages(Image[] img)
{
backgroundImages = img;
}
public void paintFocus(Graphics g)
{
}
public void paintThumb(Graphics g)
{
if (hideThumb == true) return;
Image img = thumbImage;
if (img != null)
{
if (thumbPressedImage != null)
{
if (parentSlider.getValueIsAdjusting())
{
img = thumbPressedImage;
}
}
if (newThumbHeight >= 0)
{
if (parentSlider.getOrientation() == JSlider.HORIZONTAL)
{
g.drawImage(img, thumbRect.x + thumbXOffset, thumbYOffset, img.getWidth(null), newThumbHeight, null);
}
else
{
g.drawImage(img, thumbXOffset, thumbRect.y + thumbYOffset, img.getWidth(null), newThumbHeight, null);
}
}
else
{
if (parentSlider.getOrientation() == JSlider.HORIZONTAL)
{
g.drawImage(img, thumbRect.x + thumbXOffset, thumbYOffset, img.getWidth(null), img.getHeight(null), null);
}
else
{
g.drawImage(img, thumbXOffset, thumbRect.y + thumbYOffset, img.getWidth(null), img.getHeight(null), null);
}
}
}
}
public void paintTrack(Graphics g)
{
if (backgroundImages != null)
{
int id = (int) Math.round(((double) Math.abs(parentSlider.getValue()) / (double) parentSlider.getMaximum()) * (backgroundImages.length - 1));
g.drawImage(backgroundImages[id], 0, 0, backgroundImages[id].getWidth(null), backgroundImages[id].getHeight(null), null);
}
}
public void setThumbLocation(int x, int y)
{
super.setThumbLocation(x, y);
parentSlider.repaint();
}
}
| Java |
/*
* ImageBorder.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.border.Border;
public class ImageBorder implements Border
{
private Insets insets = new Insets(0, 0, 0, 0);
private Image image = null;
public ImageBorder()
{
super();
}
public void setImage(Image image)
{
this.image = image;
}
public boolean isBorderOpaque()
{
return true;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
{
if (image != null)
{
int x0 = x + (width - image.getWidth(null)) / 2;
int y0 = y + (height - image.getHeight(null)) / 2;
g.drawImage(image, x0, y0, null);
}
}
public Insets getBorderInsets(Component c)
{
return insets;
}
}
| Java |
/*
* ActiveFont.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Image;
public class ActiveFont
{
private Image image = null;
private String index = null;
private int width = -1;
private int height = -1;
public ActiveFont()
{
super();
}
public ActiveFont(Image image, String index, int width, int height)
{
super();
this.image=image;
this.index=index;
this.width=width;
this.height=height;
}
public int getHeight()
{
return height;
}
public void setHeight(int height)
{
this.height = height;
}
public Image getImage()
{
return image;
}
public void setImage(Image image)
{
this.image = image;
}
public String getIndex()
{
return index;
}
public void setIndex(String index)
{
this.index = index;
}
public int getWidth()
{
return width;
}
public void setWidth(int width)
{
this.width = width;
}
}
| Java |
/*
* UrlDialog.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* UrlDialog class implements a DialogBox to get an URL.
*/
public class UrlDialog extends JDialog
{
private String _url = null;
/**
* Creates new form ud
*/
public UrlDialog(JFrame parent, String title, int x, int y, String url)
{
super(parent, title, true);
_url = url;
initComponents();
if (_url != null) textField.setText(_url);
this.setLocation(x, y);
}
/**
* Returns URL.
*/
public String getURL()
{
return _url;
}
/**
* Returns filename.
*/
public String getFile()
{
return _url;
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents()
{//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
textField = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
openButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Enter an Internet location to open here :");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(jLabel1, gridBagConstraints);
jLabel2.setText("\"For example : http://www.server.com:8000\"");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(jLabel2, gridBagConstraints);
textField.setColumns(10);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(textField, gridBagConstraints);
openButton.setMnemonic('O');
openButton.setText("Open");
openButton.setToolTipText("Open");
openButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
openHandler(evt);
}
});
jPanel1.add(openButton);
cancelButton.setMnemonic('C');
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cancelHandler(evt);
}
});
jPanel1.add(cancelButton);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
getContentPane().add(jPanel1, gridBagConstraints);
pack();
}//GEN-END:initComponents
private void cancelHandler(java.awt.event.ActionEvent evt)
{//GEN-FIRST:event_cancelHandler
_url = null;
this.dispose();
}//GEN-LAST:event_cancelHandler
private void openHandler(java.awt.event.ActionEvent evt)
{//GEN-FIRST:event_openHandler
_url = textField.getText();
this.dispose();
}//GEN-LAST:event_openHandler
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton openButton;
private javax.swing.JTextField textField;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* ActiveJIcon.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class ActiveJIcon extends JLabel
{
private AbsoluteConstraints constraints = null;
private ImageIcon[] icons = null;
public ActiveJIcon()
{
super();
this.setBorder(null);
this.setDoubleBuffered(true);
}
public void setIcons(ImageIcon[] icons)
{
this.icons = icons;
}
public void setIcon(int id)
{
if ((id >= 0) && (id < icons.length))
{
setIcon(icons[id]);
}
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
}
| Java |
/*
* ActiveJBar.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.JPanel;
public class ActiveJBar extends JPanel
{
private AbsoluteConstraints constraints = null;
public ActiveJBar()
{
super();
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
}
| Java |
/*
* DropTargetAdapter.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DropTargetAdapter implements DropTargetListener
{
private static Log log = LogFactory.getLog(DropTargetAdapter.class);
public DropTargetAdapter()
{
super();
}
public void dragEnter(DropTargetDragEvent e)
{
if (isDragOk(e) == false)
{
e.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent e)
{
if (isDragOk(e) == false)
{
e.rejectDrag();
}
}
public void dropActionChanged(DropTargetDragEvent e)
{
if (isDragOk(e) == false)
{
e.rejectDrag();
}
}
public void dragExit(DropTargetEvent dte)
{
}
protected boolean isDragOk(DropTargetDragEvent e)
{
// Check DataFlavor
DataFlavor[] dfs = e.getCurrentDataFlavors();
DataFlavor tdf = null;
for (int i = 0; i < dfs.length; i++)
{
if (DataFlavor.javaFileListFlavor.equals(dfs[i]))
{
tdf = dfs[i];
break;
}
else if (DataFlavor.stringFlavor.equals(dfs[i]))
{
tdf = dfs[i];
break;
}
}
// Only file list allowed.
if (tdf != null)
{
// Only DnD COPY allowed.
if ((e.getSourceActions() & DnDConstants.ACTION_COPY) != 0)
{
return true;
}
else return false;
}
else return false;
}
public void drop(DropTargetDropEvent e)
{
// Check DataFlavor
DataFlavor[] dfs = e.getCurrentDataFlavors();
DataFlavor tdf = null;
for (int i = 0; i < dfs.length; i++)
{
if (DataFlavor.javaFileListFlavor.equals(dfs[i]))
{
tdf = dfs[i];
break;
}
else if (DataFlavor.stringFlavor.equals(dfs[i]))
{
tdf = dfs[i];
break;
}
}
// Data Flavor available ?
if (tdf != null)
{
// Accept COPY DnD only.
if ((e.getSourceActions() & DnDConstants.ACTION_COPY) != 0)
{
e.acceptDrop(DnDConstants.ACTION_COPY);
}
else return;
try
{
Transferable t = e.getTransferable();
Object data = t.getTransferData(tdf);
processDrop(data);
}
catch (IOException ioe)
{
log.info("Drop error", ioe);
e.dropComplete(false);
return;
}
catch (UnsupportedFlavorException ufe)
{
log.info("Drop error", ufe);
e.dropComplete(false);
return;
}
catch (Exception ex)
{
log.info("Drop error", ex);
e.dropComplete(false);
return;
}
e.dropComplete(true);
}
}
public void processDrop(Object data)
{
}
}
| Java |
/*
* DragAdapter.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class DragAdapter extends MouseAdapter implements MouseMotionListener
{
private int mousePrevX = 0;
private int mousePrevY = 0;
private Component component = null;
public DragAdapter(Component component)
{
super();
this.component = component;
}
public void mousePressed(MouseEvent me)
{
super.mousePressed(me);
mousePrevX = me.getX();
mousePrevY = me.getY();
}
public void mouseDragged(MouseEvent me)
{
int mX = me.getX();
int mY = me.getY();
int cX = component.getX();
int cY = component.getY();
int moveX = mX - mousePrevX; // Negative if move left
int moveY = mY - mousePrevY; // Negative if move down
if (moveX == 0 && moveY == 0) return;
mousePrevX = mX - moveX;
mousePrevY = mY - moveY;
int newX = cX + moveX;
int newY = cY + moveY;
component.setLocation(newX, newY);
}
public void mouseMoved(MouseEvent e)
{
}
}
| Java |
/*
* AbsoluteConstraints.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Dimension;
import java.awt.Point;
/**
* An object that encapsulates position and (optionally) size for
* Absolute positioning of components.
*/
public class AbsoluteConstraints implements java.io.Serializable
{
/**
* generated Serialized Version UID
*/
static final long serialVersionUID = 5261460716622152494L;
/**
* The X position of the component
*/
public int x;
/**
* The Y position of the component
*/
public int y;
/**
* The width of the component or -1 if the component's preferred width should be used
*/
public int width = -1;
/**
* The height of the component or -1 if the component's preferred height should be used
*/
public int height = -1;
/**
* Creates a new AbsoluteConstraints for specified position.
*
* @param pos The position to be represented by this AbsoluteConstraints
*/
public AbsoluteConstraints(Point pos)
{
this(pos.x, pos.y);
}
/**
* Creates a new AbsoluteConstraints for specified position.
*
* @param x The X position to be represented by this AbsoluteConstraints
* @param y The Y position to be represented by this AbsoluteConstraints
*/
public AbsoluteConstraints(int x, int y)
{
this.x = x;
this.y = y;
}
/**
* Creates a new AbsoluteConstraints for specified position and size.
*
* @param pos The position to be represented by this AbsoluteConstraints
* @param size The size to be represented by this AbsoluteConstraints or null
* if the component's preferred size should be used
*/
public AbsoluteConstraints(Point pos, Dimension size)
{
this.x = pos.x;
this.y = pos.y;
if (size != null)
{
this.width = size.width;
this.height = size.height;
}
}
/**
* Creates a new AbsoluteConstraints for specified position and size.
*
* @param x The X position to be represented by this AbsoluteConstraints
* @param y The Y position to be represented by this AbsoluteConstraints
* @param width The width to be represented by this AbsoluteConstraints or -1 if the
* component's preferred width should be used
* @param height The height to be represented by this AbsoluteConstraints or -1 if the
* component's preferred height should be used
*/
public AbsoluteConstraints(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* @return The X position represented by this AbsoluteConstraints
*/
public int getX()
{
return x;
}
/**
* @return The Y position represented by this AbsoluteConstraints
*/
public int getY()
{
return y;
}
/**
* @return The width represented by this AbsoluteConstraints or -1 if the
* component's preferred width should be used
*/
public int getWidth()
{
return width;
}
/**
* @return The height represented by this AbsoluteConstraints or -1 if the
* component's preferred height should be used
*/
public int getHeight()
{
return height;
}
public String toString()
{
return super.toString() + " [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
}
}
| Java |
/*
* Skin.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
import javax.swing.JSlider;
import javazoom.jlgui.player.amp.PlayerActionEvent;
import javazoom.jlgui.player.amp.equalizer.ui.SplinePanel;
import javazoom.jlgui.player.amp.util.Config;
import javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class allows to load all skin (2.0 compliant) features.
*/
public class Skin
{
private static Log log = LogFactory.getLog(Skin.class);
public static final String TITLETEXT = "jlGui 3.0 ";
private Config config = null;
private String skinVersion = "1"; // 1, 2, for different Volume.bmp
private String path = null;
private boolean dspEnabled = true;
/*-- Window Parameters --*/
private int WinWidth, WinHeight;
private String theMain = "main.bmp";
private Image imMain = null;
/*-- Text Members --*/
private int fontWidth = 5;
private int fontHeight = 6;
private String theText = "text.bmp";
private Image imText;
private String fontIndex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\"@a " + "0123456789 :()-'!_+ /[]^&%.=$#" + " ?*";
private ActiveFont acFont = null;
private ActiveJLabel acTitleLabel = null;
private ActiveJLabel acSampleRateLabel = null;
private ActiveJLabel acBitRateLabel = null;
private String sampleRateClearText = " ";
private int[] sampleRateLocation = { 156, 43 };
private String bitsRateClearText = " ";
private int[] bitsRateLocation = { 110, 43 };
private int[] titleLocation = { 111, 27 };
/*-- Numbers Members --*/
private int numberWidth = 9;
private int numberHeight = 13;
private String theNumbers = "numbers.bmp";
private String theNumEx = "nums_ex.bmp";
private Image imNumbers;
private String numberIndex = "0123456789 ";
private int[] minuteHLocation = { 48, 26 };
private int[] minuteLLocation = { 60, 26 };
private int[] secondHLocation = { 78, 26 };
private int[] secondLLocation = { 90, 26 };
private ActiveJNumberLabel acMinuteH = null;
private ActiveJNumberLabel acMinuteL = null;
private ActiveJNumberLabel acSecondH = null;
private ActiveJNumberLabel acSecondL = null;
/*-- Buttons Panel members --*/
private String theButtons = "cbuttons.bmp";
private Image imButtons;
private ActiveJButton acPrevious, acPlay, acPause, acStop, acNext, acEject;
private Image imPrevious, imPlay, imPause, imStop, imNext, imEject;
private Image[] releasedImage = { imPrevious, imPlay, imPause, imStop, imNext, imEject };
private Image[] pressedImage = { imPrevious, imPlay, imPause, imStop, imNext, imEject };
private int[] releasedPanel = { 0, 0, 23, 18, 23, 0, 23, 18, 46, 0, 23, 18, 69, 0, 23, 18, 92, 0, 22, 18, 114, 0, 22, 16 };
private int[] pressedPanel = { 0, 18, 23, 18, 23, 18, 23, 18, 46, 18, 23, 18, 69, 18, 23, 18, 92, 18, 22, 18, 114, 16, 22, 16 };
private int[] panelLocation = { 16, 88, 39, 88, 62, 88, 85, 88, 108, 88, 136, 89 };
/*-- EqualizerUI/Playlist/Shuffle/Repeat --*/
private String theEPSRButtons = "shufrep.bmp";
private Image imEPSRButtons;
private ActiveJToggleButton acEqualizer, acPlaylist, acShuffle, acRepeat;
private Image[] releasedEPSRImage = { null, null, null, null };
private Image[] pressedEPSRImage = { null, null, null, null };
private int[] releasedEPSRPanel = { 0, 61, 23, 12, 23, 61, 23, 12, 28, 0, 47, 15, 0, 0, 28, 15 };
private int[] pressedEPSRPanel = { 0, 73, 23, 12, 23, 73, 23, 12, 28, 30, 47, 15, 0, 30, 28, 15 };
private int[] panelEPSRLocation = { 219, 58, 242, 58, 164, 89, 212, 89 };
/*-- Volume Panel members --*/
public static final int VOLUMEMAX = 100;
private String theVolume = "volume.bmp";
private Image imVolume;
private ActiveJSlider acVolume = null;;
private Image[] volumeImage = { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null };
private String fakeIndex = "abcdefghijklmnopqrstuvwxyz01";
private int[] volumeBarLocation = { 107, 57 };
private Image[] releasedVolumeImage = { null };
private Image[] pressedVolumeImage = { null };
private int[] releasedVolumePanel0 = { 15, 422, 14, 11 };
private int[] pressedVolumePanel0 = { 0, 422, 14, 11 };
private int[] releasedVolumePanel1 = { 75, 376, 14, 11 };
private int[] pressedVolumePanel1 = { 90, 376, 14, 11 };
/*-- Balance Panel members --*/
public static final int BALANCEMAX = 5;
private String theBalance = "balance.bmp";
private ActiveJSlider acBalance = null;
private Image imBalance;
private Image[] balanceImage = { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null };
private Image[] releasedBalanceImage = { null };
private Image[] pressedBalanceImage = { null };
private int[] releasedBalancePanel0 = { 15, 422, 14, 11 };
private int[] pressedBalancePanel0 = { 0, 422, 14, 11 };
private int[] releasedBalancePanel1 = { 75, 376, 14, 11 };
private int[] pressedBalancePanel1 = { 90, 376, 14, 11 };
private int[] balanceBarLocation = { 177, 57 };
/*-- Title members --*/
private String theTitleBar = "titlebar.bmp";
private Image imTitleBar;
private ActiveJBar acTitleBar = null;
private Image imTitleB;
private Image[] releasedTitleIm = { imTitleB };
private Image[] pressedTitleIm = { imTitleB };
private int[] releasedTitlePanel = { 27, 0, 264 - 20, 14 }; // -20 for the two button add by me
private int[] pressedTitlePanel = { 27, 15, 264 - 20, 14 };// -20 for the two button add by me
private int[] titleBarLocation = { 0, 0 };
/*-- Exit member --*/
private ActiveJButton acExit = null;
private int[] releasedExitPanel = { 18, 0, 9, 9 };
private int[] pressedExitPanel = { 18, 9, 9, 9 };
private Image[] releasedExitIm = { null };
private Image[] pressedExitIm = { null };
private int[] exitLocation = { 264, 3 };
/*-- Minimize member --*/
private ActiveJButton acMinimize = null;
private int[] releasedMinimizePanel = { 9, 0, 9, 9 };
private int[] pressedMinimizePanel = { 9, 9, 9, 9 };
private Image[] releasedMinimizeIm = { null };
private Image[] pressedMinimizeIm = { null };
private int[] minimizeLocation = { 244, 3 };
/*-- Mono/Stereo Members --*/
private String theMode = "monoster.bmp";
private Image imMode;
private int[] activeModePanel = { 0, 0, 28, 12, 29, 0, 27, 12 };
private int[] passiveModePanel = { 0, 12, 28, 12, 29, 12, 27, 12 };
private Image[] activeModeImage = { null, null };
private Image[] passiveModeImage = { null, null };
private int[] monoLocation = { 212, 41 };
private int[] stereoLocation = { 239, 41 };
private ActiveJIcon acMonoIcon = null;
private ActiveJIcon acStereoIcon = null;
/*-- PosBar members --*/
public static final int POSBARMAX = 1000;
private String thePosBar = "posbar.bmp";
private Image imPosBar;
private ActiveJSlider acPosBar = null;
private Image[] releasedPosIm = { null };
private Image[] pressedPosIm = { null };
private int[] releasedPosPanel = { 248, 0, 28, 10 };
private int[] pressedPosPanel = { 278, 0, 28, 10 };
private int[] posBarLocation = { 16, 72 };
/*-- Play/Pause Icons --*/
private String theIcons = "playpaus.bmp";
private Image imIcons;
private Image[] iconsImage = { null, null, null, null, null };
private int[] iconsPanel = { 0, 0, 9, 9, 9, 0, 9, 9, 18, 0, 9, 9, 36, 0, 3, 9, 27, 0, 2, 9 };
private int[] iconsLocation = { 26, 28, 24, 28 };
private ActiveJIcon acPlayIcon = null;
private ActiveJIcon acTimeIcon = null;
/*-- Readme --*/
private String theReadme = "readme.txt";
private String readme = null;
/*-- DSP and viscolor --*/
private String theViscolor = "viscolor.txt";
private String viscolor = null;
private int[] visualLocation = { 24, 44 };
private int[] visualSize = { 76, 15 };
private SpectrumTimeAnalyzer analyzer = null;
/*-- EqualizerUI --*/
private Image imFullEqualizer = null;
private Image imEqualizer = null;
private Image imSliders = null;
private ActiveJSlider[] acSlider = { null, null, null, null, null, null, null, null, null, null, null };
private Image[] sliderImage = { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null };
private int[][] sliderBarLocation = { { 21, 38 }, { 78, 38 }, { 96, 38 }, { 114, 38 }, { 132, 38 }, { 150, 38 }, { 168, 38 }, { 186, 38 }, { 204, 38 }, { 222, 38 }, { 240, 38 } };
private Image[] releasedSliderImage = { null };
private Image[] pressedSliderImage = { null };
private int[][] sliderLocation = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
private Image[] releasedPresetsImage = { null };
private Image[] pressedPresetsImage = { null };
private int[] panelPresetsLocation = { 217, 18 };
private ActiveJButton acPresets = null;
private ActiveJToggleButton acOnOff, acAuto;
private Image[] releasedOAImage = { null, null };
private Image[] pressedOAImage = { null, null };
private int[] panelOALocation = { 15, 18, 39, 18 };
private SplinePanel spline = null;
private int[] panelSplineLocation = { 88, 17, 113, 19 };
private Image splineImage = null;
private Image splineBarImage = null;
private ResourceBundle bundle = null;
/*-- Playlist --*/
private PlaylistUIDelegate playlist = null;
private Image imPlaylist = null;
private String plEdit = null;
private ActiveJSlider acPlSlider = null;
private int[] plSliderLocation = { 255, 20 };
private ActiveJButton acPlUp, acPlDown;
private ActiveJButton acPlAdd, acPlRemove, acPlSelect, acPlMisc, acPlList;
private int[] plAddLocation = { 14, 86 };
private int[] plRemoveLocation = { 14 + 30, 86 };
private int[] plSelectLocation = { 14 + 60, 86 };
private int[] plMiscLocation = { 14 + 89, 86 };
private int[] plListLocation = { 14 + 214, 86 };
private ActiveJPopup acPlAddPopup, acPlRemovePopup, acPlSelectPopup, acPlMiscPopup, acPlListPopup;
private int[] plAddPopupArea = { 14, 50, 22, 18 * 3 };
private int[] plRemovePopupArea = { 14 + 29, 32, 22, 18 * 4 };
private int[] plSelectPopupArea = { 14 + 58, 50, 22, 18 * 3 };
private int[] plMiscPopupArea = { 14 + 87, 50, 22, 18 * 3 };
private int[] plListPopupArea = { 14 + 217, 50, 22, 18 * 3 };
public Skin()
{
super();
String i18n = "javazoom/jlgui/player/amp/skin/skin";
bundle = ResourceBundle.getBundle(i18n);
}
/**
* Return I18N value of a given key.
* @param key
* @return
*/
public String getResource(String key)
{
String value = null;
try
{
value = bundle.getString(key);
}
catch (MissingResourceException e)
{
log.debug(e);
}
return value;
}
/**
* Return skin path.
* @return
*/
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public boolean isDspEnabled()
{
return dspEnabled;
}
public void setDspEnabled(boolean dspEnabled)
{
this.dspEnabled = dspEnabled;
}
/**
* Loads a new skin from local file system.
* @param skinName
*/
public void loadSkin(String skinName)
{
SkinLoader skl = new SkinLoader(skinName);
try
{
loadSkin(skl);
path = skinName;
}
catch (Exception e)
{
log.info("Can't load skin : ", e);
InputStream sis = this.getClass().getClassLoader().getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
log.info("Load default skin for JAR");
loadSkin(sis);
}
}
/**
* Loads a new skin from any input stream.
* @param skinStream
*/
public void loadSkin(InputStream skinStream)
{
SkinLoader skl = new SkinLoader(skinStream);
try
{
loadSkin(skl);
}
catch (Exception e)
{
log.info("Can't load skin : ", e);
InputStream sis = this.getClass().getClassLoader().getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
log.info("Load default skin for JAR");
loadSkin(sis);
}
}
/**
* Loads a skin from a SkinLoader.
* @param skl
* @throws Exception
*/
public void loadSkin(SkinLoader skl) throws Exception
{
skl.loadImages();
imMain = skl.getImage(theMain);
imButtons = skl.getImage(theButtons);
imTitleBar = skl.getImage(theTitleBar);
imText = skl.getImage(theText);
imMode = skl.getImage(theMode);
imNumbers = skl.getImage(theNumbers);
// add by John Yang
if (imNumbers == null)
{
log.debug("Try load nums_ex.bmp !");
imNumbers = skl.getImage(theNumEx);
}
imVolume = skl.getImage(theVolume);
imBalance = skl.getImage(theBalance);
imIcons = skl.getImage(theIcons);
imPosBar = skl.getImage(thePosBar);
imEPSRButtons = skl.getImage(theEPSRButtons);
viscolor = (String) skl.getContent(theViscolor);
String readmeStr = theReadme;
readme = (String) skl.getContent(readmeStr);
if (readme == null)
{
readmeStr = readmeStr.toUpperCase();
readme = (String) skl.getContent(readmeStr);
}
if (readme == null)
{
readmeStr = readmeStr.substring(0, 1) + theReadme.substring(1, theReadme.length());
readme = (String) skl.getContent(readmeStr);
}
// Computes volume slider height :
int vh = (imVolume.getHeight(null) - 422);
if (vh > 0)
{
releasedVolumePanel0[3] = vh;
pressedVolumePanel0[3] = vh;
releasedVolumePanel1[3] = vh;
pressedVolumePanel1[3] = vh;
}
// Computes balance slider height :
if (imBalance == null) imBalance = imVolume;
int bh = (imBalance.getHeight(null) - 422);
if (bh > 0)
{
releasedBalancePanel0[3] = bh;
pressedBalancePanel0[3] = bh;
releasedBalancePanel1[3] = bh;
pressedBalancePanel1[3] = bh;
}
// Compute posbar height.
int ph = imPosBar.getHeight(null);
if (ph > 0)
{
releasedPosPanel[3] = ph;
pressedPosPanel[3] = ph;
}
WinHeight = imMain.getHeight(null); // 116
WinWidth = imMain.getWidth(null); // 275
/*-- Text --*/
acFont = new ActiveFont(imText, fontIndex, fontWidth, fontHeight);
acTitleLabel = new ActiveJLabel();
acTitleLabel.setAcFont(acFont);
acTitleLabel.setCropRectangle(new Rectangle(0, 0, 155, 6));
acTitleLabel.setConstraints(new AbsoluteConstraints(titleLocation[0], titleLocation[1], 155, 6));
acTitleLabel.setAcText(TITLETEXT.toUpperCase());
acSampleRateLabel = new ActiveJLabel();
acSampleRateLabel.setAcFont(acFont);
acSampleRateLabel.setConstraints(new AbsoluteConstraints(sampleRateLocation[0], sampleRateLocation[1]));
acSampleRateLabel.setAcText(sampleRateClearText);
acBitRateLabel = new ActiveJLabel();
acBitRateLabel.setAcFont(acFont);
acBitRateLabel.setConstraints(new AbsoluteConstraints(bitsRateLocation[0], bitsRateLocation[1]));
acBitRateLabel.setAcText(bitsRateClearText);
/*-- Buttons --*/
readPanel(releasedImage, releasedPanel, pressedImage, pressedPanel, imButtons);
setButtonsPanel();
/*-- Volume/Balance --*/
if (skinVersion.equals("1"))
{
readPanel(releasedVolumeImage, releasedVolumePanel0, pressedVolumeImage, pressedVolumePanel0, imVolume);
readPanel(releasedBalanceImage, releasedBalancePanel0, pressedBalanceImage, pressedBalancePanel0, imBalance);
}
else
{
readPanel(releasedVolumeImage, releasedVolumePanel1, pressedVolumeImage, pressedVolumePanel1, imVolume);
readPanel(releasedBalanceImage, releasedBalancePanel1, pressedBalanceImage, pressedBalancePanel1, imBalance);
}
setVolumeBalancePanel(vh, bh);
/*-- Title Bar --*/
readPanel(releasedTitleIm, releasedTitlePanel, pressedTitleIm, pressedTitlePanel, imTitleBar);
setTitleBarPanel();
/*-- Exit --*/
readPanel(releasedExitIm, releasedExitPanel, pressedExitIm, pressedExitPanel, imTitleBar);
setExitPanel();
/*-- Minimize --*/
readPanel(releasedMinimizeIm, releasedMinimizePanel, pressedMinimizeIm, pressedMinimizePanel, imTitleBar);
setMinimizePanel();
/*-- Mode --*/
readPanel(activeModeImage, activeModePanel, passiveModeImage, passiveModePanel, imMode);
setMonoStereoPanel();
/*-- Numbers --*/
ImageIcon[] numbers = new ImageIcon[numberIndex.length()];
for (int h = 0; h < numberIndex.length(); h++)
{
numbers[h] = new ImageIcon((new Taftb(numberIndex, imNumbers, numberWidth, numberHeight, 0, "" + numberIndex.charAt(h))).getBanner());
}
acMinuteH = new ActiveJNumberLabel();
acMinuteH.setNumbers(numbers);
acMinuteH.setConstraints(new AbsoluteConstraints(minuteHLocation[0], minuteHLocation[1]));
acMinuteH.setAcText(" ");
acMinuteL = new ActiveJNumberLabel();
acMinuteL.setNumbers(numbers);
acMinuteL.setConstraints(new AbsoluteConstraints(minuteLLocation[0], minuteLLocation[1]));
acMinuteL.setAcText(" ");
acSecondH = new ActiveJNumberLabel();
acSecondH.setNumbers(numbers);
acSecondH.setConstraints(new AbsoluteConstraints(secondHLocation[0], secondHLocation[1]));
acSecondH.setAcText(" ");
acSecondL = new ActiveJNumberLabel();
acSecondL.setNumbers(numbers);
acSecondL.setConstraints(new AbsoluteConstraints(secondLLocation[0], secondLLocation[1]));
acSecondL.setAcText(" ");
/*-- Icons --*/
readPanel(iconsImage, iconsPanel, null, null, imIcons);
acPlayIcon = new ActiveJIcon();
ImageIcon[] playIcons = { new ImageIcon(iconsImage[0]), new ImageIcon(iconsImage[1]), new ImageIcon(iconsImage[2]) };
acPlayIcon.setIcons(playIcons);
acPlayIcon.setConstraints(new AbsoluteConstraints(iconsLocation[0], iconsLocation[1]));
acPlayIcon.setIcon(2);
acTimeIcon = new ActiveJIcon();
ImageIcon[] timeIcons = { new ImageIcon(iconsImage[3]), new ImageIcon(iconsImage[4]) };
acTimeIcon.setIcons(timeIcons);
acTimeIcon.setConstraints(new AbsoluteConstraints(iconsLocation[2], iconsLocation[3]));
/*-- DSP --*/
setAnalyzerPanel();
/*-- Pos Bar --*/
readPanel(releasedPosIm, releasedPosPanel, pressedPosIm, pressedPosPanel, imPosBar);
setPosBarPanel();
/*-- EqualizerUI/Playlist/Shuffle/Repeat --*/
readPanel(releasedEPSRImage, releasedEPSRPanel, pressedEPSRImage, pressedEPSRPanel, imEPSRButtons);
setEPSRButtonsPanel();
/*-- EqualizerUI --*/
imFullEqualizer = skl.getImage("eqmain.bmp");
imEqualizer = new BufferedImage(WinWidth, WinHeight, BufferedImage.TYPE_INT_RGB);
imEqualizer.getGraphics().drawImage(imFullEqualizer, 0, 0, null);
imSliders = new BufferedImage(208, 128, BufferedImage.TYPE_INT_RGB);
imSliders.getGraphics().drawImage(imFullEqualizer, 0, 0, 208, 128, 13, 164, 13 + 208, 164 + 128, null);
setSliderPanel();
setOnOffAutoPanel();
setPresetsPanel();
setSplinePanel();
/*-- Playlist --*/
imPlaylist = skl.getImage("pledit.bmp");
plEdit = (String) skl.getContent("pledit.txt");
setPlaylistPanel();
}
/**
* Instantiate Buttons Panel with ActiveComponent.
*/
private void setButtonsPanel()
{
int l = 0;
acPrevious = new ActiveJButton();
acPrevious.setIcon(new ImageIcon(releasedImage[0]));
acPrevious.setPressedIcon(new ImageIcon(pressedImage[0]));
acPrevious.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[0].getWidth(null), releasedImage[0].getHeight(null)));
acPrevious.setToolTipText(getResource("button.previous"));
acPrevious.setActionCommand(PlayerActionEvent.ACPREVIOUS);
acPlay = new ActiveJButton();
acPlay.setIcon(new ImageIcon(releasedImage[1]));
acPlay.setPressedIcon(new ImageIcon(pressedImage[1]));
acPlay.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[1].getWidth(null), releasedImage[1].getHeight(null)));
acPlay.setToolTipText(getResource("button.play"));
acPlay.setActionCommand(PlayerActionEvent.ACPLAY);
acPause = new ActiveJButton();
acPause.setIcon(new ImageIcon(releasedImage[2]));
acPause.setPressedIcon(new ImageIcon(pressedImage[2]));
acPause.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[2].getWidth(null), releasedImage[2].getHeight(null)));
acPause.setToolTipText(getResource("button.pause"));
acPause.setActionCommand(PlayerActionEvent.ACPAUSE);
acStop = new ActiveJButton();
acStop.setIcon(new ImageIcon(releasedImage[3]));
acStop.setPressedIcon(new ImageIcon(pressedImage[3]));
acStop.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[3].getWidth(null), releasedImage[3].getHeight(null)));
acStop.setToolTipText(getResource("button.stop"));
acStop.setActionCommand(PlayerActionEvent.ACSTOP);
acNext = new ActiveJButton();
acNext.setIcon(new ImageIcon(releasedImage[4]));
acNext.setPressedIcon(new ImageIcon(pressedImage[4]));
acNext.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[4].getWidth(null), releasedImage[4].getHeight(null)));
acNext.setToolTipText(getResource("button.next"));
acNext.setActionCommand(PlayerActionEvent.ACNEXT);
acEject = new ActiveJButton();
acEject.setIcon(new ImageIcon(releasedImage[5]));
acEject.setPressedIcon(new ImageIcon(pressedImage[5]));
acEject.setConstraints(new AbsoluteConstraints(panelLocation[l++], panelLocation[l++], releasedImage[5].getWidth(null), releasedImage[5].getHeight(null)));
acEject.setToolTipText(getResource("button.eject"));
acEject.setActionCommand(PlayerActionEvent.ACEJECT);
}
/**
* Instantiate EPSR Buttons Panel with ActiveComponent.
* imEqualizer, imPlaylist, imShuffle, imRepeat
*/
private void setEPSRButtonsPanel()
{
int l = 0;
acEqualizer = new ActiveJToggleButton();
acEqualizer.setIcon(new ImageIcon(releasedEPSRImage[0]));
acEqualizer.setSelectedIcon(new ImageIcon(pressedEPSRImage[0]));
acEqualizer.setPressedIcon(new ImageIcon(pressedEPSRImage[0]));
acEqualizer.setConstraints(new AbsoluteConstraints(panelEPSRLocation[l++], panelEPSRLocation[l++], releasedEPSRImage[0].getWidth(null), releasedEPSRImage[0].getHeight(null)));
acEqualizer.setToolTipText(getResource("toggle.equalizer"));
acEqualizer.setActionCommand(PlayerActionEvent.ACEQUALIZER);
acEqualizer.setSelected(config.isEqualizerEnabled());
acPlaylist = new ActiveJToggleButton();
acPlaylist.setIcon(new ImageIcon(releasedEPSRImage[1]));
acPlaylist.setSelectedIcon(new ImageIcon(pressedEPSRImage[1]));
acPlaylist.setPressedIcon(new ImageIcon(pressedEPSRImage[1]));
acPlaylist.setConstraints(new AbsoluteConstraints(panelEPSRLocation[l++], panelEPSRLocation[l++], releasedEPSRImage[1].getWidth(null), releasedEPSRImage[1].getHeight(null)));
acPlaylist.setToolTipText(getResource("toggle.playlist"));
acPlaylist.setActionCommand(PlayerActionEvent.ACPLAYLIST);
acPlaylist.setSelected(config.isPlaylistEnabled());
acShuffle = new ActiveJToggleButton();
acShuffle.setIcon(new ImageIcon(releasedEPSRImage[2]));
acShuffle.setSelectedIcon(new ImageIcon(pressedEPSRImage[2]));
acShuffle.setPressedIcon(new ImageIcon(pressedEPSRImage[2]));
acShuffle.setConstraints(new AbsoluteConstraints(panelEPSRLocation[l++], panelEPSRLocation[l++], releasedEPSRImage[2].getWidth(null), releasedEPSRImage[2].getHeight(null)));
acShuffle.setToolTipText(getResource("toggle.shuffle"));
acShuffle.setActionCommand(PlayerActionEvent.ACSHUFFLE);
acShuffle.setSelected(config.isShuffleEnabled());
acRepeat = new ActiveJToggleButton();
acRepeat.setIcon(new ImageIcon(releasedEPSRImage[3]));
acRepeat.setSelectedIcon(new ImageIcon(pressedEPSRImage[3]));
acRepeat.setPressedIcon(new ImageIcon(pressedEPSRImage[3]));
acRepeat.setConstraints(new AbsoluteConstraints(panelEPSRLocation[l++], panelEPSRLocation[l++], releasedEPSRImage[3].getWidth(null), releasedEPSRImage[3].getHeight(null)));
acRepeat.setToolTipText(getResource("toggle.repeat"));
acRepeat.setActionCommand(PlayerActionEvent.ACREPEAT);
acRepeat.setSelected(config.isRepeatEnabled());
}
/**
* Instantiate Volume/Balance Panel with ActiveComponent.
* @param vheight
* @param bheight
*/
private void setVolumeBalancePanel(int vheight, int bheight)
{
// Volume.
acVolume = new ActiveJSlider();
acVolume.setMinimum(0);
acVolume.setMaximum(VOLUMEMAX);
int volumeValue = config.getVolume();
if (volumeValue < 0) volumeValue = (int) VOLUMEMAX / 2;
acVolume.setValue(volumeValue);
acVolume.setToolTipText(getResource("slider.volume"));
int l = 0;
for (int k = 0; k < volumeImage.length; k++)
{
//volumeImage[k] = (new Taftb(fakeIndex, imVolume, 68, 13, 2, "" + fakeIndex.charAt(k))).getBanner();
volumeImage[k] = (new Taftb(fakeIndex, imVolume, imVolume.getWidth(null), 13, 2, "" + fakeIndex.charAt(k))).getBanner();
}
if (volumeImage[0].getHeight(null) > releasedVolumeImage[0].getHeight(null))
{
acVolume.setConstraints(new AbsoluteConstraints(volumeBarLocation[l++], volumeBarLocation[l++], volumeImage[0].getWidth(null), volumeImage[0].getHeight(null)));
}
else
{
acVolume.setConstraints(new AbsoluteConstraints(volumeBarLocation[l++], volumeBarLocation[l++], volumeImage[0].getWidth(null), releasedVolumeImage[0].getHeight(null)));
}
ActiveSliderUI sUI = new ActiveSliderUI(acVolume);
sUI.setThumbImage(releasedVolumeImage[0]);
sUI.setThumbPressedImage(pressedVolumeImage[0]);
sUI.setBackgroundImages(volumeImage);
if (vheight < 0) vheight = 0;
sUI.forceThumbHeight(vheight);
sUI.setThumbXOffset(0);
sUI.setThumbYOffset(1);
acVolume.setUI(sUI);
// Balance
acBalance = new ActiveJSlider();
acBalance.setMinimum(-BALANCEMAX);
acBalance.setMaximum(BALANCEMAX);
acBalance.setValue(0);
acBalance.setToolTipText(getResource("slider.balance"));
Image cropBalance = new BufferedImage(38, 418, BufferedImage.TYPE_INT_RGB);
Graphics g = cropBalance.getGraphics();
g.drawImage(imBalance, 0, 0, 38, 418, 9, 0, 9 + 38, 0 + 418, null);
for (int k = 0; k < balanceImage.length; k++)
{
balanceImage[k] = (new Taftb(fakeIndex, cropBalance, 38, 13, 2, "" + fakeIndex.charAt(k))).getBanner();
}
l = 0;
if (balanceImage[0].getHeight(null) > releasedBalanceImage[0].getHeight(null))
{
acBalance.setConstraints(new AbsoluteConstraints(balanceBarLocation[l++], balanceBarLocation[l++], balanceImage[0].getWidth(null), balanceImage[0].getHeight(null)));
}
else
{
acBalance.setConstraints(new AbsoluteConstraints(balanceBarLocation[l++], balanceBarLocation[l++], balanceImage[0].getWidth(null), releasedBalanceImage[0].getHeight(null)));
}
sUI = new ActiveSliderUI(acBalance);
sUI.setThumbImage(releasedBalanceImage[0]);
sUI.setThumbPressedImage(pressedBalanceImage[0]);
sUI.setBackgroundImages(balanceImage);
if (bheight < 0) bheight = 0;
sUI.forceThumbHeight(bheight);
sUI.setThumbXOffset(1);
sUI.setThumbYOffset(1);
acBalance.setUI(sUI);
}
/**
* Instantiate Title Panel with ActiveComponent.
*/
protected void setTitleBarPanel()
{
int l = 0;
acTitleBar = new ActiveJBar();
ImageBorder border = new ImageBorder();
border.setImage(releasedTitleIm[0]);
acTitleBar.setBorder(border);
acTitleBar.setConstraints(new AbsoluteConstraints(titleBarLocation[l++], titleBarLocation[l++], releasedTitleIm[0].getWidth(null), releasedTitleIm[0].getHeight(null)));
}
/**
* Instantiate Exit Panel with ActiveComponent.
*/
protected void setExitPanel()
{
int l = 0;
acExit = new ActiveJButton();
acExit.setIcon(new ImageIcon(releasedExitIm[0]));
acExit.setPressedIcon(new ImageIcon(pressedExitIm[0]));
acExit.setConstraints(new AbsoluteConstraints(exitLocation[l++], exitLocation[l++], releasedExitIm[0].getWidth(null), releasedExitIm[0].getHeight(null)));
acExit.setToolTipText(getResource("button.exit"));
acExit.setActionCommand(PlayerActionEvent.ACEXIT);
}
/**
* Instantiate Minimize Panel with ActiveComponent.
*/
protected void setMinimizePanel()
{
int l = 0;
acMinimize = new ActiveJButton();
acMinimize.setIcon(new ImageIcon(releasedMinimizeIm[0]));
acMinimize.setPressedIcon(new ImageIcon(pressedMinimizeIm[0]));
acMinimize.setConstraints(new AbsoluteConstraints(minimizeLocation[l++], minimizeLocation[l++], releasedMinimizeIm[0].getWidth(null), releasedMinimizeIm[0].getHeight(null)));
acMinimize.setToolTipText(getResource("button.minimize"));
acMinimize.setActionCommand(PlayerActionEvent.ACMINIMIZE);
}
/**
* Instantiate Mono/Stereo panel.
*/
private void setMonoStereoPanel()
{
acMonoIcon = new ActiveJIcon();
ImageIcon[] mono = { new ImageIcon(passiveModeImage[1]), new ImageIcon(activeModeImage[1]) };
acMonoIcon.setIcons(mono);
acMonoIcon.setIcon(0);
acMonoIcon.setConstraints(new AbsoluteConstraints(monoLocation[0], monoLocation[1], passiveModeImage[1].getWidth(null), passiveModeImage[1].getHeight(null)));
acStereoIcon = new ActiveJIcon();
ImageIcon[] stereo = { new ImageIcon(passiveModeImage[0]), new ImageIcon(activeModeImage[0]) };
acStereoIcon.setIcons(stereo);
acStereoIcon.setIcon(0);
acStereoIcon.setConstraints(new AbsoluteConstraints(stereoLocation[0], stereoLocation[1], passiveModeImage[0].getWidth(null), passiveModeImage[0].getHeight(null)));
}
/**
* Initialize Spectrum/Time analyzer.
*/
private void setAnalyzerPanel()
{
String javaVersion = System.getProperty("java.version");
if ((javaVersion != null) && ((javaVersion.startsWith("1.3"))) || (javaVersion.startsWith("1.4")))
{
log.info("DSP disabled for JRE " + javaVersion);
}
else if (!dspEnabled)
{
log.info("DSP disabled");
}
else
{
if (analyzer == null) analyzer = new SpectrumTimeAnalyzer();
String visualMode = config.getVisualMode();
if ((visualMode != null) && (visualMode.length() > 0))
{
if (visualMode.equalsIgnoreCase("off")) analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_OFF);
else if (visualMode.equalsIgnoreCase("oscillo")) analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_SCOPE);
else analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_SPECTRUM_ANALYSER);
}
else analyzer.setDisplayMode(SpectrumTimeAnalyzer.DISPLAY_MODE_SPECTRUM_ANALYSER);
analyzer.setSpectrumAnalyserBandCount(19);
analyzer.setVisColor(viscolor);
analyzer.setLocation(visualLocation[0], visualLocation[1]);
analyzer.setSize(visualSize[0], visualSize[1]);
analyzer.setSpectrumAnalyserDecay(0.05f);
int fps = SpectrumTimeAnalyzer.DEFAULT_FPS;
analyzer.setFps(fps);
analyzer.setPeakDelay((int) (fps * SpectrumTimeAnalyzer.DEFAULT_SPECTRUM_ANALYSER_PEAK_DELAY_FPS_RATIO));
analyzer.setConstraints(new AbsoluteConstraints(visualLocation[0], visualLocation[1], visualSize[0], visualSize[1]));
analyzer.setToolTipText(getResource("panel.analyzer"));
}
}
/**
* Instantiate PosBar Panel with ActiveComponent.
*/
protected void setPosBarPanel()
{
int l = 0;
Image posBackground = new BufferedImage(248, 10, BufferedImage.TYPE_INT_RGB);
posBackground.getGraphics().drawImage(imPosBar, 0, 0, 248, 10, 0, 0, 248, 10, null);
acPosBar = new ActiveJSlider();
acPosBar.setMinimum(0);
acPosBar.setMaximum(POSBARMAX);
acPosBar.setValue(0);
acPosBar.setOrientation(JSlider.HORIZONTAL);
acPosBar.setConstraints(new AbsoluteConstraints(posBarLocation[l++], posBarLocation[l++], 248, releasedPosIm[0].getHeight(null)));
ActiveSliderUI sUI = new ActiveSliderUI(acPosBar);
Image[] back = { posBackground };
sUI.setBackgroundImages(back);
sUI.setThumbXOffset(0);
sUI.setThumbYOffset(0);
sUI.setThumbImage(releasedPosIm[0]);
sUI.setThumbPressedImage(pressedPosIm[0]);
acPosBar.setUI(sUI);
acPosBar.setToolTipText(getResource("slider.seek"));
}
/**
* Set sliders for equalizer.
*/
private void setSliderPanel()
{
releasedSliderImage[0] = new BufferedImage(12, 11, BufferedImage.TYPE_INT_RGB);
Graphics g = releasedSliderImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, 12, 11, 0, 164, 0 + 12, 164 + 11, null);
pressedSliderImage[0] = new BufferedImage(10, 11, BufferedImage.TYPE_INT_RGB);
g = pressedSliderImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, 11, 11, 0, 176, 0 + 11, 176 + 11, null);
for (int k = 0; k < sliderImage.length / 2; k++)
{
sliderImage[k] = new BufferedImage(13, 63, BufferedImage.TYPE_INT_RGB);
g = sliderImage[k].getGraphics();
g.drawImage(imSliders, 0, 0, 13, 63, k * 15, 0, k * 15 + 13, 0 + 63, null);
}
for (int k = 0; k < sliderImage.length / 2; k++)
{
sliderImage[k + (sliderImage.length / 2)] = new BufferedImage(13, 63, BufferedImage.TYPE_INT_RGB);
g = sliderImage[k + (sliderImage.length / 2)].getGraphics();
g.drawImage(imSliders, 0, 0, 13, 63, k * 15, 65, k * 15 + 13, 65 + 63, null);
}
// Setup sliders
for (int i = 0; i < acSlider.length; i++)
{
sliderLocation[i][0] = sliderBarLocation[i][0] + 1;
sliderLocation[i][1] = sliderBarLocation[i][1] + 1;// + deltaSlider * gainEqValue[i] / maxEqGain;
acSlider[i] = new ActiveJSlider();
acSlider[i].setMinimum(0);
acSlider[i].setMaximum(100);
acSlider[i].setValue(50);
acSlider[i].setOrientation(JSlider.VERTICAL);
ActiveSliderUI sUI = new ActiveSliderUI(acSlider[i]);
sUI.setThumbImage(releasedSliderImage[0]);
sUI.setThumbPressedImage(pressedSliderImage[0]);
sUI.setBackgroundImages(sliderImage);
sUI.setThumbXOffset(1);
sUI.setThumbYOffset(-1);
acSlider[i].setUI(sUI);
acSlider[i].setConstraints(new AbsoluteConstraints(sliderLocation[i][0], sliderLocation[i][1], releasedSliderImage[0].getWidth(null), sliderImage[0].getHeight(null)));
}
acSlider[0].setEnabled(false);
}
/**
* Set On/Off and Auto checkbox.
*/
public void setOnOffAutoPanel()
{
// On/Off
int w = 24, h = 12;
releasedOAImage[0] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = releasedOAImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 10, 119, 10 + w, 119 + h, null);
pressedOAImage[0] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g = pressedOAImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 69, 119, 69 + w, 119 + h, null);
acOnOff = new ActiveJToggleButton();
acOnOff.setIcon(new ImageIcon(releasedOAImage[0]));
acOnOff.setSelectedIcon(new ImageIcon(pressedOAImage[0]));
acOnOff.setPressedIcon(new ImageIcon(pressedOAImage[0]));
acOnOff.setSelected(config.isEqualizerOn());
acOnOff.setConstraints(new AbsoluteConstraints(panelOALocation[0], panelOALocation[1], releasedOAImage[0].getWidth(null), releasedOAImage[0].getHeight(null)));
acOnOff.setToolTipText(getResource("equalizer.toggle.onoff"));
acOnOff.setActionCommand(PlayerActionEvent.ACEQONOFF);
// Auto
w = 34;
h = 12;
releasedOAImage[1] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g = releasedOAImage[1].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 34, 119, 34 + w, 119 + h, null);
pressedOAImage[1] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g = pressedOAImage[1].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 93, 119, 93 + w, 119 + h, null);
acAuto = new ActiveJToggleButton();
acAuto.setIcon(new ImageIcon(releasedOAImage[1]));
acAuto.setPressedIcon(new ImageIcon(pressedOAImage[1]));
acAuto.setSelectedIcon(new ImageIcon(pressedOAImage[1]));
acAuto.setConstraints(new AbsoluteConstraints(panelOALocation[2], panelOALocation[3], releasedOAImage[1].getWidth(null), releasedOAImage[1].getHeight(null)));
acAuto.setToolTipText(getResource("equalizer.toggle.auto"));
acAuto.setActionCommand(PlayerActionEvent.ACEQAUTO);
}
/**
* Set presets button.
*/
public void setPresetsPanel()
{
int w = 44, h = 12;
releasedPresetsImage[0] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = releasedPresetsImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 224, 164, 224 + w, 164 + h, null);
pressedPresetsImage[0] = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g = pressedPresetsImage[0].getGraphics();
g.drawImage(imFullEqualizer, 0, 0, w, h, 224, 176, 224 + w, 176 + h, null);
acPresets = new ActiveJButton();
acPresets.setIcon(new ImageIcon(releasedPresetsImage[0]));
acPresets.setPressedIcon(new ImageIcon(pressedPresetsImage[0]));
acPresets.setConstraints(new AbsoluteConstraints(panelPresetsLocation[0], panelPresetsLocation[1], releasedPresetsImage[0].getWidth(null), releasedPresetsImage[0].getHeight(null)));
acPresets.setToolTipText(getResource("equalizer.button.presets"));
acPresets.setActionCommand(PlayerActionEvent.ACEQPRESETS);
}
/**
* Instantiate equalizer spline panel.
*/
public void setSplinePanel()
{
int w = panelSplineLocation[2];
int h = panelSplineLocation[3];
splineImage = null;
splineBarImage = null;
spline = null;
if (imFullEqualizer.getHeight(null) > 294)
{
splineImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
splineBarImage = new BufferedImage(w, 1, BufferedImage.TYPE_INT_RGB);
splineImage.getGraphics().drawImage(imFullEqualizer, 0, 0, w, h, 0, 294, 0 + w, 294 + h, null);
splineBarImage.getGraphics().drawImage(imFullEqualizer, 0, 0, w, 1, 0, 294 + h + 1, 0 + w, 294 + h + 1 + 1, null);
spline = new SplinePanel();
spline.setBackgroundImage(splineImage);
spline.setBarImage(splineBarImage);
int[] pixels = new int[1 * h];
PixelGrabber pg = new PixelGrabber(imFullEqualizer, 115, 294, 1, h, pixels, 0, 1);
try
{
pg.grabPixels();
}
catch (InterruptedException e)
{
log.debug(e);
}
Color[] colors = new Color[h];
for (int i = 0; i < h; i++)
{
int c = pixels[i];
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
colors[i] = new Color(red, green, blue);
}
spline.setGradient(colors);
spline.setConstraints(new AbsoluteConstraints(panelSplineLocation[0], panelSplineLocation[1], panelSplineLocation[2], panelSplineLocation[3]));
}
}
/**
* Instantiate playlist panel.
*/
public void setPlaylistPanel()
{
playlist = new PlaylistUIDelegate();
Image titleCenter = new BufferedImage(100, 20, BufferedImage.TYPE_INT_RGB);
titleCenter.getGraphics().drawImage(imPlaylist, 0, 0, 100, 20, 26, 0, 126, 20, null);
playlist.setTitleCenterImage(titleCenter);
Image titleLeft = new BufferedImage(25, 20, BufferedImage.TYPE_INT_RGB);
titleLeft.getGraphics().drawImage(imPlaylist, 0, 0, 25, 20, 0, 0, 25, 20, null);
playlist.setTitleLeftImage(titleLeft);
Image titleStretch = new BufferedImage(25, 20, BufferedImage.TYPE_INT_RGB);
titleStretch.getGraphics().drawImage(imPlaylist, 0, 0, 25, 20, 127, 0, 152, 20, null);
playlist.setTitleStretchImage(titleStretch);
Image titleRight = new BufferedImage(25, 20, BufferedImage.TYPE_INT_RGB);
titleRight.getGraphics().drawImage(imPlaylist, 0, 0, 25, 20, 153, 0, 178, 20, null);
playlist.setTitleRightImage(titleRight);
Image btmLeft = new BufferedImage(125, 38, BufferedImage.TYPE_INT_RGB);
btmLeft.getGraphics().drawImage(imPlaylist, 0, 0, 125, 38, 0, 72, 125, 110, null);
playlist.setBottomLeftImage(btmLeft);
Image btmRight = new BufferedImage(150, 38, BufferedImage.TYPE_INT_RGB);
btmRight.getGraphics().drawImage(imPlaylist, 0, 0, 150, 38, 126, 72, 276, 110, null);
playlist.setBottomRightImage(btmRight);
Image bodyLeft = new BufferedImage(12, 28, BufferedImage.TYPE_INT_RGB);
bodyLeft.getGraphics().drawImage(imPlaylist, 0, 0, 12, 28, 0, 42, 12, 70, null);
playlist.setLeftImage(bodyLeft);
Image bodyRight = new BufferedImage(20, 28, BufferedImage.TYPE_INT_RGB);
bodyRight.getGraphics().drawImage(imPlaylist, 0, 0, 20, 28, 31, 42, 51, 70, null);
playlist.setRightImage(bodyRight);
// Parse color
plEdit = plEdit.toLowerCase();
ByteArrayInputStream in = new ByteArrayInputStream(plEdit.getBytes());
BufferedReader lin = new BufferedReader(new InputStreamReader(in));
try
{
for (;;)
{
String line = lin.readLine();
if (line == null) break;
if ((line.toLowerCase()).startsWith("normalbg")) playlist.setBackgroundColor(parsePlEditColor(line));
else if ((line.toLowerCase()).startsWith("normal")) playlist.setNormalColor(parsePlEditColor(line));
else if ((line.toLowerCase()).startsWith("current")) playlist.setCurrentColor(parsePlEditColor(line));
else if ((line.toLowerCase()).startsWith("selectedbg")) playlist.setSelectedBackgroundColor(parsePlEditColor(line));
}
}
catch (Exception e)
{
log.debug(e);
}
finally
{
try
{
if (in != null) in.close();
}
catch (IOException e)
{
}
}
// Playlist slider.
acPlSlider = new ActiveJSlider();
acPlSlider.setOrientation(JSlider.VERTICAL);
acPlSlider.setMinimum(0);
acPlSlider.setMaximum(100);
acPlSlider.setValue(100);
ActiveSliderUI sUI = new ActiveSliderUI(acPlSlider);
Image scrollBarReleased = new BufferedImage(8, 18, BufferedImage.TYPE_INT_RGB);
scrollBarReleased.getGraphics().drawImage(imPlaylist, 0, 0, 8, 18, 52, 53, 52 + 8, 53 + 18, null);
sUI.setThumbImage(scrollBarReleased);
Image scrollBarClicked = new BufferedImage(8, 18, BufferedImage.TYPE_INT_RGB);
scrollBarClicked.getGraphics().drawImage(imPlaylist, 0, 0, 8, 18, 61, 53, 61 + 8, 53 + 18, null);
sUI.setThumbPressedImage(scrollBarClicked);
Image sliderBackground = new BufferedImage(20, 58, BufferedImage.TYPE_INT_RGB);
sliderBackground.getGraphics().drawImage(bodyRight, 0, 0, null);
sliderBackground.getGraphics().drawImage(bodyRight, 0, 28, null);
sliderBackground.getGraphics().drawImage(bodyRight, 0, 30, null);
Image[] background = { sliderBackground };
sUI.setBackgroundImages(background);
sUI.setThumbXOffset(5);
acPlSlider.setUI(sUI);
acPlSlider.setConstraints(new AbsoluteConstraints(plSliderLocation[0], plSliderLocation[1], 20, 58));
// Up/Down scroll buttons
acPlUp = new ActiveJButton();
Image upScrollButton = new BufferedImage(8, 4, BufferedImage.TYPE_INT_RGB);
upScrollButton.getGraphics().drawImage(imPlaylist, 0, 0, 8, 4, 261, 75, 269, 79, null);
acPlUp.setIcon(new ImageIcon(upScrollButton));
acPlUp.setPressedIcon(new ImageIcon(upScrollButton));
acPlUp.setConstraints(new AbsoluteConstraints(WinWidth - 15, WinHeight - 35, 8, 4));
acPlUp.setActionCommand(PlayerActionEvent.ACPLUP);
acPlDown = new ActiveJButton();
Image downScrollButton = new BufferedImage(8, 4, BufferedImage.TYPE_INT_RGB);
downScrollButton.getGraphics().drawImage(imPlaylist, 0, 0, 8, 4, 261, 80, 269, 84, null);
acPlDown.setIcon(new ImageIcon(downScrollButton));
acPlDown.setPressedIcon(new ImageIcon(downScrollButton));
acPlDown.setConstraints(new AbsoluteConstraints(WinWidth - 15, WinHeight - 30, 8, 4));
acPlDown.setActionCommand(PlayerActionEvent.ACPLDOWN);
// Playlist AddFile/AddDir/AddURL buttons
int w = 22;
int h = 18;
Image addButtonImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
addButtonImage.getGraphics().drawImage(imPlaylist, 0, 0, w, h, 14, 80, 14 + w, 80 + h, null);
acPlAdd = new ActiveJButton();
acPlAdd.setIcon(new ImageIcon(addButtonImage));
acPlAdd.setPressedIcon(new ImageIcon(addButtonImage));
acPlAdd.setActionCommand(PlayerActionEvent.ACPLADDPOPUP);
acPlAdd.setConstraints(new AbsoluteConstraints(plAddLocation[0], plAddLocation[1], w, h));
ActiveJButton acPlAddFile = createPLButton(0, 149);
acPlAddFile.setActionCommand(PlayerActionEvent.ACPLADDFILE);
ActiveJButton acPlAddDir = createPLButton(0, 130);
acPlAddDir.setActionCommand(PlayerActionEvent.ACPLADDDIR);
ActiveJButton acPlAddURL = createPLButton(0, 111);
acPlAddURL.setActionCommand(PlayerActionEvent.ACPLADDURL);
acPlAddPopup = new ActiveJPopup();
ActiveJButton[] addbuttons = { acPlAddURL, acPlAddDir, acPlAddFile };
acPlAddPopup.setItems(addbuttons);
acPlAddPopup.setConstraints(new AbsoluteConstraints(plAddPopupArea[0], plAddPopupArea[1], plAddPopupArea[2], plAddPopupArea[3]));
// Playlist RemoveMisc/RemoveSelection/Crop/RemoveAll buttons
Image removeButtonImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
removeButtonImage.getGraphics().drawImage(imPlaylist, 0, 0, w, h, 14 + 30, 80, 14 + 30 + w, 80 + h, null);
acPlRemove = new ActiveJButton();
acPlRemove.setIcon(new ImageIcon(removeButtonImage));
acPlRemove.setPressedIcon(new ImageIcon(removeButtonImage));
acPlRemove.setActionCommand(PlayerActionEvent.ACPLREMOVEPOPUP);
acPlRemove.setConstraints(new AbsoluteConstraints(plRemoveLocation[0], plRemoveLocation[1], w, h));
ActiveJButton acPlRemoveMisc = createPLButton(54, 168);
acPlRemoveMisc.setActionCommand(PlayerActionEvent.ACPLREMOVEMISC);
ActiveJButton acPlRemoveSel = createPLButton(54, 149);
acPlRemoveSel.setActionCommand(PlayerActionEvent.ACPLREMOVESEL);
ActiveJButton acPlRemoveCrop = createPLButton(54, 130);
acPlRemoveCrop.setActionCommand(PlayerActionEvent.ACPLREMOVECROP);
ActiveJButton acPlRemoveAll = createPLButton(54, 111);
acPlRemoveAll.setActionCommand(PlayerActionEvent.ACPLREMOVEALL);
acPlRemovePopup = new ActiveJPopup();
ActiveJButton[] rembuttons = { acPlRemoveMisc, acPlRemoveAll, acPlRemoveCrop, acPlRemoveSel };
acPlRemovePopup.setItems(rembuttons);
acPlRemovePopup.setConstraints(new AbsoluteConstraints(plRemovePopupArea[0], plRemovePopupArea[1], plRemovePopupArea[2], plRemovePopupArea[3]));
// Playlist SelAll/SelZero/SelInv buttons
Image selButtonImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
selButtonImage.getGraphics().drawImage(imPlaylist, 0, 0, w, h, 14 + 60, 80, 14 + 60 + w, 80 + h, null);
acPlSelect = new ActiveJButton();
acPlSelect.setIcon(new ImageIcon(selButtonImage));
acPlSelect.setPressedIcon(new ImageIcon(selButtonImage));
acPlSelect.setActionCommand(PlayerActionEvent.ACPLSELPOPUP);
acPlSelect.setConstraints(new AbsoluteConstraints(plSelectLocation[0], plSelectLocation[1], w, h));
ActiveJButton acPlSelectAll = createPLButton(104, 149);
acPlSelectAll.setActionCommand(PlayerActionEvent.ACPLSELALL);
ActiveJButton acPlSelectZero = createPLButton(104, 130);
acPlSelectZero.setActionCommand(PlayerActionEvent.ACPLSELZERO);
ActiveJButton acPlSelectInv = createPLButton(104, 111);
acPlSelectInv.setActionCommand(PlayerActionEvent.ACPLSELINV);
acPlSelectPopup = new ActiveJPopup();
ActiveJButton[] selbuttons = { acPlSelectInv, acPlSelectZero, acPlSelectAll };
acPlSelectPopup.setItems(selbuttons);
acPlSelectPopup.setConstraints(new AbsoluteConstraints(plSelectPopupArea[0], plSelectPopupArea[1], plSelectPopupArea[2], plSelectPopupArea[3]));
// Playlist MiscOpts/MiscFile/MiscSort buttons
Image miscButtonImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
miscButtonImage.getGraphics().drawImage(imPlaylist, 0, 0, w, h, 14 + 89, 80, 14 + 89 + w, 80 + h, null);
acPlMisc = new ActiveJButton();
acPlMisc.setIcon(new ImageIcon(miscButtonImage));
acPlMisc.setPressedIcon(new ImageIcon(miscButtonImage));
acPlMisc.setActionCommand(PlayerActionEvent.ACPLMISCPOPUP);
acPlMisc.setConstraints(new AbsoluteConstraints(plMiscLocation[0], plMiscLocation[1], w, h));
ActiveJButton acPlMiscOpts = createPLButton(154, 149);
acPlMiscOpts.setActionCommand(PlayerActionEvent.ACPLMISCOPTS);
ActiveJButton acPlMiscFile = createPLButton(154, 130);
acPlMiscFile.setActionCommand(PlayerActionEvent.ACPLMISCFILE);
ActiveJButton acPlMiscSort = createPLButton(154, 111);
acPlMiscSort.setActionCommand(PlayerActionEvent.ACPLMISCSORT);
acPlMiscPopup = new ActiveJPopup();
ActiveJButton[] miscbuttons = { acPlMiscSort, acPlMiscFile, acPlMiscOpts };
acPlMiscPopup.setItems(miscbuttons);
acPlMiscPopup.setConstraints(new AbsoluteConstraints(plMiscPopupArea[0], plMiscPopupArea[1], plMiscPopupArea[2], plMiscPopupArea[3]));
// Playlist ListLoad/ListSave/ListNew buttons
Image listButtonImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
listButtonImage.getGraphics().drawImage(imPlaylist, 0, 0, w, h, 14 + 215, 80, 14 + 215 + w, 80 + h, null);
acPlList = new ActiveJButton();
acPlList.setIcon(new ImageIcon(listButtonImage));
acPlList.setPressedIcon(new ImageIcon(listButtonImage));
acPlList.setActionCommand(PlayerActionEvent.ACPLLISTPOPUP);
acPlList.setConstraints(new AbsoluteConstraints(plListLocation[0], plListLocation[1], w, h));
ActiveJButton acPlListLoad = createPLButton(204, 149);
acPlListLoad.setActionCommand(PlayerActionEvent.ACPLLISTLOAD);
ActiveJButton acPlListSave = createPLButton(204, 130);
acPlListSave.setActionCommand(PlayerActionEvent.ACPLLISTSAVE);
ActiveJButton acPlListNew = createPLButton(204, 111);
acPlListNew.setActionCommand(PlayerActionEvent.ACPLLISTNEW);
acPlListPopup = new ActiveJPopup();
ActiveJButton[] listbuttons = { acPlListNew, acPlListSave, acPlListLoad };
acPlListPopup.setItems(listbuttons);
acPlListPopup.setConstraints(new AbsoluteConstraints(plListPopupArea[0], plListPopupArea[1], plListPopupArea[2], plListPopupArea[3]));
}
/**
* Create Playlist buttons.
* @param sx
* @param sy
* @return
*/
private ActiveJButton createPLButton(int sx, int sy)
{
Image normal = new BufferedImage(22, 18, BufferedImage.TYPE_INT_RGB);
Image clicked = new BufferedImage(22, 18, BufferedImage.TYPE_INT_RGB);
Graphics g = normal.getGraphics();
g.drawImage(imPlaylist, 0, 0, 22, 18, sx, sy, sx + 22, sy + 18, null);
sx += 23;
g = clicked.getGraphics();
g.drawImage(imPlaylist, 0, 0, 22, 18, sx, sy, sx + 22, sy + 18, null);
ActiveJButton comp = new ActiveJButton();
comp.setIcon(new ImageIcon(normal));
comp.setPressedIcon(new ImageIcon(clicked));
comp.setRolloverIcon(new ImageIcon(clicked));
comp.setRolloverEnabled(true);
return comp;
}
/**
* Parse playlist colors.
* @param line
* @return
* @throws Exception
*/
private Color parsePlEditColor(String line) throws Exception
{
int pos = line.indexOf("#");
if (pos == -1)
{
pos = line.indexOf("=");
if (pos == -1) throw new Exception("Can not parse color!");
}
line = line.substring(pos + 1);
int r = Integer.parseInt(line.substring(0, 2), 16);
int g = Integer.parseInt(line.substring(2, 4), 16);
int b = Integer.parseInt(line.substring(4), 16);
return new Color(r, g, b);
}
/**
* Crop Panel Features from image file.
* @param releasedImage
* @param releasedPanel
* @param pressedImage
* @param pressedPanel
* @param imPanel
*/
public void readPanel(Image[] releasedImage, int[] releasedPanel, Image[] pressedImage, int[] pressedPanel, Image imPanel)
{
int xul, yul, xld, yld;
int j = 0;
if (releasedImage != null)
{
for (int i = 0; i < releasedImage.length; i++)
{
releasedImage[i] = new BufferedImage(releasedPanel[j + 2], releasedPanel[j + 3], BufferedImage.TYPE_INT_RGB);
xul = releasedPanel[j];
yul = releasedPanel[j + 1];
xld = releasedPanel[j] + releasedPanel[j + 2];
yld = releasedPanel[j + 1] + releasedPanel[j + 3];
(releasedImage[i].getGraphics()).drawImage(imPanel, 0, 0, releasedPanel[j + 2], releasedPanel[j + 3], xul, yul, xld, yld, null);
j = j + 4;
}
}
j = 0;
if (pressedImage != null)
{
for (int i = 0; i < pressedImage.length; i++)
{
pressedImage[i] = new BufferedImage(pressedPanel[j + 2], pressedPanel[j + 3], BufferedImage.TYPE_INT_RGB);
xul = pressedPanel[j];
yul = pressedPanel[j + 1];
xld = pressedPanel[j] + pressedPanel[j + 2];
yld = pressedPanel[j + 1] + pressedPanel[j + 3];
(pressedImage[i].getGraphics()).drawImage(imPanel, 0, 0, pressedPanel[j + 2], pressedPanel[j + 3], xul, yul, xld, yld, null);
j = j + 4;
}
}
}
public ActiveJButton getAcEject()
{
return acEject;
}
public ActiveJButton getAcNext()
{
return acNext;
}
public ActiveJButton getAcPause()
{
return acPause;
}
public ActiveJButton getAcPlay()
{
return acPlay;
}
public ActiveJButton getAcPrevious()
{
return acPrevious;
}
public ActiveJButton getAcStop()
{
return acStop;
}
public ActiveJButton getAcExit()
{
return acExit;
}
public ActiveJButton getAcMinimize()
{
return acMinimize;
}
public ActiveJBar getAcTitleBar()
{
return acTitleBar;
}
public ActiveJLabel getAcTitleLabel()
{
return acTitleLabel;
}
public ActiveJLabel getAcSampleRateLabel()
{
return acSampleRateLabel;
}
public ActiveJLabel getAcBitRateLabel()
{
return acBitRateLabel;
}
public String getSkinVersion()
{
return skinVersion;
}
public void setSkinVersion(String skinVersion)
{
this.skinVersion = skinVersion;
}
public ActiveJToggleButton getAcEqualizer()
{
return acEqualizer;
}
public ActiveJToggleButton getAcPlaylist()
{
return acPlaylist;
}
public ActiveJToggleButton getAcRepeat()
{
return acRepeat;
}
public ActiveJToggleButton getAcShuffle()
{
return acShuffle;
}
public ActiveJSlider getAcVolume()
{
return acVolume;
}
public ActiveJSlider getAcBalance()
{
return acBalance;
}
public ActiveJIcon getAcMonoIcon()
{
return acMonoIcon;
}
public ActiveJIcon getAcStereoIcon()
{
return acStereoIcon;
}
public ActiveJSlider getAcPosBar()
{
return acPosBar;
}
public ActiveJIcon getAcPlayIcon()
{
return acPlayIcon;
}
public ActiveJIcon getAcTimeIcon()
{
return acTimeIcon;
}
public ActiveJNumberLabel getAcMinuteH()
{
return acMinuteH;
}
public ActiveJNumberLabel getAcMinuteL()
{
return acMinuteL;
}
public ActiveJNumberLabel getAcSecondH()
{
return acSecondH;
}
public ActiveJNumberLabel getAcSecondL()
{
return acSecondL;
}
public SpectrumTimeAnalyzer getAcAnalyzer()
{
return analyzer;
}
public ActiveJButton getAcEqPresets()
{
return acPresets;
}
public ActiveJToggleButton getAcEqOnOff()
{
return acOnOff;
}
public ActiveJToggleButton getAcEqAuto()
{
return acAuto;
}
public ActiveJSlider[] getAcEqSliders()
{
return acSlider;
}
public ActiveJSlider getAcPlSlider()
{
return acPlSlider;
}
public ActiveJButton getAcPlUp()
{
return acPlUp;
}
public ActiveJButton getAcPlDown()
{
return acPlDown;
}
public ActiveJButton getAcPlAdd()
{
return acPlAdd;
}
public ActiveJPopup getAcPlAddPopup()
{
return acPlAddPopup;
}
public ActiveJButton getAcPlRemove()
{
return acPlRemove;
}
public ActiveJPopup getAcPlRemovePopup()
{
return acPlRemovePopup;
}
public ActiveJButton getAcPlSelect()
{
return acPlSelect;
}
public ActiveJPopup getAcPlSelectPopup()
{
return acPlSelectPopup;
}
public ActiveJButton getAcPlMisc()
{
return acPlMisc;
}
public ActiveJPopup getAcPlMiscPopup()
{
return acPlMiscPopup;
}
public ActiveJButton getAcPlList()
{
return acPlList;
}
public ActiveJPopup getAcPlListPopup()
{
return acPlListPopup;
}
public SplinePanel getSpline()
{
return spline;
}
public PlaylistUIDelegate getPlaylistPanel()
{
return playlist;
}
/**
* Return readme content from skin.
* @return
*/
public String getReadme()
{
return readme;
}
public int getMainWidth()
{
return WinWidth;
}
public int getMainHeight()
{
return WinHeight;
}
public Image getMainImage()
{
return imMain;
}
public Image getEqualizerImage()
{
return imEqualizer;
}
/**
* Return visual colors from skin.
* @return
*/
public String getVisColors()
{
return viscolor;
}
public Config getConfig()
{
return config;
}
public void setConfig(Config config)
{
this.config = config;
}
}
| Java |
/*
* SkinLoader.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.Hashtable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javazoom.jlgui.player.amp.util.BMPLoader;
import javazoom.jlgui.player.amp.util.Config;
/**
* This class implements a Skin Loader.
* WinAmp 2.x javazoom.jlgui.player.amp.skins compliant.
*/
public class SkinLoader
{
private Hashtable _images = null;
private ZipInputStream _zis = null;
/**
* Contructs a SkinLoader from a skin file.
*/
public SkinLoader(String filename)
{
_images = new Hashtable();
try
{
if (Config.startWithProtocol(filename)) _zis = new ZipInputStream((new URL(filename)).openStream());
else _zis = new ZipInputStream(new FileInputStream(filename));
}
catch (Exception e)
{
// Try to load included default skin.
ClassLoader cl = this.getClass().getClassLoader();
InputStream sis = cl.getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
if (sis != null) _zis = new ZipInputStream(sis);
}
}
/**
* Contructs a SkinLoader from any input stream.
*/
public SkinLoader(InputStream inputstream)
{
_images = new Hashtable();
_zis = new ZipInputStream(inputstream);
}
/**
* Loads data (images + info) from skin.
*/
public void loadImages() throws Exception
{
ZipEntry entry = _zis.getNextEntry();
String name;
BMPLoader bmp = new BMPLoader();
int pos;
while (entry != null)
{
name = entry.getName().toLowerCase();
pos = name.lastIndexOf("/");
if (pos != -1) name = name.substring(pos + 1);
if (name.endsWith("bmp"))
{
_images.put(name, bmp.getBMPImage(_zis));
}
else if (name.endsWith("txt"))
{
InputStreamReader reader = new InputStreamReader(_zis, "US-ASCII");
StringWriter writer = new StringWriter();
char buffer[] = new char[256];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1)
writer.write(buffer, 0, charsRead);
_images.put(name, writer.toString());
}
entry = _zis.getNextEntry();
}
_zis.close();
}
/**
* Return Image from name.
*/
public Image getImage(String name)
{
return (Image) _images.get(name);
}
// Added by John Yang - 02/05/2001
/**
* Return skin content (Image or String) from name.
*/
public Object getContent(String name)
{
return _images.get(name);
}
}
| Java |
/*
* PlaylistUIDelegate.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javazoom.jlgui.player.amp.playlist.PlaylistItem;
import javazoom.jlgui.player.amp.playlist.ui.PlaylistUI;
public class PlaylistUIDelegate
{
private AbsoluteConstraints constraints = null;
private Image titleLeftImage = null;
private Image titleRightImage = null;
private Image titleCenterImage = null;
private Image titleStretchImage = null;
private Image leftImage = null;
private Image rightImage = null;
private Image bottomLeftImage = null;
private Image bottomRightImage = null;
private Image bottomStretchImage = null;
private Color backgroundColor = null;
private Color selectedBackgroundColor = null;
private Color normalColor = null;
private Color currentColor = null;
private Font font = null;
private int listarea[] = { 12, 24 - 4, 256, 78 };
private PlaylistUI parent = null;
public PlaylistUIDelegate()
{
super();
currentColor = new Color(102, 204, 255);
normalColor = new Color(0xb2, 0xe4, 0xf6);
selectedBackgroundColor = Color.black;
backgroundColor = Color.black;
font = new Font("Dialog", Font.PLAIN, 10);
}
public void setParent(PlaylistUI playlist)
{
parent = playlist;
}
public Color getBackgroundColor()
{
return backgroundColor;
}
public void setBackgroundColor(Color backgroundColor)
{
this.backgroundColor = backgroundColor;
}
public Color getSelectedBackgroundColor()
{
return selectedBackgroundColor;
}
public Color getCurrentColor()
{
return currentColor;
}
public void setCurrentColor(Color currentColor)
{
this.currentColor = currentColor;
}
public Color getNormalColor()
{
return normalColor;
}
public void setNormalColor(Color normalColor)
{
this.normalColor = normalColor;
}
public void setSelectedBackgroundColor(Color selectedColor)
{
this.selectedBackgroundColor = selectedColor;
}
public Image getBottomLeftImage()
{
return bottomLeftImage;
}
public void setBottomLeftImage(Image bottomLeftImage)
{
this.bottomLeftImage = bottomLeftImage;
}
public Image getBottomRightImage()
{
return bottomRightImage;
}
public void setBottomRightImage(Image bottomRightImage)
{
this.bottomRightImage = bottomRightImage;
}
public Image getBottomStretchImage()
{
return bottomStretchImage;
}
public void setBottomStretchImage(Image bottomStretchImage)
{
this.bottomStretchImage = bottomStretchImage;
}
public Image getLeftImage()
{
return leftImage;
}
public void setLeftImage(Image leftImage)
{
this.leftImage = leftImage;
}
public Image getRightImage()
{
return rightImage;
}
public void setRightImage(Image rightImage)
{
this.rightImage = rightImage;
}
public Image getTitleCenterImage()
{
return titleCenterImage;
}
public void setTitleCenterImage(Image titleCenterImage)
{
this.titleCenterImage = titleCenterImage;
}
public Image getTitleLeftImage()
{
return titleLeftImage;
}
public void setTitleLeftImage(Image titleLeftImage)
{
this.titleLeftImage = titleLeftImage;
}
public Image getTitleRightImage()
{
return titleRightImage;
}
public void setTitleRightImage(Image titleRightImage)
{
this.titleRightImage = titleRightImage;
}
public Image getTitleStretchImage()
{
return titleStretchImage;
}
public void setTitleStretchImage(Image titleStretchImage)
{
this.titleStretchImage = titleStretchImage;
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
public int getLines()
{
return ((listarea[3] - listarea[1]) / 12);
}
public boolean isInSelectArea(int x, int y)
{
return (x >= listarea[0] && x <= listarea[2] && y >= listarea[1] && y <= listarea[3]);
}
public boolean isIndexArea(int y, int n)
{
return (y >= listarea[1] + 12 - 10 + n * 12 && y < listarea[1] + 12 - 10 + n * 12 + 14);
}
public void paintBackground(Graphics g)
{
g.drawImage(titleLeftImage, 0, 0, null);
g.drawImage(titleStretchImage, 25, 0, null);
g.drawImage(titleStretchImage, 50, 0, null);
g.drawImage(titleStretchImage, 62, 0, null);
g.drawImage(titleCenterImage, 87, 0, null);
g.drawImage(titleStretchImage, 187, 0, null);
g.drawImage(titleStretchImage, 200, 0, null);
g.drawImage(titleStretchImage, 225, 0, null);
g.drawImage(titleRightImage, 250, 0, null);
g.drawImage(leftImage, 0, 20, null);
g.drawImage(leftImage, 0, 48, null);
g.drawImage(leftImage, 0, 50, null);
//g.drawImage(rightImage, parent.getWidth() - 20, 20, null);
//g.drawImage(rightImage, parent.getWidth() - 20, 48, null);
//g.drawImage(rightImage, parent.getWidth() - 20, 50, null);
g.drawImage(bottomLeftImage, 0, parent.getHeight() - 38, null);
g.drawImage(bottomRightImage, 125, parent.getHeight() - 38, null);
}
public void paintList(Graphics g)
{
g.setColor(backgroundColor);
g.fillRect(listarea[0], listarea[1], listarea[2] - listarea[0], listarea[3] - listarea[1]);
if (font != null) g.setFont(font);
if (parent.getPlaylist() != null)
{
int currentSelection = parent.getPlaylist().getSelectedIndex();
g.setColor(normalColor);
int n = parent.getPlaylist().getPlaylistSize();
for (int i = 0; i < n; i++)
{
if (i < parent.getTopIndex()) continue;
int k = i - parent.getTopIndex();
if (listarea[1] + 12 + k * 12 > listarea[3]) break;
PlaylistItem pli = parent.getPlaylist().getItemAt(i);
String name = pli.getFormattedName();
if (pli.isSelected())
{
g.setColor(selectedBackgroundColor);
g.fillRect(listarea[0] + 4, listarea[1] + 12 - 10 + k * 12, listarea[2] - listarea[0] - 4, 14);
}
if (i == currentSelection) g.setColor(currentColor);
else g.setColor(normalColor);
if (i + 1 >= 10) g.drawString((i + 1) + ". " + name, listarea[0] + 12, listarea[1] + 12 + k * 12);
else g.drawString("0" + (i + 1) + ". " + name, listarea[0] + 12, listarea[1] + 12 + k * 12);
if (i == currentSelection) g.setColor(normalColor);
}
//g.drawImage(rightImage, parent.getWidth() - 20, 20, null);
//g.drawImage(rightImage, parent.getWidth() - 20, 48, null);
//g.drawImage(rightImage, parent.getWidth() - 20, 50, null);
}
}
}
| Java |
/*
* ActiveJSlider.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.JSlider;
public class ActiveJSlider extends JSlider
{
private AbsoluteConstraints constraints = null;
public ActiveJSlider()
{
super();
setDoubleBuffered(true);
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
public boolean isRequestFocusEnabled()
{
setValueIsAdjusting(true);
repaint();
return super.isRequestFocusEnabled();
}
public void setHideThumb(boolean hide)
{
((ActiveSliderUI) getUI()).setHideThumb(hide);
}
}
| Java |
/*
* Taftb.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Image;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import javax.swing.JComponent;
/**
* Taftb is used to build gif image from graphical fonts.
*/
public class Taftb extends JComponent
{
public Image theFonts;
private int imageW;
private int fontWidth;
private int fontHeight;
private int Yspacing;
protected Image theBanner;
protected int pixels[];
private PixelGrabber pg;
private String theText;
/**
* Text banner building according to the alphabet index, font size and Y spacing.
*/
public Taftb(String alphaIndex, Image fontFile, int fontW, int fontH, int Yspc, String theTxt/*, Color BgValue*/)
{
fontWidth = fontW;
fontHeight = fontH;
Yspacing = Yspc;
theText = theTxt;
theFonts = fontFile;
imageW = theFonts.getWidth(this);
/*-- We create the TextBanner by grabbing font letters in the image fonts --*/
pixels = new int[theText.length() * fontW * fontH];
int SpacePosition = 0;
int offsetSp = 0;
/*-- We search the space position in the Alphabet index --*/
while ((offsetSp < alphaIndex.length()) && (alphaIndex.charAt(offsetSp) != ' '))
{
offsetSp++;
}
if (offsetSp < alphaIndex.length()) SpacePosition = offsetSp;
for (int offsetT = 0; offsetT < theText.length(); offsetT++)
{
int xPos = 0;
int yPos = 0;
int reste = 0;
int entie = 0;
int offsetA = 0;
int FontPerLine = (int) Math.rint((imageW / fontW));
/*-- We search the letter's position in the Alphabet index --*/
while ((offsetA < alphaIndex.length()) && (theText.charAt(offsetT) != alphaIndex.charAt(offsetA)))
{
offsetA++;
}
/*-- We deduce its image's position (Int forced) --*/
if (offsetA < alphaIndex.length())
{
reste = offsetA % FontPerLine;
entie = (offsetA - reste);
xPos = reste * fontW;
yPos = ((entie / FontPerLine) * fontH) + ((entie / FontPerLine) * Yspacing);
}
else
/*-- If the letter is not indexed the space (if available) is selected --*/
{
reste = SpacePosition % FontPerLine;
entie = (SpacePosition - reste);
xPos = reste * fontW;
yPos = ((entie / FontPerLine) * fontH) + ((entie / FontPerLine) * Yspacing);
}
/*-- We grab the letter in the font image and put it in a pixel array --*/
pg = new PixelGrabber(theFonts, xPos, yPos, fontW, fontH, pixels, offsetT * fontW, theText.length() * fontW);
try
{
pg.grabPixels();
}
catch (InterruptedException e)
{
}
}
/*-- We create the final Image Banner throught an Image --*/
theBanner = createImage(new MemoryImageSource(theText.length() * fontW, fontH, pixels, 0, theText.length() * fontW));
}
/**
* Returns final banner as an image.
*/
public Image getBanner()
{
return theBanner;
}
/**
* Returns final banner as cropped image.
*/
public Image getBanner(int x, int y, int sx, int sy)
{
Image cropBanner = null;
CropImageFilter cif = new CropImageFilter(x, y, sx, sy);
cropBanner = createImage(new FilteredImageSource(theBanner.getSource(), cif));
return cropBanner;
}
/**
* Returns final banner as a pixels array.
*/
public int[] getPixels()
{
return pixels;
}
/**
* Returns banner's length.
*/
public int getPixelsW()
{
return theText.length() * fontWidth;
}
/**
* Returns banner's height.
*/
public int getPixelsH()
{
return fontHeight;
}
}
| Java |
/*
* ActiveJToggleButton.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.JToggleButton;
public class ActiveJToggleButton extends JToggleButton
{
private AbsoluteConstraints constraints = null;
public ActiveJToggleButton()
{
super();
this.setBorder(null);
this.setDoubleBuffered(true);
this.setFocusPainted(false);
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
}
| Java |
/*
* PopupAdapter.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
public class PopupAdapter extends MouseAdapter
{
private JPopupMenu popup = null;
public PopupAdapter(JPopupMenu popup)
{
super();
this.popup=popup;
}
public void mousePressed(MouseEvent e)
{
checkPopup(e);
}
public void mouseClicked(MouseEvent e)
{
checkPopup(e);
}
public void mouseReleased(MouseEvent e)
{
checkPopup(e);
}
private void checkPopup(MouseEvent e)
{
if (e.isPopupTrigger())
{
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
| Java |
/*
* ActiveJButton.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.JButton;
public class ActiveJButton extends JButton
{
private AbsoluteConstraints constraints = null;
public ActiveJButton()
{
super();
setBorder(null);
setDoubleBuffered(true);
setFocusPainted(false);
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
}
| Java |
/*
* AbsoluteLayout.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;
/**
* AbsoluteLayout is a LayoutManager that works as a replacement for "null" layout to
* allow placement of components in absolute positions.
*/
public class AbsoluteLayout implements LayoutManager2, java.io.Serializable
{
/**
* generated Serialized Version UID
*/
static final long serialVersionUID = -1919857869177070440L;
/**
* Adds the specified component with the specified name to
* the layout.
*
* @param name the component name
* @param comp the component to be added
*/
public void addLayoutComponent(String name, Component comp)
{
throw new IllegalArgumentException();
}
/**
* Removes the specified component from the layout.
*
* @param comp the component to be removed
*/
public void removeLayoutComponent(Component comp)
{
constraints.remove(comp);
}
/**
* Calculates the preferred dimension for the specified
* panel given the components in the specified parent container.
*
* @param parent the component to be laid out
* @see #minimumLayoutSize
*/
public Dimension preferredLayoutSize(Container parent)
{
int maxWidth = 0;
int maxHeight = 0;
for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();)
{
Component comp = (Component) e.nextElement();
AbsoluteConstraints ac = (AbsoluteConstraints) constraints.get(comp);
Dimension size = comp.getPreferredSize();
int width = ac.getWidth();
if (width == -1) width = size.width;
int height = ac.getHeight();
if (height == -1) height = size.height;
if (ac.x + width > maxWidth) maxWidth = ac.x + width;
if (ac.y + height > maxHeight) maxHeight = ac.y + height;
}
return new Dimension(maxWidth, maxHeight);
}
/**
* Calculates the minimum dimension for the specified
* panel given the components in the specified parent container.
*
* @param parent the component to be laid out
* @see #preferredLayoutSize
*/
public Dimension minimumLayoutSize(Container parent)
{
int maxWidth = 0;
int maxHeight = 0;
for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();)
{
Component comp = (Component) e.nextElement();
AbsoluteConstraints ac = (AbsoluteConstraints) constraints.get(comp);
Dimension size = comp.getMinimumSize();
int width = ac.getWidth();
if (width == -1) width = size.width;
int height = ac.getHeight();
if (height == -1) height = size.height;
if (ac.x + width > maxWidth) maxWidth = ac.x + width;
if (ac.y + height > maxHeight) maxHeight = ac.y + height;
}
return new Dimension(maxWidth, maxHeight);
}
/**
* Lays out the container in the specified panel.
*
* @param parent the component which needs to be laid out
*/
public void layoutContainer(Container parent)
{
for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();)
{
Component comp = (Component) e.nextElement();
AbsoluteConstraints ac = (AbsoluteConstraints) constraints.get(comp);
Dimension size = comp.getPreferredSize();
int width = ac.getWidth();
if (width == -1) width = size.width;
int height = ac.getHeight();
if (height == -1) height = size.height;
comp.setBounds(ac.x, ac.y, width, height);
}
}
/**
* Adds the specified component to the layout, using the specified
* constraint object.
*
* @param comp the component to be added
* @param constr where/how the component is added to the layout.
*/
public void addLayoutComponent(Component comp, Object constr)
{
if (!(constr instanceof AbsoluteConstraints)) throw new IllegalArgumentException();
constraints.put(comp, constr);
}
/**
* Returns the maximum size of this component.
*
* @see java.awt.Component#getMinimumSize()
* @see java.awt.Component#getPreferredSize()
* @see LayoutManager
*/
public Dimension maximumLayoutSize(Container target)
{
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX(Container target)
{
return 0;
}
/**
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY(Container target)
{
return 0;
}
/**
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target)
{
}
/**
* A mapping <Component, AbsoluteConstraints>
*/
protected java.util.Hashtable constraints = new java.util.Hashtable();
}
| Java |
/*
* ActiveJPopup.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import java.awt.GridLayout;
import javax.swing.JPanel;
public class ActiveJPopup extends JPanel
{
private AbsoluteConstraints constraints = null;
private ActiveJButton[] items = null;
public ActiveJPopup()
{
super();
setBorder(null);
setDoubleBuffered(true);
}
public void setConstraints(AbsoluteConstraints cnts)
{
constraints = cnts;
}
public AbsoluteConstraints getConstraints()
{
return constraints;
}
public ActiveJButton[] getItems()
{
return items;
}
public void setItems(ActiveJButton[] items)
{
this.items = items;
if (items != null)
{
setLayout(new GridLayout(items.length, 1, 0, 0));
for (int i=0;i<items.length;i++)
{
add(items[i]);
}
}
}
}
| Java |
/*
* ActiveJNumberLabel.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.skin;
import javax.swing.ImageIcon;
public class ActiveJNumberLabel extends ActiveJLabel
{
private ImageIcon[] numbers = null;
public ActiveJNumberLabel()
{
super();
}
public ImageIcon[] getNumbers()
{
return numbers;
}
public void setNumbers(ImageIcon[] numbers)
{
this.numbers = numbers;
}
public void setAcText(String numberStr)
{
int number = 10;
try
{
number = Integer.parseInt(numberStr);
}
catch (NumberFormatException e)
{
}
if ((number >= 0) && (number < numbers.length))
{
setIcon(numbers[number]);
}
}
}
| Java |
/*
* PlayerActionEvent.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp;
import java.awt.event.ActionEvent;
public class PlayerActionEvent extends ActionEvent
{
public static final String ACPREVIOUS = "Previous";
public static final String ACPLAY = "Play";
public static final String ACPAUSE = "Pause";
public static final String ACSTOP = "Stop";
public static final String ACNEXT = "Next";
public static final String ACEJECT = "Eject";
public static final String ACEQUALIZER = "EqualizerUI";
public static final String ACPLAYLIST = "Playlist";
public static final String ACSHUFFLE = "Shuffle";
public static final String ACREPEAT = "Repeat";
public static final String ACVOLUME = "Volume";
public static final String ACBALANCE = "Balance";
public static final String ACTITLEBAR = "TitleBar";
public static final String ACEXIT = "Exit";
public static final String ACMINIMIZE = "Minimize";
public static final String ACPOSBAR = "Seek";
public static final String MIPLAYFILE = "PlayFileMI";
public static final String MIPLAYLOCATION = "PlayLocationMI";
public static final String MIPLAYLIST = "PlaylistMI";
public static final String MIEQUALIZER = "EqualizerMI";
public static final String MIPREFERENCES = "PreferencesMI";
public static final String MISKINBROWSER = "SkinBrowserMI";
public static final String MILOADSKIN = "LoadSkinMI";
public static final String MIJUMPFILE = "JumpFileMI";
public static final String MISTOP = "StopMI";
public static final String EQSLIDER = "SliderEQ";
public static final String ACEQPRESETS = "PresetsEQ";
public static final String ACEQONOFF = "OnOffEQ";
public static final String ACEQAUTO = "AutoEQ";
public static final String ACPLUP = "ScrollUpPL";
public static final String ACPLDOWN = "ScrollDownPL";
public static final String ACPLINFO = "InfoPL";
public static final String ACPLPLAY = "PlayPL";
public static final String ACPLREMOVE = "RemovePL";
public static final String ACPLADDPOPUP = "AddPopupPL";
public static final String ACPLADDFILE = "AddFilePL";
public static final String ACPLADDDIR = "AddDirPL";
public static final String ACPLADDURL = "AddURLPL";
public static final String ACPLREMOVEPOPUP = "RemovePopupPL";
public static final String ACPLREMOVEMISC = "RemoveMiscPL";
public static final String ACPLREMOVESEL = "RemoveSelPL";
public static final String ACPLREMOVEALL = "RemoveAllPL";
public static final String ACPLREMOVECROP = "RemoveCropPL";
public static final String ACPLSELPOPUP = "SelectPopupPL";
public static final String ACPLSELALL = "SelectAllPL";
public static final String ACPLSELZERO = "SelectZeroPL";
public static final String ACPLSELINV = "SelectInvPL";
public static final String ACPLMISCPOPUP = "MiscPopupPL";
public static final String ACPLMISCOPTS = "MiscOptsPL";
public static final String ACPLMISCFILE = "MiscFilePL";
public static final String ACPLMISCSORT = "MiscSortPL";
public static final String ACPLLISTPOPUP = "ListPopupPL";
public static final String ACPLLISTLOAD = "ListLoadPL";
public static final String ACPLLISTSAVE = "ListSavePL";
public static final String ACPLLISTNEW = "ListNewPL";
public PlayerActionEvent(Object source, int id, String command)
{
super(source, id, command);
}
public PlayerActionEvent(Object source, int id, String command, int modifiers)
{
super(source, id, command, modifiers);
}
public PlayerActionEvent(Object source, int id, String command, long when, int modifiers)
{
super(source, id, command, when, modifiers);
}
}
| Java |
/*
* StandalonePlayer.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.player.amp.skin.DragAdapter;
import javazoom.jlgui.player.amp.skin.Skin;
import javazoom.jlgui.player.amp.util.Config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class StandalonePlayer extends JFrame implements Loader
{
private static Log log = LogFactory.getLog(StandalonePlayer.class);
/*-- Run parameters --*/
private String initConfig = "jlgui.ini";
private String initSong = null;
private String showPlaylist = null;
private String showEqualizer = null;
private String showDsp = null;
private String skinPath = null;
private String skinVersion = "1"; // 1, 2, for different Volume.bmp
private boolean autoRun = false;
/*-- Front-end --*/
private PlayerUI mp = null;
private JWindow eqWin = null;
private JWindow plWin = null;
private int eqFactor = 2;
private Config config = null;
private boolean playlistfound = false;
public StandalonePlayer()
{
super();
}
/**
* @param args
*/
public static void main(String[] args)
{
final StandalonePlayer player = new StandalonePlayer();
player.parseParameters(args);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
player.loadUI();
player.loadJS();
player.loadPlaylist();
player.boot();
}
});
}
/**
* Initialize the player front-end.
* @param args
*/
private void parseParameters(String[] args)
{
String currentArg = null;
String currentValue = null;
for (int i = 0; i < args.length; i++)
{
currentArg = args[i];
if (currentArg.startsWith("-"))
{
if (currentArg.toLowerCase().equals("-init"))
{
i++;
if (i >= args.length) usage("init value missing");
currentValue = args[i];
if (Config.startWithProtocol(currentValue)) initConfig = currentValue;
else initConfig = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
}
else if (currentArg.toLowerCase().equals("-song"))
{
i++;
if (i >= args.length) usage("song value missing");
currentValue = args[i];
if (Config.startWithProtocol(currentValue)) initSong = currentValue;
else initSong = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
}
else if (currentArg.toLowerCase().equals("-start"))
{
autoRun = true;
}
else if (currentArg.toLowerCase().equals("-showplaylist"))
{
showPlaylist = "true";
}
else if (currentArg.toLowerCase().equals("-showequalizer"))
{
showEqualizer = "true";
}
else if (currentArg.toLowerCase().equals("-disabledsp"))
{
showDsp = "false";
}
else if (currentArg.toLowerCase().equals("-skin"))
{
i++;
if (i >= args.length) usage("skin value missing");
currentValue = args[i];
if (Config.startWithProtocol(currentValue)) skinPath = currentValue;
else skinPath = currentValue.replace('\\', '/').replace('/', java.io.File.separatorChar);
}
else if (currentArg.toLowerCase().equals("-v"))
{
i++;
if (i >= args.length) usage("skin version value missing");
skinVersion = args[i];
}
else usage("Unknown parameter : " + currentArg);
}
else
{
usage("Invalid parameter :" + currentArg);
}
}
}
private void boot()
{
// Go to playlist begining if needed.
/*if ((playlist != null) && (playlistfound == true))
{
if (playlist.getPlaylistSize() > 0) mp.pressNext();
} */
// Start playing if needed.
if (autoRun == true)
{
mp.pressStart();
}
}
/**
* Instantiate low-level player.
*/
public void loadJS()
{
BasicPlayer bplayer = new BasicPlayer();
List mixers = bplayer.getMixers();
if (mixers != null)
{
Iterator it = mixers.iterator();
String mixer = config.getAudioDevice();
boolean mixerFound = false;
if ((mixer != null) && (mixer.length() > 0))
{
// Check if mixer is valid.
while (it.hasNext())
{
if (((String) it.next()).equals(mixer))
{
bplayer.setMixerName(mixer);
mixerFound = true;
break;
}
}
}
if (mixerFound == false)
{
// Use first mixer available.
it = mixers.iterator();
if (it.hasNext())
{
mixer = (String) it.next();
bplayer.setMixerName(mixer);
}
}
}
// Register the front-end to low-level player events.
bplayer.addBasicPlayerListener(mp);
// Adds controls for front-end to low-level player.
mp.setController(bplayer);
}
/**
* Load playlist.
*/
public void loadPlaylist()
{
if ((initSong != null) && (!initSong.equals(""))) playlistfound = mp.loadPlaylist(initSong);
else playlistfound = mp.loadPlaylist(config.getPlaylistFilename());
}
/**
* Load player front-end.
*/
public void loadUI()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex)
{
log.debug(ex);
}
config = Config.getInstance();
config.load(initConfig);
config.setTopParent(this);
if (showPlaylist != null)
{
if (showPlaylist.equalsIgnoreCase("true"))
{
config.setPlaylistEnabled(true);
}
else
{
config.setPlaylistEnabled(false);
}
}
if (showEqualizer != null)
{
if (showEqualizer.equalsIgnoreCase("true"))
{
config.setEqualizerEnabled(true);
}
else
{
config.setEqualizerEnabled(false);
}
}
if (config.isPlaylistEnabled()) eqFactor = 2;
else eqFactor = 1;
setTitle(Skin.TITLETEXT);
ClassLoader cl = this.getClass().getClassLoader();
URL iconURL = cl.getResource("javazoom/jlgui/player/amp/jlguiicon.gif");
if (iconURL != null)
{
ImageIcon jlguiIcon = new ImageIcon(iconURL);
setIconImage(jlguiIcon.getImage());
config.setIconParent(jlguiIcon);
}
setUndecorated(true);
mp = new PlayerUI();
if ((showDsp != null) && (showDsp.equalsIgnoreCase("false")))
{
mp.getSkin().setDspEnabled(false);
}
if (skinPath != null)
{
mp.getSkin().setPath(skinPath);
}
mp.getSkin().setSkinVersion(skinVersion);
mp.loadUI(this);
setContentPane(mp);
setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
eqWin = new JWindow(this);
eqWin.setContentPane(mp.getEqualizerUI());
eqWin.setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
eqWin.setVisible(false);
plWin = new JWindow(this);
plWin.setContentPane(mp.getPlaylistUI());
plWin.setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
plWin.setVisible(false);
// Window listener
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
// Closing window (Alt+F4 under Win32)
close();
}
});
// Keyboard shortcut
setKeyBoardShortcut();
// Display front-end
setLocation(config.getXLocation(), config.getYLocation());
setVisible(true);
if (config.isPlaylistEnabled()) plWin.setVisible(true);
if (config.isEqualizerEnabled()) eqWin.setVisible(true);
}
/**
* Install keyboard shortcuts.
*/
public void setKeyBoardShortcut()
{
KeyStroke jKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_J, 0, false);
KeyStroke ctrlPKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK, false);
KeyStroke altSKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.ALT_MASK, false);
KeyStroke vKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, 0, false);
String searchID = "TAGSEARCH";
String preferenceID = "PREFERENCES";
String skinbrowserID = "SKINBROWSER";
String stopplayerID = "STOPPLAYER";
Action searchAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
if (mp != null) mp.processJumpToFile(e.getModifiers());
}
};
Action preferencesAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
if (mp != null) mp.processPreferences(e.getModifiers());
}
};
Action skinbrowserAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
if (mp != null) mp.processSkinBrowser(e.getModifiers());
}
};
Action stopplayerAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
if (mp != null) mp.processStop(MouseEvent.BUTTON1_MASK);
}
};
setKeyboardAction(searchID, jKeyStroke, searchAction);
setKeyboardAction(preferenceID, ctrlPKeyStroke, preferencesAction);
setKeyboardAction(skinbrowserID, altSKeyStroke, skinbrowserAction);
setKeyboardAction(stopplayerID, vKeyStroke, stopplayerAction);
}
/**
* Set keyboard key shortcut for the whole player.
* @param id
* @param key
* @param action
*/
public void setKeyboardAction(String id, KeyStroke key, Action action)
{
mp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, id);
mp.getActionMap().put(id, action);
mp.getPlaylistUI().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, id);
mp.getPlaylistUI().getActionMap().put(id, action);
mp.getEqualizerUI().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, id);
mp.getEqualizerUI().getActionMap().put(id, action);
}
public void loaded()
{
DragAdapter dragAdapter = new DragAdapter(this);
mp.getSkin().getAcTitleBar().addMouseListener(dragAdapter);
mp.getSkin().getAcTitleBar().addMouseMotionListener(dragAdapter);
}
public void close()
{
log.info("Close player");
config.setLocation(getLocation().x, getLocation().y);
config.save();
dispose();
exit(0);
}
/* (non-Javadoc)
* @see javazoom.jlgui.player.amp.skin.Loader#togglePlaylist(boolean)
*/
public void togglePlaylist(boolean enabled)
{
if (plWin != null)
{
if (enabled)
{
if (config.isEqualizerEnabled())
{
eqFactor = 2;
eqWin.setLocation(getLocation().x, getLocation().y + mp.getSkin().getMainHeight() * eqFactor);
}
plWin.setVisible(true);
}
else
{
plWin.setVisible(false);
if (config.isEqualizerEnabled())
{
eqFactor = 1;
eqWin.setLocation(getLocation().x, getLocation().y + mp.getSkin().getMainHeight() * eqFactor);
}
}
}
}
public void toggleEqualizer(boolean enabled)
{
if (eqWin != null)
{
if (enabled)
{
if (config.isPlaylistEnabled()) eqFactor = 2;
else eqFactor = 1;
eqWin.setLocation(getLocation().x, getLocation().y + mp.getSkin().getMainHeight() * eqFactor);
eqWin.setVisible(true);
}
else
{
eqWin.setVisible(false);
}
}
}
public void minimize()
{
setState(JFrame.ICONIFIED);
}
public void setLocation(int x, int y)
{
super.setLocation(x, y);
if (plWin != null)
{
plWin.setLocation(getLocation().x, getLocation().y + getHeight());
}
if (eqWin != null)
{
eqWin.setLocation(getLocation().x, getLocation().y + eqFactor * getHeight());
}
}
public Point getLocation()
{
return super.getLocation();
}
/**
* Kills the player.
* @param status
*/
public void exit(int status)
{
System.exit(status);
}
/**
* Displays usage.
* @param msg
*/
protected static void usage(String msg)
{
System.out.println(Skin.TITLETEXT + " : " + msg);
System.out.println("");
System.out.println(Skin.TITLETEXT + " : Usage");
System.out.println(" java javazoom.jlgui.player.amp.Player [-skin skinFilename] [-song audioFilename] [-start] [-showplaylist] [-showequalizer] [-disabledsp] [-init configFilename] [-v skinversion]");
System.out.println("");
System.out.println(" skinFilename : Filename or URL to a Winamp Skin2.x");
System.out.println(" audioFilename : Filename or URL to initial song or playlist");
System.out.println(" start : Starts playing song (from the playlist)");
System.out.println(" showplaylist : Show playlist");
System.out.println(" showequalizer : Show equalizer");
System.out.println(" disabledsp : Disable spectrum/time visual");
System.out.println("");
System.out.println(" Advanced parameters :");
System.out.println(" skinversion : 1 or 2 (default 1)");
System.out.println(" configFilename : Filename or URL to jlGui initial configuration (playlist,skin,parameters ...)");
System.out.println(" Initial configuration won't be overriden by -skin and -song arguments");
System.out.println("");
System.out.println("Homepage : http://www.javazoom.net");
System.exit(0);
}
}
| Java |
/*
* PlayerUI.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.StringTokenizer;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javazoom.jlgui.basicplayer.BasicController;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerEvent;
import javazoom.jlgui.basicplayer.BasicPlayerException;
import javazoom.jlgui.basicplayer.BasicPlayerListener;
import javazoom.jlgui.player.amp.equalizer.ui.EqualizerUI;
import javazoom.jlgui.player.amp.playlist.Playlist;
import javazoom.jlgui.player.amp.playlist.PlaylistFactory;
import javazoom.jlgui.player.amp.playlist.PlaylistItem;
import javazoom.jlgui.player.amp.playlist.ui.PlaylistUI;
import javazoom.jlgui.player.amp.skin.AbsoluteLayout;
import javazoom.jlgui.player.amp.skin.DropTargetAdapter;
import javazoom.jlgui.player.amp.skin.ImageBorder;
import javazoom.jlgui.player.amp.skin.PopupAdapter;
import javazoom.jlgui.player.amp.skin.Skin;
import javazoom.jlgui.player.amp.skin.UrlDialog;
import javazoom.jlgui.player.amp.tag.ui.TagSearch;
import javazoom.jlgui.player.amp.util.Config;
import javazoom.jlgui.player.amp.util.FileSelector;
import javazoom.jlgui.player.amp.util.ui.Preferences;
import javazoom.jlgui.player.amp.visual.ui.SpectrumTimeAnalyzer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PlayerUI extends JPanel implements ActionListener, ChangeListener, BasicPlayerListener
{
private static Log log = LogFactory.getLog(PlayerUI.class);
public static final int INIT = 0;
public static final int OPEN = 1;
public static final int PLAY = 2;
public static final int PAUSE = 3;
public static final int STOP = 4;
public static final int TEXT_LENGTH_MAX = 30;
public static final long SCROLL_PERIOD = 250;
private Skin ui = null;
private Loader loader = null;
private Config config = null;
/*-- Pop up menus --*/
private JPopupMenu mainpopup = null;
private JPopupMenu ejectpopup = null;
private JCheckBoxMenuItem miPlaylist = null;
private JCheckBoxMenuItem miEqualizer = null;
private JMenuItem miPlayFile = null;
private JMenuItem miPlayLocation = null;
private PopupAdapter popupAdapter = null;
private PopupAdapter ejectpopupAdapter = null;
/*-- Sound player --*/
private BasicController theSoundPlayer = null;
private Map audioInfo = null;
private int playerState = INIT;
/*-- Title text --*/
private String titleText = Skin.TITLETEXT.toUpperCase();
private String currentTitle = Skin.TITLETEXT.toUpperCase();
private String[] titleScrollLabel = null;
private int scrollIndex = 0;
private long lastScrollTime = 0L;
private boolean scrollRight = true;
private long secondsAmount = 0;
/*-- Playlist --*/
private Playlist playlist = null;
private PlaylistUI playlistUI = null;
private String currentFileOrURL = null;
private String currentSongName = null;
private PlaylistItem currentPlaylistItem = null;
private boolean currentIsFile;
/*-- PosBar members --*/
private boolean posValueJump = false;
private boolean posDragging = false;
private double posValue = 0.0;
/*-- EqualizerUI --*/
private EqualizerUI equalizerUI = null;
public PlayerUI()
{
super();
setDoubleBuffered(true);
ui = new Skin();
}
public void setEqualizerUI(EqualizerUI eq)
{
equalizerUI = eq;
}
public EqualizerUI getEqualizerUI()
{
return equalizerUI;
}
public PlaylistUI getPlaylistUI()
{
return playlistUI;
}
public void setPlaylistUI(PlaylistUI playlistUI)
{
this.playlistUI = playlistUI;
}
public Playlist getPlaylist()
{
return playlist;
}
/**
* Return config.
* @return
*/
public Config getConfig()
{
return config;
}
/**
* Return skin.
* @return
*/
public Skin getSkin()
{
return ui;
}
/**
* Return parent loader.
* @return
*/
public Loader getLoader()
{
return loader;
}
/**
* A handle to the BasicPlayer, plugins may control the player through
* the controller (play, stop, ...)
* @param controller
*/
public void setController(BasicController controller)
{
theSoundPlayer = controller;
}
/**
* Return player controller.
* @return
*/
public BasicController getController()
{
return theSoundPlayer;
}
/**
* Load main player.
* @param loader
*/
public void loadUI(Loader loader)
{
this.loader = loader;
setLayout(new AbsoluteLayout());
config = Config.getInstance();
ui.setConfig(config);
playlistUI = new PlaylistUI();
playlistUI.setSkin(ui);
playlistUI.setPlayer(this);
equalizerUI = new EqualizerUI();
equalizerUI.setSkin(ui);
loadSkin();
// DnD support.
DropTargetAdapter dnd = new DropTargetAdapter()
{
public void processDrop(Object data)
{
processDnD(data);
}
};
DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY, dnd, true);
}
public void loadSkin()
{
log.info("Load PlayerUI (EDT=" + SwingUtilities.isEventDispatchThread() + ")");
removeAll();
// Load skin specified in args
if (ui.getPath() != null)
{
log.info("Load default skin from " + ui.getPath());
ui.loadSkin(ui.getPath());
config.setDefaultSkin(ui.getPath());
}
// Load skin specified in jlgui.ini
else if ((config.getDefaultSkin() != null) && (!config.getDefaultSkin().trim().equals("")))
{
log.info("Load default skin from " + config.getDefaultSkin());
ui.loadSkin(config.getDefaultSkin());
}
// Default included skin
else
{
ClassLoader cl = getClass().getClassLoader();
InputStream sis = cl.getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
log.info("Load default skin for JAR");
ui.loadSkin(sis);
}
// Background
ImageBorder border = new ImageBorder();
border.setImage(ui.getMainImage());
setBorder(border);
// Buttons
add(ui.getAcPrevious(), ui.getAcPrevious().getConstraints());
ui.getAcPrevious().removeActionListener(this);
ui.getAcPrevious().addActionListener(this);
add(ui.getAcPlay(), ui.getAcPlay().getConstraints());
ui.getAcPlay().removeActionListener(this);
ui.getAcPlay().addActionListener(this);
add(ui.getAcPause(), ui.getAcPause().getConstraints());
ui.getAcPause().removeActionListener(this);
ui.getAcPause().addActionListener(this);
add(ui.getAcStop(), ui.getAcStop().getConstraints());
ui.getAcStop().removeActionListener(this);
ui.getAcStop().addActionListener(this);
add(ui.getAcNext(), ui.getAcNext().getConstraints());
ui.getAcNext().removeActionListener(this);
ui.getAcNext().addActionListener(this);
add(ui.getAcEject(), ui.getAcEject().getConstraints());
ui.getAcEject().removeActionListener(this);
ui.getAcEject().addActionListener(this);
// EqualizerUI toggle
add(ui.getAcEqualizer(), ui.getAcEqualizer().getConstraints());
ui.getAcEqualizer().removeActionListener(this);
ui.getAcEqualizer().addActionListener(this);
// Playlist toggle
add(ui.getAcPlaylist(), ui.getAcPlaylist().getConstraints());
ui.getAcPlaylist().removeActionListener(this);
ui.getAcPlaylist().addActionListener(this);
// Shuffle toggle
add(ui.getAcShuffle(), ui.getAcShuffle().getConstraints());
ui.getAcShuffle().removeActionListener(this);
ui.getAcShuffle().addActionListener(this);
// Repeat toggle
add(ui.getAcRepeat(), ui.getAcRepeat().getConstraints());
ui.getAcRepeat().removeActionListener(this);
ui.getAcRepeat().addActionListener(this);
// Volume
add(ui.getAcVolume(), ui.getAcVolume().getConstraints());
ui.getAcVolume().removeChangeListener(this);
ui.getAcVolume().addChangeListener(this);
// Balance
add(ui.getAcBalance(), ui.getAcBalance().getConstraints());
ui.getAcBalance().removeChangeListener(this);
ui.getAcBalance().addChangeListener(this);
// Seek bar
add(ui.getAcPosBar(), ui.getAcPosBar().getConstraints());
ui.getAcPosBar().removeChangeListener(this);
ui.getAcPosBar().addChangeListener(this);
// Mono
add(ui.getAcMonoIcon(), ui.getAcMonoIcon().getConstraints());
// Stereo
add(ui.getAcStereoIcon(), ui.getAcStereoIcon().getConstraints());
// Title label
add(ui.getAcTitleLabel(), ui.getAcTitleLabel().getConstraints());
// Sample rate label
add(ui.getAcSampleRateLabel(), ui.getAcSampleRateLabel().getConstraints());
// Bit rate label
add(ui.getAcBitRateLabel(), ui.getAcBitRateLabel().getConstraints());
// Play icon
add(ui.getAcPlayIcon(), ui.getAcPlayIcon().getConstraints());
// Time icon
add(ui.getAcTimeIcon(), ui.getAcTimeIcon().getConstraints());
// MinuteH number
add(ui.getAcMinuteH(), ui.getAcMinuteH().getConstraints());
// MinuteL number
add(ui.getAcMinuteL(), ui.getAcMinuteL().getConstraints());
// SecondH number
add(ui.getAcSecondH(), ui.getAcSecondH().getConstraints());
// SecondL number
add(ui.getAcSecondL(), ui.getAcSecondL().getConstraints());
// TitleBar
add(ui.getAcTitleBar(), ui.getAcTitleBar().getConstraints());
add(ui.getAcMinimize(), ui.getAcMinimize().getConstraints());
ui.getAcMinimize().removeActionListener(this);
ui.getAcMinimize().addActionListener(this);
add(ui.getAcExit(), ui.getAcExit().getConstraints());
ui.getAcExit().removeActionListener(this);
ui.getAcExit().addActionListener(this);
// DSP
if (ui.getAcAnalyzer() != null)
{
add(ui.getAcAnalyzer(), ui.getAcAnalyzer().getConstraints());
}
// Popup menu
mainpopup = new JPopupMenu(ui.getResource("popup.title"));
JMenuItem mi = new JMenuItem(Skin.TITLETEXT + "- JavaZOOM");
//mi.removeActionListener(this);
//mi.addActionListener(this);
mainpopup.add(mi);
mainpopup.addSeparator();
JMenu playSubMenu = new JMenu(ui.getResource("popup.play"));
miPlayFile = new JMenuItem(ui.getResource("popup.play.file"));
miPlayFile.setActionCommand(PlayerActionEvent.MIPLAYFILE);
miPlayFile.removeActionListener(this);
miPlayFile.addActionListener(this);
miPlayLocation = new JMenuItem(ui.getResource("popup.play.location"));
miPlayLocation.setActionCommand(PlayerActionEvent.MIPLAYLOCATION);
miPlayLocation.removeActionListener(this);
miPlayLocation.addActionListener(this);
playSubMenu.add(miPlayFile);
playSubMenu.add(miPlayLocation);
mainpopup.add(playSubMenu);
mainpopup.addSeparator();
miPlaylist = new JCheckBoxMenuItem(ui.getResource("popup.playlist"));
miPlaylist.setActionCommand(PlayerActionEvent.MIPLAYLIST);
if (config.isPlaylistEnabled()) miPlaylist.setState(true);
miPlaylist.removeActionListener(this);
miPlaylist.addActionListener(this);
mainpopup.add(miPlaylist);
miEqualizer = new JCheckBoxMenuItem(ui.getResource("popup.equalizer"));
miEqualizer.setActionCommand(PlayerActionEvent.MIEQUALIZER);
if (config.isEqualizerEnabled()) miEqualizer.setState(true);
miEqualizer.removeActionListener(this);
miEqualizer.addActionListener(this);
mainpopup.add(miEqualizer);
mainpopup.addSeparator();
mi = new JMenuItem(ui.getResource("popup.preferences"));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK, false));
mi.setActionCommand(PlayerActionEvent.MIPREFERENCES);
mi.removeActionListener(this);
mi.addActionListener(this);
mainpopup.add(mi);
JMenu skinsSubMenu = new JMenu(ui.getResource("popup.skins"));
mi = new JMenuItem(ui.getResource("popup.skins.browser"));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK, false));
mi.setActionCommand(PlayerActionEvent.MISKINBROWSER);
mi.removeActionListener(this);
mi.addActionListener(this);
skinsSubMenu.add(mi);
mi = new JMenuItem(ui.getResource("popup.skins.load"));
mi.setActionCommand(PlayerActionEvent.MILOADSKIN);
mi.removeActionListener(this);
mi.addActionListener(this);
skinsSubMenu.add(mi);
mainpopup.add(skinsSubMenu);
JMenu playbackSubMenu = new JMenu(ui.getResource("popup.playback"));
mi = new JMenuItem(ui.getResource("popup.playback.jump"));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J, 0, false));
mi.setActionCommand(PlayerActionEvent.MIJUMPFILE);
mi.removeActionListener(this);
mi.addActionListener(this);
playbackSubMenu.add(mi);
mi = new JMenuItem(ui.getResource("popup.playback.stop"));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, 0, false));
mi.setActionCommand(PlayerActionEvent.MISTOP);
mi.removeActionListener(this);
mi.addActionListener(this);
playbackSubMenu.add(mi);
mainpopup.add(playbackSubMenu);
mainpopup.addSeparator();
mi = new JMenuItem(ui.getResource("popup.exit"));
mi.setActionCommand(PlayerActionEvent.ACEXIT);
mi.removeActionListener(this);
mi.addActionListener(this);
mainpopup.add(mi);
// Popup menu on TitleBar
ui.getAcTitleBar().removeMouseListener(popupAdapter);
popupAdapter = new PopupAdapter(mainpopup);
ui.getAcTitleBar().addMouseListener(popupAdapter);
// Popup menu on Eject button
ejectpopup = new JPopupMenu();
mi = new JMenuItem(ui.getResource("popup.eject.openfile"));
mi.setActionCommand(PlayerActionEvent.MIPLAYFILE);
mi.removeActionListener(this);
mi.addActionListener(this);
ejectpopup.add(mi);
mi = new JMenuItem(ui.getResource("popup.eject.openlocation"));
mi.setActionCommand(PlayerActionEvent.MIPLAYLOCATION);
mi.removeActionListener(this);
mi.addActionListener(this);
ejectpopup.add(mi);
ui.getAcEject().removeMouseListener(ejectpopupAdapter);
ejectpopupAdapter = new PopupAdapter(ejectpopup);
ui.getAcEject().addMouseListener(ejectpopupAdapter);
// EqualizerUI
if (equalizerUI != null) equalizerUI.loadUI();
if (playlistUI != null) playlistUI.loadUI();
validate();
loader.loaded();
}
/**
* Load playlist.
* @param playlistName
* @return
*/
public boolean loadPlaylist(String playlistName)
{
boolean loaded = false;
PlaylistFactory plf = PlaylistFactory.getInstance();
playlist = plf.getPlaylist();
if (playlist == null)
{
config.setPlaylistClassName("javazoom.jlgui.player.amp.playlist.BasePlaylist");
playlist = plf.getPlaylist();
}
playlistUI.setPlaylist(playlist);
if ((playlistName != null) && (!playlistName.equals("")))
{
// M3U file or URL.
if ((playlistName.toLowerCase().endsWith(ui.getResource("playlist.extension.m3u"))) || (playlistName.toLowerCase().endsWith(ui.getResource("playlist.extension.pls")))) loaded = playlist.load(playlistName);
// Simple song.
else
{
String name = playlistName;
if (!Config.startWithProtocol(playlistName))
{
int indn = playlistName.lastIndexOf(java.io.File.separatorChar);
if (indn != -1) name = playlistName.substring(indn + 1);
PlaylistItem pli = new PlaylistItem(name, playlistName, -1, true);
playlist.appendItem(pli);
loaded = true;
}
else
{
PlaylistItem pli = new PlaylistItem(name, playlistName, -1, false);
playlist.appendItem(pli);
loaded = true;
}
}
}
return loaded;
}
/* (non-Javadoc)
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent e)
{
Object src = e.getSource();
//log.debug("State (EDT=" + SwingUtilities.isEventDispatchThread() + ")");
// Volume
if (src == ui.getAcVolume())
{
Object[] args = { String.valueOf(ui.getAcVolume().getValue()) };
String volumeText = MessageFormat.format(ui.getResource("slider.volume.text"), args);
ui.getAcTitleLabel().setAcText(volumeText);
try
{
int gainValue = ui.getAcVolume().getValue();
int maxGain = ui.getAcVolume().getMaximum();
if (gainValue == 0) theSoundPlayer.setGain(0);
else theSoundPlayer.setGain(((double) gainValue / (double) maxGain));
config.setVolume(gainValue);
}
catch (BasicPlayerException ex)
{
log.debug("Cannot set gain", ex);
}
}
// Balance
else if (src == ui.getAcBalance())
{
Object[] args = { String.valueOf(Math.abs(ui.getAcBalance().getValue() * 100 / Skin.BALANCEMAX)) };
String balanceText = null;
if (ui.getAcBalance().getValue() > 0)
{
balanceText = MessageFormat.format(ui.getResource("slider.balance.text.right"), args);
}
else if (ui.getAcBalance().getValue() < 0)
{
balanceText = MessageFormat.format(ui.getResource("slider.balance.text.left"), args);
}
else
{
balanceText = MessageFormat.format(ui.getResource("slider.balance.text.center"), args);
}
ui.getAcTitleLabel().setAcText(balanceText);
try
{
float balanceValue = ui.getAcBalance().getValue() * 1.0f / Skin.BALANCEMAX;
theSoundPlayer.setPan(balanceValue);
}
catch (BasicPlayerException ex)
{
log.debug("Cannot set pan", ex);
}
}
else if (src == ui.getAcPosBar())
{
if (ui.getAcPosBar().getValueIsAdjusting() == false)
{
if (posDragging == true)
{
posDragging = false;
posValue = ui.getAcPosBar().getValue() * 1.0 / Skin.POSBARMAX;
processSeek(posValue);
}
}
else
{
posDragging = true;
posValueJump = true;
}
}
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
final ActionEvent evt = e;
if (e.getActionCommand().equals(PlayerActionEvent.ACPAUSE))
{
processActionEvent(e);
}
else if ((e.getActionCommand().equals(PlayerActionEvent.ACPLAY)) && (playerState == PAUSE))
{
processActionEvent(e);
}
else
{
new Thread("PlayerUIActionEvent")
{
public void run()
{
processActionEvent(evt);
}
}.start();
}
}
/**
* Process action event.
* @param e
*/
public void processActionEvent(ActionEvent e)
{
String cmd = e.getActionCommand();
log.debug("Action=" + cmd + " (EDT=" + SwingUtilities.isEventDispatchThread() + ")");
// Preferences.
if (cmd.equalsIgnoreCase(PlayerActionEvent.MIPREFERENCES))
{
processPreferences(e.getModifiers());
}
// Skin browser
else if (cmd.equals(PlayerActionEvent.MISKINBROWSER))
{
processSkinBrowser(e.getModifiers());
}
// Jump to file
else if (cmd.equals(PlayerActionEvent.MIJUMPFILE))
{
processJumpToFile(e.getModifiers());
}
// Stop
else if (cmd.equals(PlayerActionEvent.MISTOP))
{
processStop(MouseEvent.BUTTON1_MASK);
}
// Load skin
else if (e.getActionCommand().equals(PlayerActionEvent.MILOADSKIN))
{
File[] file = FileSelector.selectFile(loader, FileSelector.OPEN, false, ui.getResource("skin.extension"), ui.getResource("loadskin.dialog.filtername"), new File(config.getLastDir()));
if (FileSelector.getInstance().getDirectory() != null) config.setLastDir(FileSelector.getInstance().getDirectory().getPath());
if (file != null)
{
String fsFile = file[0].getName();
ui.setPath(config.getLastDir() + fsFile);
loadSkin();
config.setDefaultSkin(ui.getPath());
}
}
// Shuffle
else if (cmd.equals(PlayerActionEvent.ACSHUFFLE))
{
if (ui.getAcShuffle().isSelected())
{
config.setShuffleEnabled(true);
if (playlist != null)
{
playlist.shuffle();
playlistUI.initPlayList();
// Play from the top
PlaylistItem pli = playlist.getCursor();
setCurrentSong(pli);
}
}
else
{
config.setShuffleEnabled(false);
}
}
// Repeat
else if (cmd.equals(PlayerActionEvent.ACREPEAT))
{
if (ui.getAcRepeat().isSelected())
{
config.setRepeatEnabled(true);
}
else
{
config.setRepeatEnabled(false);
}
}
// Play file
else if (cmd.equals(PlayerActionEvent.MIPLAYFILE))
{
processEject(MouseEvent.BUTTON1_MASK);
}
// Play URL
else if (cmd.equals(PlayerActionEvent.MIPLAYLOCATION))
{
processEject(MouseEvent.BUTTON3_MASK);
}
// Playlist menu item
else if (cmd.equals(PlayerActionEvent.MIPLAYLIST))
{
ui.getAcPlaylist().setSelected(miPlaylist.getState());
togglePlaylist();
}
// Playlist toggle button
else if (cmd.equals(PlayerActionEvent.ACPLAYLIST))
{
togglePlaylist();
}
// EqualizerUI menu item
else if (cmd.equals(PlayerActionEvent.MIEQUALIZER))
{
ui.getAcEqualizer().setSelected(miEqualizer.getState());
toggleEqualizer();
}
// EqualizerUI
else if (cmd.equals(PlayerActionEvent.ACEQUALIZER))
{
toggleEqualizer();
}
// Exit player
else if (cmd.equals(PlayerActionEvent.ACEXIT))
{
closePlayer();
}
// Minimize
else if (cmd.equals(PlayerActionEvent.ACMINIMIZE))
{
loader.minimize();
}
// Eject
else if (cmd.equals(PlayerActionEvent.ACEJECT))
{
processEject(e.getModifiers());
}
// Play
else if (cmd.equals(PlayerActionEvent.ACPLAY))
{
processPlay(e.getModifiers());
}
// Pause
else if (cmd.equals(PlayerActionEvent.ACPAUSE))
{
processPause(e.getModifiers());
}
// Stop
else if (cmd.equals(PlayerActionEvent.ACSTOP))
{
processStop(e.getModifiers());
}
// Next
else if (cmd.equals(PlayerActionEvent.ACNEXT))
{
processNext(e.getModifiers());
}
// Previous
else if (cmd.equals(PlayerActionEvent.ACPREVIOUS))
{
processPrevious(e.getModifiers());
}
}
/* (non-Javadoc)
* @see javazoom.jlgui.basicplayer.BasicPlayerListener#opened(java.lang.Object, java.util.Map)
*/
public void opened(Object stream, Map properties)
{
// Not in EDT.
audioInfo = properties;
log.debug(properties.toString());
}
/* (non-Javadoc)
* @see javazoom.jlgui.basicplayer.BasicPlayerListener#stateUpdated(javazoom.jlgui.basicplayer.BasicPlayerEvent)
*/
public void stateUpdated(final BasicPlayerEvent event)
{
// Not in EDT.
processStateUpdated(event);
}
/* (non-Javadoc)
* @see javazoom.jlgui.basicplayer.BasicPlayerListener#progress(int, long, byte[], java.util.Map)
*/
public void progress(int bytesread, long microseconds, byte[] pcmdata, Map properties)
{
// Not in EDT.
processProgress(bytesread, microseconds, pcmdata, properties);
}
/**
* Process PREFERENCES event.
* @param modifiers
*/
protected void processPreferences(int modifiers)
{
Preferences preferences = Preferences.getInstance(this);
preferences.setLocation(loader.getLocation().x, loader.getLocation().y);
preferences.setSize(512, 350);
preferences.setVisible(true);
}
/**
* Process SKINS BROWSER event.
* @param modifiers
*/
protected void processSkinBrowser(int modifiers)
{
Preferences preferences = Preferences.getInstance(this);
preferences.selectSkinBrowserPane();
preferences.setLocation(loader.getLocation().x, loader.getLocation().y);
preferences.setSize(512, 350);
preferences.setVisible(true);
}
/**
* Process JUMP FILE event.
* @param modifiers
*/
protected void processJumpToFile(int modifiers)
{
TagSearch ts = new TagSearch(this);
ts.setIconImage(config.getIconParent().getImage());
ts.setSize(400, 300);
ts.setLocation(loader.getLocation());
ts.display();
}
/**
* Process EJECT event.
* @param modifiers
*/
protected void processEject(int modifiers)
{
if ((playerState == PLAY) || (playerState == PAUSE))
{
try
{
if (theSoundPlayer != null)
{
theSoundPlayer.stop();
}
}
catch (BasicPlayerException e)
{
log.info("Cannot stop", e);
}
playerState = STOP;
}
if ((playerState == INIT) || (playerState == STOP) || (playerState == OPEN))
{
PlaylistItem pli = null;
// Local File.
if (modifiers == MouseEvent.BUTTON1_MASK)
{
File[] file = FileSelector.selectFile(loader, FileSelector.OPEN, false, config.getExtensions(), ui.getResource("button.eject.filedialog.filtername"), new File(config.getLastDir()));
if (FileSelector.getInstance().getDirectory() != null) config.setLastDir(FileSelector.getInstance().getDirectory().getPath());
if (file != null)
{
String fsFile = file[0].getName();
if (fsFile != null)
{
// Loads a new playlist.
if ((fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.m3u"))) || (fsFile.toLowerCase().endsWith(ui.getResource("playlist.extension.pls"))))
{
if (loadPlaylist(config.getLastDir() + fsFile))
{
config.setPlaylistFilename(config.getLastDir() + fsFile);
playlist.begin();
playlistUI.initPlayList();
setCurrentSong(playlist.getCursor());
playlistUI.repaint();
}
}
else if (fsFile.toLowerCase().endsWith(ui.getResource("skin.extension")))
{
ui.setPath(config.getLastDir() + fsFile);
loadSkin();
config.setDefaultSkin(ui.getPath());
}
else pli = new PlaylistItem(fsFile, config.getLastDir() + fsFile, -1, true);
}
}
}
// Remote File.
else if (modifiers == MouseEvent.BUTTON3_MASK)
{
UrlDialog UD = new UrlDialog(config.getTopParent(), ui.getResource("button.eject.urldialog.title"), loader.getLocation().x, loader.getLocation().y + 10, config.getLastURL());
UD.show();
if (UD.getFile() != null)
{
showTitle(ui.getResource("title.loading"));
// Remote playlist ?
if ((UD.getURL().toLowerCase().endsWith(ui.getResource("playlist.extension.m3u"))) || (UD.getURL().toLowerCase().endsWith(ui.getResource("playlist.extension.pls"))))
{
if (loadPlaylist(UD.getURL()))
{
config.setPlaylistFilename(UD.getURL());
playlist.begin();
playlistUI.initPlayList();
setCurrentSong(playlist.getCursor());
playlistUI.repaint();
}
}
// Remote file or stream.
else
{
pli = new PlaylistItem(UD.getFile(), UD.getURL(), -1, false);
}
config.setLastURL(UD.getURL());
}
}
if ((pli != null) && (playlist != null))
{
playlist.removeAllItems();
playlist.appendItem(pli);
playlist.nextCursor();
playlistUI.initPlayList();
setCurrentSong(pli);
playlistUI.repaint();
}
}
// Display play/time icons.
ui.getAcPlayIcon().setIcon(2);
ui.getAcTimeIcon().setIcon(1);
}
/**
* Process PLAY event.
* @param modifiers
*/
protected void processPlay(int modifiers)
{
if (playlist.isModified()) // playlist has been modified since we were last there, must update our cursor pos etc.
{
PlaylistItem pli = playlist.getCursor();
if (pli == null)
{
playlist.begin();
pli = playlist.getCursor();
}
setCurrentSong(pli);
playlist.setModified(false);
playlistUI.repaint();
}
// Resume is paused.
if (playerState == PAUSE)
{
try
{
theSoundPlayer.resume();
}
catch (BasicPlayerException e)
{
log.error("Cannot resume", e);
}
playerState = PLAY;
ui.getAcPlayIcon().setIcon(0);
ui.getAcTimeIcon().setIcon(0);
}
// Stop if playing.
else if (playerState == PLAY)
{
try
{
theSoundPlayer.stop();
}
catch (BasicPlayerException e)
{
log.error("Cannot stop", e);
}
playerState = PLAY;
secondsAmount = 0;
ui.getAcMinuteH().setAcText("0");
ui.getAcMinuteL().setAcText("0");
ui.getAcSecondH().setAcText("0");
ui.getAcSecondL().setAcText("0");
if (currentFileOrURL != null)
{
try
{
if (currentIsFile == true) theSoundPlayer.open(openFile(currentFileOrURL));
else
{
theSoundPlayer.open(new URL(currentFileOrURL));
}
theSoundPlayer.play();
}
catch (Exception ex)
{
log.error("Cannot read file : " + currentFileOrURL, ex);
showMessage(ui.getResource("title.invalidfile"));
}
}
}
else if ((playerState == STOP) || (playerState == OPEN))
{
try
{
theSoundPlayer.stop();
}
catch (BasicPlayerException e)
{
log.error("Stop failed", e);
}
if (currentFileOrURL != null)
{
try
{
if (currentIsFile == true) theSoundPlayer.open(openFile(currentFileOrURL));
else theSoundPlayer.open(new URL(currentFileOrURL));
theSoundPlayer.play();
titleText = currentSongName.toUpperCase();
// Get bitrate, samplingrate, channels, time in the following order :
// PlaylistItem, BasicPlayer (JavaSound SPI), Manual computation.
int bitRate = -1;
if (currentPlaylistItem != null) bitRate = currentPlaylistItem.getBitrate();
if ((bitRate <= 0) && (audioInfo.containsKey("bitrate"))) bitRate = ((Integer) audioInfo.get("bitrate")).intValue();
if ((bitRate <= 0) && (audioInfo.containsKey("audio.framerate.fps")) && (audioInfo.containsKey("audio.framesize.bytes")))
{
float FR = ((Float) audioInfo.get("audio.framerate.fps")).floatValue();
int FS = ((Integer) audioInfo.get("audio.framesize.bytes")).intValue();
bitRate = Math.round(FS * FR * 8);
}
int channels = -1;
if (currentPlaylistItem != null) channels = currentPlaylistItem.getChannels();
if ((channels <= 0) && (audioInfo.containsKey("audio.channels"))) channels = ((Integer) audioInfo.get("audio.channels")).intValue();
float sampleRate = -1.0f;
if (currentPlaylistItem != null) sampleRate = currentPlaylistItem.getSamplerate();
if ((sampleRate <= 0) && (audioInfo.containsKey("audio.samplerate.hz"))) sampleRate = ((Float) audioInfo.get("audio.samplerate.hz")).floatValue();
long lenghtInSecond = -1L;
if (currentPlaylistItem != null) lenghtInSecond = currentPlaylistItem.getLength();
if ((lenghtInSecond <= 0) && (audioInfo.containsKey("duration"))) lenghtInSecond = ((Long) audioInfo.get("duration")).longValue() / 1000000;
if ((lenghtInSecond <= 0) && (audioInfo.containsKey("audio.length.bytes")))
{
// Try to compute time length.
lenghtInSecond = (long) Math.round(getTimeLengthEstimation(audioInfo) / 1000);
if (lenghtInSecond > 0)
{
int minutes = (int) Math.floor(lenghtInSecond / 60);
int hours = (int) Math.floor(minutes / 60);
minutes = minutes - hours * 60;
int seconds = (int) (lenghtInSecond - minutes * 60 - hours * 3600);
if (seconds >= 10) titleText = "(" + minutes + ":" + seconds + ") " + titleText;
else titleText = "(" + minutes + ":0" + seconds + ") " + titleText;
}
}
bitRate = Math.round((bitRate / 1000));
ui.getAcSampleRateLabel().setAcText(String.valueOf(Math.round((sampleRate / 1000))));
if (bitRate > 999)
{
bitRate = (int) (bitRate / 100);
ui.getAcBitRateLabel().setAcText(bitRate + "H");
}
else
{
ui.getAcBitRateLabel().setAcText(String.valueOf(bitRate));
}
if (channels == 2)
{
ui.getAcStereoIcon().setIcon(1);
ui.getAcMonoIcon().setIcon(0);
}
else if (channels == 1)
{
ui.getAcStereoIcon().setIcon(0);
ui.getAcMonoIcon().setIcon(1);
}
showTitle(titleText);
ui.getAcMinuteH().setAcText("0");
ui.getAcMinuteL().setAcText("0");
ui.getAcSecondH().setAcText("0");
ui.getAcSecondL().setAcText("0");
ui.getAcPlayIcon().setIcon(0);
ui.getAcTimeIcon().setIcon(0);
}
catch (BasicPlayerException bpe)
{
log.info("Stream error :" + currentFileOrURL, bpe);
showMessage(ui.getResource("title.invalidfile"));
}
catch (MalformedURLException mue)
{
log.info("Stream error :" + currentFileOrURL, mue);
showMessage(ui.getResource("title.invalidfile"));
}
// Set pan/gain.
try
{
theSoundPlayer.setGain(((double) ui.getAcVolume().getValue() / (double) ui.getAcVolume().getMaximum()));
theSoundPlayer.setPan((float) ui.getAcBalance().getValue() / 10.0f);
}
catch (BasicPlayerException e)
{
log.info("Cannot set control", e);
}
playerState = PLAY;
log.info(titleText);
}
}
}
/**
* Process PAUSE event.
* @param modifiers
*/
public void processPause(int modifiers)
{
if (playerState == PLAY)
{
try
{
theSoundPlayer.pause();
}
catch (BasicPlayerException e)
{
log.error("Cannot pause", e);
}
playerState = PAUSE;
ui.getAcPlayIcon().setIcon(1);
ui.getAcTimeIcon().setIcon(1);
}
else if (playerState == PAUSE)
{
try
{
theSoundPlayer.resume();
}
catch (BasicPlayerException e)
{
log.info("Cannot resume", e);
}
playerState = PLAY;
ui.getAcPlayIcon().setIcon(0);
ui.getAcTimeIcon().setIcon(0);
}
}
/**
* Process STOP event.
* @param modifiers
*/
public void processStop(int modifiers)
{
if ((playerState == PAUSE) || (playerState == PLAY))
{
try
{
theSoundPlayer.stop();
}
catch (BasicPlayerException e)
{
log.info("Cannot stop", e);
}
playerState = STOP;
secondsAmount = 0;
ui.getAcPosBar().setValue(0);
ui.getAcPlayIcon().setIcon(2);
ui.getAcTimeIcon().setIcon(1);
}
}
/**
* Process NEXT event.
* @param modifiers
*/
public void processNext(int modifiers)
{
// Try to get next song from the playlist
playlist.nextCursor();
playlistUI.nextCursor();
PlaylistItem pli = playlist.getCursor();
setCurrentSong(pli);
}
/**
* Process PREVIOUS event.
* @param modifiers
*/
public void processPrevious(int modifiers)
{
// Try to get previous song from the playlist
playlist.previousCursor();
playlistUI.nextCursor();
PlaylistItem pli = playlist.getCursor();
setCurrentSong(pli);
}
/**
* Process STATEUPDATED event.
* @param event
*/
public void processStateUpdated(BasicPlayerEvent event)
{
log.debug("Player:" + event + " (EDT=" + SwingUtilities.isEventDispatchThread() + ")");
/*-- End Of Media reached --*/
int state = event.getCode();
Object obj = event.getDescription();
if (state == BasicPlayerEvent.EOM)
{
if ((playerState == PAUSE) || (playerState == PLAY))
{
playlist.nextCursor();
playlistUI.nextCursor();
PlaylistItem pli = playlist.getCursor();
setCurrentSong(pli);
}
}
else if (state == BasicPlayerEvent.PLAYING)
{
lastScrollTime = System.currentTimeMillis();
posValueJump = false;
if (audioInfo.containsKey("basicplayer.sourcedataline"))
{
if (ui.getAcAnalyzer() != null)
{
ui.getAcAnalyzer().setupDSP((SourceDataLine) audioInfo.get("basicplayer.sourcedataline"));
ui.getAcAnalyzer().startDSP((SourceDataLine) audioInfo.get("basicplayer.sourcedataline"));
}
}
}
else if (state == BasicPlayerEvent.SEEKING)
{
posValueJump = true;
}
else if (state == BasicPlayerEvent.SEEKED)
{
try
{
theSoundPlayer.setGain(((double) ui.getAcVolume().getValue() / (double) ui.getAcVolume().getMaximum()));
theSoundPlayer.setPan((float) ui.getAcBalance().getValue() / 10.0f);
}
catch (BasicPlayerException e)
{
log.debug(e);
}
}
else if (state == BasicPlayerEvent.OPENING)
{
if ((obj instanceof URL) || (obj instanceof InputStream))
{
showTitle(ui.getResource("title.buffering"));
}
}
else if (state == BasicPlayerEvent.STOPPED)
{
if (ui.getAcAnalyzer() != null)
{
ui.getAcAnalyzer().stopDSP();
ui.getAcAnalyzer().repaint();
}
}
}
/**
* Process PROGRESS event.
* @param bytesread
* @param microseconds
* @param pcmdata
* @param properties
*/
public void processProgress(int bytesread, long microseconds, byte[] pcmdata, Map properties)
{
//log.debug("Player: Progress (EDT="+SwingUtilities.isEventDispatchThread()+")");
int byteslength = -1;
long total = -1;
// Try to get time from playlist item.
if (currentPlaylistItem != null) total = currentPlaylistItem.getLength();
// If it fails then try again with JavaSound SPI.
if (total <= 0) total = (long) Math.round(getTimeLengthEstimation(audioInfo) / 1000);
// If it fails again then it might be stream => Total = -1
if (total <= 0) total = -1;
if (audioInfo.containsKey("basicplayer.sourcedataline"))
{
// Spectrum/time analyzer
if (ui.getAcAnalyzer() != null) ui.getAcAnalyzer().writeDSP(pcmdata);
}
if (audioInfo.containsKey("audio.length.bytes"))
{
byteslength = ((Integer) audioInfo.get("audio.length.bytes")).intValue();
}
float progress = -1.0f;
if ((bytesread > 0) && ((byteslength > 0))) progress = bytesread * 1.0f / byteslength * 1.0f;
if (audioInfo.containsKey("audio.type"))
{
String audioformat = (String) audioInfo.get("audio.type");
if (audioformat.equalsIgnoreCase("mp3"))
{
//if (properties.containsKey("mp3.position.microseconds")) secondsAmount = (long) Math.round(((Long) properties.get("mp3.position.microseconds")).longValue()/1000000);
// Shoutcast stream title.
if (properties.containsKey("mp3.shoutcast.metadata.StreamTitle"))
{
String shoutTitle = ((String) properties.get("mp3.shoutcast.metadata.StreamTitle")).trim();
if (shoutTitle.length() > 0)
{
if (currentPlaylistItem != null)
{
String sTitle = " (" + currentPlaylistItem.getFormattedDisplayName() + ")";
if (!currentPlaylistItem.getFormattedName().equals(shoutTitle + sTitle))
{
currentPlaylistItem.setFormattedDisplayName(shoutTitle + sTitle);
showTitle((shoutTitle + sTitle).toUpperCase());
playlistUI.paintList();
}
}
}
}
// EqualizerUI
if (properties.containsKey("mp3.equalizer")) equalizerUI.setBands((float[]) properties.get("mp3.equalizer"));
if (total > 0) secondsAmount = (long) (total * progress);
else secondsAmount = -1;
}
else if (audioformat.equalsIgnoreCase("wave"))
{
secondsAmount = (long) (total * progress);
}
else
{
secondsAmount = (long) Math.round(microseconds / 1000000);
equalizerUI.setBands(null);
}
}
else
{
secondsAmount = (long) Math.round(microseconds / 1000000);
equalizerUI.setBands(null);
}
if (secondsAmount < 0) secondsAmount = (long) Math.round(microseconds / 1000000);
/*-- Display elapsed time --*/
int secondD = 0, second = 0, minuteD = 0, minute = 0;
int seconds = (int) secondsAmount;
int minutes = (int) Math.floor(seconds / 60);
int hours = (int) Math.floor(minutes / 60);
minutes = minutes - hours * 60;
seconds = seconds - minutes * 60 - hours * 3600;
if (seconds < 10)
{
secondD = 0;
second = seconds;
}
else
{
secondD = ((int) seconds / 10);
second = ((int) (seconds - (((int) seconds / 10)) * 10));
}
if (minutes < 10)
{
minuteD = 0;
minute = minutes;
}
else
{
minuteD = ((int) minutes / 10);
minute = ((int) (minutes - (((int) minutes / 10)) * 10));
}
ui.getAcMinuteH().setAcText(String.valueOf(minuteD));
ui.getAcMinuteL().setAcText(String.valueOf(minute));
ui.getAcSecondH().setAcText(String.valueOf(secondD));
ui.getAcSecondL().setAcText(String.valueOf(second));
// Update PosBar location.
if (total != 0)
{
if (posValueJump == false)
{
int posValue = ((int) Math.round(secondsAmount * Skin.POSBARMAX / total));
ui.getAcPosBar().setValue(posValue);
}
}
else ui.getAcPosBar().setValue(0);
long ctime = System.currentTimeMillis();
long lctime = lastScrollTime;
// Scroll title ?
if ((titleScrollLabel != null) && (titleScrollLabel.length > 0))
{
if (ctime - lctime > SCROLL_PERIOD)
{
lastScrollTime = ctime;
if (scrollRight == true)
{
scrollIndex++;
if (scrollIndex >= titleScrollLabel.length)
{
scrollIndex--;
scrollRight = false;
}
}
else
{
scrollIndex--;
if (scrollIndex <= 0)
{
scrollRight = true;
}
}
// TODO : Improve
ui.getAcTitleLabel().setAcText(titleScrollLabel[scrollIndex]);
}
}
}
/**
* Process seek feature.
* @param rate
*/
protected void processSeek(double rate)
{
try
{
if ((audioInfo != null) && (audioInfo.containsKey("audio.type")))
{
String type = (String) audioInfo.get("audio.type");
// Seek support for MP3.
if ((type.equalsIgnoreCase("mp3")) && (audioInfo.containsKey("audio.length.bytes")))
{
long skipBytes = (long) Math.round(((Integer) audioInfo.get("audio.length.bytes")).intValue() * rate);
log.debug("Seek value (MP3) : " + skipBytes);
theSoundPlayer.seek(skipBytes);
}
// Seek support for WAV.
else if ((type.equalsIgnoreCase("wave")) && (audioInfo.containsKey("audio.length.bytes")))
{
long skipBytes = (long) Math.round(((Integer) audioInfo.get("audio.length.bytes")).intValue() * rate);
log.debug("Seek value (WAVE) : " + skipBytes);
theSoundPlayer.seek(skipBytes);
}
else posValueJump = false;
}
else posValueJump = false;
}
catch (BasicPlayerException ioe)
{
log.error("Cannot skip", ioe);
posValueJump = false;
}
}
/**
* Process Drag&Drop
* @param data
*/
public void processDnD(Object data)
{
log.debug("Player DnD");
// Looking for files to drop.
if (data instanceof List)
{
List al = (List) data;
if ((al != null) && (al.size() > 0))
{
ArrayList fileList = new ArrayList();
ArrayList folderList = new ArrayList();
ListIterator li = al.listIterator();
while (li.hasNext())
{
File f = (File) li.next();
if ((f.exists()) && (f.canRead()))
{
if (f.isFile()) fileList.add(f);
else if (f.isDirectory()) folderList.add(f);
}
}
playFiles(fileList);
// TODO : Add dir support
}
}
else if (data instanceof String)
{
String files = (String) data;
if ((files.length() > 0))
{
ArrayList fileList = new ArrayList();
ArrayList folderList = new ArrayList();
StringTokenizer st = new StringTokenizer(files, System.getProperty("line.separator"));
// Transfer files dropped.
while (st.hasMoreTokens())
{
String path = st.nextToken();
if (path.startsWith("file://"))
{
path = path.substring(7, path.length());
if (path.endsWith("\r")) path = path.substring(0, (path.length() - 1));
}
File f = new File(path);
if ((f.exists()) && (f.canRead()))
{
if (f.isFile()) fileList.add(f);
else if (f.isDirectory()) folderList.add(f);
}
}
playFiles(fileList);
// TODO : Add dir support
}
}
else
{
log.info("Unknown dropped objects");
}
}
/**
* Play files from a list.
* @param files
*/
protected void playFiles(List files)
{
if (files.size() > 0)
{
// Clean the playlist.
playlist.removeAllItems();
// Add all dropped files to playlist.
ListIterator li = files.listIterator();
while (li.hasNext())
{
File file = (File) li.next();
PlaylistItem pli = null;
if (file != null)
{
pli = new PlaylistItem(file.getName(), file.getAbsolutePath(), -1, true);
if (pli != null) playlist.appendItem(pli);
}
}
// Start the playlist from the top.
playlist.nextCursor();
playlistUI.initPlayList();
setCurrentSong(playlist.getCursor());
}
}
/**
* Sets the current song to play and start playing if needed.
* @param pli
*/
public void setCurrentSong(PlaylistItem pli)
{
int playerStateMem = playerState;
if ((playerState == PAUSE) || (playerState == PLAY))
{
try
{
theSoundPlayer.stop();
}
catch (BasicPlayerException e)
{
log.error("Cannot stop", e);
}
playerState = STOP;
secondsAmount = 0;
// Display play/time icons.
ui.getAcPlayIcon().setIcon(2);
ui.getAcTimeIcon().setIcon(0);
}
playerState = OPEN;
if (pli != null)
{
// Read tag info.
pli.getTagInfo();
currentSongName = pli.getFormattedName();
currentFileOrURL = pli.getLocation();
currentIsFile = pli.isFile();
currentPlaylistItem = pli;
}
// Playlist ended.
else
{
// Try to repeat ?
if (config.isRepeatEnabled())
{
if (playlist != null)
{
// PlaylistItems available ?
if (playlist.getPlaylistSize() > 0)
{
playlist.begin();
PlaylistItem rpli = playlist.getCursor();
if (rpli != null)
{
// OK, Repeat the playlist.
rpli.getTagInfo();
currentSongName = rpli.getFormattedName();
currentFileOrURL = rpli.getLocation();
currentIsFile = rpli.isFile();
currentPlaylistItem = rpli;
}
}
// No, so display Title.
else
{
currentSongName = Skin.TITLETEXT;
currentFileOrURL = null;
currentIsFile = false;
currentPlaylistItem = null;
}
}
}
// No, so display Title.
else
{
currentSongName = Skin.TITLETEXT;
currentFileOrURL = null;
currentIsFile = false;
currentPlaylistItem = null;
}
}
if (currentIsFile == true)
{
ui.getAcPosBar().setEnabled(true);
ui.getAcPosBar().setHideThumb(false);
}
else
{
config.setLastURL(currentFileOrURL);
ui.getAcPosBar().setEnabled(false);
ui.getAcPosBar().setHideThumb(true);
}
titleText = currentSongName.toUpperCase();
showMessage(titleText);
// Start playing if needed.
if ((playerStateMem == PLAY) || (playerStateMem == PAUSE))
{
processPlay(MouseEvent.BUTTON1_MASK);
}
}
/**
* Display text in title area.
* @param str
*/
public void showTitle(String str)
{
if (str != null)
{
currentTitle = str;
titleScrollLabel = null;
scrollIndex = 0;
scrollRight = true;
if (str.length() > TEXT_LENGTH_MAX)
{
int a = ((str.length()) - (TEXT_LENGTH_MAX)) + 1;
titleScrollLabel = new String[a];
for (int k = 0; k < a; k++)
{
String sText = str.substring(k, TEXT_LENGTH_MAX + k);
titleScrollLabel[k] = sText;
}
str = str.substring(0, TEXT_LENGTH_MAX);
}
ui.getAcTitleLabel().setAcText(str);
}
}
/**
* Shows message in title an updates bitRate,sampleRate, Mono/Stereo,time features.
* @param txt
*/
public void showMessage(String txt)
{
showTitle(txt);
ui.getAcSampleRateLabel().setAcText(" ");
ui.getAcBitRateLabel().setAcText(" ");
ui.getAcStereoIcon().setIcon(0);
ui.getAcMonoIcon().setIcon(0);
ui.getAcMinuteH().setAcText("0");
ui.getAcMinuteL().setAcText("0");
ui.getAcSecondH().setAcText("0");
ui.getAcSecondL().setAcText("0");
}
/**
* Toggle playlistUI.
*/
protected void togglePlaylist()
{
if (ui.getAcPlaylist().isSelected())
{
miPlaylist.setState(true);
config.setPlaylistEnabled(true);
loader.togglePlaylist(true);
}
else
{
miPlaylist.setState(false);
config.setPlaylistEnabled(false);
loader.togglePlaylist(false);
}
}
/**
* Toggle equalizerUI.
*/
protected void toggleEqualizer()
{
if (ui.getAcEqualizer().isSelected())
{
miEqualizer.setState(true);
config.setEqualizerEnabled(true);
loader.toggleEqualizer(true);
}
else
{
miEqualizer.setState(false);
config.setEqualizerEnabled(false);
loader.toggleEqualizer(false);
}
}
/**
* Returns a File from a filename.
* @param file
* @return
*/
protected File openFile(String file)
{
return new File(file);
}
/**
* Free resources and close the player.
*/
protected void closePlayer()
{
if ((playerState == PAUSE) || (playerState == PLAY))
{
try
{
if (theSoundPlayer != null)
{
theSoundPlayer.stop();
}
}
catch (BasicPlayerException e)
{
log.error("Cannot stop", e);
}
}
if (theSoundPlayer != null)
{
config.setAudioDevice(((BasicPlayer) theSoundPlayer).getMixerName());
}
if (ui.getAcAnalyzer() != null)
{
if (ui.getAcAnalyzer().getDisplayMode() == SpectrumTimeAnalyzer.DISPLAY_MODE_OFF) config.setVisualMode("off");
else if (ui.getAcAnalyzer().getDisplayMode() == SpectrumTimeAnalyzer.DISPLAY_MODE_SCOPE) config.setVisualMode("oscillo");
else config.setVisualMode("spectrum");
}
if (playlist != null)
{
playlist.save("default.m3u");
config.setPlaylistFilename("default.m3u");
}
loader.close();
}
/**
* Return current title in player.
* @return
*/
public String getCurrentTitle()
{
return currentTitle;
}
/**
* Try to compute time length in milliseconds.
* @param properties
* @return
*/
public long getTimeLengthEstimation(Map properties)
{
long milliseconds = -1;
int byteslength = -1;
if (properties != null)
{
if (properties.containsKey("audio.length.bytes"))
{
byteslength = ((Integer) properties.get("audio.length.bytes")).intValue();
}
if (properties.containsKey("duration"))
{
milliseconds = (int) (((Long) properties.get("duration")).longValue()) / 1000;
}
else
{
// Try to compute duration
int bitspersample = -1;
int channels = -1;
float samplerate = -1.0f;
int framesize = -1;
if (properties.containsKey("audio.samplesize.bits"))
{
bitspersample = ((Integer) properties.get("audio.samplesize.bits")).intValue();
}
if (properties.containsKey("audio.channels"))
{
channels = ((Integer) properties.get("audio.channels")).intValue();
}
if (properties.containsKey("audio.samplerate.hz"))
{
samplerate = ((Float) properties.get("audio.samplerate.hz")).floatValue();
}
if (properties.containsKey("audio.framesize.bytes"))
{
framesize = ((Integer) properties.get("audio.framesize.bytes")).intValue();
}
if (bitspersample > 0)
{
milliseconds = (int) (1000.0f * byteslength / (samplerate * channels * (bitspersample / 8)));
}
else
{
milliseconds = (int) (1000.0f * byteslength / (samplerate * framesize));
}
}
}
return milliseconds;
}
/**
* Simulates "Play" selection.
*/
public void pressStart()
{
ui.getAcPlay().doClick();
}
/**
* Simulates "Pause" selection.
*/
public void pressPause()
{
ui.getAcPause().doClick();
}
/**
* Simulates "Stop" selection.
*/
public void pressStop()
{
ui.getAcStop().doClick();
}
/**
* Simulates "Next" selection.
*/
public void pressNext()
{
ui.getAcNext().doClick();
}
/**
* Simulates "Previous" selection.
*/
public void pressPrevious()
{
ui.getAcPrevious().doClick();
}
/**
* Simulates "Eject" selection.
*/
public void pressEject()
{
ui.getAcEject().doClick();
}
}
| Java |
/*
* Configuration.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.util.ini;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import javazoom.jlgui.player.amp.util.Config;
/**
* A Configuration is used to save a set of configuration
* properties. The properties can be written out to disk
* in "name=value" form, and read back in.
*
* @author Jeremy Cloud
* @version 1.2.0
*/
public class Configuration
{
private File config_file = null;
private URL config_url = null;
private Hashtable props = new Hashtable(64);
/**
* Constructs a new Configuration object that stores
* it's properties in the file with the given name.
*/
public Configuration(String file_name)
{
// E.B - URL support
if (Config.startWithProtocol(file_name))
{
try
{
this.config_url = new URL(file_name);
}
catch (Exception e)
{
e.printStackTrace();
}
load();
}
else
{
this.config_file = new File(file_name);
load();
}
}
/**
* Constructs a new Configuration object that stores
* it's properties in the given file.
*/
public Configuration(File config_file)
{
this.config_file = config_file;
load();
}
/**
* Constructs a new Configuration object that stores
* it's properties in the given file.
*/
public Configuration(URL config_file)
{
this.config_url = config_file;
load();
}
/**
* Constructs a new Configuration object that doesn't
* have a file associated with it.
*/
public Configuration()
{
this.config_file = null;
}
/**
* @return The config file.
*/
public File getConfigFile()
{
return config_file;
}
/**
* Adds a the property with the given name and value.
*
* @param name The name of the property.
* @param value The value of the property.
*/
public void add(String name, String value)
{
props.put(name, value);
}
/**
* Adds the boolean property.
*
* @param name The name of the property.
* @param value The value of the property.
*/
public void add(String name, boolean value)
{
props.put(name, value ? "true" : "false");
}
/**
* Adds the integer property.
*
* @param name The name of the property.
* @param value The value of the property.
*/
public void add(String name, int value)
{
props.put(name, Integer.toString(value));
}
/**
* Adds the double property.
*
* @param name The name of the property.
* @param value The value of the property.
*/
public void add(String name, double value)
{
props.put(name, Double.toString(value));
}
/**
* Returns the value of the property with the
* given name. Null is returned if the named
* property is not found.
*
* @param The name of the desired property.
* @return The value of the property.
*/
public String get(String name)
{
return (String) props.get(name);
}
/**
* Returns the value of the property with the
* given name. 'default_value' is returned if the
* named property is not found.
*
* @param The name of the desired property.
* @param default_value The default value of the property which is returned
* if the property does not have a specified value.
* @return The value of the property.
*/
public String get(String name, String default_value)
{
Object value = props.get(name);
return value != null ? (String) value : default_value;
}
/**
* Returns the value of the property with the given name.
* 'false' is returned if the property does not have a
* specified value.
*
* @param name The name of the desired property.
* @param return The value of the property.
*/
public boolean getBoolean(String name)
{
Object value = props.get(name);
return value != null ? value.equals("true") : false;
}
/**
* Returns the value of the property with the given name.
*
* @param name The name of the desired property.
* @param default_value The default value of the property which is returned
* if the property does not have a specified value.
* @param return The value of the property.
*/
public boolean getBoolean(String name, boolean default_value)
{
Object value = props.get(name);
return value != null ? value.equals("true") : default_value;
}
/**
* Returns the value of the property with the given name.
* '0' is returned if the property does not have a
* specified value.
*
* @param name The name of the desired property.
* @param return The value of the property.
*/
public int getInt(String name)
{
try
{
return Integer.parseInt((String) props.get(name));
}
catch (Exception e)
{
}
return -1;
}
/**
* Returns the value of the property with the given name.
*
* @param name The name of the desired property.
* @param default_value The default value of the property which is returned
* if the property does not have a specified value.
* @param return The value of the property.
*/
public int getInt(String name, int default_value)
{
try
{
return Integer.parseInt((String) props.get(name));
}
catch (Exception e)
{
}
return default_value;
}
/**
* Returns the value of the property with the given name.
* '0' is returned if the property does not have a
* specified value.
*
* @param name The name of the desired property.
* @param return The value of the property.
*/
public double getDouble(String name)
{
try
{
return new Double((String) props.get(name)).doubleValue();
}
catch (Exception e)
{
}
return -1d;
}
/**
* Returns the value of the property with the given name.
*
* @param name The name of the desired property.
* @param default_value The default value of the property which is returned
* if the property does not have a specified value.
* @param return The value of the property.
*/
public double getDouble(String name, double default_value)
{
try
{
return new Double((String) props.get(name)).doubleValue();
}
catch (Exception e)
{
}
return default_value;
}
/**
* Removes the property with the given name.
*
* @param name The name of the property to remove.
*/
public void remove(String name)
{
props.remove(name);
}
/**
* Removes all the properties.
*/
public void removeAll()
{
props.clear();
}
/**
* Loads the property list from the configuration file.
*
* @return True if the file was loaded successfully, false if
* the file does not exists or an error occurred reading
* the file.
*/
public boolean load()
{
if ((config_file == null) && (config_url == null)) return false;
// Loads from URL.
if (config_url != null)
{
try
{
return load(new BufferedReader(new InputStreamReader(config_url.openStream())));
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
// Loads from file.
else
{
if (!config_file.exists()) return false;
try
{
return load(new BufferedReader(new FileReader(config_file)));
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
}
public boolean load(BufferedReader buffy) throws IOException
{
Hashtable props = this.props;
String line = null;
while ((line = buffy.readLine()) != null)
{
int eq_idx = line.indexOf('=');
if (eq_idx > 0)
{
String name = line.substring(0, eq_idx).trim();
String value = line.substring(eq_idx + 1).trim();
props.put(name, value);
}
}
buffy.close();
return true;
}
/**
* Saves the property list to the config file.
*
* @return True if the save was successful, false othewise.
*/
public boolean save()
{
if (config_url != null) return false;
try
{
PrintWriter out = new PrintWriter(new FileWriter(config_file));
return save(out);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
public boolean save(PrintWriter out) throws IOException
{
Hashtable props = this.props;
Enumeration names = props.keys();
SortedStrings sorter = new SortedStrings();
while (names.hasMoreElements())
{
sorter.add((String) names.nextElement());
}
for (int i = 0; i < sorter.stringCount(); i++)
{
String name = sorter.stringAt(i);
String value = (String) props.get(name);
out.print(name);
out.print("=");
out.println(value);
}
out.close();
return true;
}
public void storeCRC()
{
add("crc", generateCRC());
}
public boolean isValidCRC()
{
String crc = generateCRC();
String stored_crc = (String) props.get("crc");
if (stored_crc == null) return false;
return stored_crc.equals(crc);
}
private String generateCRC()
{
Hashtable props = this.props;
CRC32OutputStream crc = new CRC32OutputStream();
PrintWriter pr = new PrintWriter(crc);
Enumeration names = props.keys();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
if (!name.equals("crc"))
{
pr.println((String) props.get(name));
}
}
pr.flush();
return "" + crc.getValue();
}
}
| Java |
/*
* Alphabetizer.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.util.ini;
/**
* This class alphabetizes strings.
*
* @author Matt "Spiked Bat" Segur
*/
public class Alphabetizer
{
public static boolean lessThan(String str1, String str2)
{
return compare(str1, str2) < 0;
}
public static boolean greaterThan(String str1, String str2)
{
return compare(str1, str2) > 0;
}
public static boolean equalTo(String str1, String str2)
{
return compare(str1, str2) == 0;
}
/**
* Performs a case-insensitive comparison of the two strings.
*/
public static int compare(String s1, String s2)
{
if (s1 == null && s2 == null) return 0;
else if (s1 == null) return -1;
else if (s2 == null) return +1;
int len1 = s1.length();
int len2 = s2.length();
int len = Math.min(len1, len2);
for (int i = 0; i < len; i++)
{
int comparison = compare(s1.charAt(i), s2.charAt(i));
if (comparison != 0) return comparison;
}
if (len1 < len2) return -1;
else if (len1 > len2) return +1;
else return 0;
}
/**
* Performs a case-insensitive comparison of the two characters.
*/
public static int compare(char c1, char c2)
{
if (65 <= c1 && c1 <= 91) c1 += 32;
if (65 <= c2 && c2 <= 91) c2 += 32;
if (c1 < c2) return -1;
else if (c1 > c2) return +1;
else return 0;
}
} | Java |
/*
* CRC32OutputStream.
*
* JavaZOOM : jlgui@javazoom.net
* http://www.javazoom.net
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jlgui.player.amp.util.ini;
import java.io.OutputStream;
import java.util.zip.CRC32;
/**
* @author Jeremy Cloud
* @version 1.0.0
*/
public class CRC32OutputStream extends OutputStream
{
private CRC32 crc;
public CRC32OutputStream()
{
crc = new CRC32();
}
public void write(int new_byte)
{
crc.update(new_byte);
}
public long getValue()
{
return crc.getValue();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.