code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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.util; import com.google.android.apps.mytracks.ContextualActionModeCallback; import android.annotation.TargetApi; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; /** * API level 11 specific implementation of the {@link ApiAdapter}. * * @author Jimmy Shih */ @TargetApi(11) public class Api11Adapter extends Api10Adapter { @Override public void hideTitle(Activity activity) { // Do nothing } @Override public void configureActionBarHomeAsUp(Activity activity) { activity.getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void configureListViewContextualMenu(final Activity activity, ListView listView, final int menuId, final int actionModeTitleId, final ContextualActionModeCallback contextualActionModeCallback) { listView.setOnItemLongClickListener(new OnItemLongClickListener() { ActionMode actionMode; @Override public boolean onItemLongClick( AdapterView<?> parent, View view, int position, final long id) { if (actionMode != null) { return false; } actionMode = activity.startActionMode(new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(menuId, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Return false to indicate no change. return false; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return contextualActionModeCallback.onClick(item.getItemId(), id); } }); TextView textView = (TextView) view.findViewById(actionModeTitleId); if (textView != null) { actionMode.setTitle(textView.getText()); } view.setSelected(true); return true; } }); }; @Override public void configureSearchWidget(Activity activity, MenuItem menuItem) { SearchManager searchManager = (SearchManager) activity.getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menuItem.getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(activity.getComponentName())); } @Override public boolean handleSearchMenuSelection(Activity activity) { // Returns false to allow the platform to expand the search widget. return false; } }
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.util; 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; /** * Utilities to access preferences stored in {@link SharedPreferences}. * * @author Jimmy Shih */ public class PreferencesUtils { private PreferencesUtils() {} /** * Gets the recording track id key. * * @param context the context */ public static String getRecordingTrackIdKey(Context context) { return getKey(context, R.string.recording_track_id_key); } /** * Gets the recording track id. * * @param context the context */ public static long getRecordingTrackId(Context context) { return getLong(context, R.string.recording_track_id_key); } /** * Sets the recording track id. * * @param context the context * @param trackId the track id */ public static void setRecordingTrackId(Context context, long trackId) { setLong(context, R.string.recording_track_id_key, trackId); } /** * Gets the selected track id key. * * @param context the context */ public static String getSelectedTrackIdKey(Context context) { return getKey(context, R.string.selected_track_id_key); } /** * Gets the selected track id. * * @param context the context */ public static long getSelectedTrackId(Context context) { return getLong(context, R.string.selected_track_id_key); } /** * Sets the selected track id. * * @param context the context * @param trackId the track id */ public static void setSelectedTrackId(Context context, long trackId) { setLong(context, R.string.selected_track_id_key, trackId); } /** * Gets a preference key * * @param context the context * @param keyId the key id */ private static String getKey(Context context, int keyId) { return context.getString(keyId); } /** * Gets a long preference value. * * @param context the context * @param keyId the key id */ private static long getLong(Context context, int keyId) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getLong(getKey(context, keyId), -1L); } /** * Sets a long preference value. * * @param context the context * @param keyId the key id * @param value the value */ private static void setLong(Context context, int keyId, long value) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putLong(getKey(context, keyId), value); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } }
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.util; import com.google.android.apps.mytracks.Constants; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; /** * Utility class for acessing basic Android functionality. * * @author Rodrigo Damazio */ public class SystemUtils { /** * Get the My Tracks version from the manifest. * * @return the version, or an empty string in case of failure. */ public static String getMyTracksVersion(Context context) { try { PackageInfo pi = context.getPackageManager().getPackageInfo( "com.google.android.maps.mytracks", PackageManager.GET_META_DATA); return pi.versionName; } catch (NameNotFoundException e) { Log.w(Constants.TAG, "Failed to get version info.", e); return ""; } } /** * Tries to acquire a partial wake lock if not already acquired. Logs errors * and gives up trying in case the wake lock cannot be acquired. */ public static WakeLock acquireWakeLock(Activity activity, WakeLock wakeLock) { Log.i(Constants.TAG, "LocationUtils: Acquiring wake lock."); try { PowerManager pm = (PowerManager) activity .getSystemService(Context.POWER_SERVICE); if (pm == null) { Log.e(Constants.TAG, "LocationUtils: Power manager not found!"); return wakeLock; } if (wakeLock == null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); if (wakeLock == null) { Log.e(Constants.TAG, "LocationUtils: Could not create wake lock (null)."); } return wakeLock; } if (!wakeLock.isHeld()) { wakeLock.acquire(); if (!wakeLock.isHeld()) { Log.e(Constants.TAG, "LocationUtils: Could not acquire wake lock."); } } } catch (RuntimeException e) { Log.e(Constants.TAG, "LocationUtils: Caught unexpected exception: " + e.getMessage(), e); } return wakeLock; } private SystemUtils() {} }
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.util; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.widget.TextView; /** * Utilities for updating the statistics UI labels and values. * * @author Jimmy Shih */ public class StatsUtils { private StatsUtils() {} /** * Sets a speed label. * * @param activity the activity * @param id the speed label resource id * @param speedId the speed string id * @param paceId the pace string id * @param reportSpeed true to report speed */ public static void setSpeedLabel( Activity activity, int id, int speedId, int paceId, boolean reportSpeed) { TextView textView = (TextView) activity.findViewById(id); textView.setText(reportSpeed ? speedId : paceId); } /** * Sets a speed value. * * @param activity the activity * @param id the speed value resource id * @param speed the speed in meters per second * @param reportSpeed true to report speed * @param metricUnits true to display in metric units */ public static void setSpeedValue( Activity activity, int id, double speed, boolean reportSpeed, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); speed *= UnitConversions.MS_TO_KMH; String value; if (metricUnits) { if (reportSpeed) { value = activity.getString(R.string.value_float_kilometer_hour, speed); } else { // convert from hours to minutes double pace = speed == 0 ? 0.0 : 60.0 / speed; value = activity.getString(R.string.value_float_minute_kilometer, pace); } } else { speed *= UnitConversions.KM_TO_MI; if (reportSpeed) { value = activity.getString(R.string.value_float_mile_hour, speed); } else { // convert from hours to minutes double pace = speed == 0 ? 0.0 : 60.0 / speed; value = activity.getString(R.string.value_float_minute_mile, pace); } } textView.setText(value); } /** * Sets a distance value. * * @param activity the activity * @param id the distance value resource id * @param distance the distance in meters * @param metricUnits true to display in metric units */ public static void setDistanceValue( Activity activity, int id, double distance, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); distance *= UnitConversions.M_TO_KM; String value; if (metricUnits) { value = activity.getString(R.string.value_float_kilometer, distance); } else { distance *= UnitConversions.KM_TO_MI; value = activity.getString(R.string.value_float_mile, distance); } textView.setText(value); } /** * Sets a time value. * * @param activity the activity * @param id the time value resource id * @param time the time */ public static void setTimeValue(Activity activity, int id, long time) { TextView textView = (TextView) activity.findViewById(id); textView.setText(StringUtils.formatElapsedTime(time)); } /** * Sets an altitude value. * * @param activity the activity * @param id the altitude value resource id * @param altitude the altitude in meters * @param metricUnits true to display in metric units */ public static void setAltitudeValue( Activity activity, int id, double altitude, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); String value; if (Double.isNaN(altitude) || Double.isInfinite(altitude)) { value = activity.getString(R.string.value_unknown); } else { if (metricUnits) { value = activity.getString(R.string.value_float_meter, altitude); } else { altitude *= UnitConversions.M_TO_FT; value = activity.getString(R.string.value_float_feet, altitude); } } textView.setText(value); } /** * Sets a grade value. * * @param activity the activity * @param id the grade value resource id * @param grade the grade in fraction between 0 and 1 */ public static void setGradeValue(Activity activity, int id, double grade) { TextView textView = (TextView) activity.findViewById(id); String value; if (Double.isNaN(grade) || Double.isInfinite(grade)) { value = activity.getString(R.string.value_unknown); } else { value = activity.getString(R.string.value_integer_percent, Math.round(grade * 100)); } textView.setText(value); } }
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.apps.mytracks.util.DialogUtils; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; /** * An activity to import GPX files from the SD card. Optionally to import one * GPX file and display it in My Tracks. * * @author Rodrigo Damazio */ public class ImportActivity extends Activity { public static final String EXTRA_IMPORT_ALL = "import_all"; private static final String TAG = ImportActivity.class.getSimpleName(); private static final int DIALOG_PROGRESS_ID = 0; private static final int DIALOG_RESULT_ID = 1; private ImportAsyncTask importAsyncTask; private ProgressDialog progressDialog; private boolean importAll; // path on the SD card to import private String path; // number of succesfully imported files private int successCount; // number of files to import private int totalCount; // last successfully imported track id private long trackId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); importAll = intent.getBooleanExtra(EXTRA_IMPORT_ALL, false); if (importAll) { path = FileUtils.buildExternalDirectoryPath("gpx"); } else { String action = intent.getAction(); if (!(Intent.ACTION_ATTACH_DATA.equals(action) || Intent.ACTION_VIEW.equals(action))) { Log.d(TAG, "Invalid action: " + intent); finish(); return; } Uri data = intent.getData(); if (!UriUtils.isFileUri(data)) { Log.d(TAG, "Invalid data: " + intent); finish(); return; } path = data.getPath(); } Object retained = getLastNonConfigurationInstance(); if (retained instanceof ImportAsyncTask) { importAsyncTask = (ImportAsyncTask) retained; importAsyncTask.setActivity(this); } else { importAsyncTask = new ImportAsyncTask(this, importAll, path); importAsyncTask.execute(); } } @Override public Object onRetainNonConfigurationInstance() { importAsyncTask.setActivity(null); return importAsyncTask; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS_ID: progressDialog = DialogUtils.createHorizontalProgressDialog( this, R.string.import_progress_message, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { importAsyncTask.cancel(true); finish(); } }); return progressDialog; case DIALOG_RESULT_ID: String message; if (successCount == 0) { message = getString(R.string.import_no_file, path); } else { String totalFiles = getResources() .getQuantityString(R.plurals.importGpxFiles, totalCount, totalCount); message = getString(R.string.import_success, successCount, totalFiles, path); } return new AlertDialog.Builder(this) .setCancelable(true) .setMessage(message) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!importAll && trackId != -1L) { Intent intent = new Intent(ImportActivity.this, TrackDetailActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, trackId); startActivity(intent); } finish(); } }) .create(); default: return null; } } /** * Invokes when the associated AsyncTask completes. * * @param success true if the AsyncTask is successful * @param imported the number of files successfully imported * @param total the total number of files to import * @param id the last successfully imported track id */ public void onAsyncTaskCompleted(boolean success, int imported, int total, long id) { successCount = imported; totalCount = total; trackId = id; removeDialog(DIALOG_PROGRESS_ID); if (success) { showDialog(DIALOG_RESULT_ID); } else { Toast.makeText(this, getString(R.string.import_error, path), Toast.LENGTH_LONG).show(); finish(); } } /** * Shows the progress dialog. */ public void showProgressDialog() { showDialog(DIALOG_PROGRESS_ID); } /** * Sets the progress dialog value. * * @param number the number of files imported * @param max the maximum number of files */ public void setProgressDialogValue(int number, int max) { if (progressDialog != null) { progressDialog.setIndeterminate(false); progressDialog.setMax(max); progressDialog.setProgress(Math.min(number, max)); } } }
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.fragments; import com.google.android.apps.mytracks.util.EulaUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to show EULA. * * @author Jimmy Shih */ public class EulaDialogFragment extends DialogFragment { public static final String EULA_DIALOG_TAG = "eulaDialog"; private static final String KEY_HAS_ACCEPTED = "hasAccepted"; /** * Creates a new instance of {@link EulaDialogFragment}. * * @param hasAccepted true if the user has accepted the eula. */ public static EulaDialogFragment newInstance(boolean hasAccepted) { Bundle bundle = new Bundle(); bundle.putBoolean(KEY_HAS_ACCEPTED, hasAccepted); EulaDialogFragment eulaDialogFragment = new EulaDialogFragment(); eulaDialogFragment.setArguments(bundle); return eulaDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { boolean hasAccepted = getArguments().getBoolean(KEY_HAS_ACCEPTED); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setCancelable(true) .setMessage(EulaUtils.getEulaMessage(getActivity())) .setTitle(R.string.eula_title); if (hasAccepted) { builder.setPositiveButton(R.string.generic_ok, null); } else { builder.setNegativeButton(R.string.eula_decline, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getActivity().finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { getActivity().finish(); } }) .setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EulaUtils.setEulaValue(getActivity()); new WelcomeDialogFragment().show( getActivity().getSupportFragmentManager(), WelcomeDialogFragment.WELCOME_DIALOG_TAG); } }); } return builder.create(); } }
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.fragments; import com.google.android.apps.mytracks.MarkerListActivity; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete one marker. * * @author Jimmy Shih */ public class DeleteOneMarkerDialogFragment extends DialogFragment { public static final String DELETE_ONE_MARKER_DIALOG_TAG = "deleteOneMarkerDialog"; private static final String KEY_MARKER_ID = "markerId"; public static DeleteOneMarkerDialogFragment newInstance(long markerId) { Bundle bundle = new Bundle(); bundle.putLong(KEY_MARKER_ID, markerId); DeleteOneMarkerDialogFragment deleteOneMarkerDialogFragment = new DeleteOneMarkerDialogFragment(); deleteOneMarkerDialogFragment.setArguments(bundle); return deleteOneMarkerDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.marker_delete_one_marker_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()).deleteWaypoint( getArguments().getLong(KEY_MARKER_ID), new DescriptionGeneratorImpl(getActivity())); startActivity(new Intent(getActivity(), MarkerListActivity.class).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); } }); } }
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.fragments; import com.google.android.apps.mytracks.MyTracksApplication; import com.google.android.apps.mytracks.StatsUtilities; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import java.util.EnumSet; /** * A fragment to display track statistics to the user. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class StatsFragment extends Fragment implements TrackDataListener { private static final String TAG = StatsFragment.class.getSimpleName(); private StatsUtilities statsUtilities; private TrackDataHub trackDataHub; private UiUpdateThread uiUpdateThread; // The start time of the current track. private long startTime = -1L; // A runnable to update the total time field. private final Runnable updateTotalTime = new Runnable() { public void run() { if (isRecording()) { statsUtilities.setTime(R.id.total_time_register, System.currentTimeMillis() - startTime); } } }; /** * A thread that updates the total time field every second. */ private class UiUpdateThread extends Thread { @Override public void run() { Log.d(TAG, "UI update thread started"); while (PreferencesUtils.getRecordingTrackId(getActivity()) != -1L) { getActivity().runOnUiThread(updateTotalTime); try { Thread.sleep(1000L); } catch (InterruptedException e) { Log.d(TAG, "UI update thread caught exception", e); break; } } Log.d(TAG, "UI update thread finished"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); statsUtilities = new StatsUtilities(getActivity()); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.stats, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrolly); scrollView.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); updateLabels(); setLocationUnknown(); } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); if (uiUpdateThread != null) { uiUpdateThread.interrupt(); uiUpdateThread = null; } } @Override public void onProviderStateChange(ProviderState state) { if (state == ProviderState.DISABLED || state == ProviderState.NO_FIX) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setLocationUnknown(); } }); } } @Override public void onCurrentLocationChanged(final Location location) { if (isRecording()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (location != null) { setLocation(location); } else { setLocationUnknown(); } } }); } } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { if (uiUpdateThread == null && isRecording) { uiUpdateThread = new UiUpdateThread(); uiUpdateThread.start(); } else if (uiUpdateThread != null && !isRecording) { uiUpdateThread.interrupt(); uiUpdateThread = null; } } @Override public void onTrackUpdated(final Track track) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (track == null || track.getStatistics() == null) { statsUtilities.setAllToUnknown(); return; } startTime = track.getStatistics().getStartTime(); if (!isRecording()) { statsUtilities.setTime(R.id.total_time_register, track.getStatistics().getTotalTime()); setLocationUnknown(); } statsUtilities.setAllStats(track.getStatistics()); } }); } @Override public void clearTrackPoints() { // We don't care. } @Override public void onNewTrackPoint(Location loc) { // We don't care. } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onSegmentSplit() { // We don't care. } @Override public void onNewTrackPointsDone() { // We don't care. } @Override public void clearWaypoints() { // We don't care. } @Override public void onNewWaypoint(Waypoint wpt) { // We don't care. } @Override public void onNewWaypointsDone() { // We don't care. } @Override public boolean onUnitsChanged(boolean metric) { if (statsUtilities.isMetricUnits() == metric) { return false; } statsUtilities.setMetricUnits(metric); getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateLabels(); } }); return true; } @Override public boolean onReportSpeedChanged(boolean speed) { if (statsUtilities.isReportSpeed() == speed) { return false; } statsUtilities.setReportSpeed(speed); getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateLabels(); } }); return true; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can * be accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can * be accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Returns true if recording. Needs to be synchronized because trackDataHub * can be accessed by multiple threads. */ private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } /** * Updates the labels. */ private void updateLabels() { statsUtilities.updateUnits(); statsUtilities.setSpeedLabel(R.id.speed_label, R.string.stat_speed, R.string.stat_pace); statsUtilities.setSpeedLabels(); } /** * Sets the current location. * * @param location the current location */ private void setLocation(Location location) { statsUtilities.setAltitude(R.id.elevation_register, location.getAltitude()); statsUtilities.setLatLong(R.id.latitude_register, location.getLatitude()); statsUtilities.setLatLong(R.id.longitude_register, location.getLongitude()); statsUtilities.setSpeed(R.id.speed_register, location.getSpeed() * UnitConversions.MS_TO_KMH); } /** * Sets the current location to unknown. */ private void setLocationUnknown() { statsUtilities.setUnknown(R.id.elevation_register); statsUtilities.setUnknown(R.id.latitude_register); statsUtilities.setUnknown(R.id.longitude_register); statsUtilities.setUnknown(R.id.speed_register); } }
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.fragments; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete all tracks. * * @author Jimmy Shih */ public class DeleteAllTrackDialogFragment extends DialogFragment { public static final String DELETE_ALL_TRACK_DIALOG_TAG = "deleteAllTrackDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.track_list_delete_all_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()).deleteAllTracks(); } }); } }
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.fragments; import static com.google.android.apps.mytracks.Constants.CHART_TAB_TAG; import com.google.android.apps.mytracks.ChartView; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; import android.widget.CheckBox; import android.widget.RadioGroup; /** * A DialogFragment to show chart settings. * * @author Jimmy Shih */ public class ChartSettingsDialogFragment extends DialogFragment { public static final String CHART_SETTINGS_DIALOG_TAG = "chartSettingsDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final ChartFragment chartFragment = (ChartFragment) getActivity() .getSupportFragmentManager().findFragmentByTag(CHART_TAB_TAG); View view = getActivity().getLayoutInflater().inflate(R.layout.chart_settings, null); final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.chart_settings_x); radioGroup.check(chartFragment.getMode() == ChartView.Mode.BY_DISTANCE ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); final CheckBox[] checkBoxes = new CheckBox[ChartView.NUM_SERIES]; checkBoxes[ChartView.ELEVATION_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_elevation); checkBoxes[ChartView.SPEED_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_speed); checkBoxes[ChartView.POWER_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_power); checkBoxes[ChartView.CADENCE_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_cadence); checkBoxes[ChartView.HEART_RATE_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_heart_rate); // set checkboxes values for (int i = 0; i < ChartView.NUM_SERIES; i++) { checkBoxes[i].setChecked(chartFragment.isChartValueSeriesEnabled(i)); } checkBoxes[ChartView.SPEED_SERIES].setText(chartFragment.isReportSpeed() ? R.string.stat_speed : R.string.stat_pace); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setNegativeButton(R.string.generic_cancel, null) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { chartFragment.setMode( radioGroup.getCheckedRadioButtonId() == R.id.chart_settings_by_distance ? ChartView.Mode.BY_DISTANCE : ChartView.Mode.BY_TIME); for (int i = 0; i < ChartView.NUM_SERIES; i++) { chartFragment.setChartValueSeriesEnabled(i, checkBoxes[i].isChecked()); } chartFragment.update(); } }) .setTitle(R.string.menu_chart_settings) .setView(view) .create(); } }
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.fragments; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.CheckUnitsUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to check preferred units. * * @author Jimmy Shih */ public class CheckUnitsDialogFragment extends DialogFragment { public static final String CHECK_UNITS_DIALOG_TAG = "checkUnitsDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CheckUnitsUtils.setCheckUnitsValue(getActivity()); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CheckUnitsUtils.setCheckUnitsValue(getActivity()); int position = ((AlertDialog) dialog).getListView().getSelectedItemPosition(); SharedPreferences sharedPreferences = getActivity() .getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(sharedPreferences.edit() .putBoolean(getString(R.string.metric_units_key), position == 0)); } }) .setSingleChoiceItems(new CharSequence[] { getString(R.string.preferred_units_metric), getString(R.string.preferred_units_imperial) }, 0, null) .setTitle(R.string.preferred_units_title) .create(); } }
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.fragments; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to install Google Earth. * * @author Jimmy Shih */ public class InstallEarthDialogFragment extends DialogFragment { public static final String INSTALL_EARTH_DIALOG_TAG = "installEarthDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setMessage(R.string.track_detail_install_earth_message) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent().setData(Uri.parse(SaveActivity.GOOGLE_EARTH_MARKET_URL))); } }) .create(); } }
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.fragments; import com.google.android.apps.mytracks.ChartView; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracksApplication; 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.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.ZoomControls; import java.util.ArrayList; import java.util.EnumSet; /** * A fragment to display track chart to the user. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class ChartFragment extends Fragment implements TrackDataListener { // Android reports 128 when the speed is invalid private static final int INVALID_SPEED = 128; private final DoubleBuffer elevationBuffer = new DoubleBuffer( Constants.ELEVATION_SMOOTHING_FACTOR); private final DoubleBuffer speedBuffer = new DoubleBuffer(Constants.SPEED_SMOOTHING_FACTOR); private final ArrayList<double[]> pendingPoints = new ArrayList<double[]>(); private TrackDataHub trackDataHub; // Stats gathered from the received data private double totalDistance = 0.0; private long startTime = -1L; private Location lastLocation = null; private double trackMaxSpeed = 0.0; // Modes of operation private boolean metricUnits = true; private boolean reportSpeed = true; // UI elements private ChartView chartView; private LinearLayout busyPane; private ZoomControls zoomControls; /** * A runnable that will remove the spinner (if any), enable/disable zoom * controls and orange pointer as appropriate and redraw. */ private final Runnable updateChart = new Runnable() { @Override public void run() { if (trackDataHub == null) { return; } busyPane.setVisibility(View.GONE); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); chartView.setShowPointer(isRecording()); chartView.invalidate(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Create a chartView here to store data thus won't need to reload all the * data on every onStart or onResume. */ chartView = new ChartView(getActivity()); }; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mytracks_charts, container, false); busyPane = (LinearLayout) view.findViewById(R.id.elevation_busypane); zoomControls = (ZoomControls) view.findViewById(R.id.elevation_zoom); zoomControls.setOnZoomInClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomIn(); } }); zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomOut(); } }); return view; } @Override public void onStart() { super.onStart(); ViewGroup layout = (ViewGroup) getActivity().findViewById(R.id.elevation_chart); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layout.addView(chartView, layoutParams); } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); getActivity().runOnUiThread(updateChart); } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); } @Override public void onStop() { super.onStop(); ViewGroup layout = (ViewGroup) getActivity().findViewById(R.id.elevation_chart); layout.removeView(chartView); } /** * Sets the chart view mode. * * @param mode the chart view mode */ public void setMode(Mode mode) { if (chartView.getMode() != mode) { chartView.setMode(mode); reloadTrackDataHub(); } } /** * Gets the chart view mode. */ public Mode getMode() { return chartView.getMode(); } /** * Enables or disables the chart value series. * * @param index the index of the series * @param enabled true to enable, false to disable */ public void setChartValueSeriesEnabled(int index, boolean enabled) { chartView.setChartValueSeriesEnabled(index, enabled); } /** * Returns true if the chart value series is enabled. * * @param index the index of the series */ public boolean isChartValueSeriesEnabled(int index) { return chartView.isChartValueSeriesEnabled(index); } /** * Returns true to report speed instead of pace. */ public boolean isReportSpeed() { return reportSpeed; } /** * Updates the chart. */ public void update() { chartView.postInvalidate(); } @Override public void onProviderStateChange(ProviderState state) { // We don't care. } @Override public void onCurrentLocationChanged(Location loc) { // We don't care. } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { busyPane.setVisibility(View.VISIBLE); } }); } @Override public void onTrackUpdated(Track track) { if (track == null || track.getStatistics() == null) { trackMaxSpeed = 0.0; return; } trackMaxSpeed = track.getStatistics().getMaxSpeed(); } @Override public void clearTrackPoints() { totalDistance = 0.0; startTime = -1L; lastLocation = null; elevationBuffer.reset(); speedBuffer.reset(); pendingPoints.clear(); chartView.reset(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.resetScroll(); } }); } @Override public void onNewTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { double[] data = new double[6]; fillDataPoint(location, data); pendingPoints.add(data); } } @Override public void onSampledOutTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { // Still account for the point in the smoothing buffers. fillDataPoint(location, null); } } @Override public void onSegmentSplit() { // Do nothing. } @Override public void onNewTrackPointsDone() { chartView.addDataPoints(pendingPoints); pendingPoints.clear(); getActivity().runOnUiThread(updateChart); } @Override public void clearWaypoints() { chartView.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { chartView.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { getActivity().runOnUiThread(updateChart); } @Override public boolean onUnitsChanged(boolean metric) { if (metricUnits == metric) { return false; } metricUnits = metric; chartView.setMetricUnits(metricUnits); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.requestLayout(); } }); return true; } @Override public boolean onReportSpeedChanged(boolean speed) { if (reportSpeed == speed) { return false; } reportSpeed = speed; chartView.setReportSpeed(speed, getActivity()); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.requestLayout(); } }); return true; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Returns true if recording. Needs to be synchronized because trackDataHub * can be accessed by multiple threads. */ private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } /** * Reloads the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void reloadTrackDataHub() { if (trackDataHub != null) { trackDataHub.reloadDataForListener(this); } } /** * To zoom in. */ private void zoomIn() { chartView.zoomIn(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } /** * To zoom out. */ private void zoomOut() { chartView.zoomOut(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } /** * Given a location, fill in a data point, an array of double[6]. <br> * data[0] = time/distance <br> * data[1] = elevation <br> * data[2] = speed <br> * data[3] = power <br> * data[4] = cadence <br> * data[5] = heart rate <br> * * @param location the location * @param data the data point to fill in, can be null */ @VisibleForTesting void fillDataPoint(Location location, double data[]) { double timeOrDistance = Double.NaN; double elevation = Double.NaN; double speed = Double.NaN; double power = Double.NaN; double cadence = Double.NaN; double heartRate = Double.NaN; // TODO: Use TripStatisticsBuilder if (chartView.getMode() == Mode.BY_DISTANCE) { if (lastLocation != null) { double distance = lastLocation.distanceTo(location) * UnitConversions.M_TO_KM; if (metricUnits) { totalDistance += distance; } else { totalDistance += distance * UnitConversions.KM_TO_MI; } } timeOrDistance = totalDistance; } else { if (startTime == -1L) { startTime = location.getTime(); } timeOrDistance = location.getTime() - startTime; } elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); elevation = elevationBuffer.getAverage(); if (lastLocation == null) { if (Math.abs(location.getSpeed() - INVALID_SPEED) > 1) { speedBuffer.setNext(location.getSpeed()); } } else if (TripStatisticsBuilder.isValidSpeed(location.getTime(), location.getSpeed(), lastLocation.getTime(), lastLocation.getSpeed(), speedBuffer) && (location.getSpeed() <= trackMaxSpeed)) { speedBuffer.setNext(location.getSpeed()); } speed = speedBuffer.getAverage() * UnitConversions.MS_TO_KMH; if (!metricUnits) { speed *= UnitConversions.KM_TO_MI; } if (!reportSpeed) { speed = speed == 0 ? 0.0 : 60.0 / speed; } if (location instanceof MyTracksLocation && ((MyTracksLocation) location).getSensorDataSet() != null) { SensorDataSet sensorDataSet = ((MyTracksLocation) location).getSensorDataSet(); if (sensorDataSet.hasPower() && sensorDataSet.getPower().getState() == Sensor.SensorState.SENDING && sensorDataSet.getPower().hasValue()) { power = sensorDataSet.getPower().getValue(); } if (sensorDataSet.hasCadence() && sensorDataSet.getCadence().getState() == Sensor.SensorState.SENDING && sensorDataSet.getCadence().hasValue()) { cadence = sensorDataSet.getCadence().getValue(); } if (sensorDataSet.hasHeartRate() && sensorDataSet.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorDataSet.getHeartRate().hasValue()) { heartRate = sensorDataSet.getHeartRate().getValue(); } } if (data != null) { data[0] = timeOrDistance; data[1] = elevation; data[2] = speed; data[3] = power; data[4] = cadence; data[5] = heartRate; } lastLocation = location; } @VisibleForTesting ChartView getChartView() { return chartView; } @VisibleForTesting void setChartView(ChartView view) { chartView = view; } @VisibleForTesting void setTrackMaxSpeed(double value) { trackMaxSpeed = value; } @VisibleForTesting void setMetricUnits(boolean value) { metricUnits = value; } @VisibleForTesting void setReportSpeed(boolean value) { reportSpeed = value; } }
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.fragments; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; import android.widget.TextView; /** * A DialogFragment to show information about My Tracks. * * @author Jimmy Shih */ public class AboutDialogFragment extends DialogFragment { public static final String ABOUT_DIALOG_TAG = "aboutDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = getActivity().getLayoutInflater().inflate(R.layout.about, null); TextView aboutVersion = (TextView) view.findViewById(R.id.about_version); aboutVersion.setText(SystemUtils.getMyTracksVersion(getActivity())); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setNegativeButton(R.string.about_license, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EulaDialogFragment.newInstance(true).show( getActivity().getSupportFragmentManager(), EulaDialogFragment.EULA_DIALOG_TAG); } }) .setPositiveButton(R.string.generic_ok, null) .setTitle(R.string.help_about) .setView(view) .create(); } }
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.fragments; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; /** * A DialogFrament to show the welcome info. * * @author Jimmy Shih */ public class WelcomeDialogFragment extends DialogFragment { public static final String WELCOME_DIALOG_TAG = "welcomeDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = getActivity().getLayoutInflater().inflate(R.layout.welcome, null); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { checkUnits(); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { checkUnits(); } }) .setTitle(R.string.welcome_title) .setView(view) .create(); } private void checkUnits() { new CheckUnitsDialogFragment().show( getActivity().getSupportFragmentManager(), CheckUnitsDialogFragment.CHECK_UNITS_DIALOG_TAG); } }
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.fragments; import com.google.android.apps.mytracks.MapOverlay; import com.google.android.apps.mytracks.MyTracksApplication; import com.google.android.apps.mytracks.TrackDetailActivity; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.GeoRect; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.mytracks.R; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.EnumSet; /** * A fragment to display map to the user. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class MapFragment extends Fragment implements View.OnTouchListener, View.OnClickListener, TrackDataListener { private static final String KEY_CURRENT_LOCATION = "currentLocation"; private static final String KEY_KEEP_MY_LOCATION_VISIBLE = "keepMyLocationVisible"; private TrackDataHub trackDataHub; // True to keep my location visible. private boolean keepMyLocationVisible; // True to zoom to my location. Only apply when keepMyLocationVisible is true. private boolean zoomToMyLocation; // The track id of the marker to show. private long markerTrackId; // The marker id to show private long markerId; // The current selected track id. Set in onSelectedTrackChanged. private long currentSelectedTrackId; // The current location. Set in onCurrentLocationChanged. private Location currentLocation; // UI elements private View mapViewContainer; private MapOverlay mapOverlay; private RelativeLayout screen; private MapView mapView; private LinearLayout messagePane; private TextView messageText; private LinearLayout busyPane; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mapViewContainer = ((TrackDetailActivity) getActivity()).getMapViewContainer(); mapOverlay = new MapOverlay(getActivity()); screen = (RelativeLayout) mapViewContainer.findViewById(R.id.screen); mapView = (MapView) mapViewContainer.findViewById(R.id.map); mapView.requestFocus(); mapView.setOnTouchListener(this); mapView.setBuiltInZoomControls(true); mapView.getOverlays().add(mapOverlay); messagePane = (LinearLayout) mapViewContainer.findViewById(R.id.messagepane); messageText = (TextView) mapViewContainer.findViewById(R.id.messagetext); busyPane = (LinearLayout) mapViewContainer.findViewById(R.id.busypane); return mapViewContainer; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { keepMyLocationVisible = savedInstanceState.getBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, false); currentLocation = (Location) savedInstanceState.getParcelable(KEY_CURRENT_LOCATION); if (currentLocation != null) { updateCurrentLocation(); } } } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, keepMyLocationVisible); if (currentLocation != null) { outState.putParcelable(KEY_CURRENT_LOCATION, currentLocation); } } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); } @Override public void onDestroyView() { super.onDestroyView(); ViewGroup parentViewGroup = (ViewGroup) mapViewContainer.getParent(); if (parentViewGroup != null) { parentViewGroup.removeView(mapViewContainer); } } /** * Shows my location. */ public void showMyLocation() { updateTrackDataHub(); keepMyLocationVisible = true; zoomToMyLocation = true; if (currentLocation != null) { updateCurrentLocation(); } } /** * Shows the marker. * * @param id the marker id */ private void showMarker(long id) { MyTracksProviderUtils MyTracksProviderUtils = Factory.get(getActivity()); Waypoint waypoint = MyTracksProviderUtils.getWaypoint(id); if (waypoint != null && waypoint.getLocation() != null) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint((int) (waypoint.getLocation().getLatitude() * 1E6), (int) (waypoint.getLocation().getLongitude() * 1E6)); mapView.getController().setCenter(center); mapView.getController().setZoom(mapView.getMaxZoomLevel()); mapView.invalidate(); } } /** * Shows the marker. * * @param trackId the track id * @param id the marker id */ public void showMarker(long trackId, long id) { /* * Synchronize to prevent race condition in changing markerTrackId and * markerId variables. */ synchronized (this) { if (trackId == currentSelectedTrackId) { showMarker(id); markerTrackId = -1L; markerId = -1L; return; } markerTrackId = trackId; markerId = id; } } /** * Returns true if in satellite mode. */ public boolean isSatelliteView() { return mapView.isSatellite(); } /** * Sets the satellite mode * * @param enabled true for satellite mode, false for map mode */ public void setSatelliteView(boolean enabled) { mapView.setSatellite(enabled); } @Override public boolean onTouch(View view, MotionEvent event) { if (keepMyLocationVisible && event.getAction() == MotionEvent.ACTION_MOVE) { if (!isVisible(currentLocation)) { /* * Only set to false when no longer visible. Thus can keep showing the * current location with the next location update. */ keepMyLocationVisible = false; } } return false; } @Override public void onClick(View v) { if (v == messagePane) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } } @Override public void onProviderStateChange(ProviderState state) { final int messageId; final boolean isGpsDisabled; switch (state) { case DISABLED: messageId = R.string.gps_need_to_enable; isGpsDisabled = true; break; case NO_FIX: case BAD_FIX: messageId = R.string.gps_wait_for_fix; isGpsDisabled = false; break; case GOOD_FIX: messageId = -1; isGpsDisabled = false; break; default: throw new IllegalArgumentException("Unexpected state: " + state); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (messageId != -1) { messageText.setText(messageId); messagePane.setVisibility(View.VISIBLE); if (isGpsDisabled) { Toast.makeText(getActivity(), R.string.gps_not_found, Toast.LENGTH_LONG).show(); // Click to show the location source settings messagePane.setOnClickListener(MapFragment.this); } else { messagePane.setOnClickListener(null); } } else { messagePane.setVisibility(View.GONE); } screen.requestLayout(); } }); } @Override public void onCurrentLocationChanged(Location location) { currentLocation = location; updateCurrentLocation(); } @Override public void onCurrentHeadingChanged(double heading) { if (mapOverlay.setHeading((float) heading)) { mapView.postInvalidate(); } } @Override public void onSelectedTrackChanged(final Track track, final boolean isRecording) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { boolean hasTrack = track != null; mapOverlay.setTrackDrawingEnabled(hasTrack); if (hasTrack) { busyPane.setVisibility(View.VISIBLE); synchronized (this) { /* * Synchronize to prevent race condition in changing markerTrackId * and markerId variables. */ currentSelectedTrackId = track.getId(); updateMap(track); } mapOverlay.setShowEndMarker(!isRecording); busyPane.setVisibility(View.GONE); } mapView.invalidate(); } }); } @Override public void onTrackUpdated(Track track) { // We don't care. } @Override public void clearTrackPoints() { mapOverlay.clearPoints(); } @Override public void onNewTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { mapOverlay.addLocation(location); } } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onSegmentSplit() { mapOverlay.addSegmentSplit(); } @Override public void onNewTrackPointsDone() { mapView.postInvalidate(); } @Override public void clearWaypoints() { mapOverlay.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { // TODO: Optimize locking inside addWaypoint mapOverlay.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { mapView.postInvalidate(); } @Override public boolean onUnitsChanged(boolean metric) { // We don't care. return false; } @Override public boolean onReportSpeedChanged(boolean reportSpeed) { // We don't care. return false; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.COMPASS_UPDATES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Updates the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void updateTrackDataHub() { if (trackDataHub != null) { trackDataHub.forceUpdateLocation(); } } /** * Updates the map by either zooming to the requested marker or showing the track. * * @param track the track */ private void updateMap(Track track) { if (track.getId() == markerTrackId) { // Show the marker showMarker(markerId); markerTrackId = -1L; markerId = -1L; } else { // Show the track showTrack(track); } } /** * Returns true if the location is visible. * * @param location the location */ private boolean isVisible(Location location) { if (location == null || mapView == null) { return false; } GeoPoint mapCenter = mapView.getMapCenter(); int latitudeSpan = mapView.getLatitudeSpan(); int longitudeSpan = mapView.getLongitudeSpan(); /* * The bottom of the mapView is obscured by the zoom controls, subtract its * height from the visible area. */ GeoPoint zoomControlBottom = mapView.getProjection().fromPixels(0, mapView.getHeight()); GeoPoint zoomControlTop = mapView.getProjection().fromPixels( 0, mapView.getHeight() - mapView.getZoomButtonsController().getZoomControls().getHeight()); int zoomControlMargin = Math.abs(zoomControlTop.getLatitudeE6() - zoomControlBottom.getLatitudeE6()); GeoRect geoRect = new GeoRect(mapCenter, latitudeSpan, longitudeSpan); geoRect.top += zoomControlMargin; GeoPoint geoPoint = LocationUtils.getGeoPoint(location); return geoRect.contains(geoPoint); } /** * Updates the current location and centers it if necessary. */ private void updateCurrentLocation() { if (mapOverlay == null || mapView == null) { return; } mapOverlay.setMyLocation(currentLocation); mapView.postInvalidate(); if (currentLocation != null && keepMyLocationVisible && !isVisible(currentLocation)) { GeoPoint geoPoint = LocationUtils.getGeoPoint(currentLocation); MapController mapController = mapView.getController(); mapController.animateTo(geoPoint); if (zoomToMyLocation) { // Only zoom in the first time we show the location. zoomToMyLocation = false; if (mapView.getZoomLevel() < mapView.getMaxZoomLevel()) { mapController.setZoom(mapView.getMaxZoomLevel()); } } } } /** * Shows the track. * * @param track the track */ private void showTrack(Track track) { if (mapView == null || track == null || track.getNumberOfPoints() < 2) { return; } TripStatistics tripStatistics = track.getStatistics(); int bottom = tripStatistics.getBottom(); int left = tripStatistics.getLeft(); int latitudeSpanE6 = tripStatistics.getTop() - bottom; int longitudeSpanE6 = tripStatistics.getRight() - left; if (latitudeSpanE6 > 0 && latitudeSpanE6 < 180E6 && longitudeSpanE6 > 0 && longitudeSpanE6 < 360E6) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint(bottom + latitudeSpanE6 / 2, left + longitudeSpanE6 / 2); if (LocationUtils.isValidGeoPoint(center)) { mapView.getController().setCenter(center); mapView.getController().zoomToSpan(latitudeSpanE6, longitudeSpanE6); } } } }
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.fragments; import com.google.android.apps.mytracks.TrackListActivity; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete one track. * * @author Jimmy Shih */ public class DeleteOneTrackDialogFragment extends DialogFragment { public static final String DELETE_ONE_TRACK_DIALOG_TAG = "deleteOneTrackDialog"; private static final String KEY_TRACK_ID = "trackId"; public static DeleteOneTrackDialogFragment newInstance(long trackId) { Bundle bundle = new Bundle(); bundle.putLong(KEY_TRACK_ID, trackId); DeleteOneTrackDialogFragment deleteOneTrackDialogFragment = new DeleteOneTrackDialogFragment(); deleteOneTrackDialogFragment.setArguments(bundle); return deleteOneTrackDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.track_detail_delete_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()) .deleteTrack(getArguments().getLong(KEY_TRACK_ID)); startActivity(new Intent(getActivity(), TrackListActivity.class).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); } }); } }
Java
package com.xyz.tag.html; import java.io.Serializable; public interface XYIHTMLTag extends Serializable { public String draw(); }
Java
package com.xyz.tag.html; public class XYHtmlConstants { /* 元素名 */ public static final String element_div = "div"; public static final String element_span = "span"; public static final String element_label = "label"; public static final String element_a = "a"; public static final String element_table = "table"; public static final String element_tr = "tr"; public static final String element_td = "td"; /* 属性名 */ public static final String attribute_id = "id"; public static final String attribute_name = "name"; public static final String attribute_classs = "class"; public static final String attribute_style = "style"; public static final String attribute_href = "href"; public static final String attribute_target = "target"; /* 符号 */ public static final String sign_lt = "<"; public static final String sign_gt = ">"; public static final String sign_slash = "/"; public static final String sign_backslash = "\\"; public static final String sign_eq = "="; public static final String sign_quot = "\""; public static final String sign_acute = "'"; public static final String sign_colon = ":"; public static final String sign_semicolon = ";"; }
Java
package com.xyz.tag.html.element; import com.xyz.tag.html.XYHtmlConstants; public class XYElementA extends XYElement { public XYElementA() { super( XYHtmlConstants.element_a ); } public void setName( String name ) { addAttribute( XYHtmlConstants.attribute_name, name ); } public void setHref( String href ) { addAttribute( XYHtmlConstants.attribute_href, href ); } public void setTarget( String target ) { addAttribute( XYHtmlConstants.attribute_target, target ); } private static final long serialVersionUID = 5844668518614160729L; }
Java
package com.xyz.tag.html.element; import com.xyz.tag.html.XYIHTMLTag; public class XYText implements XYIHTMLTag { private static final long serialVersionUID = 8397445138431377308L; private String text; public XYText( String text ) { if ( text == null ) this.text = ""; else this.text = text; } @Override public String draw() { return text; } public String getText() { return text; } }
Java
package com.xyz.tag.html.element; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.html.XYIAttribute; import com.xyz.tag.html.XYIElement; import com.xyz.tag.html.XYIHTMLTag; import com.xyz.tag.html.attribute.XYAttribute; import com.xyz.tag.util.StringUtil; public class XYElement implements XYIElement { private static final long serialVersionUID = 2014161164499768349L; private String elementName = null; private List<XYIHTMLTag> elements = null; private Set<XYIAttribute> attributes = null; public XYElement( String elementName ) { this( elementName, null, null ); } public XYElement( String elementName, Set<XYIAttribute> attributes ) { this( elementName, attributes, null ); } public XYElement( String elementName, List<XYIHTMLTag> elements ) { this( elementName, null, elements ); } public XYElement( String elementName, Set<XYIAttribute> attributes, List<XYIHTMLTag> elements ) { this.elementName = elementName; this.attributes = attributes; this.elements = elements; } @Override public XYIElement addElement( XYIHTMLTag element ) { if ( element != null ) { if ( elements == null ) { elements = new ArrayList<XYIHTMLTag>(); } elements.add( element ); } return this; } @Override public XYIElement addElements( XYIHTMLTag... elements ) { if ( elements != null && elements.length > 0 ) { return addElements( Arrays.asList( elements ) ); } return this; } @Override public XYIElement addElements( List<XYIHTMLTag> elements ) { if ( elements != null && !elements.isEmpty() ) { if ( this.elements == null ) { this.elements = new ArrayList<XYIHTMLTag>(); } this.elements.addAll( elements ); } return this; } @Override public XYIElement addAttribute( String name, String value ) { return addAttribute( new XYAttribute( name, value ) ); } @Override public XYIElement addAttribute( XYIAttribute attribute ) { if ( attribute != null ) { if ( attributes == null ) { attributes = new HashSet<XYIAttribute>(); } attributes.add( attribute ); } return this; } @Override public XYIElement addAttributes( XYIAttribute... attributes ) { if ( attributes != null && attributes.length > 0 ) { return addAttributes( new HashSet<XYIAttribute>( Arrays.asList( attributes ) ) ); } return this; } @Override public XYIElement addAttributes( Set<XYIAttribute> attributes ) { if ( attributes != null && !attributes.isEmpty() ) { if ( this.attributes == null ) { this.attributes = new HashSet<XYIAttribute>(); } this.attributes.addAll( attributes ); } return this; } @Override public XYIElement setElements( XYIHTMLTag... elements ) { if ( elements != null && elements.length > 0 ) { return setElements( Arrays.asList( elements ) ); } return this; } @Override public XYIElement setElements( List<XYIHTMLTag> elements ) { this.elements = elements; return this; } @Override public XYIElement setAttributes( Set<XYIAttribute> attributes ) { this.attributes = attributes; return this; } @Override public void setId( String id ) { addAttribute( XYHtmlConstants.attribute_id, id ); } @Override public void setClasss( String classs ) { addAttribute( XYHtmlConstants.attribute_classs, classs ); } @Override public void addClasss( String classs ) { appendToAttributeValue( XYHtmlConstants.attribute_classs, classs ); } @Override public String draw() { StringBuffer html = new StringBuffer(); html.append( XYHtmlConstants.sign_lt ); html.append( this.elementName ); if ( attributes != null && !attributes.isEmpty() ) { Iterator<XYIAttribute> iterator = attributes.iterator(); while ( iterator.hasNext() ) { html.append( " " ); html.append( iterator.next().draw() ); } } if ( elements != null && !elements.isEmpty() ) { html.append( XYHtmlConstants.sign_gt ); for ( XYIHTMLTag element : elements ) { html.append( element.draw() ); } html.append( XYHtmlConstants.sign_lt ).append( XYHtmlConstants.sign_slash ).append( this.elementName ) .append( XYHtmlConstants.sign_gt ); } else { html.append( XYHtmlConstants.sign_slash + XYHtmlConstants.sign_gt ); } return html.toString(); } protected void appendToAttributeValue( String name, String value ) { if ( !StringUtil.isEmpty( name ) && !StringUtil.isEmpty( value ) ) { if ( attributes != null && !attributes.isEmpty() ) { boolean found = false; for ( XYIAttribute attribute : attributes ) { if ( attribute.getName() != null && attribute.getName().equalsIgnoreCase( name ) ) { attribute.setValue( attribute.getValue() + " " + value ); found = true; break; } } if ( !found ) { addAttribute( name, value ); } } else { addAttribute( name, value ); } } } @Override public void setStyle( String style ) { } @Override public void addStyle( String style ) { } }
Java
package com.xyz.tag.html; import java.util.List; import java.util.Set; public interface XYIElement extends XYIHTMLTag { public void setId( String id ); public void setClasss( String classs ); public void addClasss( String classs ); public void setStyle( String style ); public void addStyle( String style ); public XYIElement addElement( XYIHTMLTag element ); public XYIElement addElements( XYIHTMLTag... elements ); public XYIElement addElements( List<XYIHTMLTag> elements ); public XYIElement addAttribute( String name, String value ); public XYIElement addAttribute( XYIAttribute attribute ); public XYIElement addAttributes( XYIAttribute... attributes ); public XYIElement addAttributes( Set<XYIAttribute> attributes ); public XYIElement setElements( XYIHTMLTag... elements ); public XYIElement setElements( List<XYIHTMLTag> elements ); public XYIElement setAttributes( Set<XYIAttribute> attributes ); }
Java
package com.xyz.tag.html; public interface XYIAttribute extends XYIHTMLTag { public String getName(); public void setName( String name ); public String getValue(); public void setValue( String value ); }
Java
package com.xyz.tag.html.attribute; import java.util.HashSet; import java.util.Set; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.util.StringUtil; public class XYAttributeStyle extends XYAttribute { private Set<XYAttributeStyleValue> styles = null; public XYAttributeStyle() { super( XYHtmlConstants.attribute_style ); } public XYAttributeStyle addStyle( String name, String value ) { if ( !StringUtil.isEmpty( name ) && !StringUtil.isEmpty( value ) ) { addStyle( new XYAttributeStyleValue( name, value ) ); } return this; } public XYAttributeStyle addStyle( XYAttributeStyleValue styleValue ) { if ( styles == null ) { styles = new HashSet<XYAttributeStyleValue>(); } styles.add( styleValue ); return this; } @Override public String draw() { StringBuffer html = new StringBuffer(); if ( styles != null && !styles.isEmpty() ) { html.append( XYHtmlConstants.attribute_style ).append( XYHtmlConstants.sign_eq ) .append( XYHtmlConstants.sign_quot ); for ( XYAttributeStyleValue styleValue : styles ) { html.append( styleValue.getName() ).append( XYHtmlConstants.sign_colon ).append( styleValue.getValue() ) .append( XYHtmlConstants.sign_semicolon ); } html.append( XYHtmlConstants.sign_quot ); } return html.toString(); } private class XYAttributeStyleValue { private String name; private String value; public XYAttributeStyleValue( String name, String value ) { this.name = name; this.value = value; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals( Object o ) { return name.equalsIgnoreCase( ( (XYAttributeStyleValue)o ).getName() ); } public String getName() { return name; } public String getValue() { return value; } } private static final long serialVersionUID = 9006660492122768338L; }
Java
package com.xyz.tag.html.attribute; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.html.XYIAttribute; import com.xyz.tag.util.StringUtil; public class XYAttribute implements XYIAttribute { private static final long serialVersionUID = 5475759902995632006L; private String name; private String value; public XYAttribute( String name ) { this( name, null ); } public XYAttribute( String name, String value ) { this.name = name; this.value = value; } @Override public String draw() { StringBuffer sb = new StringBuffer(); if ( !StringUtil.isEmpty( name ) ) { sb.append( name ); if ( !StringUtil.isEmpty( value ) ) { sb.append( XYHtmlConstants.sign_eq ).append( XYHtmlConstants.sign_quot ).append( getValue() ) .append( XYHtmlConstants.sign_quot ); } } return sb.toString(); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals( Object o ) { return name.equals( ( (XYAttribute)o ).getName() ); } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getValue() { return value; } public void setValue( String value ) { this.value = value; } }
Java
package com.xyz.tag.util; public class StringUtil { public static boolean isEmpty( String str ) { if ( str != null && str.trim().length() > 0 ) { return false; } return true; } }
Java
package com.xyz.tag.util; import com.xyz.tag.html.XYHtmlConstants; public class HtmlUtil { public static String drawNameAndValue( String name, String value ) { StringBuffer html = new StringBuffer(); if ( !StringUtil.isEmpty( name ) ) { html.append( name ); if ( !StringUtil.isEmpty( value ) ) { html.append( XYHtmlConstants.sign_eq ).append( XYHtmlConstants.sign_quot ).append( value ) .append( XYHtmlConstants.sign_quot ); } } return html.toString(); } }
Java
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResponse extends CoapMessage{ /* TODO: Response Code is part of BasicCoapResponse */ public CoapResponseCode getResponseCode(); public void setMaxAge(int maxAge); public long getMaxAge(); public void setETag(byte[] etag); public byte[] getETag(); public void setResponseCode(CoapResponseCode responseCode); }
Java
package org.ws4d.coap.interfaces; import java.util.Vector; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapRequest extends CoapMessage{ public void setUriHost(String host); public void setUriPort(int port); public void setUriPath(String path); public void setUriQuery(String query); public void setProxyUri(String proxyUri); public void setToken(byte[] token); public void addAccept(CoapMediaType mediaType); public Vector<CoapMediaType> getAccept(CoapMediaType mediaType); public String getUriHost(); public int getUriPort(); public String getUriPath(); public Vector<String> getUriQuery(); public String getProxyUri(); public void addETag(byte[] etag); public Vector<byte[]> getETag(); public CoapRequestCode getRequestCode(); public void setRequestCode(CoapRequestCode requestCode); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; public interface CoapChannel { public void sendMessage(CoapMessage msg); /*TODO: close when finished, & abort()*/ public void close(); public InetAddress getRemoteAddress(); public int getRemotePort(); /* handles an incomming message */ public void handleMessage(CoapMessage message); /*TODO: implement Error Type*/ public void lostConnection(boolean notReachable, boolean resetByServer); public CoapBlockSize getMaxReceiveBlocksize(); public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize); public CoapBlockSize getMaxSendBlocksize(); public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize); }
Java
package org.ws4d.coap.interfaces; import java.net.InetAddress; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapSocketHandler { // public void registerResponseListener(CoapResponseListener // responseListener); // public void unregisterResponseListener(CoapResponseListener // responseListener); // public int sendRequest(CoapMessage request); // public void sendResponse(CoapResponse response); // public void establish(DatagramSocket socket); // public void testConfirmation(int msgID); // // public boolean isOpen(); /* TODO */ public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort); public void close(); public void sendMessage(CoapMessage msg); public CoapChannelManager getChannelManager(); int getLocalPort(); void removeClientChannel(CoapClientChannel channel); void removeServerChannel(CoapServerChannel channel); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClient extends CoapChannelListener { public void onResponse(CoapClientChannel channel, CoapResponse response); public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public interface CoapServerChannel extends CoapChannel { /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode); /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType); /* creates a separate response and acks the current request witch an empty ACK in case of a CON. * The separate response can be send later using sendSeparateResponse() */ public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode); /* used by a server to send a separate response */ public void sendSeparateResponse(CoapResponse response); /* used by a server to create a notification (observing resources), reliability is base on the request packet type (con or non) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber); /* used by a server to create a notification (observing resources) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable); /* used by a server to send a notification (observing resources) */ public void sendNotification(CoapResponse response); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapServer extends CoapChannelListener { public CoapServer onAccept(CoapRequest request); public void onRequest(CoapServerChannel channel, CoapRequest request); public void onSeparateResponseFailed(CoapServerChannel channel); }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.BasicCoapRequest; public interface CoapChannelManager { public int getNewMessageID(); /* called by the socket Listener to create a new Server Channel * the Channel Manager then asked the Server Listener if he wants to accept a new connection */ public CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port); /* creates a server socket listener for incoming connections */ public void createServerListener(CoapServer serverListener, int localPort); /* called by a client to create a connection * TODO: allow client to bind to a special port */ public CoapClientChannel connect(CoapClient client, InetAddress addr, int port); /* This function is for testing purposes only, to have a determined message id*/ public void setMessageId(int globalMessageId); public void initRandom(); }
Java
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapChannelListener { }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.interfaces; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapMessage { public static final int RESPONSE_TIMEOUT_MS = 2000; public static final double RESPONSE_RANDOM_FACTOR = 1.5; public static final int MAX_RETRANSMIT = 4; /* TODO: what is the right value? */ public static final int ACK_RST_RETRANS_TIMEOUT_MS = 120000; /* returns the value of the internal message code * in case of an error this function returns -1 */ public int getMessageCodeValue(); public int getMessageID(); public void setMessageID(int msgID); public byte[] serialize(); public void incRetransCounterAndTimeout(); public CoapPacketType getPacketType(); public byte[] getPayload(); public void setPayload(byte[] payload); public void setPayload(char[] payload); public void setPayload(String payload); public int getPayloadLength(); public void setContentType(CoapMediaType mediaType); public CoapMediaType getContentType(); public byte[] getToken(); // public URI getRequestUri(); // // public void setRequestUri(URI uri); //TODO:allow this method only for Clients, Define Token Type CoapBlockOption getBlock1(); void setBlock1(CoapBlockOption blockOption); CoapBlockOption getBlock2(); void setBlock2(CoapBlockOption blockOption); public Integer getObserveOption(); public void setObserveOption(int sequenceNumber); public void removeOption(CoapHeaderOptionType optionType); //TODO: could this compromise the internal state? public String toString(); public CoapChannel getChannel(); public void setChannel(CoapChannel channel); public int getTimeout(); public boolean maxRetransReached(); public boolean isReliable(); public boolean isRequest(); public boolean isResponse(); public boolean isEmpty(); /* unique by remote address, remote port, local port and message id */ public int hashCode(); public boolean equals(Object obj); }
Java
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClientChannel extends CoapChannel { public CoapRequest createRequest(boolean reliable, CoapRequestCode requestCode); public void setTrigger(Object o); public Object getTrigger(); }
Java
package org.ws4d.coap.tools; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class TimeoutHashMap<K, V> extends HashMap<Object, Object>{ private static final long serialVersionUID = 4987370276778256858L; /* chronological list to remove expired elements when update() is called */ LinkedList<TimoutType<K>> timeoutQueue = new LinkedList<TimoutType<K>>(); /* Default Timeout is one minute */ long timeout = 60000; public TimeoutHashMap(long timeout){ this.timeout = timeout; } @Override public Object put(Object key, Object value) { long expires = System.currentTimeMillis() + timeout; TimoutType<V> timeoutValue = new TimoutType<V>((V) value, expires); TimoutType<K> timeoutKey = new TimoutType<K>((K) key, expires); timeoutQueue.add(timeoutKey); timeoutValue = (TimoutType<V>) super.put((K) key, timeoutValue); if (timeoutValue != null){ return timeoutValue.object; } return null; } @Override public Object get(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.get(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public Object remove(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public void clear() { super.clear(); timeoutQueue.clear(); } /* remove expired elements */ public void update(){ while(true) { TimoutType<K> timeoutKey = timeoutQueue.peek(); if (timeoutKey == null){ /* if the timeoutKey queue is empty, there must be no more elements in the hashmap * otherwise there is a bug in the implementation */ if (!super.isEmpty()){ throw new IllegalStateException("Error in TimeoutHashMap. Timeout queue is empty but hashmap not!"); } return; } long now = System.currentTimeMillis(); if (now > timeoutKey.expires){ timeoutQueue.poll(); TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(timeoutKey.object); if (timeoutValueIsValid(timeoutValue)){ /* This is a very special case which happens if an entry is overridden: * - put V with K * - put V2 with K * - K is expired but V2 not * because this is expected to be happened very seldom, we "reput" V2 to the hashmap * wich is better than every time to making a get and than a remove */ super.put(timeoutKey.object, timeoutValue); } } else { /* Key is not expired -> break the loop */ break; } } } @Override public Object clone() { // TODO implement function throw new IllegalStateException(); // return super.clone(); } @Override public boolean containsKey(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsKey(arg0); } @Override public boolean containsValue(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsValue(arg0); } @Override public Set<Entry<Object, Object>> entrySet() { // TODO implement function throw new IllegalStateException(); // return super.entrySet(); } @Override public boolean isEmpty() { // TODO implement function throw new IllegalStateException(); // return super.isEmpty(); } @Override public Set<Object> keySet() { // TODO implement function throw new IllegalStateException(); // return super.keySet(); } @Override public void putAll(Map<? extends Object, ? extends Object> arg0) { // TODO implement function throw new IllegalStateException(); // super.putAll(arg0); } @Override public int size() { // TODO implement function throw new IllegalStateException(); // return super.size(); } @Override public Collection<Object> values() { // TODO implement function throw new IllegalStateException(); // return super.values(); } /* private classes and methods */ private boolean timeoutValueIsValid(TimoutType<V> timeoutValue){ return timeoutValue != null && System.currentTimeMillis() < timeoutValue.expires; } private class TimoutType<T>{ public T object; public long expires; public TimoutType(T object, long expires) { super(); this.object = object; this.expires = expires; } } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServerChannel extends BasicCoapChannel implements CoapServerChannel{ CoapServer server = null; public BasicCoapServerChannel(CoapSocketHandler socketHandler, CoapServer server, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.server = server; } @Override public void close() { socketHandler.removeServerChannel(this); } @Override public void handleMessage(CoapMessage message) { /* message MUST be a request */ if (message.isEmpty()){ return; } if (!message.isRequest()){ return; //throw new IllegalStateException("Incomming server message is not a request"); } BasicCoapRequest request = (BasicCoapRequest) message; CoapChannel channel = request.getChannel(); /* TODO make this cast safe */ server.onRequest((CoapServerChannel) channel, request); } /*TODO: implement */ public void lostConnection(boolean notReachable, boolean resetByServer){ server.onSeparateResponseFailed(this); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode) { return createResponse(request, responseCode, null); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType){ BasicCoapResponse response; if (request.getPacketType() == CoapPacketType.CON) { response = new BasicCoapResponse(CoapPacketType.ACK, responseCode, request.getMessageID(), request.getToken()); } else if (request.getPacketType() == CoapPacketType.NON) { response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } if (contentType != null && contentType != CoapMediaType.UNKNOWN){ response.setContentType(contentType); } response.setChannel(this); return response; } @Override public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode) { BasicCoapResponse response = null; if (request.getPacketType() == CoapPacketType.CON) { /* The separate Response is CON (normally a Response is ACK or NON) */ response = new BasicCoapResponse(CoapPacketType.CON, responseCode, channelManager.getNewMessageID(), request.getToken()); /*send ack immediately */ sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, request.getMessageID())); } else if (request.getPacketType() == CoapPacketType.NON){ /* Just a normal response*/ response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } response.setChannel(this); return response; } @Override public void sendSeparateResponse(CoapResponse response) { sendMessage(response); } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber){ /*use the packet type of the request: if con than con otherwise non*/ if (request.getPacketType() == CoapPacketType.CON){ return createNotification(request, responseCode, sequenceNumber, true); } else { return createNotification(request, responseCode, sequenceNumber, false); } } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable){ BasicCoapResponse response = null; CoapPacketType packetType; if (reliable){ packetType = CoapPacketType.CON; } else { packetType = CoapPacketType.NON; } response = new BasicCoapResponse(packetType, responseCode, channelManager.getNewMessageID(), request.getToken()); response.setChannel(this); response.setObserveOption(sequenceNumber); return response; } @Override public void sendNotification(CoapResponse response) { sendMessage(response); } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.HashMap; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.AbstractCoapMessage; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.tools.TimeoutHashMap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Nico Laum <nico.laum@uni-rostock.de> */ public class BasicCoapSocketHandler implements CoapSocketHandler { /* the socket handler has its own logger * TODO: implement different socket handler for client and server channels */ private final static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class); protected WorkerThread workerThread = null; protected HashMap<ChannelKey, CoapClientChannel> clientChannels = new HashMap<ChannelKey, CoapClientChannel>(); protected HashMap<ChannelKey, CoapServerChannel> serverChannels = new HashMap<ChannelKey, CoapServerChannel>(); private CoapChannelManager channelManager = null; private DatagramChannel dgramChannel = null; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 byte[] sendBuffer = new byte[UDP_BUFFER_SIZE]; private int localPort; public BasicCoapSocketHandler(CoapChannelManager channelManager, int port) throws IOException { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); this.channelManager = channelManager; dgramChannel = DatagramChannel.open(); dgramChannel.socket().bind(new InetSocketAddress(port)); //port can be 0, then a free port is chosen this.localPort = dgramChannel.socket().getLocalPort(); dgramChannel.configureBlocking(false); workerThread = new WorkerThread(); workerThread.start(); } public BasicCoapSocketHandler(CoapChannelManager channelManager) throws IOException { this(channelManager, 0); } protected class WorkerThread extends Thread { Selector selector = null; /* contains all received message keys of a remote (message id generated by the remote) to detect duplications */ TimeoutHashMap<MessageKey, Boolean> duplicateRemoteMap = new TimeoutHashMap<MessageKey, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all received message keys of the host (message id generated by the host) to detect duplications */ TimeoutHashMap<Integer, Boolean> duplicateHostMap = new TimeoutHashMap<Integer, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that (possibly) needs to be retransmitted (ACK, RST)*/ TimeoutHashMap<MessageKey, CoapMessage> retransMsgMap = new TimeoutHashMap<MessageKey, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that are not confirmed yet (CON), * MessageID is always generated by Host and therefore unique */ TimeoutHashMap<Integer, CoapMessage> timeoutConMsgMap = new TimeoutHashMap<Integer, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* this queue handles the timeout objects in the right order*/ private PriorityQueue<TimeoutObject<Integer>> timeoutQueue = new PriorityQueue<TimeoutObject<Integer>>(); public ConcurrentLinkedQueue<CoapMessage> sendBuffer = new ConcurrentLinkedQueue<CoapMessage>(); /* Contains all sent messages sorted by message ID */ long startTime; static final int POLLING_INTERVALL = 10000; ByteBuffer dgramBuffer; public WorkerThread() { dgramBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); startTime = System.currentTimeMillis(); try { selector = Selector.open(); dgramChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } public void close() { if (clientChannels != null) clientChannels.clear(); if (serverChannels != null) serverChannels.clear(); try { dgramChannel.close(); } catch (IOException e) { e.printStackTrace(); } /* TODO: wake up thread and kill it*/ } @Override public void run() { logger.log(Level.INFO, "Receive Thread started."); long waitFor = POLLING_INTERVALL; InetSocketAddress addr = null; while (dgramChannel != null) { /* send all messages in the send buffer */ sendBufferedMessages(); /* handle incoming packets */ dgramBuffer.clear(); try { addr = (InetSocketAddress) dgramChannel.receive(dgramBuffer); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (addr != null){ logger.log(Level.INFO, "handle incomming msg"); handleIncommingMessage(dgramBuffer, addr); } /* handle timeouts */ waitFor = handleTimeouts(); /* TODO: find a good strategy when to update the timeout maps */ duplicateRemoteMap.update(); duplicateHostMap.update(); retransMsgMap.update(); timeoutConMsgMap.update(); /* wait until * 1. selector.wakeup() is called by sendMessage() * 2. incomming packet * 3. timeout */ try { /*FIXME: don't make a select, when something is in the sendQueue, otherwise the packet will be sent after some delay * move this check and the select to a critical section */ selector.select(waitFor); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected synchronized void addMessageToSendBuffer(CoapMessage msg){ sendBuffer.add(msg); /* send immediately */ selector.wakeup(); } private void sendBufferedMessages(){ CoapMessage msg = sendBuffer.poll(); while(msg != null){ sendUdpMsg(msg); msg = sendBuffer.poll(); } } private void handleIncommingMessage(ByteBuffer buffer, InetSocketAddress addr) { CoapMessage msg; try { msg = AbstractCoapMessage.parseMessage(buffer.array(), buffer.position()); } catch (Exception e) { logger.warn("Received invalid message: message dropped!"); e.printStackTrace(); return; } CoapPacketType packetType = msg.getPacketType(); int msgId = msg.getMessageID(); MessageKey msgKey = new MessageKey(msgId, addr.getAddress(), addr.getPort()); if (msg.isRequest()){ /* --- INCOMING REQUEST: This is an incoming client request with a message key generated by the remote client*/ if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: Request can not be in a ACK or a RST packet"); return; } /* check for duplicates and retransmit the response if a duplication is detected */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* find or create server channel and handle incoming message */ CoapServerChannel channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ /*no server channel found -> create*/ channel = channelManager.createServerChannel(BasicCoapSocketHandler.this, msg, addr.getAddress(), addr.getPort()); if (channel != null){ /* add the new channel to the channel map */ addServerChannel(channel); logger.info("Created new server channel."); } else { /* create failed -> server doesn't accept the connection --> send RST*/ CoapChannel fakeChannel = new BasicCoapServerChannel(BasicCoapSocketHandler.this, null, addr.getAddress(), addr.getPort()); CoapEmptyMessage rstMsg = new CoapEmptyMessage(CoapPacketType.RST, msgId); rstMsg.setChannel(fakeChannel); sendMessage(rstMsg); return; } } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isResponse()){ /* --- INCOMING RESPONSE: This is an incoming server response (message ID generated by host) * or a separate server response (message ID generated by remote)*/ if (packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: RST packet must be empty"); return; } /* check for separate response */ if (packetType == CoapPacketType.CON){ /* This is a separate response, the message ID is generated by the remote */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* This is a separate Response */ CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming separat response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } /* normal response (ACK or NON), message id was generated by host */ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm the request*/ /* confirm message by removing it from the non confirmedMsgMap*/ /* Corresponding to the spec the server should be aware of a NON as answer to a CON*/ timeoutConMsgMap.remove(msgId); CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isEmpty()){ if (packetType == CoapPacketType.CON || packetType == CoapPacketType.NON){ /* TODO: is this always true? */ logger.warn("Invalid Packet Type: CON or NON packets cannot be empty"); return; } /* ACK or RST, Message Id was generated by the host*/ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm */ timeoutConMsgMap.remove(msgId); /* get channel */ /* This can be an ACK/RST for a client or a server channel */ CoapChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); } if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); if (packetType == CoapPacketType.ACK ){ /* separate response ACK */ channel.handleMessage(msg); return; } if (packetType == CoapPacketType.RST ){ /* connection closed by remote */ channel.handleMessage(msg); return; } } else { logger.error("Invalid Message Type: not a request, not a response, not empty"); } } private long handleTimeouts(){ long nextTimeout = POLLING_INTERVALL; while (true){ TimeoutObject<Integer> tObj = timeoutQueue.peek(); if (tObj == null){ /* timeout queue is empty */ nextTimeout = POLLING_INTERVALL; break; } nextTimeout = tObj.expires - System.currentTimeMillis(); if (nextTimeout > 0){ /* timeout not expired */ break; } /* timeout expired, sendMessage will send the message and create a new timeout * if the message was already confirmed, nonConfirmedMsgMap.get() will return null */ timeoutQueue.poll(); Integer msgId = tObj.object; /* retransmit message after expired timeout*/ sendUdpMsg((CoapMessage) timeoutConMsgMap.get(msgId)); } return nextTimeout; } private boolean isRemoteDuplicate(MessageKey msgKey){ if (duplicateRemoteMap.get(msgKey) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void retransmitRemoteDuplicate(MessageKey msgKey){ CoapMessage retransMsg = (CoapMessage) retransMsgMap.get(msgKey); if (retransMsg == null){ logger.warn("Detected duplicate message but no response could be found"); } else { sendUdpMsg(retransMsg); } } private boolean isHostDuplicate(int msgId){ if (duplicateHostMap.get(msgId) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void sendUdpMsg(CoapMessage msg) { if (msg == null){ return; } CoapPacketType packetType = msg.getPacketType(); InetAddress inetAddr = msg.getChannel().getRemoteAddress(); int port = msg.getChannel().getRemotePort(); int msgId = msg.getMessageID(); if (packetType == CoapPacketType.CON){ /* in case of a CON this is a Request * requests must be added to the timeout queue * except this was the last retransmission */ if(msg.maxRetransReached()){ /* the connection is broken */ timeoutConMsgMap.remove(msgId); msg.getChannel().lostConnection(true, false); return; } msg.incRetransCounterAndTimeout(); timeoutConMsgMap.put(msgId, msg); TimeoutObject<Integer> tObj = new TimeoutObject<Integer>(msgId, msg.getTimeout() + System.currentTimeMillis()); timeoutQueue.add(tObj); } if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ /* save this type of messages for a possible retransmission */ retransMsgMap.put(new MessageKey(msgId, inetAddr, port), msg); } /* Nothing to do for NON*/ /* send message*/ ByteBuffer buf = ByteBuffer.wrap(msg.serialize()); /*TODO: check if serialization could fail... then do not put it to any Map!*/ try { dgramChannel.send(buf, new InetSocketAddress(inetAddr, port)); logger.log(Level.INFO, "Send Msg with ID: " + msg.getMessageID()); } catch (IOException e) { e.printStackTrace(); logger.error("Send UDP message failed"); } } } private class MessageKey{ public int msgID; public InetAddress inetAddr; public int port; public MessageKey(int msgID, InetAddress inetAddr, int port) { super(); this.msgID = msgID; this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + msgID; result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageKey other = (MessageKey) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (msgID != other.msgID) return false; if (port != other.port) return false; return true; } private BasicCoapSocketHandler getOuterType() { return BasicCoapSocketHandler.this; } } private class TimeoutObject<T> implements Comparable<TimeoutObject>{ private long expires; private T object; public TimeoutObject(T object, long expires) { this.expires = expires; this.object = object; } public T getObject() { return object; } public int compareTo(TimeoutObject o){ return (int) (this.expires - o.expires); } } private void addClientChannel(CoapClientChannel channel) { clientChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } private void addServerChannel(CoapServerChannel channel) { serverChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } @Override public int getLocalPort() { return localPort; } @Override public void removeClientChannel(CoapClientChannel channel) { clientChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void removeServerChannel(CoapServerChannel channel) { serverChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void close() { workerThread.close(); } @Override public void sendMessage(CoapMessage message) { if (workerThread != null) { workerThread.addMessageToSendBuffer(message); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort) { if (client == null){ return null; } if (clientChannels.containsKey(new ChannelKey(remoteAddress, remotePort))){ /* channel already exists */ logger.warn("Cannot connect: Client channel already exists"); return null; } CoapClientChannel channel = new BasicCoapClientChannel(this, client, remoteAddress, remotePort); addClientChannel(channel); return channel; } @Override public CoapChannelManager getChannelManager() { return this.channelManager; } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.util.HashMap; import java.util.Random; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapChannelManager implements CoapChannelManager { // global message id private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); private int globalMessageId; private static BasicCoapChannelManager instance; private HashMap<Integer, SocketInformation> socketMap = new HashMap<Integer, SocketInformation>(); CoapServer serverListener = null; private BasicCoapChannelManager() { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); initRandom(); } public synchronized static CoapChannelManager getInstance() { if (instance == null) { instance = new BasicCoapChannelManager(); } return instance; } /** * Creates a new server channel */ @Override public synchronized CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port){ SocketInformation socketInfo = socketMap.get(socketHandler.getLocalPort()); if (socketInfo.serverListener == null) { /* this is not a server socket */ throw new IllegalStateException("Invalid server socket"); } if (!message.isRequest()){ throw new IllegalStateException("Incomming message is not a request message"); } CoapServer server = socketInfo.serverListener.onAccept((BasicCoapRequest) message); if (server == null){ /* Server rejected channel */ return null; } CoapServerChannel newChannel= new BasicCoapServerChannel( socketHandler, server, addr, port); return newChannel; } /** * Creates a new, global message id for a new COAP message */ @Override public synchronized int getNewMessageID() { if (globalMessageId < Constants.MESSAGE_ID_MAX) { ++globalMessageId; } else globalMessageId = Constants.MESSAGE_ID_MIN; return globalMessageId; } @Override public synchronized void initRandom() { // generate random 16 bit messageId Random random = new Random(); globalMessageId = random.nextInt(Constants.MESSAGE_ID_MAX + 1); } @Override public void createServerListener(CoapServer serverListener, int localPort) { if (!socketMap.containsKey(localPort)) { try { SocketInformation socketInfo = new SocketInformation(new BasicCoapSocketHandler(this, localPort), serverListener); socketMap.put(localPort, socketInfo); } catch (IOException e) { e.printStackTrace(); } } else { /*TODO: raise exception: address already in use */ throw new IllegalStateException(); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress addr, int port) { CoapSocketHandler socketHandler = null; try { socketHandler = new BasicCoapSocketHandler(this); SocketInformation sockInfo = new SocketInformation(socketHandler, null); socketMap.put(socketHandler.getLocalPort(), sockInfo); return socketHandler.connect(client, addr, port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private class SocketInformation { public CoapSocketHandler socketHandler = null; public CoapServer serverListener = null; public SocketInformation(CoapSocketHandler socketHandler, CoapServer serverListener) { super(); this.socketHandler = socketHandler; this.serverListener = serverListener; } } @Override public void setMessageId(int globalMessageId) { this.globalMessageId = globalMessageId; } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.net.InetAddress; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class BasicCoapChannel implements CoapChannel { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected CoapSocketHandler socketHandler = null; protected CoapChannelManager channelManager = null; protected InetAddress remoteAddress; protected int remotePort; protected int localPort; CoapBlockSize maxReceiveBlocksize = null; //null means no block option CoapBlockSize maxSendBlocksize = null; //null means no block option public BasicCoapChannel(CoapSocketHandler socketHandler, InetAddress remoteAddress, int remotePort) { this.socketHandler = socketHandler; channelManager = socketHandler.getChannelManager(); this.remoteAddress = remoteAddress; this.remotePort = remotePort; this.localPort = socketHandler.getLocalPort(); //FIXME:can be 0 when socketHandler is not yet ready } @Override public void sendMessage(CoapMessage msg) { msg.setChannel(this); socketHandler.sendMessage(msg); } @Override public CoapBlockSize getMaxReceiveBlocksize() { return maxReceiveBlocksize; } @Override public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize) { this.maxReceiveBlocksize = maxReceiveBlocksize; } @Override public CoapBlockSize getMaxSendBlocksize() { return maxSendBlocksize; } @Override public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize) { this.maxSendBlocksize = maxSendBlocksize; } @Override public InetAddress getRemoteAddress() { return remoteAddress; } @Override public int getRemotePort() { return remotePort; } /*A channel is identified (and therefore unique) by its remote address, remote port and the local port * TODO: identify channel also by a token */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + localPort; result = prime * result + ((remoteAddress == null) ? 0 : remoteAddress.hashCode()); result = prime * result + remotePort; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasicCoapChannel other = (BasicCoapChannel) obj; if (localPort != other.localPort) return false; if (remoteAddress == null) { if (other.remoteAddress != null) return false; } else if (!remoteAddress.equals(other.remoteAddress)) return false; if (remotePort != other.remotePort) return false; return true; } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.io.ByteArrayOutputStream; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClientChannel extends BasicCoapChannel implements CoapClientChannel { CoapClient client = null; ClientBlockContext blockContext = null; CoapRequest lastRequest = null; Object trigger = null; public BasicCoapClientChannel(CoapSocketHandler socketHandler, CoapClient client, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.client = client; } @Override public void close() { socketHandler.removeClientChannel(this); } @Override public void handleMessage(CoapMessage message) { if (message.isRequest()){ /* this is a client channel, no requests allowed */ message.getChannel().sendMessage(new CoapEmptyMessage(CoapPacketType.RST, message.getMessageID())); return; } if (message.isEmpty() && message.getPacketType() == CoapPacketType.ACK){ /* this is the ACK of a separate response */ //TODO: implement a handler or listener, that informs a client when a sep. resp. ack was received return; } if (message.getPacketType() == CoapPacketType.CON) { /* this is a separate response */ /* send ACK */ this.sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, message.getMessageID())); } /* check for blockwise transfer */ CoapBlockOption block2 = message.getBlock2(); if (blockContext == null && block2 != null){ /* initiate blockwise transfer */ blockContext = new ClientBlockContext(block2, maxReceiveBlocksize); blockContext.setFirstRequest(lastRequest); blockContext.setFirstResponse((CoapResponse) message); } if (blockContext!= null){ /*blocking option*/ if (!blockContext.addBlock(message, block2)){ /*this was not a correct block*/ /* TODO: implement either a RST or ignore this packet */ } if (!blockContext.isFinished()){ /* TODO: implement a counter to avoid an infinity req/resp loop: * if the same block is received more than x times -> rst the connection * implement maxPayloadSize to avoid an infinity payload */ CoapBlockOption newBlock = blockContext.getNextBlock(); if (lastRequest == null){ /*TODO: this should never happen*/ System.out.println("ERROR: client channel: lastRequest == null"); } else { /* create a new request for the next block */ BasicCoapRequest request = new BasicCoapRequest(lastRequest.getPacketType(), lastRequest.getRequestCode(), channelManager.getNewMessageID()); request.copyHeaderOptions((BasicCoapRequest) blockContext.getFirstRequest()); request.setBlock2(newBlock); sendMessage(request); } /* TODO: implement handler, inform the client that a block (but not the complete message) was received*/ return; } /* blockwise transfer finished */ message.setPayload(blockContext.getPayload()); /* TODO: give the payload separately and leave the original message as they is*/ } /* normal or separate response */ client.onResponse(this, (BasicCoapResponse) message); } @Override public void lostConnection(boolean notReachable, boolean resetByServer) { client.onConnectionFailed(this, notReachable, resetByServer); } @Override public BasicCoapRequest createRequest(boolean reliable, CoapRequestCode requestCode) { BasicCoapRequest msg = new BasicCoapRequest( reliable ? CoapPacketType.CON : CoapPacketType.NON, requestCode, channelManager.getNewMessageID()); msg.setChannel(this); return msg; } @Override public void sendMessage(CoapMessage msg) { super.sendMessage(msg); //TODO: check lastRequest = (CoapRequest) msg; } // public DefaultCoapClientChannel(CoapChannelManager channelManager) { // super(channelManager); // } // // @Override // public void connect(String remoteHost, int remotePort) { // socket = null; // if (remoteHost!=null && remotePort!=-1) { // try { // socket = new DatagramSocket(); // } catch (SocketException e) { // e.printStackTrace(); // } // } // // try { // InetAddress address = InetAddress.getByName(remoteHost); // socket.connect(address, remotePort); // super.establish(socket); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // } private class ClientBlockContext{ ByteArrayOutputStream payload = new ByteArrayOutputStream(); boolean finished = false; CoapBlockSize blockSize; //null means no block option CoapRequest request; CoapResponse response; public ClientBlockContext(CoapBlockOption blockOption, CoapBlockSize maxBlocksize) { /* determine the right blocksize (min of remote and max)*/ if (maxBlocksize == null){ blockSize = blockOption.getBlockSize(); } else { int max = maxBlocksize.getSize(); int remote = blockOption.getBlockSize().getSize(); if (remote < max){ blockSize = blockOption.getBlockSize(); } else { blockSize = maxBlocksize; } } } public byte[] getPayload() { return payload.toByteArray(); } public boolean addBlock(CoapMessage msg, CoapBlockOption block){ int blockPos = block.getBytePosition(); int blockLength = msg.getPayloadLength(); int bufSize = payload.size(); /*TODO: check if payload length = blocksize (except for the last block)*/ if (blockPos > bufSize){ /* data is missing before this block */ return false; } else if ((blockPos + blockLength) <= bufSize){ /* data already received */ return false; } int offset = bufSize - blockPos; payload.write(msg.getPayload(), offset, blockLength - offset); if (block.isLast()){ /* was this the last block */ finished = true; } return true; } public CoapBlockOption getNextBlock() { int num = payload.size() / blockSize.getSize(); //ignore the rest (no rest should be there) return new CoapBlockOption(num, false, blockSize); } public boolean isFinished() { return finished; } public CoapRequest getFirstRequest() { return request; } public void setFirstRequest(CoapRequest request) { this.request = request; } public CoapResponse getFirstResponse() { return response; } public void setFirstResponse(CoapResponse response) { this.response = response; } } @Override public void setTrigger(Object o) { trigger = o; } @Override public Object getTrigger() { return trigger; } }
Java
package org.ws4d.coap.connection; import java.net.InetAddress; public class ChannelKey { public InetAddress inetAddr; public int port; public ChannelKey(InetAddress inetAddr, int port) { this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChannelKey other = (ChannelKey) obj; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (port != other.port) return false; return true; } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.messages; /** * Type-safe class for CoapPacketTypes * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Sebastian Unger <sebastian.unger@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapPacketType { CON(0x00), NON(0x01), ACK(0x02), RST(0x03); private int packetType; CoapPacketType(int packetType) { if (packetType >= 0x00 && packetType <= 0x03){ this.packetType = packetType; } else { throw new IllegalStateException("Unknown CoAP Packet Type"); } } public static CoapPacketType getPacketType(int packetType) { if (packetType == 0x00) return CON; else if (packetType == 0x01) return NON; else if (packetType == 0x02) return ACK; else if (packetType == 0x03) return RST; else throw new IllegalStateException("Unknown CoAP Packet Type"); } public int getValue() { return packetType; } }
Java
package org.ws4d.coap.messages; import java.io.UnsupportedEncodingException; import java.util.Vector; import org.ws4d.coap.interfaces.CoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapRequest extends AbstractCoapMessage implements CoapRequest { CoapRequestCode requestCode; public BasicCoapRequest(byte[] bytes, int length) { /* length ought to be provided by UDP header */ this(bytes, length, 0); } public BasicCoapRequest(byte[] bytes, int length, int offset) { serialize(bytes, length, offset); /* check if request code is valid, this function throws an error in case of an invalid argument */ requestCode = CoapRequestCode.parseRequestCode(this.messageCodeValue); //TODO: check integrity of header options } public BasicCoapRequest(CoapPacketType packetType, CoapRequestCode requestCode, int messageId) { this.version = 1; this.packetType = packetType; this.requestCode = requestCode; this.messageCodeValue = requestCode.getValue(); this.messageId = messageId; } @Override public void setToken(byte[] token){ /* this function is only public for a request*/ super.setToken(token); } @Override public CoapRequestCode getRequestCode() { return requestCode; } @Override public void setUriHost(String host) { if (host == null) return; if (options.optionExists(CoapHeaderOptionType.Uri_Host)){ throw new IllegalArgumentException("Uri-Host option already exists"); } if (host.length() < 1 || host.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Host option length"); } /*TODO: check if host is a valid address */ options.addOption(CoapHeaderOptionType.Uri_Host, host.getBytes()); } @Override public void setUriPort(int port) { if (port < 0) return; if (options.optionExists(CoapHeaderOptionType.Uri_Port)){ throw new IllegalArgumentException("Uri-Port option already exists"); } byte[] value = long2CoapUint(port); if(value.length < 0 || value.length > 2){ throw new IllegalStateException("Illegal Uri-Port length"); } options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Uri_Port, value)); } @Override public void setUriPath(String path) { if (path == null) return; if (path.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Path option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Path); /*create substrings */ String[] pathElements = path.split("/"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Path, element.getBytes()); } } } @Override public void setUriQuery(String query) { if (query == null) return; if (query.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Query option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Query); /*create substrings */ String[] pathElements = query.split("&"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Query, element.getBytes()); } } } @Override public void setProxyUri(String proxyUri) { if (proxyUri == null) return; if (options.optionExists(CoapHeaderOptionType.Proxy_Uri)){ throw new IllegalArgumentException("Proxy Uri already exists"); } if (proxyUri.length() < 1){ throw new IllegalArgumentException("Proxy Uri must be at least one byte long"); } if (proxyUri.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Proxy Uri longer then 270 bytes are not supported yet (to be implemented)"); } options.addOption(CoapHeaderOptionType.Proxy_Uri, proxyUri.getBytes()); } @Override public Vector<String> getUriQuery(){ Vector<String> queryList = new Vector<String>(); for (CoapHeaderOption option : options) { if(option.getOptionType() == CoapHeaderOptionType.Uri_Query){ queryList.add(new String(option.getOptionData())); } } return queryList; } @Override public String getUriHost(){ return new String(options.getOption(CoapHeaderOptionType.Uri_Host).getOptionData()); } @Override public int getUriPort(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Uri_Port); if (option == null){ return -1; //TODO: return default Coap Port? } byte[] value = option.getOptionData(); if(value.length < 0 || value.length > 2){ /* should never happen because this is an internal variable and should be checked during serialization */ throw new IllegalStateException("Illegal Uri-Port Option length"); } /* checked length -> cast is safe*/ return (int)coapUint2Long(options.getOption(CoapHeaderOptionType.Uri_Port).getOptionData()); } @Override public String getUriPath() { if (options.getOption(CoapHeaderOptionType.Uri_Path) == null){ return null; } StringBuilder uriPathBuilder = new StringBuilder(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Uri_Path) { String uriPathElement; try { uriPathElement = new String(option.getOptionData(), "UTF-8"); uriPathBuilder.append("/"); uriPathBuilder.append(uriPathElement); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Invalid Encoding"); } } } return uriPathBuilder.toString(); } @Override public void addAccept(CoapMediaType mediaType){ options.addOption(CoapHeaderOptionType.Accept, long2CoapUint(mediaType.getValue())); } @Override public Vector<CoapMediaType> getAccept(CoapMediaType mediaType){ if (options.getOption(CoapHeaderOptionType.Accept) == null){ return null; } Vector<CoapMediaType> acceptList = new Vector<CoapMediaType>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Accept) { CoapMediaType accept = CoapMediaType.parse((int)coapUint2Long(option.optionData)); // if (accept != CoapMediaType.UNKNOWN){ /* add also UNKNOWN types to list */ acceptList.add(accept); // } } } return acceptList; } @Override public String getProxyUri(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Proxy_Uri); if (option == null) return null; return new String(option.getOptionData()); } @Override public void addETag(byte[] etag) { if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public Vector<byte[]> getETag() { if (options.getOption(CoapHeaderOptionType.Etag) == null){ return null; } Vector<byte[]> etagList = new Vector<byte[]>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Etag) { byte[] data = option.getOptionData(); if (data.length >= 1 && data.length <= 8){ etagList.add(option.getOptionData()); } } } return etagList; } @Override public boolean isRequest() { return true; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + requestCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setRequestCode(CoapRequestCode requestCode) { this.requestCode = requestCode; } }
Java
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ /* WS4D Java CoAP Implementation * (c) 2011 WS4D.org * * written by Sebastian Unger */ package org.ws4d.coap.messages; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Iterator; import java.util.Random; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class AbstractCoapMessage implements CoapMessage { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected static final int HEADER_LENGTH = 4; /* Header */ protected int version; protected CoapPacketType packetType; protected int messageCodeValue; //protected int optionCount; protected int messageId; /* Options */ protected CoapHeaderOptions options = new CoapHeaderOptions(); /* Payload */ protected byte[] payload = null; protected int payloadLength = 0; /* corresponding channel */ CoapChannel channel = null; /* Retransmission State */ int timeout = 0; int retransmissionCounter = 0; protected void serialize(byte[] bytes, int length, int offset){ /* check length to avoid buffer overflow exceptions */ this.version = 1; this.packetType = (CoapPacketType.getPacketType((bytes[offset + 0] & 0x30) >> 4)); int optionCount = bytes[offset + 0] & 0x0F; this.messageCodeValue = (bytes[offset + 1] & 0xFF); this.messageId = ((bytes[offset + 2] << 8) & 0xFF00) + (bytes[offset + 3] & 0xFF); /* serialize options */ this.options = new CoapHeaderOptions(bytes, offset + HEADER_LENGTH, optionCount); /* get and check payload length */ payloadLength = length - HEADER_LENGTH - options.getDeserializedLength(); if (payloadLength < 0){ throw new IllegalStateException("Invaldid CoAP Message (payload length negative)"); } /* copy payload */ int payloadOffset = offset + HEADER_LENGTH + options.getDeserializedLength(); payload = new byte[payloadLength]; for (int i = 0; i < payloadLength; i++){ payload[i] = bytes[i + payloadOffset]; } } /* TODO: this function should be in another class */ public static CoapMessage parseMessage(byte[] bytes, int length){ return parseMessage(bytes, length, 0); } public static CoapMessage parseMessage(byte[] bytes, int length, int offset){ /* we "peek" the header to determine the kind of message * TODO: duplicate Code */ int messageCodeValue = (bytes[offset + 1] & 0xFF); if (messageCodeValue == 0){ return new CoapEmptyMessage(bytes, length, offset); } else if (messageCodeValue >= 0 && messageCodeValue <= 31 ){ return new BasicCoapRequest(bytes, length, offset); } else if (messageCodeValue >= 64 && messageCodeValue <= 191){ return new BasicCoapResponse(bytes, length, offset); } else { throw new IllegalArgumentException("unknown CoAP message"); } } public int getVersion() { return version; } @Override public int getMessageCodeValue() { return messageCodeValue; } @Override public CoapPacketType getPacketType() { return packetType; } public byte[] getPayload() { return payload; } public int getPayloadLength() { return payloadLength; } @Override public int getMessageID() { return messageId; } @Override public void setMessageID(int messageId) { this.messageId = messageId; } public byte[] serialize() { /* TODO improve memory allocation */ /* serialize header options first to get the length*/ int optionsLength = 0; byte[] optionsArray = null; if (options != null) { optionsArray = this.options.serialize(); optionsLength = this.options.getSerializedLength(); } /* allocate memory for the complete packet */ int length = HEADER_LENGTH + optionsLength + payloadLength; byte[] serializedPacket = new byte[length]; /* serialize header */ serializedPacket[0] = (byte) ((this.version & 0x03) << 6); serializedPacket[0] |= (byte) ((this.packetType.getValue() & 0x03) << 4); serializedPacket[0] |= (byte) (options.getOptionCount() & 0x0F); serializedPacket[1] = (byte) (this.getMessageCodeValue() & 0xFF); serializedPacket[2] = (byte) ((this.messageId >> 8) & 0xFF); serializedPacket[3] = (byte) (this.messageId & 0xFF); /* copy serialized options to the final array */ int offset = HEADER_LENGTH; if (options != null) { for (int i = 0; i < optionsLength; i++) serializedPacket[i + offset] = optionsArray[i]; } /* copy payload to the final array */ offset = HEADER_LENGTH + optionsLength; for (int i = 0; i < this.payloadLength; i++) { serializedPacket[i + offset] = payload[i]; } return serializedPacket; } public void setPayload(byte[] payload) { this.payload = payload; if (payload!=null) this.payloadLength = payload.length; else this.payloadLength = 0; } public void setPayload(char[] payload) { this.payload = new byte[payload.length]; for (int i = 0; i < payload.length; i++) { this.payload[i] = (byte) payload[i]; } this.payloadLength = payload.length; } public void setPayload(String payload) { setPayload(payload.toCharArray()); } @Override public void setContentType(CoapMediaType mediaType){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option != null){ /* content Type MUST only exists once */ throw new IllegalStateException("added content option twice"); } if ( mediaType == CoapMediaType.UNKNOWN){ throw new IllegalStateException("unknown content type"); } /* convert value */ byte[] data = long2CoapUint(mediaType.getValue()); /* no need to check result, mediaType is safe */ /* add option to Coap Header*/ options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Content_Type, data)); } @Override public CoapMediaType getContentType(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option == null){ /* not content type TODO: return UNKNOWN ?*/ return null; } /* no need to check length, CoapMediaType parse function will do*/ int mediaTypeCode = (int) coapUint2Long(options.getOption(CoapHeaderOptionType.Content_Type).getOptionData()); return CoapMediaType.parse(mediaTypeCode); } @Override public byte[] getToken(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Token); if (option == null){ return null; } return option.getOptionData(); } protected void setToken(byte[] token){ if (token == null){ return; } if (token.length < 1 || token.length > 8){ throw new IllegalArgumentException("Invalid Token Length"); } options.addOption(CoapHeaderOptionType.Token, token); } @Override public CoapBlockOption getBlock1(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock1(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block1); } options.addOption(CoapHeaderOptionType.Block1, blockOption.getBytes()); } @Override public CoapBlockOption getBlock2(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock2(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block2); } options.addOption(CoapHeaderOptionType.Block2, blockOption.getBytes()); } @Override public Integer getObserveOption() { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option == null){ return null; } byte[] data = option.getOptionData(); if (data.length < 0 || data.length > 2){ logger.warn("invalid observe option length, return null"); return null; } return (int) AbstractCoapMessage.coapUint2Long(data); } @Override public void setObserveOption(int sequenceNumber) { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option != null){ options.removeOption(CoapHeaderOptionType.Observe); } byte[] data = long2CoapUint(sequenceNumber); if (data.length < 0 || data.length > 2){ throw new IllegalArgumentException("invalid observe option length"); } options.addOption(CoapHeaderOptionType.Observe, data); } public void copyHeaderOptions(AbstractCoapMessage origin){ options.removeAll(); options.copyFrom(origin.options); } public void removeOption(CoapHeaderOptionType optionType){ options.removeOption(optionType); } @Override public CoapChannel getChannel() { return channel; } @Override public void setChannel(CoapChannel channel) { this.channel = channel; } @Override public int getTimeout() { if (timeout == 0) { Random random = new Random(); timeout = RESPONSE_TIMEOUT_MS + random.nextInt((int) (RESPONSE_TIMEOUT_MS * RESPONSE_RANDOM_FACTOR) - RESPONSE_TIMEOUT_MS); } return timeout; } @Override public boolean maxRetransReached() { if (retransmissionCounter < MAX_RETRANSMIT) { return false; } return true; } @Override public void incRetransCounterAndTimeout() { /*TODO: Rename*/ retransmissionCounter += 1; timeout *= 2; } @Override public boolean isReliable() { if (packetType == CoapPacketType.NON){ return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); result = prime * result + getMessageID(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractCoapMessage other = (AbstractCoapMessage) obj; if (channel == null) { if (other.channel != null) return false; } else if (!channel.equals(other.channel)) return false; if (getMessageID() != other.getMessageID()) return false; return true; } protected static long coapUint2Long(byte[] data){ /* avoid buffer overflow */ if(data.length > 8){ return -1; } /* fill with leading zeros */ byte[] tmp = new byte[8]; for (int i = 0; i < data.length; i++) { tmp[i + 8 - data.length] = data[i]; } /* convert to long */ ByteBuffer buf = ByteBuffer.wrap(tmp); /* byte buffer contains 8 bytes */ return buf.getLong(); } protected static byte[] long2CoapUint(long value){ /* only unsigned values supported */ if (value < 0){ return null; } /* a zero length value implies zero */ if (value == 0){ return new byte[0]; } /* convert long to byte array with a fixed length of 8 byte*/ ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(value); byte[] tmp = buf.array(); /* remove leading zeros */ int leadingZeros = 0; for (int i = 0; i < tmp.length; i++) { if (tmp[i] == 0){ leadingZeros = i+1; } else { break; } } /* copy to byte array without leading zeros */ byte[] result = new byte[8 - leadingZeros]; for (int i = 0; i < result.length; i++) { result[i] = tmp[i + leadingZeros]; } return result; } public enum CoapHeaderOptionType { UNKNOWN(-1), Content_Type (1), Max_Age (2), Proxy_Uri(3), Etag (4), Uri_Host (5), Location_Path (6), Uri_Port (7), Location_Query (8), Uri_Path (9), Observe (10), Token (11), Accept (12), If_Match (13), Uri_Query (15), If_None_Match (21), Block1 (19), Block2 (17); int value; CoapHeaderOptionType(int optionValue){ value = optionValue; } public static CoapHeaderOptionType parse(int optionTypeValue){ switch(optionTypeValue){ case 1: return Content_Type; case 2: return Max_Age; case 3: return Proxy_Uri; case 4: return Etag; case 5: return Uri_Host; case 6: return Location_Path; case 7: return Uri_Port; case 8: return Location_Query; case 9: return Uri_Path; case 10: return Observe; case 11:return Token; case 12:return Accept; case 13:return If_Match; case 15:return Uri_Query; case 21:return If_None_Match; case 19:return Block1; case 17:return Block2; default: return UNKNOWN; } } public int getValue(){ return value; } /* TODO: implement validity checks */ /*TODO: implement isCritical(int optionTypeValue), isElective()*/ } protected class CoapHeaderOption implements Comparable<CoapHeaderOption> { CoapHeaderOptionType optionType; int optionTypeValue; /* integer representation of optionType*/ byte[] optionData; int shortLength; int longLength; int deserializedLength; static final int MAX_LENGTH = 270; public int getDeserializedLength() { return deserializedLength; } public CoapHeaderOption(CoapHeaderOptionType optionType, byte[] value) { if (optionType == CoapHeaderOptionType.UNKNOWN){ /*TODO: implement check if it is a critical option */ throw new IllegalStateException("Unknown header option"); } if (value == null){ throw new IllegalArgumentException("Header option value MUST NOT be null"); } this.optionTypeValue = optionType.getValue(); this.optionData = value; if (value.length < 15) { shortLength = value.length; longLength = 0; } else { shortLength = 15; longLength = value.length - shortLength; } } public CoapHeaderOption(byte[] bytes, int offset, int lastOptionNumber){ int headerLength; /* parse option type */ optionTypeValue = ((bytes[offset] & 0xF0) >> 4) + lastOptionNumber; optionType = CoapHeaderOptionType.parse(optionTypeValue); if (optionType == CoapHeaderOptionType.UNKNOWN){ if (optionTypeValue % 14 == 0){ /* no-op: no operation for deltas > 14 */ } else { /*TODO: implement check if it is a critical option */ throw new IllegalArgumentException("Unknown header option"); } } /* parse length */ if ((bytes[offset] & 0x0F) < 15) { shortLength = bytes[offset] & 0x0F; longLength = 0; headerLength = 1; } else { shortLength = 15; longLength = bytes[offset + 1]; headerLength = 2; /* additional length byte */ } /* copy value */ optionData = new byte[shortLength + longLength]; for (int i = 0; i < shortLength + longLength; i++){ optionData[i] = bytes[i + headerLength + offset]; } deserializedLength += headerLength + shortLength + longLength; } @Override public int compareTo(CoapHeaderOption option) { /* compare function for sorting * TODO: check what happens in case of equal option values * IMPORTANT: order must be the same for e.g., URI path*/ if (this.optionTypeValue != option.optionTypeValue) return this.optionTypeValue < option.optionTypeValue ? -1 : 1; else return 0; } public boolean hasLongLength(){ if (shortLength == 15){ return true; } else return false; } public int getLongLength() { return longLength; } public int getShortLength() { return shortLength; } public int getOptionTypeValue() { return optionTypeValue; } public byte[] getOptionData() { return optionData; } public int getSerializeLength(){ if (hasLongLength()){ return optionData.length + 2; } else { return optionData.length + 1; } } @Override public String toString() { char[] printableOptionValue = new char[optionData.length]; for (int i = 0; i < optionData.length; i++) printableOptionValue[i] = (char) optionData[i]; return "Option Number: " + " (" + optionTypeValue + ")" + ", Option Value: " + String.copyValueOf(printableOptionValue); } public CoapHeaderOptionType getOptionType() { return optionType; } } protected class CoapHeaderOptions implements Iterable<CoapHeaderOption>{ private Vector<CoapHeaderOption> headerOptions = new Vector<CoapHeaderOption>(); private int deserializedLength; private int serializedLength = 0; public CoapHeaderOptions(byte[] bytes, int option_count){ this(bytes, option_count, option_count); } public CoapHeaderOptions(byte[] bytes, int offset, int optionCount){ /* note: we only receive deltas and never concrete numbers */ /* TODO: check integrity */ deserializedLength = 0; int lastOptionNumber = 0; int optionOffset = offset; for (int i = 0; i < optionCount; i++) { CoapHeaderOption option = new CoapHeaderOption(bytes, optionOffset, lastOptionNumber); lastOptionNumber = option.getOptionTypeValue(); deserializedLength += option.getDeserializedLength(); optionOffset += option.getDeserializedLength(); addOption(option); } } public CoapHeaderOptions() { /* creates empty header options */ } public CoapHeaderOption getOption(int optionNumber) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionTypeValue() == optionNumber) { return headerOption; } } return null; } public CoapHeaderOption getOption(CoapHeaderOptionType optionType) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionType() == optionType) { return headerOption; } } return null; } public boolean optionExists(CoapHeaderOptionType optionType) { CoapHeaderOption option = getOption(optionType); if (option == null){ return false; } else return true; } public void addOption(CoapHeaderOption option) { headerOptions.add(option); /*TODO: only sort when options are serialized*/ Collections.sort(headerOptions); } public void addOption(CoapHeaderOptionType optionType, byte[] value){ addOption(new CoapHeaderOption(optionType, value)); } public void removeOption(CoapHeaderOptionType optionType){ CoapHeaderOption headerOption; // get elements of Vector /* note: iterating over and changing a vector at the same time is not allowed */ int i = 0; while (i < headerOptions.size()){ headerOption = headerOptions.get(i); if (headerOption.getOptionType() == optionType) { headerOptions.remove(i); } else { /* only increase when no element was removed*/ i++; } } Collections.sort(headerOptions); } public void removeAll(){ headerOptions.clear(); } public void copyFrom(CoapHeaderOptions origin){ for (CoapHeaderOption option : origin) { addOption(option); } } public int getOptionCount() { return headerOptions.size(); } public byte[] serialize() { /* options are serialized here to be more efficient (only one byte array necessary)*/ int length = 0; /* calculate the overall length first */ for (CoapHeaderOption option : headerOptions) { length += option.getSerializeLength(); } byte[] data = new byte[length]; int arrayIndex = 0; int lastOptionNumber = 0; /* let's keep track of this */ for (CoapHeaderOption headerOption : headerOptions) { /* TODO: move the serialization implementation to CoapHeaderOption */ int optionDelta = headerOption.getOptionTypeValue() - lastOptionNumber; lastOptionNumber = headerOption.getOptionTypeValue(); // set length(s) data[arrayIndex++] = (byte) (((optionDelta & 0x0F) << 4) | (headerOption.getShortLength() & 0x0F)); if (headerOption.hasLongLength()) { data[arrayIndex++] = (byte) (headerOption.getLongLength() & 0xFF); } // copy option value byte[] value = headerOption.getOptionData(); for (int i = 0; i < value.length; i++) { data[arrayIndex++] = value[i]; } } serializedLength = length; return data; } public int getDeserializedLength(){ return deserializedLength; } public int getSerializedLength() { return serializedLength; } @Override public Iterator<CoapHeaderOption> iterator() { return headerOptions.iterator(); } @Override public String toString() { String result = "\tOptions:\n"; for (CoapHeaderOption option : headerOptions) { result += "\t\t" + option.toString() + "\n"; } return result; } } }
Java
package org.ws4d.coap.messages; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResponse extends AbstractCoapMessage implements CoapResponse { CoapResponseCode responseCode; public BasicCoapResponse(byte[] bytes, int length){ this(bytes, length, 0); } public BasicCoapResponse(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ responseCode = CoapResponseCode.parseResponseCode(this.messageCodeValue); //TODO: check integrity of header options } /* token can be null */ public BasicCoapResponse(CoapPacketType packetType, CoapResponseCode responseCode, int messageId, byte[] requestToken){ this.version = 1; this.packetType = packetType; this.responseCode = responseCode; if (responseCode == CoapResponseCode.UNKNOWN){ throw new IllegalArgumentException("UNKNOWN Response Code not allowed"); } this.messageCodeValue = responseCode.getValue(); this.messageId = messageId; setToken(requestToken); } @Override public CoapResponseCode getResponseCode() { return responseCode; } @Override public void setMaxAge(int maxAge){ if (options.optionExists(CoapHeaderOptionType.Max_Age)){ throw new IllegalStateException("Max Age option already exists"); } if (maxAge < 0){ throw new IllegalStateException("Max Age MUST be an unsigned value"); } options.addOption(CoapHeaderOptionType.Max_Age, long2CoapUint(maxAge)); } @Override public long getMaxAge(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Max_Age); if (option == null){ return -1; } return coapUint2Long((options.getOption(CoapHeaderOptionType.Max_Age).getOptionData())); } @Override public void setETag(byte[] etag){ if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public byte[] getETag(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Etag); if (option == null){ return null; } return option.getOptionData(); } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return true; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + responseCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setResponseCode(CoapResponseCode responseCode) { if (responseCode != CoapResponseCode.UNKNOWN){ this.responseCode = responseCode; this.messageCodeValue = responseCode.getValue(); } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapRequestCode { GET(1), POST(2), PUT(3), DELETE(4); private int code; private CoapRequestCode(int code) { this.code = code; } public static CoapRequestCode parseRequestCode(int codeValue){ switch (codeValue) { case 1: return GET; case 2: return POST; case 3: return PUT; case 4: return DELETE; default: throw new IllegalArgumentException("Invalid Request Code"); } } public int getValue() { return code; } @Override public String toString() { switch (this) { case GET: return "GET"; case POST: return "POST"; case PUT: return "PUT"; case DELETE: return "DELETE"; } return null; } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapResponseCode { Created_201(65), Deleted_202(66), Valid_203(67), Changed_204(68), Content_205(69), Bad_Request_400(128), Unauthorized_401(129), Bad_Option_402(130), Forbidden_403(131), Not_Found_404(132), Method_Not_Allowed_405(133), Precondition_Failed_412(140), Request_Entity_To_Large_413(141), Unsupported_Media_Type_415(143), Internal_Server_Error_500(160), Not_Implemented_501(161), Bad_Gateway_502(162), Service_Unavailable_503(163), Gateway_Timeout_504(164), Proxying_Not_Supported_505(165), UNKNOWN(-1); private int code; private CoapResponseCode(int code) { this.code = code; } public static CoapResponseCode parseResponseCode(int codeValue) { switch (codeValue) { /* 32..63: reserved */ /* 64 is not used anymore */ // case 64: // this.code = ResponseCode.OK_200; // break; case 65: return Created_201; case 66: return Deleted_202; case 67: return Valid_203; case 68: return Changed_204; case 69: return Content_205; case 128: return Bad_Request_400; case 129: return Unauthorized_401; case 130: return Bad_Option_402; case 131: return Forbidden_403; case 132: return Not_Found_404; case 133: return Method_Not_Allowed_405; case 140: return Precondition_Failed_412; case 141: return Request_Entity_To_Large_413; case 143: return Unsupported_Media_Type_415; case 160: return Internal_Server_Error_500; case 161: return Not_Implemented_501; case 162: return Bad_Gateway_502; case 163: return Service_Unavailable_503; case 164: return Gateway_Timeout_504; case 165: return Proxying_Not_Supported_505; default: if (codeValue >= 64 && codeValue <= 191) { return UNKNOWN; } else { throw new IllegalArgumentException("Invalid Response Code"); } } } public int getValue() { return code; } @Override public String toString() { switch (this) { case Created_201: return "Created_201"; case Deleted_202: return "Deleted_202"; case Valid_203: return "Valid_203"; case Changed_204: return "Changed_204"; case Content_205: return "Content_205"; case Bad_Request_400: return "Bad_Request_400"; case Unauthorized_401: return "Unauthorized_401"; case Bad_Option_402: return "Bad_Option_402"; case Forbidden_403: return "Forbidden_403"; case Not_Found_404: return "Not_Found_404"; case Method_Not_Allowed_405: return "Method_Not_Allowed_405"; case Precondition_Failed_412: return "Precondition_Failed_412"; case Request_Entity_To_Large_413: return "Request_Entity_To_Large_413"; case Unsupported_Media_Type_415: return "Unsupported_Media_Type_415"; case Internal_Server_Error_500: return "Internal_Server_Error_500"; case Not_Implemented_501: return "Not_Implemented_501"; case Bad_Gateway_502: return "Bad_Gateway_502"; case Service_Unavailable_503: return "Service_Unavailable_503"; case Gateway_Timeout_504: return "Gateway_Timeout_504"; case Proxying_Not_Supported_505: return "Proxying_Not_Supported_505"; default: return "Unknown_Response_Code"; } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapEmptyMessage extends AbstractCoapMessage { public CoapEmptyMessage(byte[] bytes, int length){ this(bytes, length, 0); } public CoapEmptyMessage(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ if (this.messageCodeValue != 0){ throw new IllegalArgumentException("Not an empty CoAP message."); } if (length != HEADER_LENGTH){ throw new IllegalArgumentException("Invalid length of an empty message"); } } public CoapEmptyMessage(CoapPacketType packetType, int messageId) { this.version = 1; this.packetType = packetType; this.messageCodeValue = 0; this.messageId = messageId; } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return true; } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapBlockOption{ private int number; private boolean more; private CoapBlockSize blockSize; public CoapBlockOption(byte[] data){ if (data.length <1 || data.length > 3){ throw new IllegalArgumentException("invalid block option"); } long val = AbstractCoapMessage.coapUint2Long(data); this.blockSize = CoapBlockSize.parse((int) (val & 0x7)); if (blockSize == null){ throw new IllegalArgumentException("invalid block options"); } if ((val & 0x8) == 0){ //more bit not set more = false; } else { more = true; } number = (int) (val >> 4); } public CoapBlockOption(int number, boolean more, CoapBlockSize blockSize){ if (blockSize == null){ throw new IllegalArgumentException(); } if (number < 0 || number > 0xFFFFFF ){ //not an unsigned 20 bit value throw new IllegalArgumentException(); } this.blockSize = blockSize; this.number = number; this.more = more; } public int getNumber() { return number; } public boolean isLast() { return !more; } public CoapBlockSize getBlockSize() { return blockSize; } public int getBytePosition(){ return number << (blockSize.getExponent() + 4); } public byte[] getBytes(){ int value = number << 4; value |= blockSize.getExponent(); if (more){ value |= 0x8; } return AbstractCoapMessage.long2CoapUint(value); } public enum CoapBlockSize { BLOCK_16 (0), BLOCK_32 (1), BLOCK_64 (2), BLOCK_128(3), BLOCK_256 (4), BLOCK_512 (5), BLOCK_1024 (6); int exp; CoapBlockSize(int exponent){ exp = exponent; } public static CoapBlockSize parse(int exponent){ switch(exponent){ case 0: return BLOCK_16; case 1: return BLOCK_32; case 2: return BLOCK_64; case 3: return BLOCK_128; case 4: return BLOCK_256; case 5: return BLOCK_512; case 6: return BLOCK_1024; default : return null; } } public int getExponent(){ return exp; } public int getSize(){ return 1 << (exp+4); } } }
Java
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapMediaType { text_plain (0), //text/plain; charset=utf-8 link_format (40), //application/link-format xml(41), //application/xml octet_stream (42), //application/octet-stream exi(47), //application/exi json(50), //application/json UNKNOWN (-1); int mediaType; private CoapMediaType(int mediaType){ this.mediaType = mediaType; } public static CoapMediaType parse(int mediaType){ switch(mediaType){ case 0: return text_plain; case 40:return link_format; case 41:return xml; case 42:return octet_stream; case 47:return exi; case 50:return json; default: return UNKNOWN; } } public int getValue(){ return mediaType; } }
Java
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private CoapMediaType mediaType; private String path; private byte[] value; ResourceHandler resourceHandler = null; ResourceServer serverListener = null; //could be a list of listener String resourceType = null; HashMap<CoapChannel, CoapRequest> observer = new HashMap<CoapChannel, CoapRequest>(); boolean observable = false; int observeSequenceNumber = 0; //MUST NOT greater than 0xFFFF (2 byte integer) Boolean reliableNotification = null; long expires = -1; //DEFAULT: expires never public BasicCoapResource(String path, byte[] value, CoapMediaType mediaType) { this.path = path; this.value = value; this.mediaType = mediaType; } public void setCoapMediaType(CoapMediaType mediaType) { this.mediaType = mediaType; } @Override public CoapMediaType getCoapMediaType() { return mediaType; } public String getMimeType(){ //TODO: implement return null; } @Override public String getPath() { return path; } @Override public String getShortName() { return null; } @Override public byte[] getValue() { return value; } @Override public byte[] getValue(Vector<String> query) { return value; } public void setValue(byte[] value) { this.value = value; } @Override public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public Boolean getReliableNotification() { return reliableNotification; } /* NULL lets the client decide */ public void setReliableNotification(Boolean reliableNotification) { this.reliableNotification = reliableNotification; } @Override public String toString() { return getPath(); //TODO implement } @Override public void post(byte[] data) { if (resourceHandler != null){ resourceHandler.onPost(data); } return; } @Override public void changed() { if (serverListener != null){ serverListener.resourceChanged(this); } observeSequenceNumber++; if (observeSequenceNumber > 0xFFFF){ observeSequenceNumber = 0; } /* notify all observers */ for (CoapRequest obsRequest : observer.values()) { CoapServerChannel channel = (CoapServerChannel) obsRequest.getChannel(); CoapResponse response; if (reliableNotification == null){ response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber); } else { response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber, reliableNotification); } response.setPayload(getValue()); channel.sendNotification(response); } } public void registerResourceHandler(ResourceHandler handler){ this.resourceHandler = handler; } public void registerServerListener(ResourceServer server){ this.serverListener = server; } public void unregisterServerListener(ResourceServer server){ this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { observer.put(request.getChannel(), request); return true; } public void removeObserver(CoapChannel channel){ observer.remove(channel); } public boolean isObservable(){ return observable; } public void setObservable(boolean observable) { this.observable = observable; } public int getObserveSequenceNumber(){ return observeSequenceNumber; } @Override public long expires() { return expires; } @Override public boolean isExpired(){ if (expires == -1){ return false; //-1 == never expires } if(expires < System.currentTimeMillis()){ return true; } else { return false; } } public void setExpires(long expires){ this.expires = expires; } }
Java
package org.ws4d.coap.rest; import java.net.URI; /** * A ResourceServer provides network access to resources via a network protocol such as HTTP or CoAP. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceServer { /** * * @param resource The resource to be handled. */ /* creates a resource. resource must not exist. if resource exists, false is returned */ public boolean createResource(Resource resource); /* returns the resource at the given path, null if no resource exists*/ public Resource readResource(String path); /* updates a resource. resource must exist. if does not resource exist, false is returned. Resource is NOT created. */ public boolean updateResource(Resource resource); /* deletes resource, returns false is resource does not exist */ public boolean deleteResource(String path); /** * Start the ResourceServer. This usually opens network ports and makes the * resources available through a certain network protocol. */ public void start() throws Exception; /** * Stops the ResourceServer. */ public void stop(); /** * Returns the Host Uri */ public URI getHostUri(); public void resourceChanged(Resource resource); }
Java
package org.ws4d.coap.rest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapResourceServer implements CoapServer, ResourceServer { private int port = 0; private final static Logger logger = Logger.getLogger(CoapResourceServer.class); protected HashMap<String, Resource> resources = new HashMap<String, Resource>(); private CoreResource coreResource = new CoreResource(this); public CoapResourceServer(){ logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.WARN); } public HashMap<String, Resource> getResources(){ return resources; } private void addResource(Resource resource){ resource.registerServerListener(this); resources.put(resource.getPath(), resource); coreResource.registerResource(resource); } @Override public boolean createResource(Resource resource) { if (resource==null) return false; if (!resources.containsKey(resource.getPath())) { addResource(resource); logger.info("created ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean updateResource(Resource resource) { if (resource==null) return false; if (resources.containsKey(resource.getPath())) { addResource(resource); logger.info("updated ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean deleteResource(String path) { if (null != resources.remove(path)) { logger.info("deleted ressource: " + path); return true; } else return false; } @Override public final Resource readResource(String path) { logger.info("read ressource: " + path); return resources.get(path); } /*corresponding to the coap spec the put is an update or create (or error)*/ public CoapResponseCode CoapResponseCode(Resource resource) { Resource res = readResource(resource.getPath()); //TODO: check results if (res == null){ createResource(resource); return CoapResponseCode.Created_201; } else { updateResource(resource); return CoapResponseCode.Changed_204; } } @Override public void start() throws Exception { start(Constants.COAP_DEFAULT_PORT); } public void start(int port) throws Exception { resources.put(coreResource.getPath(), coreResource); CoapChannelManager channelManager = BasicCoapChannelManager .getInstance(); this.port = port; channelManager.createServerListener(this, port); } @Override public void stop() { } public int getPort() { return port; } @Override public URI getHostUri() { URI hostUri = null; try { hostUri = new URI("coap://" + this.getLocalIpAddress() + ":" + getPort()); } catch (URISyntaxException e) { e.printStackTrace(); } return hostUri; } @Override public void resourceChanged(Resource resource) { logger.info("Resource changed: " + resource.getPath()); } @Override public CoapServer onAccept(CoapRequest request) { return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { CoapMessage response = null; CoapRequestCode requestCode = request.getRequestCode(); String targetPath = request.getUriPath(); //TODO make this cast safe (send internal server error if it is not a CoapResource) CoapResource resource = (CoapResource) readResource(targetPath); /* TODO: check return values of create, read, update and delete * TODO: implement forbidden * TODO: implement ETag * TODO: implement If-Match... * TODO: check for well known addresses (do not override well known core) * TODO: check that path begins with "/" */ switch (requestCode) { case GET: if (resource != null) { // URI queries Vector<String> uriQueries = request.getUriQuery(); final byte[] responseValue; if (uriQueries != null) { responseValue = resource.getValue(uriQueries); } else { responseValue = resource.getValue(); } response = channel.createResponse(request, CoapResponseCode.Content_205, resource.getCoapMediaType()); response.setPayload(responseValue); if (request.getObserveOption() != null){ /*client wants to observe this resource*/ if (resource.addObserver(request)){ /* successfully added observer */ response.setObserveOption(resource.getObserveSequenceNumber()); } } } else { response = channel.createResponse(request, CoapResponseCode.Not_Found_404); } break; case DELETE: /* CoAP: "A 2.02 (Deleted) response SHOULD be sent on success or in case the resource did not exist before the request.*/ deleteResource(targetPath); response = channel.createResponse(request, CoapResponseCode.Deleted_202); break; case POST: if (resource != null){ resource.post(request.getPayload()); response = channel.createResponse(request, CoapResponseCode.Changed_204); } else { /* if the resource does not exist, a new resource will be created */ createResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Created_201); } break; case PUT: if (resource == null){ /* create*/ createResource(parseRequest(request)); response = channel.createResponse(request,CoapResponseCode.Created_201); } else { /*update*/ updateResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Changed_204); } break; default: response = channel.createResponse(request, CoapResponseCode.Bad_Request_400); break; } channel.sendMessage(response); } private CoapResource parseRequest(CoapRequest request) { CoapResource resource = new BasicCoapResource(request.getUriPath(), request.getPayload(), request.getContentType()); // TODO add content type return resource; } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { logger.error("Separate response failed but server never used separate responses"); } protected String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { } return null; } }
Java
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * Well-Known CoRE support (draft-ietf-core-link-format-05) * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoreResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private final static String uriPath = "/.well-known/core"; private HashMap<Resource, String> coreStrings = new HashMap<Resource, String>(); ResourceServer serverListener = null; CoapResourceServer server = null; public CoreResource (CoapResourceServer server){ this.server = server; } /*Hide*/ @SuppressWarnings("unused") private CoreResource (){ } @Override public String getMimeType() { return null; } @Override public String getPath() { return uriPath; } @Override public String getShortName() { return getPath(); } @Override public byte[] getValue() { return buildCoreString(null).getBytes(); } public void registerResource(Resource resource) { if (resource != null) { StringBuilder coreLine = new StringBuilder(); coreLine.append("<"); coreLine.append(resource.getPath()); coreLine.append(">"); // coreLine.append(";ct=???"); coreLine.append(";rt=\"" + resource.getResourceType() + "\""); // coreLine.append(";if=\"observations\""); coreStrings.put(resource, coreLine.toString()); } } private String buildCoreString(String resourceType) { /* TODO: implement filtering also with ct and if*/ HashMap<String, Resource> resources = server.getResources(); StringBuilder returnString = new StringBuilder(); for (Resource resource : resources.values()){ if (resourceType == null || resource.getResourceType() == resourceType) { returnString.append("<"); returnString.append(resource.getPath()); returnString.append(">"); // coreLine.append(";ct=???"); if (resource.getResourceType() != null) { returnString.append(";rt=\"" + resource.getResourceType() + "\""); } // coreLine.append(";if=\"observations\""); returnString.append(","); } } return returnString.toString(); } @Override public byte[] getValue(Vector<String> queries) { for (String query : queries) { if (query.startsWith("rt=")) return buildCoreString(query.substring(3)).getBytes(); } return getValue(); } @Override public String getResourceType() { // TODO implement return null; } @Override public CoapMediaType getCoapMediaType() { return CoapMediaType.link_format; } @Override public void post(byte[] data) { /* nothing happens in case of a post */ return; } @Override public void changed() { } @Override public void registerServerListener(ResourceServer server) { this.serverListener = server; } @Override public void unregisterServerListener(ResourceServer server) { this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { // TODO: implement. Is this resource observeable? (should) return false; } @Override public void removeObserver(CoapChannel channel) { // TODO: implement. Is this resource observeable? (should) } @Override public boolean isObservable() { return false; } public int getObserveSequenceNumber(){ return 0; } @Override public long expires() { /* expires never */ return -1; } @Override public boolean isExpired() { return false; } }
Java
package org.ws4d.coap.rest; import java.util.Vector; /** * A resource known from the REST architecture style. A resource has a type, * name and data associated with it. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public interface Resource { /** * Get the MIME Type of the resource (e.g., "application/xml") * @return The MIME Type of this resource as String. */ public String getMimeType(); /** * Get the unique name of this resource * @return The unique name of the resource. */ public String getPath(); public String getShortName(); public byte[] getValue(); public byte[] getValue(Vector<String> query); //TODO: bad api: no return value public void post(byte[] data); public String getResourceType(); public void registerServerListener(ResourceServer server); public void unregisterServerListener(ResourceServer server); }
Java
package org.ws4d.coap.rest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceHandler { public void onPost(byte[] data); }
Java
package org.ws4d.coap.rest; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResource extends Resource { /* returns the CoAP Media Type */ public CoapMediaType getCoapMediaType(); /* called by the application, when the resource state changed -> used for observation */ public void changed(); /* called by the server to register a new observer, returns false if resource is not observable */ public boolean addObserver(CoapRequest request); /* removes an observer from the list */ public void removeObserver(CoapChannel channel); /* returns if the resource is observable */ public boolean isObservable(); /* returns if the resource is observable */ public int getObserveSequenceNumber(); /* returns the unix time when resource expires, -1 for never */ public long expires(); public boolean isExpired(); }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public final class Constants { public final static int MESSAGE_ID_MIN = 0; public final static int MESSAGE_ID_MAX = 65535; public final static int COAP_MESSAGE_SIZE_MAX = 1152; public final static int COAP_DEFAULT_PORT = 5683; public final static int COAP_DEFAULT_MAX_AGE_S = 60; public final static int COAP_DEFAULT_MAX_AGE_MS = COAP_DEFAULT_MAX_AGE_S * 1000; }
Java
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestServer { private static PlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { if (args.length > 1 || args.length < 1) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); plugtestServer = new PlugtestServer(); plugtestServer.start(args[0]); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start(String testId) { System.out.println("===Run Test Server: " + testId + "==="); init(); if (testId.equals("TD_COAP_CORE_01")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_02")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_03")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_04")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_05")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_06")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_07")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_08")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_09")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_10")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_11")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_12")) { resourceServer.createResource(new LongPathResource()); run(); } else if (testId.equals("TD_COAP_CORE_13")) { resourceServer.createResource(new QueryResource()); run(); } else if (testId.equals("TD_COAP_CORE_14")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_15")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_16")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_LINK_01")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_LINK_02")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_BLOCK_01")) { } else if (testId.equals("TD_COAP_BLOCK_02")) { } else if (testId.equals("TD_COAP_BLOCK_03")) { } else if (testId.equals("TD_COAP_BLOCK_04")) { } else if (testId.equals("TD_COAP_OBS_01")) { } else if (testId.equals("TD_COAP_OBS_02")) { } else if (testId.equals("TD_COAP_OBS_03")) { } else if (testId.equals("TD_COAP_OBS_04")) { } else if (testId.equals("TD_COAP_OBS_05")) { } else { System.out.println("unknown test case"); System.exit(-1); } } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.test; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public class PlugtestSeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; int separateResponseTimeMs = 4000; public void start(int separateResponseTimeMs){ CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(this, PORT); this.separateResponseTimeMs = separateResponseTimeMs; } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); (new Thread( new SendDelayedResponse())).start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(separateResponseTimeMs); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); System.out.println("Send separate Response: " + response.toString()); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
Java
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CompletePlugtestServer { private static CompletePlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { logger.setLevel(Level.WARNING); plugtestServer = new CompletePlugtestServer(); plugtestServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start() { System.out.println("===Run Test Server ==="); init(); resourceServer.createResource(new TestResource()); resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new QueryResource()); run(); } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
Java
/** * Client Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestClient implements CoapClient{ CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; CoapRequest request = null; private static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class.getName()); boolean exitAfterResponse = true; String serverAddress = null; int serverPort = 0; String filter = null; public static void main(String[] args) { if (args.length > 4 || args.length < 4) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); PlugtestClient client = new PlugtestClient(); client.start(args[0], Integer.parseInt(args[1]), args[2], args[3]); } public void start(String serverAddress, int serverPort, String testcase, String filter){ System.out.println("===START=== (Run Test Client: " + testcase + ")"); String testId = testcase; this.serverAddress = serverAddress; this.serverPort = serverPort; this.filter = filter; if (testId.equals("TD_COAP_CORE_01")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_02")) { init(true, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_03")) { init(true, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_04")) { init(true, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_05")) { init(false, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_06")) { init(false, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_07")) { init(false, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_08")) { init(false, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_09")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_10")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); request.setToken("AABBCCDD".getBytes()); } else if (testId.equals("TD_COAP_CORE_11")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_12")) { init(true, CoapRequestCode.GET); request.setUriPath("/seg1/seg2/seg3"); } else if (testId.equals("TD_COAP_CORE_13")) { init(true, CoapRequestCode.GET); request.setUriPath("/query"); request.setUriQuery("first=1&second=2&third=3"); } else if (testId.equals("TD_COAP_CORE_14")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_15")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_16")) { init(false, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_LINK_01")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); } else if (testId.equals("TD_COAP_LINK_02")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); request.setUriQuery("rt=" + this.filter); } else { System.out.println("===Failure=== (unknown test case)"); System.exit(-1); } run(); } public void init(boolean reliable, CoapRequestCode requestCode) { channelManager = BasicCoapChannelManager.getInstance(); channelManager.setMessageId(1000); try { clientChannel = channelManager.connect(this, InetAddress.getByName(this.serverAddress), this.serverPort); if (clientChannel == null){ System.out.println("Connect failed."); System.exit(-1); } request = clientChannel.createRequest(reliable, requestCode); } catch (UnknownHostException e) { e.printStackTrace(); System.exit(-1); } } public void run() { if(request.getPayload() != null){ System.out.println("Send Request: " + request.toString() + " (" + new String(request.getPayload()) +")"); }else { System.out.println("Send Request: " + request.toString()); } clientChannel.sendMessage(request); } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); System.exit(-1); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { if (response.getPayload() != null){ System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) +")"); } else { System.out.println("Response: " + response.toString()); } if (exitAfterResponse){ System.out.println("===END==="); System.exit(0); } } public class WaitAndExit implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("===END==="); System.exit(0); } } }
Java
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapBlockClient implements CoapClient { private static final String SERVER_ADDRESS = "129.132.15.80"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapBlockClient client = new BasicCoapBlockClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); coapRequest.setUriPath("/large"); clientChannel.setMaxReceiveBlocksize(CoapBlockSize.BLOCK_64); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); System.out.println(response.toString()); System.out.println(new String(response.getPayload())); } }
Java
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClient implements CoapClient { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapClient client = new BasicCoapClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); // coapRequest.setContentType(CoapMediaType.octet_stream); // coapRequest.setToken("ABCD".getBytes()); // coapRequest.setUriHost("123.123.123.123"); // coapRequest.setUriPort(1234); // coapRequest.setUriPath("/sub1/sub2/sub3/"); // coapRequest.setUriQuery("a=1&b=2&c=3"); // coapRequest.setProxyUri("http://proxy.org:1234/proxytest"); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); } }
Java
package org.ws4d.coap.udp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class UDPRelay { public static final int SERVER_PORT = 6000; public static final int CLIENT_PORT = 8000; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 public static void main(String[] args) { if (args.length < 2){ System.out.println("expected parameter: server host and port, e.g. 192.168.1.1 1234"); System.exit(-1); } UDPRelay relay = new UDPRelay(); relay.run(new InetSocketAddress(args[0], Integer.parseInt(args[1]))); } private DatagramChannel serverChannel = null; private DatagramChannel clientChannel = null; ByteBuffer serverBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); ByteBuffer clientBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); Selector selector = null; InetSocketAddress clientAddr = null; public void run(InetSocketAddress serverAddr) { try { serverChannel = DatagramChannel.open(); serverChannel.socket().bind(new InetSocketAddress(SERVER_PORT)); serverChannel.configureBlocking(false); serverChannel.connect(serverAddr); clientChannel = DatagramChannel.open(); clientChannel.socket().bind(new InetSocketAddress(CLIENT_PORT)); clientChannel.configureBlocking(false); try { selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_READ); clientChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); System.out.println("Initialization failed, Shut down"); System.exit(-1); } System.out.println("Start UDP Realy on Server Port " + SERVER_PORT + " and Client Port " + CLIENT_PORT); int serverLen = 0; while (true) { /* Receive Packets */ InetSocketAddress tempClientAddr = null; try { clientBuffer.clear(); tempClientAddr = (InetSocketAddress) clientChannel.receive(clientBuffer); clientBuffer.flip(); serverBuffer.clear(); serverLen = serverChannel.read(serverBuffer); serverBuffer.flip(); } catch (IOException e1) { e1.printStackTrace(); System.out.println("Read failed"); } /* forward/send packets client -> server*/ if (tempClientAddr != null) { /* the client address is obtained automatically by the first request of the client * clientAddr is the last known valid address of the client */ clientAddr = tempClientAddr; try { serverChannel.write(clientBuffer); System.out.println("Forwarded Message client ("+clientAddr.getHostName()+" "+clientAddr.getPort() + ") -> server (" + serverAddr.getHostName()+" " + serverAddr.getPort() + "): " + clientBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* forward/send packets server -> client*/ if (serverLen > 0) { try { clientChannel.send(serverBuffer, clientAddr); System.out.println("Forwarded Message server ("+serverAddr.getHostName()+" "+serverAddr.getPort() + ") -> client (" + clientAddr.getHostName()+" " + clientAddr.getPort() + "): " + serverBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* Select */ try { selector.select(2000); } catch (IOException e) { e.printStackTrace(); System.out.println("select failed"); } } } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); BasicCoapServer server = new BasicCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()+ " URI: " + request.getUriPath()); CoapMessage response = channel.createResponse(request, CoapResponseCode.Content_205); response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); if (request.getObserveOption() != null){ System.out.println("Client wants to observe this resource."); } response.setObserveOption(1); channel.sendMessage(response); } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate response transmission failed."); } }
Java
package org.ws4d.coap.server; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.rest.ResourceHandler; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CoapSampleResourceServer { private static CoapSampleResourceServer sampleServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(CoapSampleResourceServer.class.getName()); /** * @param args */ public static void main(String[] args) { logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.INFO); logger.info("Start Sample Resource Server"); sampleServer = new CoapSampleResourceServer(); sampleServer.run(); } private void run() { if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); /* Show detailed logging of Resource Server*/ Logger resourceLogger = Logger.getLogger(CoapResourceServer.class.getName()); resourceLogger.setLevel(Level.ALL); /* add resources */ BasicCoapResource light = new BasicCoapResource("/test/light", "Content".getBytes(), CoapMediaType.text_plain); light.registerResourceHandler(new ResourceHandler() { @Override public void onPost(byte[] data) { System.out.println("Post to /test/light"); } }); light.setResourceType("light"); light.setObservable(true); resourceServer.createResource(light); try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } int counter = 0; while(true){ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } counter++; light.setValue(((String)"Message #" + counter).getBytes()); light.changed(); } } }
Java
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class SeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); SeparateResponseCoapServer server = new SeparateResponseCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); Thread t = new Thread( new SendDelayedResponse() ); t.start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.ContentListener; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; /** * This class is used to consume an entity and get the entity-data as byte-array. * The only other class which implements ContentListener is SkipContentListener. * SkipContentListener is ignoring all content. * Look at Apache HTTP Components Core NIO Framework -> Java-Documentation of SkipContentListener. */ /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ class ByteContentListener implements ContentListener { final SimpleInputBuffer input = new SimpleInputBuffer(2048, new HeapByteBufferAllocator()); public void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException { input.consumeContent(decoder); } public void finish() { input.reset(); } byte[] getContent() throws IOException { byte[] b = new byte[input.length()]; input.read(b); return b; } @Override public void contentAvailable(ContentDecoder decoder, IOControl arg1) throws IOException { input.consumeContent(decoder); } @Override public void finished() { input.reset(); } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.InetAddress; import java.net.URI; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMessageContext { /*unique for reqMessageID, remoteHost, remotePort*/ /* * Server Client * inRequest +--------+ TRANSFORM +--------+ outRequest * ------------->| |-----|||---->| |-------------> * | | | | * outResponse | | TRANSFORM | | inResponse * <-------------| |<----|||-----| |<------------- * +--------+ +--------+ * */ /* incomming messages */ private CoapRequest inCoapRequest; //the coapRequest of the origin client (maybe translated) private HttpRequest inHttpRequest; //the httpRequest of the origin client (maybe translated) private CoapResponse inCoapResponse; //the coap response of the final server private HttpResponse inHttpResponse; //the http response of the final server /* generated outgoing messages */ private CoapResponse outCoapResponse; //the coap response send to the client private CoapRequest outCoapRequest; private HttpResponse outHttpResponse; private HttpUriRequest outHttpRequest; /* trigger and channels*/ private CoapClientChannel outCoapClientChannel; NHttpResponseTrigger trigger; //needed by http /* corresponding cached resource*/ private ProxyResource resource; private URI uri; private InetAddress clientAddress; private int clientPort; private InetAddress serverAddress; private int serverPort; /* is true if a translation was done (always true for incoming http requests)*/ private boolean translate; //translate from coap to http /* indicates that the response comes from the cache*/ private boolean cached = false; /* in case of a HTTP Head this is true, GET and HEAD are both mapped to CoAP GET */ private boolean httpHeadMethod = false; /* times */ long requestTime; long responseTime; public ProxyMessageContext(CoapRequest request, boolean translate, URI uri) { this.inCoapRequest = request; this.translate = translate; this.uri = uri; } public ProxyMessageContext(HttpRequest request, boolean translate, URI uri, NHttpResponseTrigger trigger) { this.inHttpRequest = request; this.translate = translate; this.uri = uri; this.trigger = trigger; } public boolean isCoapRequest(){ return inCoapRequest != null; } public boolean isHttpRequest(){ return inHttpRequest != null; } public CoapRequest getInCoapRequest() { return inCoapRequest; } public void setInCoapRequest(CoapRequest inCoapRequest) { this.inCoapRequest = inCoapRequest; } public HttpRequest getInHttpRequest() { return inHttpRequest; } public void setInHttpRequest(HttpRequest inHttpRequest) { this.inHttpRequest = inHttpRequest; } public CoapResponse getInCoapResponse() { return inCoapResponse; } public void setInCoapResponse(CoapResponse inCoapResponse) { this.inCoapResponse = inCoapResponse; } public HttpResponse getInHttpResponse() { return inHttpResponse; } public void setInHttpResponse(HttpResponse inHttpResponse) { this.inHttpResponse = inHttpResponse; } public CoapResponse getOutCoapResponse() { return outCoapResponse; } public void setOutCoapResponse(CoapResponse outCoapResponse) { this.outCoapResponse = outCoapResponse; } public CoapRequest getOutCoapRequest() { return outCoapRequest; } public void setOutCoapRequest(CoapRequest outCoapRequest) { this.outCoapRequest = outCoapRequest; } public HttpResponse getOutHttpResponse() { return outHttpResponse; } public void setOutHttpResponse(HttpResponse outHttpResponse) { this.outHttpResponse = outHttpResponse; } public HttpUriRequest getOutHttpRequest() { return outHttpRequest; } public void setOutHttpRequest(HttpUriRequest outHttpRequest) { this.outHttpRequest = outHttpRequest; } public CoapClientChannel getOutCoapClientChannel() { return outCoapClientChannel; } public void setOutCoapClientChannel(CoapClientChannel outClientChannel) { this.outCoapClientChannel = outClientChannel; } public InetAddress getClientAddress() { return clientAddress; } public void setClientAddress(InetAddress clientAddress, int clientPort) { this.clientAddress = clientAddress; this.clientPort = clientPort; } public InetAddress getServerAddress() { return serverAddress; } public void setServerAddress(InetAddress serverAddress, int serverPort) { this.serverAddress = serverAddress; this.serverPort = serverPort; } public int getClientPort() { return clientPort; } public int getServerPort() { return serverPort; } public boolean isTranslate() { return translate; } public void setTranslatedCoapRequest(CoapRequest request) { this.inCoapRequest = request; } public void setTranslatedHttpRequest(HttpRequest request) { this.inHttpRequest = request; } public URI getUri() { return uri; } public NHttpResponseTrigger getTrigger() { return trigger; } public boolean isCached() { return cached; } public void setCached(boolean cached) { this.cached = cached; } public ProxyResource getResource() { return resource; } public void setResource(ProxyResource resource) { this.resource = resource; } public void setHttpHeadMethod(boolean httpHeadMethod) { this.httpHeadMethod = httpHeadMethod; } public boolean isHttpHeadMethod() { return httpHeadMethod; } public long getRequestTime() { return requestTime; } public void setRequestTime(long requestTime) { this.requestTime = requestTime; } public long getResponseTime() { return responseTime; } public void setResponseTime(long responseTime) { this.responseTime = responseTime; } }
Java
package org.ws4d.coap.proxy; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; public class ProxyResource extends BasicCoapResource { static Logger logger = Logger.getLogger(Proxy.class); private ProxyResourceKey key = null; public ProxyResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyResourceKey getKey() { return key; } public void setKey(ProxyResourceKey key) { this.key = key; } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> * * TODO: IMPROVE Async Server Implementation, avoid ModifiedAsyncNHttpServiceHandler and deprecated function calls */ public class HttpServerNIO extends Thread{ static Logger logger = Logger.getLogger(Proxy.class); static private int PORT = 8080; ProxyMapper mapper = ProxyMapper.getInstance(); //interface-function for other classes/modules public void sendResponse(ProxyMessageContext context) { HttpResponse httpResponse = context.getOutHttpResponse(); NHttpResponseTrigger trigger = context.getTrigger(); trigger.submitResponse(httpResponse); } public void run() { this.setName("HTTP_NIO_Server"); //parameters for connection HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 50000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); //needed by framework, don't need any processors except the connection-control HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseConnControl() }); //create own service-handler with bytecontentlistener-class ModifiedAsyncNHttpServiceHandler handler = new ModifiedAsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers, use the same request-handler for all uris NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry(); reqistry.register("*", new ProxyHttpRequestHandler()); handler.setHandlerResolver(reqistry); try { //create and start responder-thread //ioreactor is used by nio-framework to listen and react to http connections //2 dispatcher-threads are used to do the work ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); IOEventDispatch ioeventdispatch = new DefaultServerIOEventDispatch(handler, params); ioReactor.listen(new InetSocketAddress(PORT)); ioReactor.execute(ioeventdispatch); } catch (IOReactorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static class ProxyHttpRequestHandler implements NHttpRequestHandler { public ProxyHttpRequestHandler() { super(); } @Override public ConsumingNHttpEntity entityRequest( HttpEntityEnclosingRequest arg0, HttpContext arg1) throws HttpException, IOException { return null; } //handle() is called when a request is received //response is automatically generated by HttpProcessor, but use response from mapper //trigger is used for asynchronous response, see java-documentation @Override public void handle(final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, HttpContext con) throws HttpException, IOException { logger.info("incomming HTTP request"); URI uri = ProxyMapper.resolveHttpRequestUri(request); if (uri != null){ InetAddress serverAddress = InetAddress.getByName(uri.getHost()); //FIXME: blocking operation??? int serverPort = uri.getPort(); if (serverPort == -1) { serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT; } /* translate always */ ProxyMessageContext context = new ProxyMessageContext(request, true, uri, trigger); context.setServerAddress(serverAddress, serverPort); ProxyMapper.getInstance().handleHttpServerRequest(context); } else { trigger.submitResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Header: Host")); } } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class Proxy { static Logger logger = Logger.getLogger(Proxy.class); static int defaultCachingTime = Constants.COAP_DEFAULT_MAX_AGE_S; public static void main(String[] args) { CommandLineParser cmdParser = new GnuParser(); Options options = new Options(); /* Add command line options */ options.addOption("c", "default-cache-time", true, "Default caching time in seconds"); CommandLine cmd = null; try { cmd = cmdParser.parse(options, args); } catch (ParseException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } /* evaluate command line */ if(cmd.hasOption("c")) { try { defaultCachingTime = Integer.parseInt(cmd.getOptionValue("c")); if (defaultCachingTime == 0){ ProxyMapper.getInstance().setCacheEnabled(false); } System.out.println("Set caching time to " + cmd.getOptionValue("c") + " seconds (0 disables the cache)"); } catch (NumberFormatException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } } logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.ALL); HttpServerNIO httpserver = new HttpServerNIO(); HttpClientNIO httpclient = new HttpClientNIO(); CoapClientProxy coapclient = new CoapClientProxy(); CoapServerProxy coapserver = new CoapServerProxy(); ProxyMapper.getInstance().setHttpServer(httpserver); ProxyMapper.getInstance().setHttpClient(httpclient); ProxyMapper.getInstance().setCoapClient(coapclient); ProxyMapper.getInstance().setCoapServer(coapserver); httpserver.start(); httpclient.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("===END==="); try { Thread.sleep(500); } catch (InterruptedException e) { } } }); ProxyRestInterface restInterface = new ProxyRestInterface(); restInterface.start(); } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Element; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMapper { static Logger logger = Logger.getLogger(Proxy.class); static final int DEFAULT_MAX_AGE_MS = 60000; //Max Age Default in ms //introduce other needed classes for communication private CoapClientProxy coapClient; private CoapServerProxy coapServer; private HttpServerNIO httpServer; private HttpClientNIO httpClient; private static ProxyCache cache; private static ProxyMapper instance; /*for statistics*/ private int httpRequestCount = 0; private int coapRequestCount = 0; private int servedFromCacheCount = 0; public synchronized static ProxyMapper getInstance() { if (instance == null) { instance = new ProxyMapper(); } return instance; } private ProxyMapper() { cache = new ProxyCache(); } /* * Server Client * +------+ +------+ RequestTime * InRequ --->| |----+-->Requ.Trans.-------->| |--->OutReq * | | | | | * | | | | | * | | ERROR | | * | | | | | * | | +<---ERROR -----+ | | * | | | | | | ResponseTime * OutResp<---| +<---+<--Resp.Trans.-+-------+ |<---InResp * +------+ +------+ * * HTTP -----------------------------> CoAP * * CoAP -----------------------------> HTTP * * CoAP -----------------------------> CoAP */ public void handleHttpServerRequest(ProxyMessageContext context) { httpRequestCount++; // do not translate methods: OPTIONS,TRACE,CONNECT -> error // "Not Implemented" if (isHttpRequestMethodSupported(context.getInHttpRequest())) { // perform request-transformation /* try to get from cache */ ProxyResource resource = null; if (context.getInHttpRequest().getRequestLine().getMethod().toLowerCase().equals("get")){ resource = cache.get(context); } if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served HTTP request from cache"); servedFromCacheCount++; } else { /* not cached -> forward request */ try { coapClient.createChannel(context); //channel must be created first transRequestHttpToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("HTTP to CoAP Request failed: " + e.getMessage()); /* close if a channel was connected */ if (context.getOutCoapClientChannel() != null){ context.getOutCoapClientChannel().close(); } sendDirectHttpError(context, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } } } else { /* method not supported */ sendDirectHttpError(context, HttpStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); } } public void handleCoapServerRequest(ProxyMessageContext context) { coapRequestCount++; ProxyResource resource = null; if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.GET){ resource = cache.get(context); } if (context.isTranslate()) { /* coap to http */ if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served CoAP request from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> HTTP Request */ try { transRequestCoapToHttp(context); context.setRequestTime(System.currentTimeMillis()); httpClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to HTTP Request translation failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } else { /* coap to coap */ if (resource != null) { /* answer from cache */ resourceToCoap(context, resource); context.setCached(true); // avoid "recaching" coapServer.sendResponse(context); logger.info("served from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> CoAP Request */ try { coapClient.createChannel(context); //channel must be created first transRequestCoapToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to CoAP Request forwarding failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } } public void handleCoapClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached() && context.getInCoapResponse() !=null ) { // avoid recaching cache.cacheCoapResponse(context); } if (context.isTranslate()) { /* coap to HTTP */ try { transResponseCoapToHttp(context); } catch (Exception e) { logger.warn("CoAP to HTTP Response translation failed: " + e.getMessage()); context.setOutHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error")); } httpServer.sendResponse(context); } else { /* coap to coap */ try { transResponseCoapToCoap(context); } catch (Exception e) { logger.warn("CoAP to CoAP Response forwarding failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } } public void handleHttpClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached()) { cache.cacheHttpResponse(context); } try { transResponseHttpToCoap(context); } catch (Exception e) { logger.warn("HTTP to CoAP Response translation failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } /* ------------------------------------ Translate Functions -----------------------------------*/ public static void transRequestCoapToCoap(ProxyMessageContext context){ CoapRequest in = context.getInCoapRequest(); CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, in.getRequestCode())); CoapRequest out = context.getOutCoapRequest(); /*TODO: translate not using copy header options */ ((BasicCoapRequest) out).copyHeaderOptions((BasicCoapRequest)in); /* TODO: check if the next hop is a proxy or the final serer * implement coapUseProxy option for proxy */ out.removeOption(CoapHeaderOptionType.Proxy_Uri); out.setUriPath(context.getUri().getPath()); if (context.getUri().getQuery() != null){ out.setUriQuery(context.getUri().getQuery()); } out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transRequestHttpToCoap(ProxyMessageContext context) throws IOException { HttpRequest httpRequest = context.getInHttpRequest(); boolean hasContent = false; CoapRequestCode requestCode; String method; method = httpRequest.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("get")) { requestCode = CoapRequestCode.GET; } else if (method.contentEquals("put")) { requestCode = CoapRequestCode.PUT; hasContent = true; } else if (method.contentEquals("post")) { requestCode = CoapRequestCode.POST; hasContent = true; } else if (method.contentEquals("delete")) { requestCode = CoapRequestCode.DELETE; } else if (method.contentEquals("head")) { // if we have a head request, coap should handle it as a get, // but without any message-body requestCode = CoapRequestCode.GET; context.setHttpHeadMethod(true); } else { throw new IllegalStateException("unknown message code"); } CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, requestCode)); // Translate Headers CoapRequest coapRequest = context.getOutCoapRequest(); URI uri = null; // construct uri for later use uri = resolveHttpRequestUri(httpRequest); // Content-Type is in response only // Max-Age is in response only // Proxy-Uri doesn't matter for this purpose // ETag: if (httpRequest.containsHeader("Etag")) { Header[] headers = httpRequest.getHeaders("Etag"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { String etag = headers[i].getValue(); coapRequest.addETag(etag.getBytes()); } } } // Uri-Host: // don't needs to be there // Location-Path is in response-only // Location-Query is in response-only // Uri-Path: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { coapRequest.setUriPath(uri.getPath()); } else { throw new IllegalStateException("uri has wrong format"); } // Token is the same number as msgID, not needed now // in future development it should be generated here // Accept: possible values are numeric media-types if (httpRequest.containsHeader("Accept")) { Header[] headers = httpRequest.getHeaders("Accept"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { httpMediaType2coapMediaType(headers[i].getValue(), coapRequest); } } } // TODO: if-match: // if (request.containsHeader("If-Match")) { // Header[] headers = request.getHeaders("If-Match"); // if (headers.length > 0) { // for (int i=0; i < headers.length; i++) { // String header_value = headers[i].getValue(); // CoapHeaderOption option_ifmatch = new // CoapHeaderOption(CoapHeaderOptionType.If_Match, // header_value.getBytes()); // header.addOption(option_ifmatch ); // } // } // } // Uri-Query: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { if (uri.getQuery() != null) { // only add options if there are // some coapRequest.setUriQuery(uri.getQuery()); } } else { throw new IllegalStateException("uri has wrong format"); } // TODO: If-None-Match: // if (request.containsHeader("If-None-Match")) { // Header[] headers = request.getHeaders("If-None-Match"); // if (headers.length > 0) { // if (headers.length > 1) { // System.out.println("multiple headers in request, ignoring all except the first"); // } // String header_value = headers[0].getValue(); // CoapHeaderOption option_ifnonematch = new // CoapHeaderOption(CoapHeaderOptionType.If_None_Match, // header_value.getBytes()); // header.addOption(option_ifnonematch); // } // } // pass-through the payload if (hasContent){ BasicHttpEntityEnclosingRequest entirequest = (BasicHttpEntityEnclosingRequest) httpRequest; ConsumingNHttpEntityTemplate entity = (ConsumingNHttpEntityTemplate) entirequest.getEntity(); ByteContentListener listener = (ByteContentListener) entity.getContentListener(); byte[] data = listener.getContent(); context.getOutCoapRequest().setPayload(data); } } public static void transRequestCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ HttpUriRequest httpRequest; CoapRequest request = context.getInCoapRequest(); CoapRequestCode code = request.getRequestCode(); //TODO:translate header options from coap-request to http-request NStringEntity entity; entity = new NStringEntity(new String(request.getPayload())); switch (code) { case GET: httpRequest = new HttpGet(context.getUri().toString()); break; case PUT: httpRequest = new HttpPut(context.getUri().toString()); ((HttpPut)httpRequest).setEntity(entity); break; case POST: httpRequest = new HttpPost(context.getUri().toString()); ((HttpPost)httpRequest).setEntity(entity); break; case DELETE: httpRequest = new HttpDelete(context.getUri().toString()); default: throw new IllegalStateException("unknown request code"); } context.setOutHttpRequest(httpRequest); } public static void transResponseCoapToCoap(ProxyMessageContext context){ CoapResponse in = context.getInCoapResponse(); CoapResponse out = context.getOutCoapResponse(); /*TODO: translate not using copy header options */ ((BasicCoapResponse) out).copyHeaderOptions((BasicCoapResponse)in); out.setResponseCode(in.getResponseCode()); out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transResponseCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ CoapResponse coapResponse = context.getInCoapResponse(); //create a response-object, set http version and assume a default state of ok HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); // differ between methods is necessary to set the right status-code String requestMethod = context.getInHttpRequest().getRequestLine().getMethod(); if (requestMethod.toLowerCase().contains("get")){ // set status code and reason phrase setHttpMsgCode(coapResponse, "get", httpResponse); // pass-through the payload, if we do not answer a head-request if (!context.isHttpHeadMethod()) { NStringEntity entity; entity = new NStringEntity(new String(coapResponse.getPayload()), "UTF-8"); entity.setContentType("text/plain"); httpResponse.setEntity(entity); } } else if (requestMethod.toLowerCase().contains("put")){ setHttpMsgCode(coapResponse, "put", httpResponse); } else if (requestMethod.toLowerCase().contains("post")){ setHttpMsgCode(coapResponse, "post", httpResponse); } else if (requestMethod.toLowerCase().contains("delete")){ setHttpMsgCode(coapResponse, "delete", httpResponse); } else { throw new IllegalStateException("unknown request method"); } // set Headers headerTranslateCoapToHttp(coapResponse, httpResponse); context.setOutHttpResponse(httpResponse); } public static void transResponseHttpToCoap(ProxyMessageContext context) throws ParseException, IOException{ //set the response-code according to response-code-mapping-table CoapResponse coapResponse = context.getOutCoapResponse(); coapResponse.setResponseCode(getCoapResponseCode(context)); //throws an exception if mapping failed //TODO: translate header-options //assume in this case a string-entity //TODO: add more entity-types coapResponse.setContentType(CoapMediaType.text_plain); String entity = ""; entity = EntityUtils.toString(context.getInHttpResponse().getEntity()); coapResponse.setPayload(entity); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectHttpError(ProxyMessageContext context,int code, String reason){ HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, code, reason); context.setOutHttpResponse(httpResponse); httpServer.sendResponse(context); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectCoapError(ProxyMessageContext context, CoapResponseCode code){ CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel(); CoapResponse response = channel.createResponse(context.getInCoapRequest(), code); context.setInCoapResponse(response); coapServer.sendResponse(context); } public static void resourceToHttp(ProxyMessageContext context, ProxyResource resource){ /* TODO: very rudimentary implementation */ HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); try { NStringEntity entity; entity = new NStringEntity(new String(resource.getValue()), "UTF-8"); entity.setContentType("text/plain"); response.setEntity(entity); } catch (UnsupportedEncodingException e) { logger.error("HTTP entity creation failed"); } context.setOutHttpResponse(response); } public static void resourceToCoap(ProxyMessageContext context, ProxyResource resource){ CoapResponse response = context.getOutCoapResponse(); //already generated /* response code */ response.setResponseCode(CoapResponseCode.Content_205); /* payload */ response.setPayload(resource.getValue()); /* mediatype */ if (resource.getCoapMediaType() != null) { response.setContentType(resource.getCoapMediaType()); } /* Max-Age */ int maxAge = (int)(resource.expires() - System.currentTimeMillis()) / 1000; if (maxAge < 0){ /* should never happen because the function is only called if the resource is valid. * However, processing time can be an issue */ logger.warn("return expired resource (Max-Age = 0)"); maxAge = 0; } response.setMaxAge(maxAge); } public static void setHttpMsgCode(CoapResponse coapResponse, String requestMethod, HttpResponse httpResponse) { CoapResponseCode responseCode = coapResponse.getResponseCode(); switch(responseCode) { // case OK_200: { //removed from CoAP draft // httpResponse.setStatusCode(HttpStatus.SC_OK); // httpResponse.setReasonPhrase("Ok"); // break; // } case Created_201: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_CREATED); httpResponse.setReasonPhrase("Created"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Deleted_202: { if (requestMethod.contains("delete")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Valid_203: { httpResponse.setStatusCode(HttpStatus.SC_NOT_MODIFIED); httpResponse.setReasonPhrase("Not Modified"); break; } case Changed_204: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Content_205: { if (requestMethod.contains("get")) { httpResponse.setStatusCode(HttpStatus.SC_OK); httpResponse.setReasonPhrase("OK"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Bad_Request_400: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request"); break; } case Unauthorized_401: { httpResponse.setStatusCode(HttpStatus.SC_UNAUTHORIZED); httpResponse.setReasonPhrase("Unauthorized"); break; } case Bad_Option_402: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Option"); break; } case Forbidden_403: { httpResponse.setStatusCode(HttpStatus.SC_FORBIDDEN); httpResponse.setReasonPhrase("Forbidden"); break; } case Not_Found_404: { httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND); httpResponse.setReasonPhrase("Not Found"); break; } case Method_Not_Allowed_405: { httpResponse.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); httpResponse.setReasonPhrase("Method Not Allowed"); break; } case Precondition_Failed_412: { httpResponse.setStatusCode(HttpStatus.SC_PRECONDITION_FAILED); httpResponse.setReasonPhrase("Precondition Failed"); break; } case Request_Entity_To_Large_413: { httpResponse.setStatusCode(HttpStatus.SC_REQUEST_TOO_LONG); httpResponse.setReasonPhrase("Request Too Long : Request entity too large"); break; } case Unsupported_Media_Type_415: { httpResponse.setStatusCode(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); httpResponse.setReasonPhrase("Unsupported Media Type"); break; } case Internal_Server_Error_500: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error"); break; } case Not_Implemented_501: { httpResponse.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); httpResponse.setReasonPhrase("Not Implemented"); break; } case Bad_Gateway_502: { httpResponse.setStatusCode(HttpStatus.SC_BAD_GATEWAY); httpResponse.setReasonPhrase("Bad Gateway"); break; } case Service_Unavailable_503: { httpResponse.setStatusCode(HttpStatus.SC_SERVICE_UNAVAILABLE); httpResponse.setReasonPhrase("Service Unavailable"); break; } case Gateway_Timeout_504: { httpResponse.setStatusCode(HttpStatus.SC_GATEWAY_TIMEOUT); httpResponse.setReasonPhrase("Gateway Timeout"); break; } case Proxying_Not_Supported_505: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error : Proxying not supported"); break; } case UNKNOWN: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } default: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } } } //sets the coap-response code under use of http-status code; used in case coap-http public static CoapResponseCode getCoapResponseCode(ProxyMessageContext context) { HttpResponse httpResponse = context.getInHttpResponse(); //TODO: add cases in which http-code is the same, but coap-code is different, look at response-code-mapping-table switch(httpResponse.getStatusLine().getStatusCode()) { case HttpStatus.SC_CREATED: return CoapResponseCode.Created_201; case HttpStatus.SC_NO_CONTENT: if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.DELETE) { return CoapResponseCode.Deleted_202; } else { return CoapResponseCode.Changed_204; } case HttpStatus.SC_NOT_MODIFIED: return CoapResponseCode.Valid_203; case HttpStatus.SC_OK: return CoapResponseCode.Content_205; case HttpStatus.SC_UNAUTHORIZED: return CoapResponseCode.Unauthorized_401; case HttpStatus.SC_FORBIDDEN:return CoapResponseCode.Forbidden_403; case HttpStatus.SC_NOT_FOUND:return CoapResponseCode.Not_Found_404; case HttpStatus.SC_METHOD_NOT_ALLOWED:return CoapResponseCode.Method_Not_Allowed_405; case HttpStatus.SC_PRECONDITION_FAILED: return CoapResponseCode.Precondition_Failed_412; case HttpStatus.SC_REQUEST_TOO_LONG: return CoapResponseCode.Request_Entity_To_Large_413; case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:return CoapResponseCode.Unsupported_Media_Type_415; case HttpStatus.SC_INTERNAL_SERVER_ERROR:return CoapResponseCode.Internal_Server_Error_500; case HttpStatus.SC_NOT_IMPLEMENTED:return CoapResponseCode.Not_Implemented_501; case HttpStatus.SC_BAD_GATEWAY:return CoapResponseCode.Bad_Gateway_502; case HttpStatus.SC_SERVICE_UNAVAILABLE:return CoapResponseCode.Service_Unavailable_503; case HttpStatus.SC_GATEWAY_TIMEOUT:return CoapResponseCode.Gateway_Timeout_504; default: throw new IllegalStateException("unknown HTTP response code"); } } //mediatype-mapping: public static void httpMediaType2coapMediaType(String mediatype, CoapRequest request) { String[] type_subtype = mediatype.split(","); for (String value : type_subtype) { if (value.toLowerCase().contains("text") && value.toLowerCase().contains("plain")) { request.addAccept(CoapMediaType.text_plain); } else if (value.toLowerCase().contains("application")) { // value is for example "application/xml;q=0.9" String[] subtypes = value.toLowerCase().split("/"); String subtype = ""; if (subtypes.length == 2) { subtype = subtypes[1]; // subtype is for example now "xml;q=0.9" } else { System.out.println("Error in reading Mediatypes!"); } // extract the subtype-name and remove the quality identifiers: String[] subname = subtype.split(";"); String name = ""; if (subname.length > 0) { name = subname[0]; // name is for example "xml" } else { System.out.println("Error in reading Mediatypes!"); } if (name.contentEquals("link-format")) { request.addAccept(CoapMediaType.link_format); } if (name.contentEquals("xml")) { request.addAccept(CoapMediaType.xml); } if (name.contentEquals("octet-stream")) { request.addAccept(CoapMediaType.octet_stream); } if (name.contentEquals("exi")) { request.addAccept(CoapMediaType.exi); } if (name.contentEquals("json")) { request.addAccept(CoapMediaType.json); } } } } // translate response-header-options in case of http-coap public static void headerTranslateCoapToHttp(CoapResponse coapResponse, HttpResponse httpResponse) { // investigate all coap-headers and set corresponding http-headers CoapMediaType contentType = coapResponse.getContentType(); if (contentType != null) { switch (contentType) { case text_plain: httpResponse.addHeader("Content-Type", "text/plain"); break; case link_format: httpResponse.addHeader("Content-Type", "application/link-format"); break; case json: httpResponse.addHeader("Content-Type", "application/json"); break; case exi: httpResponse.addHeader("Content-Type", "application/exi"); break; case octet_stream: httpResponse.addHeader("Content-Type", "application/octet-stream"); break; case xml: httpResponse.addHeader("Content-Type", "application/xml"); break; default: httpResponse.addHeader("Content-Type", "text/plain"); break; } } else { httpResponse.addHeader("Content-Type", "text/plain"); } long maxAge = coapResponse.getMaxAge(); if (maxAge < 0){ maxAge = DEFAULT_MAX_AGE_MS; } long maxAgeMs = maxAge * 1000; if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE){ httpResponse.addHeader("Retry-After", String.valueOf(maxAge)); } byte[] etag = coapResponse.getETag(); if (etag != null){ httpResponse.addHeader("Etag", new String(etag)); } //generate content-length-header if (httpResponse.getEntity() != null) httpResponse.addHeader("Content-length", "" + httpResponse.getEntity().getContentLength()); //set creation-date for Caching: httpResponse.addHeader("Date", "" + formatDate(new GregorianCalendar().getTime())); //expires-option is option-value (default is 60 secs) + current_date Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(calendar.getTimeInMillis() + maxAgeMs); String date = formatDate(calendar.getTime()); httpResponse.addHeader("Expires", date); } public static HttpResponse handleCoapDELETEresponse(CoapResponse response, HttpResponse httpResponse) { //set status code and reason phrase headerTranslateCoapToHttp(response, httpResponse); return httpResponse; } // //the mode is used to indicate for which case the proxy is listening to // //mode is unneccessary when proxy is listening to all cases, then there are more threads neccessary // public void setMode(Integer modenumber) { // mode = modenumber; // } //setter-functions to introduce other threads public void setHttpServer(HttpServerNIO server) { httpServer = server; } public void setHttpClient(HttpClientNIO client) { httpClient = client; } public void setCoapServer(CoapServerProxy server) { coapServer = server; } public void setCoapClient(CoapClientProxy client) { coapClient = client; } //exclude methods from processing:OPTIONS/TRACE/CONNECT public static boolean isHttpRequestMethodSupported(HttpRequest request) { String method = request.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("options") || method.contentEquals("trace") || method.contentEquals("connect")) return false; return true; } //makes a date to a string; http-header-values (expires, date...) must be a string in most cases public static String formatDate(Date date) { final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; if (date == null) { throw new IllegalArgumentException("date is null"); } SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST String ret = formatter.format(date); return ret; } public static URI resolveHttpRequestUri(HttpRequest request){ URI uri = null; String uriString = request.getRequestLine().getUri(); /* make sure to have the scheme */ if (uriString.startsWith("coap://")){ /* do nothing */ } else if (uriString.startsWith("http://")){ uriString = "coap://" + uriString.substring(7); } else { /* not an absolute uri */ Header[] host = request.getHeaders("Host"); /* only one is accepted */ if (host.length <= 0){ /* error, unknown host*/ return null; } uriString = "coap://" + host[0].getValue() + uriString; } try { uri = new URI(uriString); } catch (URISyntaxException e) { return null; //indicates that resolve failed } return uri; } public static boolean isIPv4Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet4Address addr4 = (Inet4Address) addr; return true; } catch (ClassCastException ex) { return false; } } public static boolean isIPv6Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet6Address addr6 = (Inet6Address) addr; return true; } catch (ClassCastException ex) { return false; } } public int getHttpRequestCount() { return httpRequestCount; } public int getCoapRequestCount() { return coapRequestCount; } public int getServedFromCacheCount() { return servedFromCacheCount; } public void resetCounter(){ httpRequestCount = 0; coapRequestCount = 0; servedFromCacheCount = 0; } public void setCacheEnabled(boolean enabled) { cache.setEnabled(enabled); } public CoapClientProxy getCoapClient() { return coapClient; } public CoapServerProxy getCoapServer() { return coapServer; } public HttpServerNIO getHttpServer() { return httpServer; } public HttpClientNIO getHttpClient() { return httpClient; } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.concurrent.ArrayBlockingQueue; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class CoapServerProxy implements CoapServer{ static Logger logger = Logger.getLogger(Proxy.class); private static final int LOCAL_PORT = 5683; //port on which the server is listening ProxyMapper mapper = ProxyMapper.getInstance(); //coapOUTq_ receives a coap-response from mapper in case of coap-http CoapChannelManager channelManager; //constructor of coapserver-class, initiates the jcoap-components and starts CoapSender public CoapServerProxy() { channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(this, LOCAL_PORT); } //interface-function for the message-queue public void sendResponse(ProxyMessageContext context) { CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel(); channel.sendMessage(context.getOutCoapResponse()); channel.close(); //TODO: implement strategy when to close a channel } @Override public CoapServer onAccept(CoapRequest request) { logger.info("new incomming CoAP connection"); /* accept every incoming connection */ return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { /* draft-08: * CoAP distinguishes between requests to an origin server and a request made through a proxy. A proxy is a CoAP end-point that can be tasked by CoAP clients to perform requests on their behalf. This may be useful, for example, when the request could otherwise not be made, or to service the response from a cache in order to reduce response time and network bandwidth or energy consumption. CoAP requests to a proxy are made as normal confirmable or non- confirmable requests to the proxy end-point, but specify the request URI in a different way: The request URI in a proxy request is specified as a string in the Proxy-Uri Option (see Section 5.10.3), while the request URI in a request to an origin server is split into the Uri-Host, Uri-Port, Uri-Path and Uri-Query Options (see Section 5.10.2). */ URI proxyUri = null; /* we need to cast to allow an efficient header copy */ //create a prototype response, will be changed during the translation process try { BasicCoapResponse response = (BasicCoapResponse) channel.createResponse(request, CoapResponseCode.Internal_Server_Error_500); try { proxyUri = new URI(request.getProxyUri()); } catch (Exception e) { proxyUri = null; } if (proxyUri == null) { /* PROXY URI MUST BE AVAILABLE */ logger.warn("received CoAP request without Proxy-Uri option"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); return; } /* check scheme if we should translate */ boolean translate; if (proxyUri.getScheme().compareToIgnoreCase("http") == 0) { translate = true; } else if (proxyUri.getScheme().compareToIgnoreCase("coap") == 0) { translate = false; } else { /* unknown scheme */ logger.warn("invalid proxy uri scheme"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); return; } /* parse URL */ InetAddress serverAddress = InetAddress.getByName(proxyUri.getHost()); int serverPort = proxyUri.getPort(); if (serverPort == -1) { if (translate) { /* HTTP Server */ serverPort = 80; // FIXME: use constant for HTTP well known // port } else { /* CoAP Server */ serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT; } } /* generate context and forward message */ ProxyMessageContext context = new ProxyMessageContext(request, translate, proxyUri); context.setServerAddress(serverAddress, serverPort); context.setOutCoapResponse(response); mapper.handleCoapServerRequest(context); } catch (Exception e) { logger.warn("invalid message"); channel.sendMessage(channel.createResponse(request, CoapResponseCode.Bad_Request_400)); channel.close(); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { // TODO Auto-generated method stub } }
Java
package org.ws4d.coap.proxy; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; public class ProxyRestInterface { static Logger logger = Logger.getLogger(Proxy.class); private CoapResourceServer resourceServer; public void start(){ if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); resourceServer.createResource(new ProxyStatisticResource()); try { resourceServer.start(5684); } catch (Exception e) { e.printStackTrace(); } } public class ProxyStatisticResource extends BasicCoapResource{ private ProxyStatisticResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyStatisticResource(){ this("/statistic", null, CoapMediaType.text_plain); } @Override public byte[] getValue(Vector<String> query) { StringBuilder val = new StringBuilder(); ProxyMapper.getInstance().getCoapRequestCount(); val.append("Number of HTTP Requests: " + ProxyMapper.getInstance().getHttpRequestCount() + "\n"); val.append("Number of CoAP Requests: " + ProxyMapper.getInstance().getCoapRequestCount() + "\n"); val.append("Number of Reqeusts served from cache: " + ProxyMapper.getInstance().getServedFromCacheCount() + "\n"); return val.toString().getBytes(); } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ /* * TODO's: * - implement Date option as described in "Connecting the Web with the Web of Things: Lessons Learned From Implementing a CoAP-HTTP Proxy" * - caching of HTTP resources not supported as HTTP servers may have enough resources (in terms of RAM/ROM/batery/computation) * * */ public class ProxyCache { static Logger logger = Logger.getLogger(Proxy.class); private static final int MAX_LIFETIME = Integer.MAX_VALUE; private static Cache cache; private static CacheManager cacheManager; private boolean enabled = true; private static final int defaultMaxAge = org.ws4d.coap.Constants.COAP_DEFAULT_MAX_AGE_S; private static final ProxyCacheTimePolicy cacheTimePolicy = ProxyCacheTimePolicy.Halftime; public ProxyCache() { cacheManager = CacheManager.create(); cache = new Cache(new CacheConfiguration("proxy", 100) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(true) .eternal(false) .diskPersistent(false) .diskExpiryThreadIntervalSeconds(0)); cacheManager.addCache(cache); } public void removeKey(URI uri) { cache.remove(uri); } // public void put(ProxyMessageContext context) { // if (isEnabled() || context == null){ // return; // } // //TODO: check for overwrites // // // insertElement(context.getResource().getKey(), context.getResource()); //// URI uri = context.getUri(); //// if (uri.getScheme().equalsIgnoreCase("coap")){ //// putCoapRes(uri, context.getCoapResponse()); //// } else if (uri.getScheme().equalsIgnoreCase("http")){ //// putHttpRes(uri, context.getHttpResponse()); //// } // } // private void putHttpRes(URI uri, HttpResponse response){ // if (response == null){ // return; // } // logger.info( "Cache HTTP Resource (" + uri.toString() + ")"); // //first determine what to do // int code = response.getStatusLine().getStatusCode(); // // //make some garbage collection to avoid a cache overflow caused by many expired elements (when 80% charged as first idea) // if (cache.getSize() > cache.getCacheConfiguration().getMaxElementsInMemory()*0.8) { // cache.evictExpiredElements(); // } // // //set the max-age of new element // //use the http-header-options expires and date // //difference is the same value as the corresponding max-age from coap-response, but at this point we only have a http-response // int timeToLive = 0; // Header[] expireHeaders = response.getHeaders("Expires"); // if (expireHeaders.length == 1) { // String expire = expireHeaders[0].getValue(); // Date expireDate = StringToDate(expire); // // Header[] dateHeaders = response.getHeaders("Date"); // if (dateHeaders.length == 1) { // String dvalue = dateHeaders[0].getValue(); // Date date = StringToDate(dvalue); // // timeToLive = (int) ((expireDate.getTime() - date.getTime()) / 1000); // } // } // // //cache-actions are dependent of response-code, as described in coap-rfc-draft-7 // switch(code) { // case HttpStatus.SC_CREATED: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NO_CONTENT: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NOT_MODIFIED: { // if (cache.isKeyInCache(uri)) { // insertElement(uri, response, timeToLive); //should update the response if req is already in cache // } // break; // } // default: { // insertElement(uri, response, timeToLive); // break; // } // } // } // private void putCoapRes(ProxyResourceKey key, CoapResponse response){ // if (response == null){ // return; // } // logger.debug( "Cache CoAP Resource (" + uri.toString() + ")"); // // long timeToLive = response.getMaxAge(); // if (timeToLive < 0){ // timeToLive = defaultTimeToLive; // } // insertElement(key, response); // } // // public HttpResponse getHttpRes(URI uri) { // if (defaultTimeToLive == 0) return null; // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (HttpResponse) o; // } else { // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } // // public CoapResponse getCoapRes(URI uri) { // if (defaultTimeToLive == 0) return null; // // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (CoapResponse) o; // }else{ // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } public boolean isInCache(ProxyResourceKey key) { if (!isEnabled()){ return false; } if (cache.isKeyInCache(key)) { return true; } else { return false; } } //for some operations it is necessary to build an http-date from string private static Date StringToDate(String string_date) { Date date = null; //this pattern is the official http-date format final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST, default is GMT try { date = (Date) formatter.parse(string_date); } catch (ParseException e) { e.printStackTrace(); } return date; } // //mark an element as expired // private void markExpired(ProxyResourceKey key) { // if (cache.getQuiet(key) != null) { // cache.get(key).setTimeToLive(0); // } // } private boolean insertElement(ProxyResourceKey key, ProxyResource resource) { Element elem = new Element(key, resource); if (resource.expires() == -1) { /* never expires */ cache.put(elem); } else { long ttl = resource.expires() - System.currentTimeMillis(); if (ttl > 0) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); cache.put(elem); logger.debug("cache insert: " + resource.getPath() ); } else { /* resource is already expired */ return false; } } return true; } private void updateTtl(ProxyResourceKey key, long newExpires) { /*getQuiet is used to not update statistics */ Element elem = cache.getQuiet(key); if (elem != null) { long ttl = newExpires - System.currentTimeMillis(); if (ttl > 0 || newExpires == -1 ) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); } } } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public ProxyResource get(ProxyMessageContext context) { if (!isEnabled()){ return null; } String path = context.getUri().getPath(); if(path == null){ /* no caching */ return null; } Element elem = cache.get(new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path)); logger.debug("cache get: " + context.getServerAddress().toString() + " " + context.getServerPort() + " " + path); if (elem != null) { /* found cached entry */ ProxyResource res = (ProxyResource) elem.getObjectValue(); if (!res.isExpired()) { return res; } } return null; } public void cacheHttpResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } /* TODO caching of HTTP responses currently not supported (not use to unload HTTP servers) */ return; } public void cacheCoapResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } CoapResponse response = context.getInCoapResponse(); String path = context.getUri().getPath(); if(path == null){ /* no caching */ return; } ProxyResourceKey key = new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path); /* NOTE: * - currently caching is only implemented for success error codes (2.xx) * - not fresh resources are removed (could be used for validation model)*/ switch (context.getInCoapResponse().getResponseCode()) { case Created_201: /* A cache SHOULD mark any stored response for the created resource as not fresh. This response is not cacheable.*/ cache.remove(key); break; case Deleted_202: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the deleted resource as not fresh.*/ cache.remove(key); break; case Valid_203: /* When a cache receives a 2.03 (Valid) response, it needs to update the stored response with the value of the Max-Age Option included in the response (see Section 5.6.2). */ //TODO break; case Changed_204: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the changed resource as not fresh. */ cache.remove(key); break; case Content_205: /* This response is cacheable: Caches can use the Max-Age Option to determine freshness (see Section 5.6.1) and (if present) the ETag Option for validation (see Section 5.6.2).*/ /* CACHE RESOURCE */ ProxyResource resource = new ProxyResource(path, response.getPayload(), response.getContentType()); resource.setExpires(cacheTimePolicy.calcExpires(context.getRequestTime(), context.getResponseTime(), response.getMaxAge())); insertElement(key, resource); break; default: break; } } public enum ProxyCacheTimePolicy{ Request(0), Response(1), Halftime(2); int state; private ProxyCacheTimePolicy(int state){ this.state = state; } public long calcExpires(long requestTime, long responseTime, long maxAge){ if (maxAge == -1){ maxAge = defaultMaxAge; } switch (this) { case Request: return requestTime + (maxAge * 1000) ; case Response: return responseTime + (maxAge * 1000); case Halftime: return requestTime + ((responseTime - requestTime) / 2) + (maxAge * 1000); } return 0; } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class CoapClientProxy implements CoapClient{ static Logger logger = Logger.getLogger(Proxy.class); ProxyMapper mapper = ProxyMapper.getInstance(); static final boolean RELIABLE = true; //use CON as client (NON has no timeout!!!) /* creates a client channel and stores it in the context*/ public void createChannel(ProxyMessageContext context){ // create channel CoapClientChannel channel; channel = BasicCoapChannelManager.getInstance().connect(this, context.getServerAddress(), context.getServerPort()); if (channel != null) { channel.setTrigger(context); context.setOutCoapClientChannel(channel); } else { throw new IllegalStateException("CoAP client connect() failed"); } } public void closeChannel(ProxyMessageContext context){ context.getOutCoapClientChannel().close(); } public void sendRequest(ProxyMessageContext context) { context.getOutCoapRequest().getChannel().sendMessage(context.getOutCoapRequest()); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger(); channel.close(); if (context != null) { context.setInCoapResponse(response); mapper.handleCoapClientResponse(context); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { ProxyMessageContext context = (ProxyMessageContext) channel.getTrigger(); channel.close(); if (context != null) { logger.warn("Coap client connection failed (e.g., timeout)!"); context.setInCoapResponse(null); // null indicates no response mapper.handleCoapClientResponse(context); } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.nio.client.DefaultHttpAsyncClient; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.concurrent.FutureCallback; import org.apache.http.nio.reactor.IOReactorException; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class HttpClientNIO extends Thread { static Logger logger = Logger.getLogger(Proxy.class); ProxyMapper mapper = ProxyMapper.getInstance(); HttpAsyncClient httpClient; public HttpClientNIO() { try { httpClient = new DefaultHttpAsyncClient(); } catch (IOReactorException e) { System.exit(-1); e.printStackTrace(); } httpClient.start(); logger.info("HTTP client started"); } public void sendRequest(ProxyMessageContext context) { // future is used to receive response asynchronous, without blocking //ProxyHttpFutureCallback allows to associate a ProxyMessageContext logger.info("send HTTP request"); ProxyHttpFutureCallback fc = new ProxyHttpFutureCallback(); fc.setContext(context); httpClient.execute(context.getOutHttpRequest(), fc); } private class ProxyHttpFutureCallback implements FutureCallback<HttpResponse>{ private ProxyMessageContext context = null; public void setContext(ProxyMessageContext context) { this.context = context; } // this is called when response is received public void completed(final HttpResponse response) { if (context != null) { context.setInHttpResponse(response); mapper.handleHttpClientResponse(context); } } public void failed(final Exception ex) { logger.warn("HTTP client request failed"); if (context != null) { context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ex.getMessage())); mapper.handleHttpClientResponse(context); } } public void cancelled() { logger.warn("HTTP Client Request cancelled"); if (context != null) { /* null indicates no response */ context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "http connection canceled")); mapper.handleHttpClientResponse(context); } } } }
Java
/* * Copyright 2012 University of Rostock, Institute of Applied Microelectronics and Computer Engineering * * 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. * * This work has been sponsored by Siemens Corporate Technology. * */ package org.ws4d.coap.proxy; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NHttpEntityWrapper; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.protocol.NHttpHandlerBase; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerResolver; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.EncodingUtils; /** * Fully asynchronous HTTP server side protocol handler implementation that * implements the essential requirements of the HTTP protocol for the server * side message processing as described by RFC . It is capable of processing * HTTP requests with nearly constant memory footprint. Only HTTP message heads * are stored in memory, while content of message bodies is streamed directly * from the entity to the underlying channel (and vice versa) * {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces. * <p/> * When using this class, it is important to ensure that entities supplied for * writing implement {@link ProducingNHttpEntity}. Doing so will allow the * entity to be written out asynchronously. If entities supplied for writing do * not implement {@link ProducingNHttpEntity}, a delegate is added that buffers * the entire contents in memory. Additionally, the buffering might take place * in the I/O thread, which could cause I/O to block temporarily. For best * results, ensure that all entities set on {@link HttpResponse}s from * {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}. * <p/> * If incoming requests enclose a content entity, {@link NHttpRequestHandler}s * are expected to return a {@link ConsumingNHttpEntity} for reading the * content. After the entity is finished reading the data, * {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)} * is called to generate a response. * <p/> * Individual {@link NHttpRequestHandler}s do not have to submit a response * immediately. They can defer transmission of the HTTP response back to the * client without blocking the I/O thread and to delegate the processing the * HTTP request to a worker thread. The worker thread in its turn can use an * instance of {@link NHttpResponseTrigger} passed as a parameter to submit * a response as at a later point of time once the response becomes available. * * @see ConsumingNHttpEntity * @see ProducingNHttpEntity * * @since 4.0 */ /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ModifiedAsyncNHttpServiceHandler extends NHttpHandlerBase implements NHttpServiceHandler { protected final HttpResponseFactory responseFactory; protected NHttpRequestHandlerResolver handlerResolver; protected HttpExpectationVerifier expectationVerifier; public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); if (responseFactory == null) { throw new IllegalArgumentException("Response factory may not be null"); } this.responseFactory = responseFactory; } public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, new HeapByteBufferAllocator(), params); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void connected(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = new ServerConnState(); context.setAttribute(CONN_STATE, connState); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } } public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = conn.getHttpRequest(); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); connState.setRequest(request); NHttpRequestHandler requestHandler = getRequestHandler(request); connState.setRequestHandler(requestHandler); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } HttpResponse response; try { if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (entityRequest.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met conn.submitResponse(response); } else { conn.resetInput(); sendResponse(conn, request, response); } } // Request content is expected. ConsumingNHttpEntity consumingEntity = null; // Lookup request handler for this request if (requestHandler != null) { consumingEntity = requestHandler.entityRequest(entityRequest, context); } if (consumingEntity == null) { consumingEntity = new ConsumingNHttpEntityTemplate( entityRequest.getEntity(), new ByteContentListener()); } entityRequest.setEntity(consumingEntity); connState.setConsumingEntity(consumingEntity); } else { // No request content is expected. // Process request right away conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void closed(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { connState.reset(); } catch (IOException ex) { if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { if (conn.isResponseSubmitted()) { // There is not much that we can do if a response head // has already been submitted closeConnection(conn, httpex); if (eventListener != null) { eventListener.fatalProtocolException(httpex, conn); } return; } HttpContext context = conn.getContext(); try { HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); response.setEntity(null); sendResponse(conn, null, response); } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void timeout(final NHttpServerConnection conn) { handleTimeout(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = connState.getRequest(); ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity(); try { consumingEntity.consumeContent(decoder, conn); if (decoder.isCompleted()) { conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void responseReady(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); if (connState.isHandled()) { return; } HttpRequest request = connState.getRequest(); try { IOException ioex = connState.getIOException(); if (ioex != null) { throw ioex; } HttpException httpex = connState.getHttpException(); if (httpex != null) { HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); connState.setResponse(response); } HttpResponse response = connState.getResponse(); if (response != null) { connState.setHandled(true); sendResponse(conn, request, response); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpResponse response = conn.getHttpResponse(); try { ProducingNHttpEntity entity = connState.getProducingEntity(); entity.produceContent(encoder, conn); if (encoder.isCompleted()) { connState.finishOutput(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } private void handleException(final HttpException ex, final HttpResponse response) { int code = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (ex instanceof MethodNotSupportedException) { code = HttpStatus.SC_NOT_IMPLEMENTED; } else if (ex instanceof UnsupportedHttpVersionException) { code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED; } else if (ex instanceof ProtocolException) { code = HttpStatus.SC_BAD_REQUEST; } response.setStatusCode(code); byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); NByteArrayEntity entity = new NByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } /** * @throws HttpException - not thrown currently */ private void processRequest( final NHttpServerConnection conn, final HttpRequest request) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn); try { this.httpProcessor.process(request, context); NHttpRequestHandler handler = connState.getRequestHandler(); if (handler != null) { HttpResponse response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handler.handle( request, response, trigger, context); } else { HttpResponse response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_NOT_IMPLEMENTED, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); trigger.submitResponse(response); } } catch (HttpException ex) { trigger.handleException(ex); } } private void sendResponse( final NHttpServerConnection conn, final HttpRequest request, final HttpResponse response) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); // Now that a response is ready, we can cleanup the listener for the request. connState.finishInput(); // Some processers need the request that generated this response. context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(response, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, null); if (response.getEntity() != null && !canResponseHaveBody(request, response)) { response.setEntity(null); } HttpEntity entity = response.getEntity(); if (entity != null) { if (entity instanceof ProducingNHttpEntity) { connState.setProducingEntity((ProducingNHttpEntity) entity); } else { connState.setProducingEntity(new NHttpEntityWrapper(entity)); } } conn.submitResponse(response); if (entity == null) { if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } /** * Signals that this response has been fully sent. This will be called after * submitting the response to a connection, if there is no entity in the * response. If there is an entity, it will be called after the entity has * completed. */ protected void responseComplete(HttpResponse response, HttpContext context) { } private NHttpRequestHandler getRequestHandler(HttpRequest request) { NHttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } return handler; } protected static class ServerConnState { private volatile NHttpRequestHandler requestHandler; private volatile HttpRequest request; private volatile ConsumingNHttpEntity consumingEntity; private volatile HttpResponse response; private volatile ProducingNHttpEntity producingEntity; private volatile IOException ioex; private volatile HttpException httpex; private volatile boolean handled; public void finishInput() throws IOException { if (this.consumingEntity != null) { this.consumingEntity.finish(); this.consumingEntity = null; } } public void finishOutput() throws IOException { if (this.producingEntity != null) { this.producingEntity.finish(); this.producingEntity = null; } } public void reset() throws IOException { finishInput(); this.request = null; finishOutput(); this.handled = false; this.response = null; this.ioex = null; this.httpex = null; this.requestHandler = null; } public NHttpRequestHandler getRequestHandler() { return this.requestHandler; } public void setRequestHandler(final NHttpRequestHandler requestHandler) { this.requestHandler = requestHandler; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public ConsumingNHttpEntity getConsumingEntity() { return this.consumingEntity; } public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) { this.consumingEntity = consumingEntity; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public ProducingNHttpEntity getProducingEntity() { return this.producingEntity; } public void setProducingEntity(final ProducingNHttpEntity producingEntity) { this.producingEntity = producingEntity; } public IOException getIOException() { return this.ioex; } @Deprecated public IOException getIOExepction() { return this.ioex; } public void setIOException(final IOException ex) { this.ioex = ex; } @Deprecated public void setIOExepction(final IOException ex) { this.ioex = ex; } public HttpException getHttpException() { return this.httpex; } @Deprecated public HttpException getHttpExepction() { return this.httpex; } public void setHttpException(final HttpException ex) { this.httpex = ex; } @Deprecated public void setHttpExepction(final HttpException ex) { this.httpex = ex; } public boolean isHandled() { return this.handled; } public void setHandled(boolean handled) { this.handled = handled; } } private static class ResponseTriggerImpl implements NHttpResponseTrigger { private final ServerConnState connState; private final IOControl iocontrol; private volatile boolean triggered; public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) { super(); this.connState = connState; this.iocontrol = iocontrol; } public void submitResponse(final HttpResponse response) { if (response == null) { throw new IllegalArgumentException("Response may not be null"); } if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setResponse(response); this.iocontrol.requestOutput(); } public void handleException(final HttpException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setHttpException(ex); this.iocontrol.requestOutput(); } public void handleException(final IOException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setIOException(ex); this.iocontrol.requestOutput(); } } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Example of requesting and displaying an interstitial ad. */ public class InterstitialActivity extends Activity { private InterstitialAd mInterstitial; private Button mShowButton; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_interstitial); mInterstitial = new InterstitialAd(this); mInterstitial.setAdUnitId(getResources().getString(R.string.ad_unit_id)); mInterstitial.setAdListener(new ToastAdListener(this) { @Override public void onAdLoaded() { super.onAdLoaded(); mShowButton.setText("Show Interstitial"); mShowButton.setEnabled(true); } @Override public void onAdFailedToLoad(int errorCode) { super.onAdFailedToLoad(errorCode); mShowButton.setText("Ad Failed to Load"); mShowButton.setEnabled(false); } }); mShowButton = (Button) findViewById(R.id.showButton); mShowButton.setEnabled(false); } public void loadInterstitial(View unusedView) { mShowButton.setText("Loading Interstitial..."); mShowButton.setEnabled(false); mInterstitial.loadAd(new AdRequest.Builder().build()); } public void showInterstitial(View unusedView) { if (mInterstitial.isLoaded()) { mInterstitial.show(); } mShowButton.setText("Interstitial Not Ready"); mShowButton.setEnabled(false); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik.activity; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.SlidingDrawer; import android.widget.Toast; import com.sky.musik.R; /** * Example of including a Google banner ad in code and listening for ad events. */ @SuppressWarnings("deprecation") public class PlayerActivity extends Activity { SlidingDrawer sliding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); sliding = (SlidingDrawer) findViewById(R.id.player_sliding); } @Override public boolean onTouchEvent(MotionEvent event) { //Toast.makeText(getApplicationContext(), "aaaa", Toast.LENGTH_SHORT).show(); sliding.onTouchEvent(event); return super.onTouchEvent(event); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Displays examples of integrating different ad formats with the Google AdMob SDK for * Android. */ public class GoogleAdsSampleActivity extends ListActivity { private static class Sample { private String mTitle; private Class<? extends Activity> mActivityClass; private Sample(String title, Class<? extends Activity> activityClass) { mTitle = title; mActivityClass = activityClass; } @Override public String toString() { return mTitle; } public Class<? extends Activity> getActivityClass() { return mActivityClass; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Resources res = getResources(); Sample[] samples = { new Sample(res.getString(R.string.banner_in_xml), BannerXmlActivity.class), new Sample(res.getString(R.string.banner_in_code), BannerCodeActivity.class), new Sample(res.getString(R.string.interstitial), InterstitialActivity.class) }; setListAdapter( new ArrayAdapter<Sample>(this, android.R.layout.simple_list_item_1, samples)); } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { Sample sample = (Sample) listView.getItemAtPosition(position); Intent intent = new Intent(this.getApplicationContext(), sample.getActivityClass()); startActivity(intent); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import android.content.Context; import android.widget.Toast; /** * An ad listener that toasts all ad events. */ public class ToastAdListener extends AdListener { private Context mContext; public ToastAdListener(Context context) { this.mContext = context; } @Override public void onAdLoaded() { Toast.makeText(mContext, "onAdLoaded()", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { String errorReason = ""; switch(errorCode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: errorReason = "Internal error"; break; case AdRequest.ERROR_CODE_INVALID_REQUEST: errorReason = "Invalid request"; break; case AdRequest.ERROR_CODE_NETWORK_ERROR: errorReason = "Network Error"; break; case AdRequest.ERROR_CODE_NO_FILL: errorReason = "No fill"; break; } Toast.makeText(mContext, String.format("onAdFailedToLoad(%s)", errorReason), Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { Toast.makeText(mContext, "onAdOpened()", Toast.LENGTH_SHORT).show(); } @Override public void onAdClosed() { Toast.makeText(mContext, "onAdClosed()", Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(mContext, "onAdLeftApplication()", Toast.LENGTH_SHORT).show(); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import android.app.Activity; import android.os.Bundle; /** * Example of including a Google banner ad in XML. */ public class BannerXmlActivity extends Activity { private AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner_xml); mAdView = (AdView) findViewById(R.id.adView); mAdView.setAdListener(new ToastAdListener(this)); mAdView.loadAd(new AdRequest.Builder().build()); } @Override protected void onPause() { mAdView.pause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mAdView.resume(); } @Override protected void onDestroy() { mAdView.destroy(); super.onDestroy(); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import android.app.Activity; import android.os.Bundle; import android.widget.RelativeLayout; /** * Example of including a Google banner ad in code and listening for ad events. */ public class BannerCodeActivity extends Activity { private AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner_code_ad_listener); mAdView = new AdView(this); mAdView.setAdUnitId(getResources().getString(R.string.ad_unit_id)); mAdView.setAdSize(AdSize.BANNER); mAdView.setAdListener(new ToastAdListener(this)); RelativeLayout layout = (RelativeLayout) findViewById(R.id.mainLayout); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layout.addView(mAdView, params); mAdView.loadAd(new AdRequest.Builder().build()); } @Override protected void onPause() { mAdView.pause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mAdView.resume(); } @Override protected void onDestroy() { mAdView.destroy(); super.onDestroy(); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.widget.navigation; import android.R; import android.app.ActionBar; import android.app.Activity; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.lang.reflect.Method; /** * This class encapsulates some awful hacks. * * Before JB-MR2 (API 18) it was not possible to change the home-as-up indicator glyph * in an action bar without some really gross hacks. Since the MR2 SDK is not published as of * this writing, the new API is accessed via reflection here if available. */ class ActionBarDrawerToggleHoneycomb { private static final String TAG = "ActionBarDrawerToggleHoneycomb"; private static final int[] THEME_ATTRS = new int[] { R.attr.homeAsUpIndicator }; public static Object setActionBarUpIndicator(Object info, Activity activity, Drawable drawable, int contentDescRes) { if (info == null) { info = new SetIndicatorInfo(activity); } final SetIndicatorInfo sii = (SetIndicatorInfo) info; if (sii.setHomeAsUpIndicator != null) { try { final ActionBar actionBar = activity.getActionBar(); sii.setHomeAsUpIndicator.invoke(actionBar, drawable); sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes); } catch (Exception e) { Log.w(TAG, "Couldn't set home-as-up indicator via JB-MR2 API", e); } } else if (sii.upIndicatorView != null) { sii.upIndicatorView.setImageDrawable(drawable); } else { Log.w(TAG, "Couldn't set home-as-up indicator"); } return info; } public static Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { if (info == null) { info = new SetIndicatorInfo(activity); } final SetIndicatorInfo sii = (SetIndicatorInfo) info; if (sii.setHomeAsUpIndicator != null) { try { final ActionBar actionBar = activity.getActionBar(); sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes); } catch (Exception e) { Log.w(TAG, "Couldn't set content description via JB-MR2 API", e); } } return info; } public static Drawable getThemeUpIndicator(Activity activity) { final TypedArray a = activity.obtainStyledAttributes(THEME_ATTRS); final Drawable result = a.getDrawable(0); a.recycle(); return result; } private static class SetIndicatorInfo { public Method setHomeAsUpIndicator; public Method setHomeActionContentDescription; public ImageView upIndicatorView; SetIndicatorInfo(Activity activity) { try { setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator", Drawable.class); setHomeActionContentDescription = ActionBar.class.getDeclaredMethod( "setHomeActionContentDescription", Integer.TYPE); // If we got the method we won't need the stuff below. return; } catch (NoSuchMethodException e) { // Oh well. We'll use the other mechanism below instead. } final View home = activity.findViewById(android.R.id.home); if (home == null) { // Action bar doesn't have a known configuration, an OEM messed with things. return; } final ViewGroup parent = (ViewGroup) home.getParent(); final int childCount = parent.getChildCount(); if (childCount != 2) { // No idea which one will be the right one, an OEM messed with things. return; } final View first = parent.getChildAt(0); final View second = parent.getChildAt(1); final View up = first.getId() == android.R.id.home ? second : first; if (up instanceof ImageView) { // Jackpot! (Probably...) upIndicatorView = (ImageView) up; } } } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.widget.navigation; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewGroupCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; /** * DrawerLayout acts as a top-level container for window content that allows for * interactive "drawer" views to be pulled out from the edge of the window. * * <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code> * attribute on child views corresponding to which side of the view you want the drawer * to emerge from: left or right. (Or start/end on platform versions that support layout direction.) * </p> * * <p>To use a DrawerLayout, position your primary content view as the first child with * a width and height of <code>match_parent</code>. Add drawers as child views after the main * content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use * <code>match_parent</code> for height with a fixed width.</p> * * <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views. * Avoid performing expensive operations such as layout during animation as it can cause * stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state. * {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p> * * <p>As per the Android Design guide, any drawers positioned to the left/start should * always contain content for navigating around the application, whereas any drawers * positioned to the right/end should always contain actions to take on the current content. * This preserves the same navigation left, actions right structure present in the Action Bar * and elsewhere.</p> */ public class DrawerLayout extends ViewGroup { private static final String TAG = "DrawerLayout"; /** * Indicates that any drawers are in an idle, settled state. No animation is in progress. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * Indicates that a drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * Indicates that a drawer is in the process of settling to a final position. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** * The drawer is unlocked. */ public static final int LOCK_MODE_UNLOCKED = 0; /** * The drawer is locked closed. The user may not open it, though * the app may open it programmatically. */ public static final int LOCK_MODE_LOCKED_CLOSED = 1; /** * The drawer is locked open. The user may not close it, though the app * may close it programmatically. */ public static final int LOCK_MODE_LOCKED_OPEN = 2; private static final int MIN_DRAWER_MARGIN = 64; // dp private static final int DEFAULT_SCRIM_COLOR = 0x99000000; /** * Length of time to delay before peeking the drawer. */ private static final int PEEK_DELAY = 160; // ms /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second /** * Experimental feature. */ private static final boolean ALLOW_EDGE_LOCK = false; private static final boolean CHILDREN_DISALLOW_INTERCEPT = true; private static final float TOUCH_SLOP_SENSITIVITY = 1.f; private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; private int mMinDrawerMargin; private int mScrimColor = DEFAULT_SCRIM_COLOR; private float mScrimOpacity; private Paint mScrimPaint = new Paint(); private final ViewDragHelper mLeftDragger; private final ViewDragHelper mRightDragger; private final ViewDragCallback mLeftCallback; private final ViewDragCallback mRightCallback; private int mDrawerState; private boolean mInLayout; private boolean mFirstLayout = true; private int mLockModeLeft; private int mLockModeRight; private boolean mDisallowInterceptRequested; private boolean mChildrenCanceledTouch; private DrawerListener mListener; private float mInitialMotionX; private float mInitialMotionY; private Drawable mShadowLeft; private Drawable mShadowRight; /** * Listener for monitoring events about drawers. */ public interface DrawerListener { /** * Called when a drawer's position changes. * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ public void onDrawerSlide(View drawerView, float slideOffset); /** * Called when a drawer has settled in a completely open state. * The drawer is interactive at this point. * * @param drawerView Drawer view that is now open */ public void onDrawerOpened(View drawerView); /** * Called when a drawer has settled in a completely closed state. * * @param drawerView Drawer view that is now closed */ public void onDrawerClosed(View drawerView); /** * Called when the drawer motion state changes. The new state will * be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * * @param newState The new drawer motion state */ public void onDrawerStateChanged(int newState); } /** * Stub/no-op implementations of all methods of {@link DrawerListener}. * Override this if you only care about a few of the available callback methods. */ public static abstract class SimpleDrawerListener implements DrawerListener { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } } public DrawerLayout(Context context) { this(context, null); } public DrawerLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DrawerLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final float density = getResources().getDisplayMetrics().density; mMinDrawerMargin = (int) (MIN_DRAWER_MARGIN * density + 0.5f); final float minVel = MIN_FLING_VELOCITY * density; mLeftCallback = new ViewDragCallback(Gravity.LEFT); mRightCallback = new ViewDragCallback(Gravity.RIGHT); mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback); mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); mLeftDragger.setMinVelocity(minVel); mLeftCallback.setDragger(mLeftDragger); mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback); mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mRightDragger.setMinVelocity(minVel); mRightCallback.setDragger(mRightDragger); // So that we can catch the back button setFocusableInTouchMode(true); ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate()); ViewGroupCompat.setMotionEventSplittingEnabled(this, false); } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param shadowDrawable Shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(Drawable shadowDrawable, int gravity) { /* * TODO Someone someday might want to set more complex drawables here. * They're probably nuts, but we might want to consider registering callbacks, * setting states, etc. properly. */ final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); if ((absGravity & Gravity.LEFT) == Gravity.LEFT) { mShadowLeft = shadowDrawable; invalidate(); } if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) { mShadowRight = shadowDrawable; invalidate(); } } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param resId Resource id of a shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(int resId, int gravity) { setDrawerShadow(getResources().getDrawable(resId), gravity); } /** * Set a color to use for the scrim that obscures primary content while a drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set a listener to be notified of drawer events. * * @param listener Listener to notify when drawer events occur * @see DrawerListener */ public void setDrawerListener(DrawerListener listener) { mListener = listener; } /** * Enable or disable interaction with all drawers. * * <p>This allows the application to restrict the user's ability to open or close * any drawer within this layout. DrawerLayout will still respond to calls to * {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking drawers open or closed will implicitly open or close * any drawers as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. */ public void setDrawerLockMode(int lockMode) { setDrawerLockMode(lockMode, Gravity.LEFT); setDrawerLockMode(lockMode, Gravity.RIGHT); } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param edgeGravity Gravity.LEFT, RIGHT, START or END. * Expresses which drawer to change the mode for. * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(int lockMode, int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mLockModeLeft = lockMode; } else if (absGravity == Gravity.RIGHT) { mLockModeRight = lockMode; } if (lockMode != LOCK_MODE_UNLOCKED) { // Cancel interaction in progress final ViewDragHelper helper = absGravity == Gravity.LEFT ? mLeftDragger : mRightDragger; helper.cancel(); } switch (lockMode) { case LOCK_MODE_LOCKED_OPEN: final View toOpen = findDrawerWithGravity(absGravity); if (toOpen != null) { openDrawer(toOpen); } break; case LOCK_MODE_LOCKED_CLOSED: final View toClose = findDrawerWithGravity(absGravity); if (toClose != null) { closeDrawer(toClose); } break; // default: do nothing } } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param drawerView The drawer view to change the lock mode for * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(int lockMode, View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity"); } final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; setDrawerLockMode(lockMode, gravity); } /** * Check the lock mode of the drawer with the given gravity. * * @param edgeGravity Gravity of the drawer to check * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ public int getDrawerLockMode(int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Check the lock mode of the given drawer view. * * @param drawerView Drawer view to check lock mode * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ public int getDrawerLockMode(View drawerView) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Resolve the shared state of all drawers from the component ViewDragHelpers. * Should be called whenever a ViewDragHelper's state changes. */ void updateDrawerState(int forGravity, int activeState, View activeDrawer) { final int leftState = mLeftDragger.getViewDragState(); final int rightState = mRightDragger.getViewDragState(); final int state; if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) { state = STATE_DRAGGING; } else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) { state = STATE_SETTLING; } else { state = STATE_IDLE; } if (activeDrawer != null && activeState == STATE_IDLE) { final LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams(); if (lp.onScreen == 0) { dispatchOnDrawerClosed(activeDrawer); } else if (lp.onScreen == 1) { dispatchOnDrawerOpened(activeDrawer); } } if (state != mDrawerState) { mDrawerState = state; if (mListener != null) { mListener.onDrawerStateChanged(state); } } } void dispatchOnDrawerClosed(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (lp.knownOpen) { lp.knownOpen = false; if (mListener != null) { mListener.onDrawerClosed(drawerView); } sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } void dispatchOnDrawerOpened(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (!lp.knownOpen) { lp.knownOpen = true; if (mListener != null) { mListener.onDrawerOpened(drawerView); } drawerView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } void dispatchOnDrawerSlide(View drawerView, float slideOffset) { if (mListener != null) { mListener.onDrawerSlide(drawerView, slideOffset); } } void setDrawerViewOffset(View drawerView, float slideOffset) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (slideOffset == lp.onScreen) { return; } lp.onScreen = slideOffset; dispatchOnDrawerSlide(drawerView, slideOffset); } float getDrawerViewOffset(View drawerView) { return ((LayoutParams) drawerView.getLayoutParams()).onScreen; } /** * @return the absolute gravity of the child drawerView, resolved according * to the current layout direction */ int getDrawerViewAbsoluteGravity(View drawerView) { final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; return GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); } boolean checkDrawerViewAbsoluteGravity(View drawerView, int checkFor) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); return (absGravity & checkFor) == checkFor; } View findOpenDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (((LayoutParams) child.getLayoutParams()).knownOpen) { return child; } } return null; } void moveDrawerToOffset(View drawerView, float slideOffset) { final float oldOffset = getDrawerViewOffset(drawerView); final int width = drawerView.getWidth(); final int oldPos = (int) (width * oldOffset); final int newPos = (int) (width * slideOffset); final int dx = newPos - oldPos; drawerView.offsetLeftAndRight( checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT) ? dx : -dx); setDrawerViewOffset(drawerView, slideOffset); } /** * @param gravity the gravity of the child to return. If specified as a * relative value, it will be resolved according to the current * layout direction. * @return the drawer with the specified gravity */ View findDrawerWithGravity(int gravity) { final int absHorizGravity = GravityCompat.getAbsoluteGravity( gravity, ViewCompat.getLayoutDirection(this)) & Gravity.HORIZONTAL_GRAVITY_MASK; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childAbsGravity = getDrawerViewAbsoluteGravity(child); if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) { return child; } } return null; } /** * Simple gravity to string - only supports LEFT and RIGHT for debugging output. * * @param gravity Absolute gravity value * @return LEFT or RIGHT as appropriate, or a hex string */ static String gravityToString(int gravity) { if ((gravity & Gravity.LEFT) == Gravity.LEFT) { return "LEFT"; } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { return "RIGHT"; } return Integer.toHexString(gravity); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mFirstLayout = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { if (isInEditMode()) { // Don't crash the layout editor. Consume all of the space if specified // or pick a magic number from thin air otherwise. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (widthMode == MeasureSpec.AT_MOST) { widthMode = MeasureSpec.EXACTLY; } else if (widthMode == MeasureSpec.UNSPECIFIED) { widthMode = MeasureSpec.EXACTLY; widthSize = 300; } if (heightMode == MeasureSpec.AT_MOST) { heightMode = MeasureSpec.EXACTLY; } else if (heightMode == MeasureSpec.UNSPECIFIED) { heightMode = MeasureSpec.EXACTLY; heightSize = 300; } } else { throw new IllegalArgumentException( "DrawerLayout must be measured with MeasureSpec.EXACTLY."); } } setMeasuredDimension(widthSize, heightSize); // Gravity value for each drawer we've seen. Only one of each permitted. int foundDrawers = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { // Content views get measured at exactly the layout's size. final int contentWidthSpec = MeasureSpec.makeMeasureSpec( widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); final int contentHeightSpec = MeasureSpec.makeMeasureSpec( heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (isDrawerView(child)) { final int childGravity = getDrawerViewAbsoluteGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK; if ((foundDrawers & childGravity) != 0) { throw new IllegalStateException("Child drawer has absolute gravity " + gravityToString(childGravity) + " but this " + TAG + " already has a " + "drawer view along that edge"); } final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec, mMinDrawerMargin + lp.leftMargin + lp.rightMargin, lp.width); final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height); child.measure(drawerWidthSpec, drawerHeightSpec); } else { throw new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY"); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; final int width = r - l; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight()); } else { // Drawer, if it wasn't onMeasure would have thrown an exception. final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); int childLeft; final float newOffset; if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { childLeft = -childWidth + (int) (childWidth * lp.onScreen); newOffset = (float) (childWidth + childLeft) / childWidth; } else { // Right; onMeasure checked for us. childLeft = width - (int) (childWidth * lp.onScreen); newOffset = (float) (width - childLeft) / childWidth; } final boolean changeOffset = newOffset != lp.onScreen; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { default: case Gravity.TOP: { child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight); break; } case Gravity.BOTTOM: { final int height = b - t; child.layout(childLeft, height - lp.bottomMargin - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin); break; } case Gravity.CENTER_VERTICAL: { final int height = b - t; int childTop = (height - childHeight) / 2; // Offset for margins. If things don't fit right because of // bad measurement before, oh well. if (childTop < lp.topMargin) { childTop = lp.topMargin; } else if (childTop + childHeight > height - lp.bottomMargin) { childTop = height - lp.bottomMargin - childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); break; } } if (changeOffset) { setDrawerViewOffset(child, newOffset); } final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE; if (child.getVisibility() != newVisibility) { child.setVisibility(newVisibility); } } } mInLayout = false; mFirstLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override public void computeScroll() { final int childCount = getChildCount(); float scrimOpacity = 0; for (int i = 0; i < childCount; i++) { final float onscreen = ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen; scrimOpacity = Math.max(scrimOpacity, onscreen); } mScrimOpacity = scrimOpacity; // "|" used on purpose; both need to run. if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private static boolean hasOpaqueBackground(View v) { final Drawable bg = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final int height = getHeight(); final boolean drawingContent = isContentView(child); int clipLeft = 0, clipRight = getWidth(); final int restoreCount = canvas.save(); if (drawingContent) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); if (v == child || v.getVisibility() != VISIBLE || !hasOpaqueBackground(v) || !isDrawerView(v) || v.getHeight() < height) { continue; } if (checkDrawerViewAbsoluteGravity(v, Gravity.LEFT)) { final int vright = v.getRight(); if (vright > clipLeft) clipLeft = vright; } else { final int vleft = v.getLeft(); if (vleft < clipRight) clipRight = vleft; } } canvas.clipRect(clipLeft, 0, clipRight, getHeight()); } final boolean result = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(restoreCount); if (mScrimOpacity > 0 && drawingContent) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int imag = (int) (baseAlpha * mScrimOpacity); final int color = imag << 24 | (mScrimColor & 0xffffff); mScrimPaint.setColor(color); canvas.drawRect(clipLeft, 0, clipRight, getHeight(), mScrimPaint); } else if (mShadowLeft != null && checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { final int shadowWidth = mShadowLeft.getIntrinsicWidth(); final int childRight = child.getRight(); final int drawerPeekDistance = mLeftDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) childRight / drawerPeekDistance, 1.f)); mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom()); mShadowLeft.setAlpha((int) (0xff * alpha)); mShadowLeft.draw(canvas); } else if (mShadowRight != null && checkDrawerViewAbsoluteGravity(child, Gravity.RIGHT)) { final int shadowWidth = mShadowRight.getIntrinsicWidth(); final int childLeft = child.getLeft(); final int showing = getWidth() - childLeft; final int drawerPeekDistance = mRightDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) showing / drawerPeekDistance, 1.f)); mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); mShadowRight.setAlpha((int) (0xff * alpha)); mShadowRight.draw(canvas); } return result; } boolean isContentView(View child) { return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY; } boolean isDrawerView(View child) { final int gravity = ((LayoutParams) child.getLayoutParams()).gravity; final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(child)); return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); // "|" used deliberately here; both methods should be invoked. final boolean interceptForDrag = mLeftDragger.shouldInterceptTouchEvent(ev) | mRightDragger.shouldInterceptTouchEvent(ev); boolean interceptForTap = false; switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; if (mScrimOpacity > 0 && isContentView(mLeftDragger.findTopChildUnder((int) x, (int) y))) { interceptForTap = true; } mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_MOVE: { // If we cross the touch slop, don't perform the delayed peek for an edge touch. if (mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) { mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; } } return interceptForDrag || interceptForTap || hasPeekingDrawer() || mChildrenCanceledTouch; } @Override public boolean onTouchEvent(MotionEvent ev) { mLeftDragger.processTouchEvent(ev); mRightDragger.processTouchEvent(ev); final int action = ev.getAction(); boolean wantTouchEvents = true; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_UP: { final float x = ev.getX(); final float y = ev.getY(); boolean peekingOnly = true; final View touchedView = mLeftDragger.findTopChildUnder((int) x, (int) y); if (touchedView != null && isContentView(touchedView)) { final float dx = x - mInitialMotionX; final float dy = y - mInitialMotionY; final int slop = mLeftDragger.getTouchSlop(); if (dx * dx + dy * dy < slop * slop) { // Taps close a dimmed open drawer but only if it isn't locked open. final View openDrawer = findOpenDrawer(); if (openDrawer != null) { peekingOnly = getDrawerLockMode(openDrawer) == LOCK_MODE_LOCKED_OPEN; } } } closeDrawers(peekingOnly); mDisallowInterceptRequested = false; break; } case MotionEvent.ACTION_CANCEL: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } } return wantTouchEvents; } public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (CHILDREN_DISALLOW_INTERCEPT || (!mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) && !mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) { // If we have an edge touch we want to skip this and track it for later instead. super.requestDisallowInterceptTouchEvent(disallowIntercept); } mDisallowInterceptRequested = disallowIntercept; if (disallowIntercept) { closeDrawers(true); } } /** * Close all currently open drawer views by animating them out of view. */ public void closeDrawers() { closeDrawers(false); } void closeDrawers(boolean peekingOnly) { boolean needsInvalidate = false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!isDrawerView(child) || (peekingOnly && !lp.isPeeking)) { continue; } final int childWidth = child.getWidth(); if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { needsInvalidate |= mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop()); } else { needsInvalidate |= mRightDragger.smoothSlideViewTo(child, getWidth(), child.getTop()); } lp.isPeeking = false; } mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); if (needsInvalidate) { invalidate(); } } /** * Open the specified drawer view by animating it into view. * * @param drawerView Drawer view to open */ public void openDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 1.f; lp.knownOpen = true; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(), drawerView.getTop()); } } invalidate(); } /** * Open the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void openDrawer(int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } openDrawer(drawerView); } /** * Close the specified drawer view by animating it into view. * * @param drawerView Drawer view to close */ public void closeDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 0.f; lp.knownOpen = false; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop()); } } invalidate(); } /** * Close the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void closeDrawer(int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } closeDrawer(drawerView); } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. To check for partial visibility use * {@link #isDrawerVisible(android.view.View)}. * * @param drawer Drawer view to check * @return true if the given drawer view is in an open state * @see #isDrawerVisible(android.view.View) */ public boolean isDrawerOpen(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).knownOpen; } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. If there is no drawer with the given gravity this method * will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer view is in an open state */ public boolean isDrawerOpen(int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerOpen(drawerView); } return false; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * * @param drawer Drawer view to check * @return true if the given drawer is visible on-screen * @see #isDrawerOpen(android.view.View) */ public boolean isDrawerVisible(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * If there is no drawer with the given gravity this method will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer is visible on-screen */ public boolean isDrawerVisible(int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerVisible(drawerView); } return false; } private boolean hasPeekingDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); if (lp.isPeeking) { return true; } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams ? new LayoutParams((LayoutParams) p) : p instanceof ViewGroup.MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } private boolean hasVisibleDrawer() { return findVisibleDrawer() != null; } private View findVisibleDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (isDrawerView(child) && isDrawerVisible(child)) { return child; } } return null; } void cancelChildViewTouch() { // Cancel child touches if (!mChildrenCanceledTouch) { final long now = SystemClock.uptimeMillis(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); mChildrenCanceledTouch = true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && hasVisibleDrawer()) { KeyEventCompat.startTracking(event); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == LOCK_MODE_UNLOCKED) { closeDrawers(); } return visibleDrawer != null; } return super.onKeyUp(keyCode, event); } @Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.openDrawerGravity != Gravity.NO_GRAVITY) { final View toOpen = findDrawerWithGravity(ss.openDrawerGravity); if (toOpen != null) { openDrawer(toOpen); } } setDrawerLockMode(ss.lockModeLeft, Gravity.LEFT); setDrawerLockMode(ss.lockModeRight, Gravity.RIGHT); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState ss = new SavedState(superState); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (!isDrawerView(child)) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.knownOpen) { ss.openDrawerGravity = lp.gravity; // Only one drawer can be open at a time. break; } } ss.lockModeLeft = mLockModeLeft; ss.lockModeRight = mLockModeRight; return ss; } /** * State persisted across instances */ protected static class SavedState extends BaseSavedState { int openDrawerGravity = Gravity.NO_GRAVITY; int lockModeLeft = LOCK_MODE_UNLOCKED; int lockModeRight = LOCK_MODE_UNLOCKED; public SavedState(Parcel in) { super(in); openDrawerGravity = in.readInt(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(openDrawerGravity); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel source) { return new SavedState(source); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class ViewDragCallback extends ViewDragHelper.Callback { private final int mAbsGravity; private ViewDragHelper mDragger; private final Runnable mPeekRunnable = new Runnable() { @Override public void run() { peekDrawer(); } }; public ViewDragCallback(int gravity) { mAbsGravity = gravity; } public void setDragger(ViewDragHelper dragger) { mDragger = dragger; } public void removeCallbacks() { DrawerLayout.this.removeCallbacks(mPeekRunnable); } @Override public boolean tryCaptureView(View child, int pointerId) { // Only capture views where the gravity matches what we're looking for. // This lets us use two ViewDragHelpers, one for each side drawer. return isDrawerView(child) && checkDrawerViewAbsoluteGravity(child, mAbsGravity) && getDrawerLockMode(child) == LOCK_MODE_UNLOCKED; } @Override public void onViewDragStateChanged(int state) { updateDrawerState(mAbsGravity, state, mDragger.getCapturedView()); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { float offset; final int childWidth = changedView.getWidth(); // This reverses the positioning shown in onLayout. if (checkDrawerViewAbsoluteGravity(changedView, Gravity.LEFT)) { offset = (float) (childWidth + left) / childWidth; } else { final int width = getWidth(); offset = (float) (width - left) / childWidth; } setDrawerViewOffset(changedView, offset); changedView.setVisibility(offset == 0 ? INVISIBLE : VISIBLE); invalidate(); } @Override public void onViewCaptured(View capturedChild, int activePointerId) { final LayoutParams lp = (LayoutParams) capturedChild.getLayoutParams(); lp.isPeeking = false; closeOtherDrawer(); } private void closeOtherDrawer() { final int otherGrav = mAbsGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT; final View toClose = findDrawerWithGravity(otherGrav); if (toClose != null) { closeDrawer(toClose); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { // Offset is how open the drawer is, therefore left/right values // are reversed from one another. final float offset = getDrawerViewOffset(releasedChild); final int childWidth = releasedChild.getWidth(); int left; if (checkDrawerViewAbsoluteGravity(releasedChild, Gravity.LEFT)) { left = xvel > 0 || xvel == 0 && offset > 0.5f ? 0 : -childWidth; } else { final int width = getWidth(); left = xvel < 0 || xvel == 0 && offset > 0.5f ? width - childWidth : width; } mDragger.settleCapturedViewAt(left, releasedChild.getTop()); invalidate(); } @Override public void onEdgeTouched(int edgeFlags, int pointerId) { postDelayed(mPeekRunnable, PEEK_DELAY); } private void peekDrawer() { final View toCapture; final int childLeft; final int peekDistance = mDragger.getEdgeSize(); final boolean leftEdge = mAbsGravity == Gravity.LEFT; if (leftEdge) { toCapture = findDrawerWithGravity(Gravity.LEFT); childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance; } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); childLeft = getWidth() - peekDistance; } // Only peek if it would mean making the drawer more visible and the drawer isn't locked if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { final LayoutParams lp = (LayoutParams) toCapture.getLayoutParams(); mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop()); lp.isPeeking = true; invalidate(); closeOtherDrawer(); cancelChildViewTouch(); } } @Override public boolean onEdgeLock(int edgeFlags) { if (ALLOW_EDGE_LOCK) { final View drawer = findDrawerWithGravity(mAbsGravity); if (drawer != null && !isDrawerOpen(drawer)) { closeDrawer(drawer); } return true; } return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { final View toCapture; if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) { toCapture = findDrawerWithGravity(Gravity.LEFT); } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); } if (toCapture != null && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { mDragger.captureChildView(toCapture, pointerId); } } @Override public int getViewHorizontalDragRange(View child) { return child.getWidth(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { return Math.max(-child.getWidth(), Math.min(left, 0)); } else { final int width = getWidth(); return Math.max(width - child.getWidth(), Math.min(left, width)); } } @Override public int clampViewPositionVertical(View child, int top, int dy) { return child.getTop(); } } public static class LayoutParams extends ViewGroup.MarginLayoutParams { public int gravity = Gravity.NO_GRAVITY; float onScreen; boolean isPeeking; boolean knownOpen; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS); this.gravity = a.getInt(0, Gravity.NO_GRAVITY); a.recycle(); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(int width, int height, int gravity) { this(width, height); this.gravity = gravity; } public LayoutParams(LayoutParams source) { super(source); this.gravity = source.gravity; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } } class AccessibilityDelegate extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info); super.onInitializeAccessibilityNodeInfo(host, superNode); info.setSource(host); final ViewParent parent = ViewCompat.getParentForAccessibility(host); if (parent instanceof View) { info.setParent((View) parent); } copyNodeInfoNoChildren(info, superNode); superNode.recycle(); addChildrenForAccessibility(info, (ViewGroup) host); } private void addChildrenForAccessibility(AccessibilityNodeInfoCompat info, ViewGroup v) { final int childCount = v.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = v.getChildAt(i); if (filter(child)) { continue; } // Adding children that are marked as not important for // accessibility will break the hierarchy, so we need to check // that value and re-parent views if necessary. final int importance = ViewCompat.getImportantForAccessibility(child); switch (importance) { case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS: // Always skip NO_HIDE views and their descendants. break; case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO: // Re-parent children of NO view groups, skip NO views. if (child instanceof ViewGroup) { addChildrenForAccessibility(info, (ViewGroup) child); } break; case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO: // Force AUTO views to YES and add them. ViewCompat.setImportantForAccessibility( child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES: info.addChild(child); break; } } } @Override public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { if (!filter(child)) { return super.onRequestSendAccessibilityEvent(host, child, event); } return false; } public boolean filter(View child) { final View openDrawer = findOpenDrawer(); return openDrawer != null && openDrawer != child; } /** * This should really be in AccessibilityNodeInfoCompat, but there unfortunately * seem to be a few elements that are not easily cloneable using the underlying API. * Leave it private here as it's not general-purpose useful. */ private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) { final Rect rect = mTmpRect; src.getBoundsInParent(rect); dest.setBoundsInParent(rect); src.getBoundsInScreen(rect); dest.setBoundsInScreen(rect); dest.setVisibleToUser(src.isVisibleToUser()); dest.setPackageName(src.getPackageName()); dest.setClassName(src.getClassName()); dest.setContentDescription(src.getContentDescription()); dest.setEnabled(src.isEnabled()); dest.setClickable(src.isClickable()); dest.setFocusable(src.isFocusable()); dest.setFocused(src.isFocused()); dest.setAccessibilityFocused(src.isAccessibilityFocused()); dest.setSelected(src.isSelected()); dest.setLongClickable(src.isLongClickable()); dest.addAction(src.getActions()); } } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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.sky.widget.navigation; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.InsetDrawable; import android.os.Build; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.view.MenuItem; import android.view.View; /** * This class provides a handy way to tie together the functionality of * {@link DrawerLayout} and the framework <code>ActionBar</code> to implement the recommended * design for navigation drawers. * * <p>To use <code>ActionBarDrawerToggle</code>, create one in your Activity and call through * to the following methods corresponding to your Activity callbacks:</p> * * <ul> * <li>{@link Activity#onConfigurationChanged(android.content.res.Configuration) onConfigurationChanged}</li> * <li>{@link Activity#onOptionsItemSelected(android.view.MenuItem) onOptionsItemSelected}</li> * </ul> * * <p>Call {@link #syncState()} from your <code>Activity</code>'s * {@link Activity#onPostCreate(android.os.Bundle) onPostCreate} to synchronize the indicator * with the state of the linked DrawerLayout after <code>onRestoreInstanceState</code> * has occurred.</p> * * <p><code>ActionBarDrawerToggle</code> can be used directly as a * {@link DrawerLayout.DrawerListener}, or if you are already providing your own listener, * call through to each of the listener methods from your own.</p> */ public class ActionBarDrawerToggle implements DrawerLayout.DrawerListener { /** * Allows an implementing Activity to return an {@link ActionBarDrawerToggle.Delegate} to use * with ActionBarDrawerToggle. */ public interface DelegateProvider { /** * @return Delegate to use for ActionBarDrawableToggles, or null if the Activity * does not wish to override the default behavior. */ Delegate getDrawerToggleDelegate(); } public interface Delegate { /** * @return Up indicator drawable as defined in the Activity's theme, or null if one is not * defined. */ Drawable getThemeUpIndicator(); /** * Set the Action Bar's up indicator drawable and content description. * * @param upDrawable - Drawable to set as up indicator * @param contentDescRes - Content description to set */ void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes); /** * Set the Action Bar's up indicator content description. * * @param contentDescRes - Content description to set */ void setActionBarDescription(int contentDescRes); } private interface ActionBarDrawerToggleImpl { Drawable getThemeUpIndicator(Activity activity); Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes); Object setActionBarDescription(Object info, Activity activity, int contentDescRes); } private static class ActionBarDrawerToggleImplBase implements ActionBarDrawerToggleImpl { @Override public Drawable getThemeUpIndicator(Activity activity) { return null; } @Override public Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes) { // No action bar to set. return info; } @Override public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { // No action bar to set return info; } } private static class ActionBarDrawerToggleImplHC implements ActionBarDrawerToggleImpl { @Override public Drawable getThemeUpIndicator(Activity activity) { return ActionBarDrawerToggleHoneycomb.getThemeUpIndicator(activity); } @Override public Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes) { return ActionBarDrawerToggleHoneycomb.setActionBarUpIndicator(info, activity, themeImage, contentDescRes); } @Override public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { return ActionBarDrawerToggleHoneycomb.setActionBarDescription(info, activity, contentDescRes); } } private static final ActionBarDrawerToggleImpl IMPL; static { final int version = Build.VERSION.SDK_INT; if (version >= 11) { IMPL = new ActionBarDrawerToggleImplHC(); } else { IMPL = new ActionBarDrawerToggleImplBase(); } } /** Fraction of its total width by which to offset the toggle drawable. */ private static final float TOGGLE_DRAWABLE_OFFSET = 1 / 3f; // android.R.id.home as defined by public API in v11 private static final int ID_HOME = 0x0102002c; private final Activity mActivity; private final Delegate mActivityImpl; private final DrawerLayout mDrawerLayout; private boolean mDrawerIndicatorEnabled = true; private Drawable mThemeImage; private Drawable mDrawerImage; private SlideDrawable mSlider; private final int mDrawerImageResource; private final int mOpenDrawerContentDescRes; private final int mCloseDrawerContentDescRes; private Object mSetIndicatorInfo; /** * Construct a new ActionBarDrawerToggle. * * <p>The given {@link Activity} will be linked to the specified {@link DrawerLayout}. * The provided drawer indicator drawable will animate slightly off-screen as the drawer * is opened, indicating that in the open state the drawer will move off-screen when pressed * and in the closed state the drawer will move on-screen when pressed.</p> * * <p>String resources must be provided to describe the open/close drawer actions for * accessibility services.</p> * * @param activity The Activity hosting the drawer * @param drawerLayout The DrawerLayout to link to the given Activity's ActionBar * @param drawerImageRes A Drawable resource to use as the drawer indicator * @param openDrawerContentDescRes A String resource to describe the "open drawer" action * for accessibility * @param closeDrawerContentDescRes A String resource to describe the "close drawer" action * for accessibility */ public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes) { mActivity = activity; // Allow the Activity to provide an impl if (activity instanceof DelegateProvider) { mActivityImpl = ((DelegateProvider) activity).getDrawerToggleDelegate(); } else { mActivityImpl = null; } mDrawerLayout = drawerLayout; mDrawerImageResource = drawerImageRes; mOpenDrawerContentDescRes = openDrawerContentDescRes; mCloseDrawerContentDescRes = closeDrawerContentDescRes; mThemeImage = getThemeUpIndicator(); mDrawerImage = activity.getResources().getDrawable(drawerImageRes); mSlider = new SlideDrawable(mDrawerImage); mSlider.setOffset(TOGGLE_DRAWABLE_OFFSET); } /** * Synchronize the state of the drawer indicator/affordance with the linked DrawerLayout. * * <p>This should be called from your <code>Activity</code>'s * {@link Activity#onPostCreate(android.os.Bundle) onPostCreate} method to synchronize after * the DrawerLayout's instance state has been restored, and any other time when the state * may have diverged in such a way that the ActionBarDrawerToggle was not notified. * (For example, if you stop forwarding appropriate drawer events for a period of time.)</p> */ public void syncState() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mSlider.setPosition(1); } else { mSlider.setPosition(0); } if (mDrawerIndicatorEnabled) { setActionBarUpIndicator(mSlider, mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mCloseDrawerContentDescRes : mOpenDrawerContentDescRes); } } /** * Enable or disable the drawer indicator. The indicator defaults to enabled. * * <p>When the indicator is disabled, the <code>ActionBar</code> will revert to displaying * the home-as-up indicator provided by the <code>Activity</code>'s theme in the * <code>android.R.attr.homeAsUpIndicator</code> attribute instead of the animated * drawer glyph.</p> * * @param enable true to enable, false to disable */ public void setDrawerIndicatorEnabled(boolean enable) { if (enable != mDrawerIndicatorEnabled) { if (enable) { setActionBarUpIndicator(mSlider, mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mCloseDrawerContentDescRes : mOpenDrawerContentDescRes); } else { setActionBarUpIndicator(mThemeImage, 0); } mDrawerIndicatorEnabled = enable; } } /** * @return true if the enhanced drawer indicator is enabled, false otherwise * @see #setDrawerIndicatorEnabled(boolean) */ public boolean isDrawerIndicatorEnabled() { return mDrawerIndicatorEnabled; } /** * This method should always be called by your <code>Activity</code>'s * {@link Activity#onConfigurationChanged(android.content.res.Configuration) onConfigurationChanged} * method. * * @param newConfig The new configuration */ public void onConfigurationChanged(Configuration newConfig) { // Reload drawables that can change with configuration mThemeImage = getThemeUpIndicator(); mDrawerImage = mActivity.getResources().getDrawable(mDrawerImageResource); syncState(); } /** * This method should be called by your <code>Activity</code>'s * {@link Activity#onOptionsItemSelected(android.view.MenuItem) onOptionsItemSelected} method. * If it returns true, your <code>onOptionsItemSelected</code> method should return true and * skip further processing. * * @param item the MenuItem instance representing the selected menu item * @return true if the event was handled and further processing should not occur */ public boolean onOptionsItemSelected(MenuItem item) { if (item != null && item.getItemId() == ID_HOME && mDrawerIndicatorEnabled) { if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { mDrawerLayout.openDrawer(GravityCompat.START); } return true; } return false; } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ @Override public void onDrawerSlide(View drawerView, float slideOffset) { float glyphOffset = mSlider.getPosition(); if (slideOffset > 0.5f) { glyphOffset = Math.max(glyphOffset, Math.max(0.f, slideOffset - 0.5f) * 2); } else { glyphOffset = Math.min(glyphOffset, slideOffset * 2); } mSlider.setPosition(glyphOffset); } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView Drawer view that is now open */ @Override public void onDrawerOpened(View drawerView) { mSlider.setPosition(1); if (mDrawerIndicatorEnabled) { setActionBarDescription(mCloseDrawerContentDescRes); } } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView Drawer view that is now closed */ @Override public void onDrawerClosed(View drawerView) { mSlider.setPosition(0); if (mDrawerIndicatorEnabled) { setActionBarDescription(mOpenDrawerContentDescRes); } } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param newState The new drawer motion state */ @Override public void onDrawerStateChanged(int newState) { } Drawable getThemeUpIndicator() { if (mActivityImpl != null) { return mActivityImpl.getThemeUpIndicator(); } return IMPL.getThemeUpIndicator(mActivity); } void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes) { if (mActivityImpl != null) { mActivityImpl.setActionBarUpIndicator(upDrawable, contentDescRes); return; } mSetIndicatorInfo = IMPL .setActionBarUpIndicator(mSetIndicatorInfo, mActivity, upDrawable, contentDescRes); } void setActionBarDescription(int contentDescRes) { if (mActivityImpl != null) { mActivityImpl.setActionBarDescription(contentDescRes); return; } mSetIndicatorInfo = IMPL .setActionBarDescription(mSetIndicatorInfo, mActivity, contentDescRes); } private class SlideDrawable extends InsetDrawable implements Drawable.Callback { private final boolean mHasMirroring = Build.VERSION.SDK_INT > 18; private final Rect mTmpRect = new Rect(); private float mPosition; private float mOffset; private SlideDrawable(Drawable wrapped) { super(wrapped, 0); } /** * Sets the current position along the offset. * * @param position a value between 0 and 1 */ public void setPosition(float position) { mPosition = position; invalidateSelf(); } public float getPosition() { return mPosition; } /** * Specifies the maximum offset when the position is at 1. * * @param offset maximum offset as a fraction of the drawable width, * positive to shift left or negative to shift right. * @see #setPosition(float) */ public void setOffset(float offset) { mOffset = offset; invalidateSelf(); } @Override public void draw(Canvas canvas) { copyBounds(mTmpRect); canvas.save(); // Layout direction must be obtained from the activity. final boolean isLayoutRTL = ViewCompat.getLayoutDirection( mActivity.getWindow().getDecorView()) == ViewCompat.LAYOUT_DIRECTION_RTL; final int flipRtl = isLayoutRTL ? -1 : 1; final int width = mTmpRect.width(); canvas.translate(-mOffset * width * mPosition * flipRtl, 0); // Force auto-mirroring if it's not supported by the platform. if (isLayoutRTL && !mHasMirroring) { canvas.translate(width, 0); canvas.scale(-1, 1); } super.draw(canvas); canvas.restore(); } } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Read the throttle position in percentage. */ public class ThrottlePositionObdCommand extends PercentageObdCommand { /** * Default ctor. */ public ThrottlePositionObdCommand() { super("01 11"); } /** * Copy ctor. * * @param other */ public ThrottlePositionObdCommand(ThrottlePositionObdCommand other) { super(other); } /** * */ @Override public String getName() { return AvailableCommandNames.THROTTLE_POS.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Calculated Engine Load value. */ public class EngineLoadObdCommand extends PercentageObdCommand { /** * @param command */ public EngineLoadObdCommand() { super("01 04"); } /** * @param other */ public EngineLoadObdCommand(ObdCommand other) { super(other); } /* (non-Javadoc) * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.ENGINE_LOAD.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Displays the current engine revolutions per minute (RPM). */ public class EngineRPMObdCommand extends ObdCommand { private int _rpm = -1; /** * Default ctor. */ public EngineRPMObdCommand() { super("01 0C"); } /** * Copy ctor. * * @param other */ public EngineRPMObdCommand(EngineRPMObdCommand other) { super(other); } /** * @return the engine RPM per minute */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [41 0C] of the response int a = buffer.get(2); int b = buffer.get(3); _rpm = (a * 256 + b) / 4; } return String.format("%d%s", _rpm, " RPM"); } @Override public String getName() { return AvailableCommandNames.ENGINE_RPM.getValue(); } public int getRPM() { return _rpm; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Mass Air Flow */ public class MassAirFlowObdCommand extends ObdCommand { private float _maf = -1.0f; /** * Default ctor. */ public MassAirFlowObdCommand() { super("01 10"); } /** * Copy ctor. * * @param other */ public MassAirFlowObdCommand(MassAirFlowObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); _maf = (a * 256 + b) / 100.0f; } return String.format("%.2f%s", _maf, "g/s"); } /** * @return MAF value for further calculus. */ public double getMAF() { return _maf; } @Override public String getName() { return AvailableCommandNames.MAF.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class EngineRuntimeObdCommand extends ObdCommand { /** * Default ctor. */ public EngineRuntimeObdCommand() { super("01 1F"); } /** * Copy ctor. * * @param other */ public EngineRuntimeObdCommand(EngineRuntimeObdCommand other) { super(other); } @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [01 0C] of the response int a = buffer.get(2); int b = buffer.get(3); int value = a * 256 + b; // determine time String hh = String.format("%02d", value / 3600); String mm = String.format("%02d", (value % 3600) / 60); String ss = String.format("%02d", value % 60); res = String.format("%s:%s:%s", hh, mm, ss); } return res; } @Override public String getName() { return AvailableCommandNames.ENGINE_RUNTIME.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Fuel systems that use conventional oxygen sensor display the commanded open * loop equivalence ratio while the system is in open loop. Should report 100% * when in closed loop fuel. * * To obtain the actual air/fuel ratio being commanded, multiply the * stoichiometric A/F ratio by the equivalence ratio. For example, gasoline, * stoichiometric is 14.64:1 ratio. If the fuel control system was commanded an * equivalence ratio of 0.95, the commanded A/F ratio to the engine would be * 14.64 * 0.95 = 13.9 A/F. */ public class CommandEquivRatioObdCommand extends ObdCommand { /* * Equivalent ratio (%) */ private double ratio = 0.00; /** * Default ctor. */ public CommandEquivRatioObdCommand() { super("01 44"); } /** * Copy ctor. * * @param other */ public CommandEquivRatioObdCommand(CommandEquivRatioObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); ratio = (a * 256 + b) / 32768; res = String.format("%.1f%s", ratio, "%"); } return res; } /** * @return */ public double getRatio() { return ratio; } @Override public String getName() { return AvailableCommandNames.EQUIV_RATIO.getValue(); } }
Java