code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Feb 25, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import nl.sogeti.android.gpstracker.R;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;
/**
* ????
*
* @version $Id:$
* @author rene (c) Feb 25, 2012, Sogeti B.V.
*/
public class About extends Activity
{
private static final String TAG = "OGT.About";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
fillContentFields();
}
private void fillContentFields()
{
TextView version = (TextView) findViewById(R.id.version);
try
{
version.setText(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
}
catch (NameNotFoundException e)
{
version.setText("");
}
WebView license = (WebView) findViewById(R.id.license_body);
license.loadUrl("file:///android_asset/license_short.html");
WebView contributions = (WebView) findViewById(R.id.contribution_body);
contributions.loadUrl("file:///android_asset/contributions.html");
WebView notice = (WebView) findViewById(R.id.notices_body);
notice.loadUrl("file:///android_asset/notices.html");
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try
{
while ((line = buffreader.readLine()) != null)
{
text.append(line);
text.append('\n');
}
}
catch (IOException e)
{
Log.e(TAG, "Failed to read raw text resource", e);
}
return text.toString();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer.map;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.SlidingIndicatorView;
import nl.sogeti.android.gpstracker.viewer.map.overlay.FixedMyLocationOverlay;
import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
/**
* Main activity showing a track and allowing logging control
*
* @version $Id$
* @author rene (c) Jan 18, 2009, Sogeti B.V.
*/
public class GoogleLoggerMap extends MapActivity implements LoggerMap
{
LoggerMapHelper mHelper;
private MapView mMapView;
private TextView[] mSpeedtexts;
private TextView mLastGPSSpeedView;
private TextView mLastGPSAltitudeView;
private TextView mDistanceView;
private FixedMyLocationOverlay mMylocation;
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate(Bundle load)
{
super.onCreate(load);
setContentView(R.layout.map_google);
mHelper = new LoggerMapHelper(this);
mMapView = (MapView) findViewById(R.id.myMapView);
mMylocation = new FixedMyLocationOverlay(this, mMapView);
mMapView.setBuiltInZoomControls(true);
TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03),
(TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) };
mSpeedtexts = speeds;
mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed);
mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude);
mDistanceView = (TextView) findViewById(R.id.currentDistance);
mHelper.onCreate(load);
}
@Override
protected void onResume()
{
super.onResume();
mHelper.onResume();
}
@Override
protected void onPause()
{
mHelper.onPause();
super.onPause();
}
@Override
protected void onDestroy()
{
mHelper.onDestroy();
super.onDestroy();
}
@Override
public void onNewIntent(Intent newIntent)
{
mHelper.onNewIntent(newIntent);
}
@Override
protected void onRestoreInstanceState(Bundle load)
{
if (load != null)
{
super.onRestoreInstanceState(load);
}
mHelper.onRestoreInstanceState(load);
}
@Override
protected void onSaveInstanceState(Bundle save)
{
super.onSaveInstanceState(save);
mHelper.onSaveInstanceState(save);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
mHelper.onCreateOptionsMenu(menu);
return result;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
mHelper.onPrepareOptionsMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
boolean handled = mHelper.onOptionsItemSelected(item);
if( !handled )
{
handled = super.onOptionsItemSelected(item);
}
return handled;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
mHelper.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean propagate = true;
switch (keyCode)
{
case KeyEvent.KEYCODE_S:
setSatelliteOverlay(!this.mMapView.isSatellite());
propagate = false;
break;
case KeyEvent.KEYCODE_A:
setTrafficOverlay(!this.mMapView.isTraffic());
propagate = false;
break;
default:
propagate = mHelper.onKeyDown(keyCode, event);
if( propagate )
{
propagate = super.onKeyDown(keyCode, event);
}
break;
}
return propagate;
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = mHelper.onCreateDialog(id);
if( dialog == null )
{
dialog = super.onCreateDialog(id);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
mHelper.onPrepareDialog(id, dialog);
super.onPrepareDialog(id, dialog);
}
/******************************/
/** Own methods **/
/******************************/
private void setTrafficOverlay(boolean b)
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.TRAFFIC, b);
editor.commit();
}
private void setSatelliteOverlay(boolean b)
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.SATELLITE, b);
editor.commit();
}
@Override
protected boolean isRouteDisplayed()
{
return true;
}
@Override
protected boolean isLocationDisplayed()
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
return sharedPreferences.getBoolean(Constants.LOCATION, false) || mHelper.isLogging();
}
/******************************/
/** Loggermap methods **/
/******************************/
@Override
public void updateOverlays()
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
GoogleLoggerMap.this.mMapView.setSatellite(sharedPreferences.getBoolean(Constants.SATELLITE, false));
GoogleLoggerMap.this.mMapView.setTraffic(sharedPreferences.getBoolean(Constants.TRAFFIC, false));
}
@Override
public void setDrawingCacheEnabled(boolean b)
{
findViewById(R.id.mapScreen).setDrawingCacheEnabled(true);
}
@Override
public Activity getActivity()
{
return this;
}
@Override
public void onLayerCheckedChanged(int checkedId, boolean isChecked)
{
switch (checkedId)
{
case R.id.layer_google_satellite:
setSatelliteOverlay(true);
break;
case R.id.layer_google_regular:
setSatelliteOverlay(false);
break;
case R.id.layer_traffic:
setTrafficOverlay(isChecked);
break;
default:
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.TRAFFIC))
{
updateOverlays();
}
else if (key.equals(Constants.SATELLITE))
{
updateOverlays();
}
}
@Override
public Bitmap getDrawingCache()
{
return findViewById(R.id.mapScreen).getDrawingCache();
}
@Override
public void showMediaDialog(BaseAdapter mediaAdapter)
{
mHelper.showMediaDialog(mediaAdapter);
}
public void onDateOverlayChanged()
{
mMapView.postInvalidate();
}
@Override
public String getDataSourceId()
{
return LoggerMapHelper.GOOGLE_PROVIDER;
}
@Override
public boolean isOutsideScreen(GeoPoint lastPoint)
{
Point out = new Point();
this.mMapView.getProjection().toPixels(lastPoint, out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < 0 || out.y < 0 || out.y > height || out.x > width);
}
@Override
public boolean isNearScreenEdge(GeoPoint lastPoint)
{
Point out = new Point();
this.mMapView.getProjection().toPixels(lastPoint, out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3);
}
@Override
public void executePostponedActions()
{
// NOOP for Google Maps
}
@Override
public void enableCompass()
{
mMylocation.enableCompass();
}
@Override
public void enableMyLocation()
{
mMylocation.enableMyLocation();
}
@Override
public void disableMyLocation()
{
mMylocation.disableMyLocation();
}
@Override
public void disableCompass()
{
mMylocation.disableCompass();
}
@Override
public void setZoom(int zoom)
{
mMapView.getController().setZoom(zoom);
}
@Override
public void animateTo(GeoPoint storedPoint)
{
mMapView.getController().animateTo(storedPoint);
}
@Override
public int getZoomLevel()
{
return mMapView.getZoomLevel();
}
@Override
public GeoPoint getMapCenter()
{
return mMapView.getMapCenter();
}
@Override
public boolean zoomOut()
{
return mMapView.getController().zoomOut();
}
@Override
public boolean zoomIn()
{
return mMapView.getController().zoomIn();
}
@Override
public void postInvalidate()
{
mMapView.postInvalidate();
}
@Override
public void clearAnimation()
{
mMapView.clearAnimation();
}
@Override
public void setCenter(GeoPoint lastPoint)
{
mMapView.getController().setCenter(lastPoint);
}
@Override
public int getMaxZoomLevel()
{
return mMapView.getMaxZoomLevel();
}
@Override
public GeoPoint fromPixels(int x, int y)
{
return mMapView.getProjection().fromPixels(x, y);
}
@Override
public boolean hasProjection()
{
return mMapView.getProjection() != null;
}
@Override
public float metersToEquatorPixels(float float1)
{
return mMapView.getProjection().metersToEquatorPixels(float1);
}
@Override
public void toPixels(GeoPoint geoPoint, Point screenPoint)
{
mMapView.getProjection().toPixels(geoPoint, screenPoint);
}
@Override
public TextView[] getSpeedTextViews()
{
return mSpeedtexts;
}
@Override
public TextView getAltitideTextView()
{
return mLastGPSAltitudeView;
}
@Override
public TextView getSpeedTextView()
{
return mLastGPSSpeedView;
}
@Override
public TextView getDistanceTextView()
{
return mDistanceView;
}
@Override
public void addOverlay(OverlayProvider overlay)
{
mMapView.getOverlays().add(overlay.getGoogleOverlay());
}
@Override
public void clearOverlays()
{
mMapView.getOverlays().clear();
}
@Override
public SlidingIndicatorView getScaleIndicatorView()
{
return (SlidingIndicatorView) findViewById(R.id.scaleindicator);
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer.map;
import java.util.concurrent.Semaphore;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.ControlTracking;
import nl.sogeti.android.gpstracker.actions.InsertNote;
import nl.sogeti.android.gpstracker.actions.ShareTrack;
import nl.sogeti.android.gpstracker.actions.Statistics;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.Segments;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.SlidingIndicatorView;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.About;
import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity;
import nl.sogeti.android.gpstracker.viewer.TrackList;
import nl.sogeti.android.gpstracker.viewer.map.overlay.BitmapSegmentsOverlay;
import nl.sogeti.android.gpstracker.viewer.map.overlay.SegmentRendering;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Gallery;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
/**
* ????
*
* @version $Id:$
* @author rene (c) Feb 26, 2012, Sogeti B.V.
*/
public class LoggerMapHelper
{
public static final String OSM_PROVIDER = "OSM";
public static final String GOOGLE_PROVIDER = "GOOGLE";
public static final String MAPQUEST_PROVIDER = "MAPQUEST";
private static final String INSTANCE_E6LONG = "e6long";
private static final String INSTANCE_E6LAT = "e6lat";
private static final String INSTANCE_ZOOM = "zoom";
private static final String INSTANCE_AVGSPEED = "averagespeed";
private static final String INSTANCE_HEIGHT = "averageheight";
private static final String INSTANCE_TRACK = "track";
private static final String INSTANCE_SPEED = "speed";
private static final String INSTANCE_ALTITUDE = "altitude";
private static final String INSTANCE_DISTANCE = "distance";
private static final int ZOOM_LEVEL = 16;
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_TRACKLIST = 3;
private static final int MENU_STATS = 4;
private static final int MENU_ABOUT = 5;
private static final int MENU_LAYERS = 6;
private static final int MENU_NOTE = 7;
private static final int MENU_SHARE = 13;
private static final int MENU_CONTRIB = 14;
private static final int DIALOG_NOTRACK = 24;
private static final int DIALOG_LAYERS = 31;
private static final int DIALOG_URIS = 34;
private static final int DIALOG_CONTRIB = 35;
private static final String TAG = "OGT.LoggerMap";
private double mAverageSpeed = 33.33d / 3d;
private double mAverageHeight = 33.33d / 3d;
private long mTrackId = -1;
private long mLastSegment = -1;
private UnitsI18n mUnits;
private WakeLock mWakeLock = null;
private SharedPreferences mSharedPreferences;
private GPSLoggerServiceManager mLoggerServiceManager;
private SegmentRendering mLastSegmentOverlay;
private BaseAdapter mMediaAdapter;
private Handler mHandler;
private ContentObserver mTrackSegmentsObserver;
private ContentObserver mSegmentWaypointsObserver;
private ContentObserver mTrackMediasObserver;
private DialogInterface.OnClickListener mNoTrackDialogListener;
private OnItemSelectedListener mGalerySelectListener;
private Uri mSelected;
private OnClickListener mNoteSelectDialogListener;
private OnCheckedChangeListener mCheckedChangeListener;
private android.widget.RadioGroup.OnCheckedChangeListener mGroupCheckedChangeListener;
private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener;
private UnitsI18n.UnitsChangeListener mUnitsChangeListener;
/**
* Run after the ServiceManager completes the binding to the remote service
*/
private Runnable mServiceConnected;
private Runnable speedCalculator;
private Runnable heightCalculator;
private LoggerMap mLoggerMap;
private BitmapSegmentsOverlay mBitmapSegmentsOverlay;
private float mSpeed;
private double mAltitude;
private float mDistance;
public LoggerMapHelper(LoggerMap loggerMap)
{
mLoggerMap = loggerMap;
}
/**
* Called when the activity is first created.
*/
protected void onCreate(Bundle load)
{
mLoggerMap.setDrawingCacheEnabled(true);
mUnits = new UnitsI18n(mLoggerMap.getActivity());
mLoggerServiceManager = new GPSLoggerServiceManager(mLoggerMap.getActivity());
final Semaphore calulatorSemaphore = new Semaphore(0);
Thread calulator = new Thread("OverlayCalculator")
{
@Override
public void run()
{
Looper.prepare();
mHandler = new Handler();
calulatorSemaphore.release();
Looper.loop();
}
};
calulator.start();
try
{
calulatorSemaphore.acquire();
}
catch (InterruptedException e)
{
Log.e(TAG, "Failed waiting for a semaphore", e);
}
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mLoggerMap.getActivity());
mBitmapSegmentsOverlay = new BitmapSegmentsOverlay(mLoggerMap, mHandler);
createListeners();
onRestoreInstanceState(load);
mLoggerMap.updateOverlays();
}
protected void onResume()
{
updateMapProvider();
mLoggerServiceManager.startup(mLoggerMap.getActivity(), mServiceConnected);
mSharedPreferences.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);
mUnits.setUnitsChangeListener(mUnitsChangeListener);
updateTitleBar();
updateBlankingBehavior();
if (mTrackId >= 0)
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Uri trackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments");
Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints");
Uri mediaUri = ContentUris.withAppendedId(Media.CONTENT_URI, mTrackId);
resolver.unregisterContentObserver(this.mTrackSegmentsObserver);
resolver.unregisterContentObserver(this.mSegmentWaypointsObserver);
resolver.unregisterContentObserver(this.mTrackMediasObserver);
resolver.registerContentObserver(trackUri, false, this.mTrackSegmentsObserver);
resolver.registerContentObserver(lastSegmentUri, true, this.mSegmentWaypointsObserver);
resolver.registerContentObserver(mediaUri, true, this.mTrackMediasObserver);
}
updateDataOverlays();
updateSpeedColoring();
updateSpeedDisplayVisibility();
updateAltitudeDisplayVisibility();
updateDistanceDisplayVisibility();
updateCompassDisplayVisibility();
updateLocationDisplayVisibility();
updateTrackNumbers();
mLoggerMap.executePostponedActions();
}
protected void onPause()
{
if (this.mWakeLock != null && this.mWakeLock.isHeld())
{
this.mWakeLock.release();
Log.w(TAG, "onPause(): Released lock to keep screen on!");
}
mLoggerMap.clearOverlays();
mBitmapSegmentsOverlay.clearSegments();
mLastSegmentOverlay = null;
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
resolver.unregisterContentObserver(this.mTrackSegmentsObserver);
resolver.unregisterContentObserver(this.mSegmentWaypointsObserver);
resolver.unregisterContentObserver(this.mTrackMediasObserver);
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener);
mUnits.setUnitsChangeListener(null);
mLoggerMap.disableMyLocation();
mLoggerMap.disableCompass();
this.mLoggerServiceManager.shutdown(mLoggerMap.getActivity());
}
protected void onDestroy()
{
mLoggerMap.clearOverlays();
mHandler.post(new Runnable()
{
@Override
public void run()
{
Looper.myLooper().quit();
}
});
if (mWakeLock != null && mWakeLock.isHeld())
{
mWakeLock.release();
Log.w(TAG, "onDestroy(): Released lock to keep screen on!");
}
if (mLoggerServiceManager.getLoggingState() == Constants.STOPPED)
{
mLoggerMap.getActivity().stopService(new Intent(Constants.SERVICENAME));
}
mUnits = null;
}
public void onNewIntent(Intent newIntent)
{
Uri data = newIntent.getData();
if (data != null)
{
moveToTrack(Long.parseLong(data.getLastPathSegment()), true);
}
}
protected void onRestoreInstanceState(Bundle load)
{
Uri data = mLoggerMap.getActivity().getIntent().getData();
if (load != null && load.containsKey(INSTANCE_TRACK)) // 1st method: track from a previous instance of this activity
{
long loadTrackId = load.getLong(INSTANCE_TRACK);
moveToTrack(loadTrackId, false);
if (load.containsKey(INSTANCE_AVGSPEED))
{
mAverageSpeed = load.getDouble(INSTANCE_AVGSPEED);
}
if (load.containsKey(INSTANCE_HEIGHT))
{
mAverageHeight = load.getDouble(INSTANCE_HEIGHT);
}
if( load.containsKey(INSTANCE_SPEED))
{
mSpeed = load.getFloat(INSTANCE_SPEED);
}
if( load.containsKey(INSTANCE_ALTITUDE))
{
mAltitude = load.getDouble(INSTANCE_HEIGHT);
}
if( load.containsKey(INSTANCE_DISTANCE))
{
mDistance = load.getFloat(INSTANCE_DISTANCE);
}
}
else if (data != null) // 2nd method: track ordered to make
{
long loadTrackId = Long.parseLong(data.getLastPathSegment());
moveToTrack(loadTrackId, true);
}
else
// 3rd method: just try the last track
{
moveToLastTrack();
}
if (load != null && load.containsKey(INSTANCE_ZOOM))
{
mLoggerMap.setZoom(load.getInt(INSTANCE_ZOOM));
}
else
{
mLoggerMap.setZoom(ZOOM_LEVEL);
}
if (load != null && load.containsKey(INSTANCE_E6LAT) && load.containsKey(INSTANCE_E6LONG))
{
GeoPoint storedPoint = new GeoPoint(load.getInt(INSTANCE_E6LAT), load.getInt(INSTANCE_E6LONG));
mLoggerMap.animateTo(storedPoint);
}
else
{
GeoPoint lastPoint = getLastTrackPoint();
mLoggerMap.animateTo(lastPoint);
}
}
protected void onSaveInstanceState(Bundle save)
{
save.putLong(INSTANCE_TRACK, this.mTrackId);
save.putDouble(INSTANCE_AVGSPEED, mAverageSpeed);
save.putDouble(INSTANCE_HEIGHT, mAverageHeight);
save.putInt(INSTANCE_ZOOM, mLoggerMap.getZoomLevel());
save.putFloat(INSTANCE_SPEED, mSpeed);
save.putDouble(INSTANCE_ALTITUDE, mAltitude);
save.putFloat(INSTANCE_DISTANCE, mDistance);
GeoPoint point = mLoggerMap.getMapCenter();
save.putInt(INSTANCE_E6LAT, point.getLatitudeE6());
save.putInt(INSTANCE_E6LONG, point.getLongitudeE6());
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean propagate = true;
switch (keyCode)
{
case KeyEvent.KEYCODE_T:
propagate = mLoggerMap.zoomIn();
propagate = false;
break;
case KeyEvent.KEYCODE_G:
propagate = mLoggerMap.zoomOut();
propagate = false;
break;
case KeyEvent.KEYCODE_F:
moveToTrack(this.mTrackId - 1, true);
propagate = false;
break;
case KeyEvent.KEYCODE_H:
moveToTrack(this.mTrackId + 1, true);
propagate = false;
break;
}
return propagate;
}
private void setSpeedOverlay(boolean b)
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.SPEED, b);
editor.commit();
}
private void setAltitudeOverlay(boolean b)
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.ALTITUDE, b);
editor.commit();
}
private void setDistanceOverlay(boolean b)
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.DISTANCE, b);
editor.commit();
}
private void setCompassOverlay(boolean b)
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.COMPASS, b);
editor.commit();
}
private void setLocationOverlay(boolean b)
{
Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.LOCATION, b);
editor.commit();
}
private void setOsmBaseOverlay(int b)
{
Editor editor = mSharedPreferences.edit();
editor.putInt(Constants.OSMBASEOVERLAY, b);
editor.commit();
}
private void createListeners()
{
/*******************************************************
* 8 Runnable listener actions
*/
speedCalculator = new Runnable()
{
@Override
public void run()
{
double avgspeed = 0.0;
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Cursor waypointsCursor = null;
try
{
waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] {
"avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null, null, null);
if (waypointsCursor != null && waypointsCursor.moveToLast())
{
double average = waypointsCursor.getDouble(0);
double maxBasedAverage = waypointsCursor.getDouble(1) / 2;
avgspeed = Math.min(average, maxBasedAverage);
}
if (avgspeed < 2)
{
avgspeed = 5.55d / 2;
}
}
finally
{
if (waypointsCursor != null)
{
waypointsCursor.close();
}
}
mAverageSpeed = avgspeed;
mLoggerMap.getActivity().runOnUiThread(new Runnable()
{
@Override
public void run()
{
updateSpeedColoring();
}
});
}
};
heightCalculator = new Runnable()
{
@Override
public void run()
{
double avgHeight = 0.0;
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Cursor waypointsCursor = null;
try
{
waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] {
"avg(" + Waypoints.ALTITUDE + ")", "max(" + Waypoints.ALTITUDE + ")" }, null, null, null);
if (waypointsCursor != null && waypointsCursor.moveToLast())
{
double average = waypointsCursor.getDouble(0);
double maxBasedAverage = waypointsCursor.getDouble(1) / 2;
avgHeight = Math.min(average, maxBasedAverage);
}
}
finally
{
if (waypointsCursor != null)
{
waypointsCursor.close();
}
}
mAverageHeight = avgHeight;
mLoggerMap.getActivity().runOnUiThread(new Runnable()
{
@Override
public void run()
{
updateSpeedColoring();
}
});
}
};
mServiceConnected = new Runnable()
{
@Override
public void run()
{
updateBlankingBehavior();
}
};
/*******************************************************
* 8 Various dialog listeners
*/
mGalerySelectListener = new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView< ? > parent, View view, int pos, long id)
{
mSelected = (Uri) parent.getSelectedItem();
}
@Override
public void onNothingSelected(AdapterView< ? > arg0)
{
mSelected = null;
}
};
mNoteSelectDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
SegmentRendering.handleMedia(mLoggerMap.getActivity(), mSelected);
mSelected = null;
}
};
mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.layer_osm_cloudmade:
setOsmBaseOverlay(Constants.OSM_CLOUDMADE);
break;
case R.id.layer_osm_maknik:
setOsmBaseOverlay(Constants.OSM_MAKNIK);
break;
case R.id.layer_osm_bicycle:
setOsmBaseOverlay(Constants.OSM_CYCLE);
break;
default:
mLoggerMap.onLayerCheckedChanged(checkedId, true);
break;
}
}
};
mCheckedChangeListener = new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
int checkedId;
checkedId = buttonView.getId();
switch (checkedId)
{
case R.id.layer_speed:
setSpeedOverlay(isChecked);
break;
case R.id.layer_altitude:
setAltitudeOverlay(isChecked);
break;
case R.id.layer_distance:
setDistanceOverlay(isChecked);
break;
case R.id.layer_compass:
setCompassOverlay(isChecked);
break;
case R.id.layer_location:
setLocationOverlay(isChecked);
break;
default:
mLoggerMap.onLayerCheckedChanged(checkedId, isChecked);
break;
}
}
};
mNoTrackDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Log.d( TAG, "mNoTrackDialogListener" + which);
Intent tracklistIntent = new Intent(mLoggerMap.getActivity(), TrackList.class);
tracklistIntent.putExtra(Tracks._ID, mTrackId);
mLoggerMap.getActivity().startActivityForResult(tracklistIntent, MENU_TRACKLIST);
}
};
/**
* Listeners to events outside this mapview
*/
mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener()
{
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.TRACKCOLORING))
{
mAverageSpeed = 0.0;
mAverageHeight = 0.0;
updateSpeedColoring();
}
else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING))
{
updateBlankingBehavior();
}
else if (key.equals(Constants.SPEED))
{
updateSpeedDisplayVisibility();
}
else if (key.equals(Constants.ALTITUDE))
{
updateAltitudeDisplayVisibility();
}
else if (key.equals(Constants.DISTANCE))
{
updateDistanceDisplayVisibility();
}
else if (key.equals(Constants.COMPASS))
{
updateCompassDisplayVisibility();
}
else if (key.equals(Constants.LOCATION))
{
updateLocationDisplayVisibility();
}
else if (key.equals(Constants.MAPPROVIDER))
{
updateMapProvider();
}
else if (key.equals(Constants.OSMBASEOVERLAY))
{
mLoggerMap.updateOverlays();
}
else
{
mLoggerMap.onSharedPreferenceChanged(sharedPreferences, key);
}
}
};
mTrackMediasObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
if (mLastSegmentOverlay != null)
{
mLastSegmentOverlay.calculateMedia();
}
}
else
{
Log.w(TAG, "mTrackMediasObserver skipping change on " + mLastSegment);
}
}
};
mTrackSegmentsObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
updateDataOverlays();
}
else
{
Log.w(TAG, "mTrackSegmentsObserver skipping change on " + mLastSegment);
}
}
};
mSegmentWaypointsObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
updateTrackNumbers();
if (mLastSegmentOverlay != null)
{
moveActiveViewWindow();
updateMapProviderAdministration(mLoggerMap.getDataSourceId());
}
else
{
Log.e(TAG, "Error the last segment changed but it is not on screen! " + mLastSegment);
}
}
else
{
Log.w(TAG, "mSegmentWaypointsObserver skipping change on " + mLastSegment);
}
}
};
mUnitsChangeListener = new UnitsI18n.UnitsChangeListener()
{
@Override
public void onUnitsChange()
{
mAverageSpeed = 0.0;
mAverageHeight = 0.0;
updateTrackNumbers();
updateSpeedColoring();
}
};
}
public void onCreateOptionsMenu(Menu menu)
{
menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T');
menu.add(ContextMenu.NONE, MENU_LAYERS, ContextMenu.NONE, R.string.menu_showLayers).setIcon(R.drawable.ic_menu_mapmode).setAlphabeticShortcut('L');
menu.add(ContextMenu.NONE, MENU_NOTE, ContextMenu.NONE, R.string.menu_insertnote).setIcon(R.drawable.ic_menu_myplaces);
menu.add(ContextMenu.NONE, MENU_STATS, ContextMenu.NONE, R.string.menu_statistics).setIcon(R.drawable.ic_menu_picture).setAlphabeticShortcut('S');
menu.add(ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack).setIcon(R.drawable.ic_menu_share).setAlphabeticShortcut('I');
// More
menu.add(ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist).setIcon(R.drawable.ic_menu_show_list).setAlphabeticShortcut('P');
menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C');
menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A');
menu.add(ContextMenu.NONE, MENU_CONTRIB, ContextMenu.NONE, R.string.menu_contrib).setIcon(R.drawable.ic_menu_allfriends);
}
public void onPrepareOptionsMenu(Menu menu)
{
MenuItem noteMenu = menu.findItem(MENU_NOTE);
noteMenu.setEnabled(mLoggerServiceManager.isMediaPrepared());
MenuItem shareMenu = menu.findItem(MENU_SHARE);
shareMenu.setEnabled(mTrackId >= 0);
}
public boolean onOptionsItemSelected(MenuItem item)
{
boolean handled = false;
Uri trackUri;
Intent intent;
switch (item.getItemId())
{
case MENU_TRACKING:
intent = new Intent(mLoggerMap.getActivity(), ControlTracking.class);
mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKING);
handled = true;
break;
case MENU_LAYERS:
mLoggerMap.getActivity().showDialog(DIALOG_LAYERS);
handled = true;
break;
case MENU_NOTE:
intent = new Intent(mLoggerMap.getActivity(), InsertNote.class);
mLoggerMap.getActivity().startActivityForResult(intent, MENU_NOTE);
handled = true;
break;
case MENU_SETTINGS:
intent = new Intent(mLoggerMap.getActivity(), ApplicationPreferenceActivity.class);
mLoggerMap.getActivity().startActivity(intent);
handled = true;
break;
case MENU_TRACKLIST:
intent = new Intent(mLoggerMap.getActivity(), TrackList.class);
intent.putExtra(Tracks._ID, this.mTrackId);
mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKLIST);
handled = true;
break;
case MENU_STATS:
if (this.mTrackId >= 0)
{
intent = new Intent(mLoggerMap.getActivity(), Statistics.class);
trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId);
intent.setData(trackUri);
mLoggerMap.getActivity().startActivity(intent);
break;
}
else
{
mLoggerMap.getActivity().showDialog(DIALOG_NOTRACK);
}
handled = true;
break;
case MENU_ABOUT:
intent = new Intent(mLoggerMap.getActivity(), About.class);
mLoggerMap.getActivity().startActivity(intent);
break;
case MENU_SHARE:
intent = new Intent(Intent.ACTION_RUN);
trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId);
intent.setDataAndType(trackUri, Tracks.CONTENT_ITEM_TYPE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Bitmap bm = mLoggerMap.getDrawingCache();
Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm);
intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri);
mLoggerMap.getActivity().startActivityForResult(Intent.createChooser(intent, mLoggerMap.getActivity().getString(R.string.share_track)), MENU_SHARE);
handled = true;
break;
case MENU_CONTRIB:
mLoggerMap.getActivity().showDialog(DIALOG_CONTRIB);
default:
handled = false;
break;
}
return handled;
}
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_LAYERS:
builder = new AlertDialog.Builder(mLoggerMap.getActivity());
factory = LayoutInflater.from(mLoggerMap.getActivity());
view = factory.inflate(R.layout.layerdialog, null);
CheckBox traffic = (CheckBox) view.findViewById(R.id.layer_traffic);
CheckBox speed = (CheckBox) view.findViewById(R.id.layer_speed);
CheckBox altitude = (CheckBox) view.findViewById(R.id.layer_altitude);
CheckBox distance = (CheckBox) view.findViewById(R.id.layer_distance);
CheckBox compass = (CheckBox) view.findViewById(R.id.layer_compass);
CheckBox location = (CheckBox) view.findViewById(R.id.layer_location);
((RadioGroup) view.findViewById(R.id.google_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener);
((RadioGroup) view.findViewById(R.id.osm_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener);
traffic.setOnCheckedChangeListener(mCheckedChangeListener);
speed.setOnCheckedChangeListener(mCheckedChangeListener);
altitude.setOnCheckedChangeListener(mCheckedChangeListener);
distance.setOnCheckedChangeListener(mCheckedChangeListener);
compass.setOnCheckedChangeListener(mCheckedChangeListener);
location.setOnCheckedChangeListener(mCheckedChangeListener);
builder.setTitle(R.string.dialog_layer_title).setIcon(android.R.drawable.ic_dialog_map).setPositiveButton(R.string.btn_okay, null).setView(view);
dialog = builder.create();
return dialog;
case DIALOG_NOTRACK:
builder = new AlertDialog.Builder(mLoggerMap.getActivity());
builder.setTitle(R.string.dialog_notrack_title).setMessage(R.string.dialog_notrack_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_selecttrack, mNoTrackDialogListener).setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
case DIALOG_URIS:
builder = new AlertDialog.Builder(mLoggerMap.getActivity());
factory = LayoutInflater.from(mLoggerMap.getActivity());
view = factory.inflate(R.layout.mediachooser, null);
builder.setTitle(R.string.dialog_select_media_title).setMessage(R.string.dialog_select_media_message).setIcon(android.R.drawable.ic_dialog_alert)
.setNegativeButton(R.string.btn_cancel, null).setPositiveButton(R.string.btn_okay, mNoteSelectDialogListener).setView(view);
dialog = builder.create();
return dialog;
case DIALOG_CONTRIB:
builder = new AlertDialog.Builder(mLoggerMap.getActivity());
factory = LayoutInflater.from(mLoggerMap.getActivity());
view = factory.inflate(R.layout.contrib, null);
TextView contribView = (TextView) view.findViewById(R.id.contrib_view);
contribView.setText(R.string.dialog_contrib_message);
builder.setTitle(R.string.dialog_contrib_title).setView(view).setIcon(android.R.drawable.ic_dialog_email)
.setPositiveButton(R.string.btn_okay, null);
dialog = builder.create();
return dialog;
default:
return null;
}
}
protected void onPrepareDialog(int id, Dialog dialog)
{
RadioButton satellite;
RadioButton regular;
RadioButton cloudmade;
RadioButton mapnik;
RadioButton cycle;
switch (id)
{
case DIALOG_LAYERS:
satellite = (RadioButton) dialog.findViewById(R.id.layer_google_satellite);
regular = (RadioButton) dialog.findViewById(R.id.layer_google_regular);
satellite.setChecked(mSharedPreferences.getBoolean(Constants.SATELLITE, false));
regular.setChecked(!mSharedPreferences.getBoolean(Constants.SATELLITE, false));
int osmbase = mSharedPreferences.getInt(Constants.OSMBASEOVERLAY, 0);
cloudmade = (RadioButton) dialog.findViewById(R.id.layer_osm_cloudmade);
mapnik = (RadioButton) dialog.findViewById(R.id.layer_osm_maknik);
cycle = (RadioButton) dialog.findViewById(R.id.layer_osm_bicycle);
cloudmade.setChecked(osmbase == Constants.OSM_CLOUDMADE);
mapnik.setChecked(osmbase == Constants.OSM_MAKNIK);
cycle.setChecked(osmbase == Constants.OSM_CYCLE);
((CheckBox) dialog.findViewById(R.id.layer_traffic)).setChecked(mSharedPreferences.getBoolean(Constants.TRAFFIC, false));
((CheckBox) dialog.findViewById(R.id.layer_speed)).setChecked(mSharedPreferences.getBoolean(Constants.SPEED, false));
((CheckBox) dialog.findViewById(R.id.layer_altitude)).setChecked(mSharedPreferences.getBoolean(Constants.ALTITUDE, false));
((CheckBox) dialog.findViewById(R.id.layer_distance)).setChecked(mSharedPreferences.getBoolean(Constants.DISTANCE, false));
((CheckBox) dialog.findViewById(R.id.layer_compass)).setChecked(mSharedPreferences.getBoolean(Constants.COMPASS, false));
((CheckBox) dialog.findViewById(R.id.layer_location)).setChecked(mSharedPreferences.getBoolean(Constants.LOCATION, false));
int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue();
switch (provider)
{
case Constants.GOOGLE:
dialog.findViewById(R.id.google_backgrounds).setVisibility(View.VISIBLE);
dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE);
dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE);
dialog.findViewById(R.id.google_overlays).setVisibility(View.VISIBLE);
break;
case Constants.OSM:
dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.VISIBLE);
dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE);
dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE);
dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE);
break;
default:
dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE);
dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE);
dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE);
dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE);
break;
}
break;
case DIALOG_URIS:
Gallery gallery = (Gallery) dialog.findViewById(R.id.gallery);
gallery.setAdapter(mMediaAdapter);
gallery.setOnItemSelectedListener(mGalerySelectListener);
default:
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Uri trackUri;
long trackId;
switch (requestCode)
{
case MENU_TRACKLIST:
if (resultCode == Activity.RESULT_OK)
{
trackUri = intent.getData();
trackId = Long.parseLong(trackUri.getLastPathSegment());
moveToTrack(trackId, true);
}
break;
case MENU_TRACKING:
if (resultCode == Activity.RESULT_OK)
{
trackUri = intent.getData();
if (trackUri != null)
{
trackId = Long.parseLong(trackUri.getLastPathSegment());
moveToTrack(trackId, true);
}
}
break;
case MENU_SHARE:
ShareTrack.clearScreenBitmap();
break;
default:
Log.e(TAG, "Returned form unknow activity: " + requestCode);
break;
}
}
private void updateTitleBar()
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Cursor trackCursor = null;
try
{
trackCursor = resolver.query(ContentUris.withAppendedId(Tracks.CONTENT_URI, this.mTrackId), new String[] { Tracks.NAME }, null, null, null);
if (trackCursor != null && trackCursor.moveToLast())
{
String trackName = trackCursor.getString(0);
mLoggerMap.getActivity().setTitle(mLoggerMap.getActivity().getString(R.string.app_name) + ": " + trackName);
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
}
private void updateMapProvider()
{
Class< ? > mapClass = null;
int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue();
switch (provider)
{
case Constants.GOOGLE:
mapClass = GoogleLoggerMap.class;
break;
case Constants.OSM:
mapClass = OsmLoggerMap.class;
break;
case Constants.MAPQUEST:
mapClass = MapQuestLoggerMap.class;
break;
default:
mapClass = GoogleLoggerMap.class;
Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps.");
break;
}
if (mapClass != mLoggerMap.getActivity().getClass())
{
Intent myIntent = mLoggerMap.getActivity().getIntent();
Intent realIntent;
if (myIntent != null)
{
realIntent = new Intent(myIntent.getAction(), myIntent.getData(), mLoggerMap.getActivity(), mapClass);
realIntent.putExtras(myIntent);
}
else
{
realIntent = new Intent(mLoggerMap.getActivity(), mapClass);
realIntent.putExtras(myIntent);
}
mLoggerMap.getActivity().startActivity(realIntent);
mLoggerMap.getActivity().finish();
}
}
protected void updateMapProviderAdministration(String provider)
{
mLoggerServiceManager.storeDerivedDataSource(provider);
}
private void updateBlankingBehavior()
{
boolean disableblanking = mSharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
boolean disabledimming = mSharedPreferences.getBoolean(Constants.DISABLEDIMMING, false);
if (disableblanking)
{
if (mWakeLock == null)
{
PowerManager pm = (PowerManager) mLoggerMap.getActivity().getSystemService(Context.POWER_SERVICE);
if (disabledimming)
{
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
}
else
{
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
}
}
if (mLoggerServiceManager.getLoggingState() == Constants.LOGGING && !mWakeLock.isHeld())
{
mWakeLock.acquire();
Log.w(TAG, "Acquired lock to keep screen on!");
}
}
}
private void updateSpeedColoring()
{
int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue();
View speedbar = mLoggerMap.getActivity().findViewById(R.id.speedbar);
SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView();
TextView[] speedtexts = mLoggerMap.getSpeedTextViews();
switch (trackColoringMethod)
{
case SegmentRendering.DRAW_MEASURED:
case SegmentRendering.DRAW_CALCULATED:
// mAverageSpeed is set to 0 if unknown or to trigger an recalculation here
if (mAverageSpeed == 0.0)
{
mHandler.removeCallbacks(speedCalculator);
mHandler.post(speedCalculator);
}
else
{
drawSpeedTexts();
speedtexts = mLoggerMap.getSpeedTextViews();
speedbar.setVisibility(View.VISIBLE);
scaleIndicator.setVisibility(View.VISIBLE);
for (int i = 0; i < speedtexts.length; i++)
{
speedtexts[i].setVisibility(View.VISIBLE);
}
}
break;
case SegmentRendering.DRAW_DOTS:
case SegmentRendering.DRAW_GREEN:
case SegmentRendering.DRAW_RED:
speedbar.setVisibility(View.INVISIBLE);
scaleIndicator.setVisibility(View.INVISIBLE);
for (int i = 0; i < speedtexts.length; i++)
{
speedtexts[i].setVisibility(View.INVISIBLE);
}
break;
case SegmentRendering.DRAW_HEIGHT:
if (mAverageHeight == 0.0)
{
mHandler.removeCallbacks(heightCalculator);
mHandler.post(heightCalculator);
}
else
{
drawHeightTexts();
speedtexts = mLoggerMap.getSpeedTextViews();
speedbar.setVisibility(View.VISIBLE);
scaleIndicator.setVisibility(View.VISIBLE);
for (int i = 0; i < speedtexts.length; i++)
{
speedtexts[i].setVisibility(View.VISIBLE);
}
}
break;
default:
break;
}
mBitmapSegmentsOverlay.setTrackColoringMethod(trackColoringMethod, mAverageSpeed, mAverageHeight);
}
private void updateSpeedDisplayVisibility()
{
boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false);
TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView();
if (showspeed)
{
lastGPSSpeedView.setVisibility(View.VISIBLE);
}
else
{
lastGPSSpeedView.setVisibility(View.GONE);
}
updateScaleDisplayVisibility();
}
private void updateAltitudeDisplayVisibility()
{
boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false);
TextView lastGPSAltitudeView = mLoggerMap.getAltitideTextView();
if (showaltitude)
{
lastGPSAltitudeView.setVisibility(View.VISIBLE);
}
else
{
lastGPSAltitudeView.setVisibility(View.GONE);
}
updateScaleDisplayVisibility();
}
private void updateScaleDisplayVisibility()
{
SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView();
boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false);
boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false);
int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue();
switch (trackColoringMethod)
{
case SegmentRendering.DRAW_MEASURED:
case SegmentRendering.DRAW_CALCULATED:
if( showspeed )
{
scaleIndicator.setVisibility(View.VISIBLE);
}
else
{
scaleIndicator.setVisibility(View.GONE);
}
break;
case SegmentRendering.DRAW_HEIGHT:
default:
if( showaltitude )
{
scaleIndicator.setVisibility(View.VISIBLE);
}
else
{
scaleIndicator.setVisibility(View.GONE);
}
break;
}
}
private void updateDistanceDisplayVisibility()
{
boolean showdistance = mSharedPreferences.getBoolean(Constants.DISTANCE, false);
TextView distanceView = mLoggerMap.getDistanceTextView();
if (showdistance)
{
distanceView.setVisibility(View.VISIBLE);
}
else
{
distanceView.setVisibility(View.GONE);
}
}
private void updateCompassDisplayVisibility()
{
boolean compass = mSharedPreferences.getBoolean(Constants.COMPASS, false);
if (compass)
{
mLoggerMap.enableCompass();
}
else
{
mLoggerMap.disableCompass();
}
}
private void updateLocationDisplayVisibility()
{
boolean location = mSharedPreferences.getBoolean(Constants.LOCATION, false);
if (location)
{
mLoggerMap.enableMyLocation();
}
else
{
mLoggerMap.disableMyLocation();
}
}
/**
* Retrieves the numbers of the measured speed and altitude from the most
* recent waypoint and updates UI components with this latest bit of
* information.
*/
private void updateTrackNumbers()
{
Location lastWaypoint = mLoggerServiceManager.getLastWaypoint();
UnitsI18n units = mUnits;
if (lastWaypoint != null && units != null)
{
// Speed number
mSpeed = lastWaypoint.getSpeed();
mAltitude = lastWaypoint.getAltitude();
mDistance = mLoggerServiceManager.getTrackedDistance();
}
//Distance number
double distance = units.conversionFromMeter(mDistance);
String distanceText = String.format("%.2f %s", distance, units.getDistanceUnit());
TextView mDistanceView = mLoggerMap.getDistanceTextView();
mDistanceView.setText(distanceText);
//Speed number
double speed = units.conversionFromMetersPerSecond(mSpeed);
String speedText = units.formatSpeed(speed, false);
TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView();
lastGPSSpeedView.setText(speedText);
//Altitude number
double altitude = units.conversionFromMeterToHeight(mAltitude);
String altitudeText = String.format("%.0f %s", altitude, units.getHeightUnit());
TextView mLastGPSAltitudeView = mLoggerMap.getAltitideTextView();
mLastGPSAltitudeView.setText(altitudeText);
// Slider indicator
SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView();
int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue();
if( trackColoringMethod == SegmentRendering.DRAW_MEASURED || trackColoringMethod == SegmentRendering.DRAW_CALCULATED)
{
currentScaleIndicator.setValue((float) speed);
// Speed color bar and reference numbers
if (speed > 2 * mAverageSpeed )
{
mAverageSpeed = 0.0;
updateSpeedColoring();
mBitmapSegmentsOverlay.scheduleRecalculation();
}
}
else if(trackColoringMethod == SegmentRendering.DRAW_HEIGHT)
{
currentScaleIndicator.setValue((float) altitude);
// Speed color bar and reference numbers
if (altitude > 2 * mAverageHeight )
{
mAverageHeight = 0.0;
updateSpeedColoring();
mLoggerMap.postInvalidate();
}
}
}
/**
* For the current track identifier the route of that track is drawn by
* adding a OverLay for each segments in the track
*
* @param trackId
* @see SegmentRendering
*/
private void createDataOverlays()
{
mLastSegmentOverlay = null;
mBitmapSegmentsOverlay.clearSegments();
mLoggerMap.clearOverlays();
mLoggerMap.addOverlay(mBitmapSegmentsOverlay);
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Cursor segments = null;
int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "2")).intValue();
try
{
Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments");
segments = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null);
if (segments != null && segments.moveToFirst())
{
do
{
long segmentsId = segments.getLong(0);
Uri segmentUri = ContentUris.withAppendedId(segmentsUri, segmentsId);
SegmentRendering segmentOverlay = new SegmentRendering(mLoggerMap, segmentUri, trackColoringMethod, mAverageSpeed, mAverageHeight, mHandler);
mBitmapSegmentsOverlay.addSegment(segmentOverlay);
mLastSegmentOverlay = segmentOverlay;
if (segments.isFirst())
{
segmentOverlay.addPlacement(SegmentRendering.FIRST_SEGMENT);
}
if (segments.isLast())
{
segmentOverlay.addPlacement(SegmentRendering.LAST_SEGMENT);
}
mLastSegment = segmentsId;
}
while (segments.moveToNext());
}
}
finally
{
if (segments != null)
{
segments.close();
}
}
Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints");
resolver.unregisterContentObserver(this.mSegmentWaypointsObserver);
resolver.registerContentObserver(lastSegmentUri, false, this.mSegmentWaypointsObserver);
}
private void updateDataOverlays()
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments");
Cursor segmentsCursor = null;
int segmentOverlaysCount = mBitmapSegmentsOverlay.size();
try
{
segmentsCursor = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null);
if (segmentsCursor != null && segmentsCursor.getCount() == segmentOverlaysCount)
{
// Log.d( TAG, "Alignment of segments" );
}
else
{
createDataOverlays();
}
}
finally
{
if (segmentsCursor != null)
{
segmentsCursor.close();
}
}
}
/**
* Call when an overlay has recalulated and has new information to be redrawn
*/
private void moveActiveViewWindow()
{
GeoPoint lastPoint = getLastTrackPoint();
if (lastPoint != null && mLoggerServiceManager.getLoggingState() == Constants.LOGGING)
{
if (mLoggerMap.isOutsideScreen(lastPoint))
{
mLoggerMap.clearAnimation();
mLoggerMap.setCenter(lastPoint);
}
else if (mLoggerMap.isNearScreenEdge(lastPoint))
{
mLoggerMap.clearAnimation();
mLoggerMap.animateTo(lastPoint);
}
}
}
/**
* Updates the labels next to the color bar with speeds
*/
private void drawSpeedTexts()
{
UnitsI18n units = mUnits;
if (units != null)
{
double avgSpeed = units.conversionFromMetersPerSecond(mAverageSpeed);
TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews();
SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView();
for (int i = 0; i < mSpeedtexts.length; i++)
{
mSpeedtexts[i].setVisibility(View.VISIBLE);
double speed;
if (mUnits.isUnitFlipped())
{
speed = ((avgSpeed * 2d) / 5d) * (mSpeedtexts.length - i - 1);
}
else
{
speed = ((avgSpeed * 2d) / 5d) * i;
}
if( i == 0 )
{
currentScaleIndicator.setMin((float) speed);
}
else
{
currentScaleIndicator.setMax((float) speed);
}
String speedText = units.formatSpeed(speed, false);
mSpeedtexts[i].setText(speedText);
}
}
}
/**
* Updates the labels next to the color bar with heights
*/
private void drawHeightTexts()
{
UnitsI18n units = mUnits;
if (units != null)
{
double avgHeight = units.conversionFromMeterToHeight(mAverageHeight);
TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews();
SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView();
for (int i = 0; i < mSpeedtexts.length; i++)
{
mSpeedtexts[i].setVisibility(View.VISIBLE);
double height = ((avgHeight * 2d) / 5d) * i;
String heightText = String.format( "%d %s", (int)height, units.getHeightUnit() );
mSpeedtexts[i].setText(heightText);
if( i == 0 )
{
currentScaleIndicator.setMin((float) height);
}
else
{
currentScaleIndicator.setMax((float) height);
}
}
}
}
/**
* Alter this to set a new track as current.
*
* @param trackId
* @param center center on the end of the track
*/
private void moveToTrack(long trackId, boolean center)
{
if( trackId == mTrackId )
{
return;
}
Cursor track = null;
try
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
Uri trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId);
track = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null);
if (track != null && track.moveToFirst())
{
this.mTrackId = trackId;
mLastSegment = -1;
resolver.unregisterContentObserver(this.mTrackSegmentsObserver);
resolver.unregisterContentObserver(this.mTrackMediasObserver);
Uri tracksegmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments");
resolver.registerContentObserver(tracksegmentsUri, false, this.mTrackSegmentsObserver);
resolver.registerContentObserver(Media.CONTENT_URI, true, this.mTrackMediasObserver);
mLoggerMap.clearOverlays();
mBitmapSegmentsOverlay.clearSegments();
mAverageSpeed = 0.0;
mAverageHeight = 0.0;
updateTitleBar();
updateDataOverlays();
updateSpeedColoring();
if (center)
{
GeoPoint lastPoint = getLastTrackPoint();
mLoggerMap.animateTo(lastPoint);
}
}
}
finally
{
if (track != null)
{
track.close();
}
}
}
/**
* Get the last know position from the GPS provider and return that
* information wrapped in a GeoPoint to which the Map can navigate.
*
* @see GeoPoint
* @return
*/
private GeoPoint getLastKnowGeopointLocation()
{
int microLatitude = 0;
int microLongitude = 0;
LocationManager locationManager = (LocationManager) mLoggerMap.getActivity().getApplication().getSystemService(Context.LOCATION_SERVICE);
Location locationFine = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationFine != null)
{
microLatitude = (int) (locationFine.getLatitude() * 1E6d);
microLongitude = (int) (locationFine.getLongitude() * 1E6d);
}
if (locationFine == null || microLatitude == 0 || microLongitude == 0)
{
Location locationCoarse = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (locationCoarse != null)
{
microLatitude = (int) (locationCoarse.getLatitude() * 1E6d);
microLongitude = (int) (locationCoarse.getLongitude() * 1E6d);
}
if (locationCoarse == null || microLatitude == 0 || microLongitude == 0)
{
microLatitude = 51985105;
microLongitude = 5106132;
}
}
GeoPoint geoPoint = new GeoPoint(microLatitude, microLongitude);
return geoPoint;
}
/**
* Retrieve the last point of the current track
*
* @param context
*/
private GeoPoint getLastTrackPoint()
{
Cursor waypoint = null;
GeoPoint lastPoint = null;
// First try the service which might have a cached version
Location lastLoc = mLoggerServiceManager.getLastWaypoint();
if (lastLoc != null)
{
int microLatitude = (int) (lastLoc.getLatitude() * 1E6d);
int microLongitude = (int) (lastLoc.getLongitude() * 1E6d);
lastPoint = new GeoPoint(microLatitude, microLongitude);
}
// If nothing yet, try the content resolver and query the track
if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0)
{
try
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
waypoint = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/waypoints"), new String[] { Waypoints.LATITUDE,
Waypoints.LONGITUDE, "max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null);
if (waypoint != null && waypoint.moveToLast())
{
int microLatitude = (int) (waypoint.getDouble(0) * 1E6d);
int microLongitude = (int) (waypoint.getDouble(1) * 1E6d);
lastPoint = new GeoPoint(microLatitude, microLongitude);
}
}
finally
{
if (waypoint != null)
{
waypoint.close();
}
}
}
// If nothing yet, try the last generally known location
if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0)
{
lastPoint = getLastKnowGeopointLocation();
}
return lastPoint;
}
private void moveToLastTrack()
{
int trackId = -1;
Cursor track = null;
try
{
ContentResolver resolver = mLoggerMap.getActivity().getContentResolver();
track = resolver.query(Tracks.CONTENT_URI, new String[] { "max(" + Tracks._ID + ")", Tracks.NAME, }, null, null, null);
if (track != null && track.moveToLast())
{
trackId = track.getInt(0);
moveToTrack(trackId, false);
}
}
finally
{
if (track != null)
{
track.close();
}
}
}
/**
* Enables a SegmentOverlay to call back to the MapActivity to show a dialog
* with choices of media
*
* @param mediaAdapter
*/
public void showMediaDialog(BaseAdapter mediaAdapter)
{
mMediaAdapter = mediaAdapter;
mLoggerMap.getActivity().showDialog(DIALOG_URIS);
}
public SharedPreferences getPreferences()
{
return mSharedPreferences;
}
public boolean isLogging()
{
return mLoggerServiceManager.getLoggingState() == Constants.LOGGING;
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer.map;
import nl.sogeti.android.gpstracker.util.Constants;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* ????
*
* @version $Id:$
* @author rene (c) Feb 26, 2012, Sogeti B.V.
*/
public class CommonLoggerMap extends Activity
{
private static final String TAG = "OGT.CommonLoggerMap";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent myIntent = getIntent();
Intent realIntent;
Class<?> mapClass = GoogleLoggerMap.class;
int provider = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue();
switch (provider)
{
case Constants.GOOGLE:
mapClass = GoogleLoggerMap.class;
break;
case Constants.OSM:
mapClass = OsmLoggerMap.class;
break;
case Constants.MAPQUEST:
mapClass = MapQuestLoggerMap.class;
break;
default:
mapClass = GoogleLoggerMap.class;
Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps.");
break;
}
if( myIntent != null )
{
realIntent = new Intent(myIntent.getAction(), myIntent.getData(), this, mapClass);
realIntent.putExtras(myIntent);
}
else
{
realIntent = new Intent(this, mapClass);
realIntent.putExtras(myIntent);
}
startActivity(realIntent);
finish();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer.map;
import nl.sogeti.android.gpstracker.util.SlidingIndicatorView;
import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
/**
* ????
*
* @version $Id$
* @author rene (c) Feb 26, 2012, Sogeti B.V.
*/
public interface LoggerMap
{
void setDrawingCacheEnabled(boolean b);
Activity getActivity();
void updateOverlays();
void onLayerCheckedChanged(int checkedId, boolean b);
void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key);
Bitmap getDrawingCache();
void showMediaDialog(BaseAdapter mediaAdapter);
String getDataSourceId();
boolean isOutsideScreen(GeoPoint lastPoint);
boolean isNearScreenEdge(GeoPoint lastPoint);
void executePostponedActions();
void disableMyLocation();
void disableCompass();
void setZoom(int int1);
void animateTo(GeoPoint storedPoint);
int getZoomLevel();
GeoPoint getMapCenter();
boolean zoomOut();
boolean zoomIn();
void postInvalidate();
void enableCompass();
void enableMyLocation();
void addOverlay(OverlayProvider overlay);
void clearAnimation();
void setCenter(GeoPoint lastPoint);
int getMaxZoomLevel();
GeoPoint fromPixels(int x, int y);
boolean hasProjection();
float metersToEquatorPixels(float float1);
void toPixels(GeoPoint geopoint, Point screenPoint);
TextView[] getSpeedTextViews();
TextView getAltitideTextView();
TextView getSpeedTextView();
TextView getDistanceTextView();
void clearOverlays();
SlidingIndicatorView getScaleIndicatorView();
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Mar 3, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer.map;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.util.SlidingIndicatorView;
import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.mapquest.android.maps.MapActivity;
import com.mapquest.android.maps.MapView;
import com.mapquest.android.maps.MyLocationOverlay;
/**
* ????
*
* @version $Id:$
* @author rene (c) Mar 3, 2012, Sogeti B.V.
*/
public class MapQuestLoggerMap extends MapActivity implements LoggerMap
{
LoggerMapHelper mHelper;
private MapView mMapView;
private TextView[] mSpeedtexts;
private TextView mLastGPSSpeedView;
private TextView mLastGPSAltitudeView;
private TextView mDistanceView;
private MyLocationOverlay mMylocation;
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate(Bundle load)
{
super.onCreate(load);
setContentView(R.layout.map_mapquest);
mMapView = (MapView) findViewById(R.id.myMapView);
mHelper = new LoggerMapHelper(this);
mMapView = (MapView) findViewById(R.id.myMapView);
mMylocation = new MyLocationOverlay(this, mMapView);
mMapView.setBuiltInZoomControls(true);
TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03),
(TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) };
mSpeedtexts = speeds;
mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed);
mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude);
mDistanceView = (TextView) findViewById(R.id.currentDistance);
mHelper.onCreate(load);
}
@Override
protected void onResume()
{
super.onResume();
mHelper.onResume();
}
@Override
protected void onPause()
{
mHelper.onPause();
super.onPause();
}
@Override
protected void onDestroy()
{
mHelper.onDestroy();
super.onDestroy();
}
@Override
public void onNewIntent(Intent newIntent)
{
mHelper.onNewIntent(newIntent);
}
@Override
protected void onRestoreInstanceState(Bundle load)
{
if (load != null)
{
super.onRestoreInstanceState(load);
}
mHelper.onRestoreInstanceState(load);
}
@Override
protected void onSaveInstanceState(Bundle save)
{
super.onSaveInstanceState(save);
mHelper.onSaveInstanceState(save);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
mHelper.onCreateOptionsMenu(menu);
return result;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
mHelper.onPrepareOptionsMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
boolean handled = mHelper.onOptionsItemSelected(item);
if( !handled )
{
handled = super.onOptionsItemSelected(item);
}
return handled;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
mHelper.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean propagate = true;
switch (keyCode)
{
default:
propagate = mHelper.onKeyDown(keyCode, event);
if( propagate )
{
propagate = super.onKeyDown(keyCode, event);
}
break;
}
return propagate;
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = mHelper.onCreateDialog(id);
if( dialog == null )
{
dialog = super.onCreateDialog(id);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
mHelper.onPrepareDialog(id, dialog);
super.onPrepareDialog(id, dialog);
}
/******************************/
/** Loggermap methods **/
/******************************/
@Override
public void updateOverlays()
{
}
@Override
public void setDrawingCacheEnabled(boolean b)
{
findViewById(R.id.mapScreen).setDrawingCacheEnabled(true);
}
@Override
public Activity getActivity()
{
return this;
}
@Override
public void onLayerCheckedChanged(int checkedId, boolean isChecked)
{
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
}
@Override
public Bitmap getDrawingCache()
{
return findViewById(R.id.mapScreen).getDrawingCache();
}
@Override
public void showMediaDialog(BaseAdapter mediaAdapter)
{
mHelper.showMediaDialog(mediaAdapter);
}
public void onDateOverlayChanged()
{
mMapView.postInvalidate();
}
@Override
public String getDataSourceId()
{
return LoggerMapHelper.MAPQUEST_PROVIDER;
}
@Override
public boolean isOutsideScreen(GeoPoint lastPoint)
{
Point out = new Point();
this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < 0 || out.y < 0 || out.y > height || out.x > width);
}
@Override
public boolean isNearScreenEdge(GeoPoint lastPoint)
{
Point out = new Point();
this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3);
}
@Override
public void executePostponedActions()
{
}
@Override
public void enableCompass()
{
mMylocation.enableCompass();
}
@Override
public void enableMyLocation()
{
mMylocation.enableMyLocation();
}
@Override
public void disableMyLocation()
{
mMylocation.disableMyLocation();
}
@Override
public void disableCompass()
{
mMylocation.disableCompass();
}
@Override
public void setZoom(int zoom)
{
mMapView.getController().setZoom(zoom);
}
@Override
public void animateTo(GeoPoint storedPoint)
{
mMapView.getController().animateTo(MapQuestLoggerMap.convertGeoPoint(storedPoint));
}
@Override
public int getZoomLevel()
{
return mMapView.getZoomLevel();
}
@Override
public GeoPoint getMapCenter()
{
return MapQuestLoggerMap.convertMapQuestGeoPoint(mMapView.getMapCenter());
}
@Override
public boolean zoomOut()
{
return mMapView.getController().zoomOut();
}
@Override
public boolean zoomIn()
{
return mMapView.getController().zoomIn();
}
@Override
public void postInvalidate()
{
mMapView.postInvalidate();
}
@Override
public void addOverlay(OverlayProvider overlay)
{
mMapView.getOverlays().add(overlay.getMapQuestOverlay());
}
@Override
public void clearAnimation()
{
mMapView.clearAnimation();
}
@Override
public void setCenter(GeoPoint lastPoint)
{
mMapView.getController().setCenter( MapQuestLoggerMap.convertGeoPoint(lastPoint));
}
@Override
public int getMaxZoomLevel()
{
return mMapView.getMaxZoomLevel();
}
@Override
public GeoPoint fromPixels(int x, int y)
{
com.mapquest.android.maps.GeoPoint mqGeopoint = mMapView.getProjection().fromPixels(x, y);
return convertMapQuestGeoPoint(mqGeopoint);
}
@Override
public boolean hasProjection()
{
return mMapView.getProjection() != null;
}
@Override
public float metersToEquatorPixels(float float1)
{
return mMapView.getProjection().metersToEquatorPixels(float1);
}
@Override
public void toPixels(GeoPoint geoPoint, Point screenPoint)
{
com.mapquest.android.maps.GeoPoint mqGeopoint = MapQuestLoggerMap.convertGeoPoint(geoPoint);
mMapView.getProjection().toPixels( mqGeopoint, screenPoint);
}
@Override
public TextView[] getSpeedTextViews()
{
return mSpeedtexts;
}
@Override
public TextView getAltitideTextView()
{
return mLastGPSAltitudeView;
}
@Override
public TextView getSpeedTextView()
{
return mLastGPSSpeedView;
}
@Override
public TextView getDistanceTextView()
{
return mDistanceView;
}
static com.mapquest.android.maps.GeoPoint convertGeoPoint( GeoPoint point )
{
return new com.mapquest.android.maps.GeoPoint(point.getLatitudeE6(), point.getLongitudeE6() );
}
static GeoPoint convertMapQuestGeoPoint( com.mapquest.android.maps.GeoPoint mqPoint )
{
return new GeoPoint(mqPoint.getLatitudeE6(), mqPoint.getLongitudeE6() );
}
@Override
public void clearOverlays()
{
mMapView.getOverlays().clear();
}
@Override
public SlidingIndicatorView getScaleIndicatorView()
{
return (SlidingIndicatorView) findViewById(R.id.scaleindicator);
}
/******************************/
/** Own methods **/
/******************************/
@Override
public boolean isRouteDisplayed()
{
return true;
}
}
| Java |
/*
* Written by Pieter @ android-developers on groups.google.com
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer.map.overlay;
import nl.sogeti.android.gpstracker.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;
/**
* Fix for a ClassCastException found on some Google Maps API's implementations.
* @see <a href="http://www.spectrekking.com/download/FixedMyLocationOverlay.java">www.spectrekking.com</a>
* @version $Id$
*/
public class FixedMyLocationOverlay extends MyLocationOverlay {
private boolean bugged = false;
private Paint accuracyPaint;
private Point center;
private Point left;
private Drawable drawable;
private int width;
private int height;
public FixedMyLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
}
@Override
protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) {
if (!bugged) {
try {
super.drawMyLocation(canvas, mapView, lastFix, myLoc, when);
} catch (Exception e) {
bugged = true;
}
}
if (bugged) {
if (drawable == null) {
if( accuracyPaint == null )
{
accuracyPaint = new Paint();
accuracyPaint.setAntiAlias(true);
accuracyPaint.setStrokeWidth(2.0f);
}
drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation);
width = drawable.getIntrinsicWidth();
height = drawable.getIntrinsicHeight();
center = new Point();
left = new Point();
}
Projection projection = mapView.getProjection();
double latitude = lastFix.getLatitude();
double longitude = lastFix.getLongitude();
float accuracy = lastFix.getAccuracy();
float[] result = new float[1];
Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
float longitudeLineDistance = result[0];
GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6));
projection.toPixels(leftGeo, left);
projection.toPixels(myLoc, center);
int radius = center.x - left.x;
accuracyPaint.setColor(0xff6666ff);
accuracyPaint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
accuracyPaint.setColor(0x186666ff);
accuracyPaint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2);
drawable.draw(canvas);
}
}
} | Java |
package nl.sogeti.android.gpstracker.viewer.map.overlay;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public abstract class AsyncOverlay extends Overlay implements OverlayProvider
{
private static final int OFFSET = 20;
private static final String TAG = "GG.AsyncOverlay";
/**
* Handler provided by the MapActivity to recalculate graphics
*/
private Handler mHandler;
private GeoPoint mGeoTopLeft;
private GeoPoint mGeoBottumRight;
private int mWidth;
private int mHeight;
private Bitmap mActiveBitmap;
private GeoPoint mActiveTopLeft;
private Point mActivePointTopLeft;
private Bitmap mCalculationBitmap;
private Paint mPaint;
private LoggerMap mLoggerMap;
SegmentOsmOverlay mOsmOverlay;
private SegmentMapQuestOverlay mMapQuestOverlay;
private int mActiveZoomLevel;
private Runnable mBitmapUpdater = new Runnable()
{
@Override
public void run()
{
postedBitmapUpdater = false;
mCalculationBitmap.eraseColor(Color.TRANSPARENT);
mGeoTopLeft = mLoggerMap.fromPixels(0, 0);
mGeoBottumRight = mLoggerMap.fromPixels(mWidth, mHeight);
Canvas calculationCanvas = new Canvas(mCalculationBitmap);
redrawOffscreen(calculationCanvas, mLoggerMap);
synchronized (mActiveBitmap)
{
Bitmap oldActiveBitmap = mActiveBitmap;
mActiveBitmap = mCalculationBitmap;
mActiveTopLeft = mGeoTopLeft;
mCalculationBitmap = oldActiveBitmap;
}
mLoggerMap.postInvalidate();
}
};
private boolean postedBitmapUpdater;
AsyncOverlay(LoggerMap loggermap, Handler handler)
{
mLoggerMap = loggermap;
mHandler = handler;
mWidth = 1;
mHeight = 1;
mPaint = new Paint();
mActiveZoomLevel = -1;
mActiveBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mActiveTopLeft = new GeoPoint(0, 0);
mActivePointTopLeft = new Point();
mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mOsmOverlay = new SegmentOsmOverlay(mLoggerMap.getActivity(), mLoggerMap, this);
mMapQuestOverlay = new SegmentMapQuestOverlay(this);
}
protected void reset()
{
synchronized (mActiveBitmap)
{
mCalculationBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
mActiveBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
}
}
protected void considerRedrawOffscreen()
{
int oldZoomLevel = mActiveZoomLevel;
mActiveZoomLevel = mLoggerMap.getZoomLevel();
boolean needNewCalculation = false;
if (mCalculationBitmap.getWidth() != mWidth || mCalculationBitmap.getHeight() != mHeight)
{
mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
needNewCalculation = true;
}
boolean unaligned = isOutAlignment();
if (needNewCalculation || mActiveZoomLevel != oldZoomLevel || unaligned)
{
scheduleRecalculation();
}
}
private boolean isOutAlignment()
{
Point screenPoint = new Point(0, 0);
if (mGeoTopLeft != null)
{
mLoggerMap.toPixels(mGeoTopLeft, screenPoint);
}
return mGeoTopLeft == null || mGeoBottumRight == null || screenPoint.x > OFFSET || screenPoint.y > OFFSET || screenPoint.x < -OFFSET
|| screenPoint.y < -OFFSET;
}
public void onDateOverlayChanged()
{
if (!postedBitmapUpdater)
{
postedBitmapUpdater = true;
mHandler.post(mBitmapUpdater);
}
}
protected abstract void redrawOffscreen(Canvas asyncBuffer, LoggerMap loggermap);
protected abstract void scheduleRecalculation();
/**
* {@inheritDoc}
*/
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
if (!shadow)
{
draw(canvas);
}
}
private void draw(Canvas canvas)
{
mWidth = canvas.getWidth();
mHeight = canvas.getHeight();
considerRedrawOffscreen();
if (mActiveBitmap.getWidth() > 1)
{
synchronized (mActiveBitmap)
{
mLoggerMap.toPixels(mActiveTopLeft, mActivePointTopLeft);
canvas.drawBitmap(mActiveBitmap, mActivePointTopLeft.x, mActivePointTopLeft.y, mPaint);
}
}
}
protected boolean isPointOnScreen(Point point)
{
return point.x < 0 || point.y < 0 || point.x > mWidth || point.y > mHeight;
}
@Override
public boolean onTap(GeoPoint tappedGeoPoint, MapView mapview)
{
return commonOnTap(tappedGeoPoint);
}
/**************************************/
/** Multi map support **/
/**************************************/
@Override
public Overlay getGoogleOverlay()
{
return this;
}
@Override
public org.osmdroid.views.overlay.Overlay getOSMOverlay()
{
return mOsmOverlay;
}
@Override
public com.mapquest.android.maps.Overlay getMapQuestOverlay()
{
return mMapQuestOverlay;
}
protected abstract boolean commonOnTap(GeoPoint tappedGeoPoint);
static class SegmentOsmOverlay extends org.osmdroid.views.overlay.Overlay
{
AsyncOverlay mSegmentOverlay;
LoggerMap mLoggerMap;
public SegmentOsmOverlay(Context ctx, LoggerMap map, AsyncOverlay segmentOverlay)
{
super(ctx);
mLoggerMap = map;
mSegmentOverlay = segmentOverlay;
}
public AsyncOverlay getSegmentOverlay()
{
return mSegmentOverlay;
}
@Override
public boolean onSingleTapUp(MotionEvent e, org.osmdroid.views.MapView openStreetMapView)
{
int x = (int) e.getX();
int y = (int) e.getY();
GeoPoint tappedGeoPoint = mLoggerMap.fromPixels(x, y);
return mSegmentOverlay.commonOnTap(tappedGeoPoint);
}
@Override
protected void draw(Canvas canvas, org.osmdroid.views.MapView view, boolean shadow)
{
if (!shadow)
{
mSegmentOverlay.draw(canvas);
}
}
}
static class SegmentMapQuestOverlay extends com.mapquest.android.maps.Overlay
{
AsyncOverlay mSegmentOverlay;
public SegmentMapQuestOverlay(AsyncOverlay segmentOverlay)
{
super();
mSegmentOverlay = segmentOverlay;
}
public AsyncOverlay getSegmentOverlay()
{
return mSegmentOverlay;
}
@Override
public boolean onTap(com.mapquest.android.maps.GeoPoint p, com.mapquest.android.maps.MapView mapView)
{
GeoPoint tappedGeoPoint = new GeoPoint(p.getLatitudeE6(), p.getLongitudeE6());
return mSegmentOverlay.commonOnTap(tappedGeoPoint);
}
@Override
public void draw(Canvas canvas, com.mapquest.android.maps.MapView mapView, boolean shadow)
{
if (!shadow)
{
mSegmentOverlay.draw(canvas);
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer.map.overlay;
import com.mapquest.android.maps.Overlay;
public interface OverlayProvider
{
public com.google.android.maps.Overlay getGoogleOverlay();
public org.osmdroid.views.overlay.Overlay getOSMOverlay();
public Overlay getMapQuestOverlay();
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer.map.overlay;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import nl.sogeti.android.gpstracker.BuildConfig;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff.Mode;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/**
* Creates an overlay that can draw a single segment of connected waypoints
*
* @version $Id$
* @author rene (c) Jan 11, 2009, Sogeti B.V.
*/
public class SegmentRendering
{
public static final int MIDDLE_SEGMENT = 0;
public static final int FIRST_SEGMENT = 1;
public static final int LAST_SEGMENT = 2;
public static final int DRAW_GREEN = 0;
public static final int DRAW_RED = 1;
public static final int DRAW_MEASURED = 2;
public static final int DRAW_CALCULATED = 3;
public static final int DRAW_DOTS = 4;
public static final int DRAW_HEIGHT = 5;
private static final String TAG = "OGT.SegmentRendering";
private static final float MINIMUM_PX_DISTANCE = 15;
private static SparseArray<Bitmap> sBitmapCache = new SparseArray<Bitmap>();;
private int mTrackColoringMethod = DRAW_CALCULATED;
private ContentResolver mResolver;
private LoggerMap mLoggerMap;
private int mPlacement = SegmentRendering.MIDDLE_SEGMENT;
private Uri mWaypointsUri;
private Uri mMediaUri;
private double mAvgSpeed;
private double mAvgHeight;
private GeoPoint mGeoTopLeft;
private GeoPoint mGeoBottumRight;
private Vector<DotVO> mDotPath;
private Vector<DotVO> mDotPathCalculation;
private Path mCalculatedPath;
private Point mCalculatedStart;
private Point mCalculatedStop;
private Path mPathCalculation;
private Shader mShader;
private Vector<MediaVO> mMediaPath;
private Vector<MediaVO> mMediaPathCalculation;
private GeoPoint mStartPoint;
private GeoPoint mEndPoint;
private Point mPrevDrawnScreenPoint;
private Point mScreenPointBackup;
private Point mScreenPoint;
private Point mMediaScreenPoint;
private int mStepSize = -1;
private Location mLocation;
private Location mPrevLocation;
private Cursor mWaypointsCursor;
private Cursor mMediaCursor;
private Uri mSegmentUri;
private int mWaypointCount = -1;
private int mWidth;
private int mHeight;
private GeoPoint mPrevGeoPoint;
private int mCurrentColor;
private Paint dotpaint;
private Paint radiusPaint;
private Paint routePaint;
private Paint defaultPaint;
private boolean mRequeryFlag;
private Handler mHandler;
private static Bitmap sStartBitmap;
private static Bitmap sStopBitmap;
private AsyncOverlay mAsyncOverlay;
private ContentObserver mTrackSegmentsObserver;
private final Runnable mMediaCalculator = new Runnable()
{
@Override
public void run()
{
SegmentRendering.this.calculateMediaAsync();
}
};
private final Runnable mTrackCalculator = new Runnable()
{
@Override
public void run()
{
SegmentRendering.this.calculateTrackAsync();
}
};
/**
* Constructor: create a new TrackingOverlay.
*
* @param loggermap
* @param segmentUri
* @param color
* @param avgSpeed
* @param handler
*/
public SegmentRendering(LoggerMap loggermap, Uri segmentUri, int color, double avgSpeed, double avgHeight, Handler handler)
{
super();
mHandler = handler;
mLoggerMap = loggermap;
mTrackColoringMethod = color;
mAvgSpeed = avgSpeed;
mAvgHeight = avgHeight;
mSegmentUri = segmentUri;
mMediaUri = Uri.withAppendedPath(mSegmentUri, "media");
mWaypointsUri = Uri.withAppendedPath(mSegmentUri, "waypoints");
mResolver = mLoggerMap.getActivity().getContentResolver();
mRequeryFlag = true;
mCurrentColor = Color.rgb(255, 0, 0);
dotpaint = new Paint();
radiusPaint = new Paint();
radiusPaint.setColor(Color.YELLOW);
radiusPaint.setAlpha(100);
routePaint = new Paint();
routePaint.setStyle(Paint.Style.STROKE);
routePaint.setStrokeWidth(6);
routePaint.setAntiAlias(true);
routePaint.setPathEffect(new CornerPathEffect(10));
defaultPaint = new Paint();
mScreenPoint = new Point();
mMediaScreenPoint = new Point();
mScreenPointBackup = new Point();
mPrevDrawnScreenPoint = new Point();
mDotPath = new Vector<DotVO>();
mDotPathCalculation = new Vector<DotVO>();
mCalculatedPath = new Path();
mPathCalculation = new Path();
mMediaPath = new Vector<MediaVO>();
mMediaPathCalculation = new Vector<MediaVO>();
mTrackSegmentsObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
mRequeryFlag = true;
}
else
{
Log.w(TAG, "mTrackSegmentsObserver skipping change on " + mSegmentUri);
}
}
};
openResources();
}
public void closeResources()
{
mResolver.unregisterContentObserver(mTrackSegmentsObserver);
mHandler.removeCallbacks(mMediaCalculator);
mHandler.removeCallbacks(mTrackCalculator);
mHandler.postAtFrontOfQueue(new Runnable()
{
@Override
public void run()
{
if (mWaypointsCursor != null)
{
mWaypointsCursor.close();
mWaypointsCursor = null;
}
if (mMediaCursor != null)
{
mMediaCursor.close();
mMediaCursor = null;
}
}
});
SegmentRendering.sStopBitmap = null;
SegmentRendering.sStartBitmap = null;
}
public void openResources()
{
mResolver.registerContentObserver(mWaypointsUri, false, mTrackSegmentsObserver);
}
/**
* Private draw method called by both the draw from Google Overlay and the
* OSM Overlay
*
* @param canvas
*/
public void draw(Canvas canvas)
{
switch (mTrackColoringMethod)
{
case DRAW_HEIGHT:
case DRAW_CALCULATED:
case DRAW_MEASURED:
case DRAW_RED:
case DRAW_GREEN:
drawPath(canvas);
break;
case DRAW_DOTS:
drawDots(canvas);
break;
}
drawStartStopCircles(canvas);
drawMedia(canvas);
mWidth = canvas.getWidth();
mHeight = canvas.getHeight();
}
public void calculateTrack()
{
mHandler.removeCallbacks(mTrackCalculator);
mHandler.post(mTrackCalculator);
}
/**
* Either the Path or the Dots are calculated based on he current track
* coloring method
*/
private synchronized void calculateTrackAsync()
{
mGeoTopLeft = mLoggerMap.fromPixels(0, 0);
mGeoBottumRight = mLoggerMap.fromPixels(mWidth, mHeight);
calculateStepSize();
mScreenPoint.x = -1;
mScreenPoint.y = -1;
this.mPrevDrawnScreenPoint.x = -1;
this.mPrevDrawnScreenPoint.y = -1;
switch (mTrackColoringMethod)
{
case DRAW_HEIGHT:
case DRAW_CALCULATED:
case DRAW_MEASURED:
case DRAW_RED:
case DRAW_GREEN:
calculatePath();
synchronized (mCalculatedPath) // Switch the fresh path with the old Path object
{
Path oldPath = mCalculatedPath;
mCalculatedPath = mPathCalculation;
mPathCalculation = oldPath;
}
break;
case DRAW_DOTS:
calculateDots();
synchronized (mDotPath) // Switch the fresh path with the old Path object
{
Vector<DotVO> oldDotPath = mDotPath;
mDotPath = mDotPathCalculation;
mDotPathCalculation = oldDotPath;
}
break;
}
calculateStartStopCircles();
mAsyncOverlay.onDateOverlayChanged();
}
/**
* Calculated the new contents of segment in the mDotPathCalculation
*/
private void calculatePath()
{
mDotPathCalculation.clear();
this.mPathCalculation.rewind();
this.mShader = null;
GeoPoint geoPoint;
this.mPrevLocation = null;
if (mWaypointsCursor == null)
{
mWaypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.SPEED, Waypoints.TIME,
Waypoints.ACCURACY, Waypoints.ALTITUDE }, null, null, null);
mRequeryFlag = false;
}
if (mRequeryFlag)
{
mWaypointsCursor.requery();
mRequeryFlag = false;
}
if (mLoggerMap.hasProjection() && mWaypointsCursor.moveToFirst())
{
// Start point of the segments, possible a dot
this.mStartPoint = extractGeoPoint();
mPrevGeoPoint = mStartPoint;
this.mLocation = new Location(this.getClass().getName());
this.mLocation.setLatitude(mWaypointsCursor.getDouble(0));
this.mLocation.setLongitude(mWaypointsCursor.getDouble(1));
this.mLocation.setTime(mWaypointsCursor.getLong(3));
moveToGeoPoint(this.mStartPoint);
do
{
geoPoint = extractGeoPoint();
// Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
if (geoPoint.getLatitudeE6() == 0 || geoPoint.getLongitudeE6() == 0)
{
continue;
}
double speed = -1d;
switch (mTrackColoringMethod)
{
case DRAW_GREEN:
case DRAW_RED:
plainLineToGeoPoint(geoPoint);
break;
case DRAW_MEASURED:
speedLineToGeoPoint(geoPoint, mWaypointsCursor.getDouble(2));
break;
case DRAW_CALCULATED:
this.mPrevLocation = this.mLocation;
this.mLocation = new Location(this.getClass().getName());
this.mLocation.setLatitude(mWaypointsCursor.getDouble(0));
this.mLocation.setLongitude(mWaypointsCursor.getDouble(1));
this.mLocation.setTime(mWaypointsCursor.getLong(3));
speed = calculateSpeedBetweenLocations(this.mPrevLocation, this.mLocation);
speedLineToGeoPoint(geoPoint, speed);
break;
case DRAW_HEIGHT:
heightLineToGeoPoint(geoPoint, mWaypointsCursor.getDouble(5));
break;
default:
Log.w(TAG, "Unknown coloring method");
break;
}
}
while (moveToNextWayPoint());
this.mEndPoint = extractGeoPoint(); // End point of the segments, possible a dot
}
// Log.d( TAG, "transformSegmentToPath stop: points "+mCalculatedPoints+" from "+moves+" moves" );
}
/**
* @param canvas
* @param mapView
* @param shadow
* @see SegmentRendering#draw(Canvas, MapView, boolean)
*/
private void calculateDots()
{
mPathCalculation.reset();
mDotPathCalculation.clear();
if (mWaypointsCursor == null)
{
mWaypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.SPEED, Waypoints.TIME,
Waypoints.ACCURACY }, null, null, null);
}
if (mRequeryFlag)
{
mWaypointsCursor.requery();
mRequeryFlag = false;
}
if (mLoggerMap.hasProjection() && mWaypointsCursor.moveToFirst())
{
GeoPoint geoPoint;
mStartPoint = extractGeoPoint();
mPrevGeoPoint = mStartPoint;
do
{
geoPoint = extractGeoPoint();
// Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
if (geoPoint.getLatitudeE6() == 0 || geoPoint.getLongitudeE6() == 0)
{
continue;
}
setScreenPoint(geoPoint);
float distance = (float) distanceInPoints(this.mPrevDrawnScreenPoint, this.mScreenPoint);
if (distance > MINIMUM_PX_DISTANCE)
{
DotVO dotVO = new DotVO();
dotVO.x = this.mScreenPoint.x;
dotVO.y = this.mScreenPoint.y;
dotVO.speed = mWaypointsCursor.getLong(2);
dotVO.time = mWaypointsCursor.getLong(3);
dotVO.radius = mLoggerMap.metersToEquatorPixels(mWaypointsCursor.getFloat(4));
mDotPathCalculation.add(dotVO);
this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x;
this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y;
}
}
while (moveToNextWayPoint());
this.mEndPoint = extractGeoPoint();
DotVO pointVO = new DotVO();
pointVO.x = this.mScreenPoint.x;
pointVO.y = this.mScreenPoint.y;
pointVO.speed = mWaypointsCursor.getLong(2);
pointVO.time = mWaypointsCursor.getLong(3);
pointVO.radius = mLoggerMap.metersToEquatorPixels(mWaypointsCursor.getFloat(4));
mDotPathCalculation.add(pointVO);
}
}
public void calculateMedia()
{
mHandler.removeCallbacks(mMediaCalculator);
mHandler.post(mMediaCalculator);
}
public synchronized void calculateMediaAsync()
{
mMediaPathCalculation.clear();
if (mMediaCursor == null)
{
mMediaCursor = this.mResolver.query(this.mMediaUri, new String[] { Media.WAYPOINT, Media.URI }, null, null, null);
}
else
{
mMediaCursor.requery();
}
if (mLoggerMap.hasProjection() && mMediaCursor.moveToFirst())
{
GeoPoint lastPoint = null;
int wiggle = 0;
do
{
MediaVO mediaVO = new MediaVO();
mediaVO.waypointId = mMediaCursor.getLong(0);
mediaVO.uri = Uri.parse(mMediaCursor.getString(1));
Uri mediaWaypoint = ContentUris.withAppendedId(mWaypointsUri, mediaVO.waypointId);
Cursor waypointCursor = null;
try
{
waypointCursor = this.mResolver.query(mediaWaypoint, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE }, null, null, null);
if (waypointCursor != null && waypointCursor.moveToFirst())
{
int microLatitude = (int) (waypointCursor.getDouble(0) * 1E6d);
int microLongitude = (int) (waypointCursor.getDouble(1) * 1E6d);
mediaVO.geopoint = new GeoPoint(microLatitude, microLongitude);
}
}
finally
{
if (waypointCursor != null)
{
waypointCursor.close();
}
}
if (isGeoPointOnScreen(mediaVO.geopoint))
{
mLoggerMap.toPixels(mediaVO.geopoint, this.mMediaScreenPoint);
if (mediaVO.geopoint.equals(lastPoint))
{
wiggle += 4;
}
else
{
wiggle = 0;
}
mediaVO.bitmapKey = getResourceForMedia(mLoggerMap.getActivity().getResources(), mediaVO.uri);
mediaVO.w = sBitmapCache.get(mediaVO.bitmapKey).getWidth();
mediaVO.h = sBitmapCache.get(mediaVO.bitmapKey).getHeight();
int left = (mediaVO.w * 3) / 7 + wiggle;
int up = (mediaVO.h * 6) / 7 - wiggle;
mediaVO.x = mMediaScreenPoint.x - left;
mediaVO.y = mMediaScreenPoint.y - up;
lastPoint = mediaVO.geopoint;
}
mMediaPathCalculation.add(mediaVO);
}
while (mMediaCursor.moveToNext());
}
synchronized (mMediaPath) // Switch the fresh path with the old Path object
{
Vector<MediaVO> oldmMediaPath = mMediaPath;
mMediaPath = mMediaPathCalculation;
mMediaPathCalculation = oldmMediaPath;
}
if (mMediaPathCalculation.size() != mMediaPath.size())
{
mAsyncOverlay.onDateOverlayChanged();
}
}
private void calculateStartStopCircles()
{
if ((this.mPlacement == FIRST_SEGMENT || this.mPlacement == FIRST_SEGMENT + LAST_SEGMENT) && this.mStartPoint != null)
{
if (sStartBitmap == null)
{
sStartBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip);
}
if (mCalculatedStart == null)
{
mCalculatedStart = new Point();
}
mLoggerMap.toPixels(this.mStartPoint, mCalculatedStart);
}
if ((this.mPlacement == LAST_SEGMENT || this.mPlacement == FIRST_SEGMENT + LAST_SEGMENT) && this.mEndPoint != null)
{
if (sStopBitmap == null)
{
sStopBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip2);
}
if (mCalculatedStop == null)
{
mCalculatedStop = new Point();
}
mLoggerMap.toPixels(this.mEndPoint, mCalculatedStop);
}
}
/**
* @param canvas
* @see SegmentRendering#draw(Canvas, MapView, boolean)
*/
private void drawPath(Canvas canvas)
{
switch (mTrackColoringMethod)
{
case DRAW_HEIGHT:
case DRAW_CALCULATED:
case DRAW_MEASURED:
routePaint.setShader(this.mShader);
break;
case DRAW_RED:
routePaint.setShader(null);
routePaint.setColor(Color.RED);
break;
case DRAW_GREEN:
routePaint.setShader(null);
routePaint.setColor(Color.GREEN);
break;
default:
routePaint.setShader(null);
routePaint.setColor(Color.YELLOW);
break;
}
synchronized (mCalculatedPath)
{
canvas.drawPath(mCalculatedPath, routePaint);
}
}
private void drawDots(Canvas canvas)
{
synchronized (mDotPath)
{
if (sStopBitmap == null)
{
sStopBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip2);
}
for (DotVO dotVO : mDotPath)
{
canvas.drawBitmap(sStopBitmap, dotVO.x - 8, dotVO.y - 8, dotpaint);
if (dotVO.radius > 8f)
{
canvas.drawCircle(dotVO.x, dotVO.y, dotVO.radius, radiusPaint);
}
}
}
}
private void drawMedia(Canvas canvas)
{
synchronized (mMediaPath)
{
for (MediaVO mediaVO : mMediaPath)
{
if (mediaVO.bitmapKey != null)
{
Log.d(TAG, "Draw bitmap at (" + mediaVO.x + ", " + mediaVO.y + ") on " + canvas);
canvas.drawBitmap(sBitmapCache.get(mediaVO.bitmapKey), mediaVO.x, mediaVO.y, defaultPaint);
}
}
}
}
private void drawStartStopCircles(Canvas canvas)
{
if (mCalculatedStart != null)
{
canvas.drawBitmap(sStartBitmap, mCalculatedStart.x - 8, mCalculatedStart.y - 8, defaultPaint);
}
if (mCalculatedStop != null)
{
canvas.drawBitmap(sStopBitmap, mCalculatedStop.x - 5, mCalculatedStop.y - 5, defaultPaint);
}
}
private Integer getResourceForMedia(Resources resources, Uri uri)
{
int drawable = 0;
if (uri.getScheme().equals("file"))
{
if (uri.getLastPathSegment().endsWith("3gp"))
{
drawable = R.drawable.media_film;
}
else if (uri.getLastPathSegment().endsWith("jpg"))
{
drawable = R.drawable.media_camera;
}
else if (uri.getLastPathSegment().endsWith("txt"))
{
drawable = R.drawable.media_notepad;
}
}
else if (uri.getScheme().equals("content"))
{
if (uri.getAuthority().equals(GPStracking.AUTHORITY + ".string"))
{
drawable = R.drawable.media_mark;
}
else if (uri.getAuthority().equals("media"))
{
drawable = R.drawable.media_speech;
}
}
Bitmap bitmap = null;
int bitmapKey = drawable;
synchronized (sBitmapCache)
{
if (sBitmapCache.get(bitmapKey) == null)
{
bitmap = BitmapFactory.decodeResource(resources, drawable);
sBitmapCache.put(bitmapKey, bitmap);
}
bitmap = sBitmapCache.get(bitmapKey);
}
return bitmapKey;
}
/**
* Set the mPlace to the specified value.
*
* @see SegmentRendering.FIRST
* @see SegmentRendering.MIDDLE
* @see SegmentRendering.LAST
* @param place The placement of this segment in the line.
*/
public void addPlacement(int place)
{
this.mPlacement += place;
}
public boolean isLast()
{
return (mPlacement >= LAST_SEGMENT);
}
public long getSegmentId()
{
return Long.parseLong(mSegmentUri.getLastPathSegment());
}
/**
* Set the beginnging to the next contour of the line to the give GeoPoint
*
* @param geoPoint
*/
private void moveToGeoPoint(GeoPoint geoPoint)
{
setScreenPoint(geoPoint);
if (this.mPathCalculation != null)
{
this.mPathCalculation.moveTo(this.mScreenPoint.x, this.mScreenPoint.y);
this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x;
this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y;
}
}
/**
* Line to point without shaders
*
* @param geoPoint
*/
private void plainLineToGeoPoint(GeoPoint geoPoint)
{
shaderLineToGeoPoint(geoPoint, 0, 0);
}
/**
* Line to point with speed
*
* @param geoPoint
* @param height
*/
private void heightLineToGeoPoint(GeoPoint geoPoint, double height)
{
shaderLineToGeoPoint(geoPoint, height, mAvgHeight);
}
/**
* Line to point with speed
*
* @param geoPoint
* @param speed
*/
private void speedLineToGeoPoint(GeoPoint geoPoint, double speed)
{
shaderLineToGeoPoint(geoPoint, speed, mAvgSpeed);
}
private void shaderLineToGeoPoint(GeoPoint geoPoint, double value, double average)
{
setScreenPoint(geoPoint);
// Log.d( TAG, "Draw line to " + geoPoint+" with speed "+speed );
if (value > 0)
{
int greenfactor = (int) Math.min((127 * value) / average, 255);
int redfactor = 255 - greenfactor;
mCurrentColor = Color.rgb(redfactor, greenfactor, 0);
}
else
{
int greenfactor = Color.green(mCurrentColor);
int redfactor = Color.red(mCurrentColor);
mCurrentColor = Color.argb(128, redfactor, greenfactor, 0);
}
float distance = (float) distanceInPoints(this.mPrevDrawnScreenPoint, this.mScreenPoint);
if (distance > MINIMUM_PX_DISTANCE)
{
// Log.d( TAG, "Circle between " + mPrevDrawnScreenPoint+" and "+mScreenPoint );
int x_circle = (this.mPrevDrawnScreenPoint.x + this.mScreenPoint.x) / 2;
int y_circle = (this.mPrevDrawnScreenPoint.y + this.mScreenPoint.y) / 2;
float radius_factor = 0.4f;
Shader lastShader = new RadialGradient(x_circle, y_circle, distance, new int[] { mCurrentColor, mCurrentColor, Color.TRANSPARENT }, new float[] { 0,
radius_factor, 0.6f }, TileMode.CLAMP);
// Paint debug = new Paint();
// debug.setStyle( Paint.Style.FILL_AND_STROKE );
// this.mDebugCanvas.drawCircle(
// x_circle,
// y_circle,
// distance*radius_factor/2,
// debug );
// this.mDebugCanvas.drawCircle(
// x_circle,
// y_circle,
// distance*radius_factor,
// debug );
// if( distance > 100 )
// {
// Log.d( TAG, "Created shader for speed " + speed + " on " + x_circle + "," + y_circle );
// }
if (this.mShader != null)
{
this.mShader = new ComposeShader(this.mShader, lastShader, Mode.DST_OVER);
}
else
{
this.mShader = lastShader;
}
this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x;
this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y;
}
this.mPathCalculation.lineTo(this.mScreenPoint.x, this.mScreenPoint.y);
}
/**
* Use to update location/point state when calculating the line
*
* @param geoPoint
*/
private void setScreenPoint(GeoPoint geoPoint)
{
mScreenPointBackup.x = this.mScreenPoint.x;
mScreenPointBackup.y = this.mScreenPoint.x;
mLoggerMap.toPixels(geoPoint, this.mScreenPoint);
}
/**
* Move to a next waypoint, for on screen this are the points with mStepSize
* % position == 0 to avoid jittering in the rendering or the points on the
* either side of the screen edge.
*
* @return if a next waypoint is pointed to with the mWaypointsCursor
*/
private boolean moveToNextWayPoint()
{
boolean cursorReady = true;
boolean onscreen = isGeoPointOnScreen(extractGeoPoint());
if (mWaypointsCursor.isLast()) // End of the line, cant move onward
{
cursorReady = false;
}
else if (onscreen) // Are on screen
{
cursorReady = moveOnScreenWaypoint();
}
else
// Are off screen => accelerate
{
int acceleratedStepsize = mStepSize * (mWaypointCount / 1000 + 6);
cursorReady = moveOffscreenWaypoint(acceleratedStepsize);
}
return cursorReady;
}
/**
* Move the cursor to the next waypoint modulo of the step size or less if
* the screen edge is reached
*
* @param trackCursor
* @return
*/
private boolean moveOnScreenWaypoint()
{
int nextPosition = mStepSize * (mWaypointsCursor.getPosition() / mStepSize) + mStepSize;
if (mWaypointsCursor.moveToPosition(nextPosition))
{
if (isGeoPointOnScreen(extractGeoPoint())) // Remained on screen
{
return true; // Cursor is pointing to somewhere
}
else
{
mWaypointsCursor.move(-1 * mStepSize); // Step back
boolean nowOnScreen = true; // onto the screen
while (nowOnScreen) // while on the screen
{
mWaypointsCursor.moveToNext(); // inch forward to the edge
nowOnScreen = isGeoPointOnScreen(extractGeoPoint());
}
return true; // with a cursor point to somewhere
}
}
else
{
return mWaypointsCursor.moveToLast(); // No full step can be taken, move to last
}
}
/**
* Previous path GeoPoint was off screen and the next one will be to or the
* first on screen when the path reaches the projection.
*
* @return
*/
private boolean moveOffscreenWaypoint(int flexStepsize)
{
while (mWaypointsCursor.move(flexStepsize))
{
if (mWaypointsCursor.isLast())
{
return true;
}
GeoPoint evalPoint = extractGeoPoint();
// Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
if (evalPoint.getLatitudeE6() == 0 || evalPoint.getLongitudeE6() == 0)
{
continue;
}
// Log.d( TAG, String.format( "Evaluate point number %d ", mWaypointsCursor.getPosition() ) );
if (possibleScreenPass(mPrevGeoPoint, evalPoint))
{
mPrevGeoPoint = evalPoint;
if (flexStepsize == 1) // Just stumbled over a border
{
return true;
}
else
{
mWaypointsCursor.move(-1 * flexStepsize); // Take 1 step back
return moveOffscreenWaypoint(flexStepsize / 2); // Continue at halve accelerated speed
}
}
else
{
moveToGeoPoint(evalPoint);
mPrevGeoPoint = evalPoint;
}
}
return mWaypointsCursor.moveToLast();
}
/**
* If a segment contains more then 500 waypoints and is zoomed out more then
* twice then some waypoints will not be used to render the line, this
* speeding things along.
*/
private void calculateStepSize()
{
Cursor waypointsCursor = null;
if (mRequeryFlag || mStepSize < 1 || mWaypointCount < 0)
{
try
{
waypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints._ID }, null, null, null);
mWaypointCount = waypointsCursor.getCount();
}
finally
{
if (waypointsCursor != null)
{
waypointsCursor.close();
}
}
}
if (mWaypointCount < 250)
{
mStepSize = 1;
}
else
{
int zoomLevel = mLoggerMap.getZoomLevel();
int maxZoomLevel = mLoggerMap.getMaxZoomLevel();
if (zoomLevel >= maxZoomLevel - 2)
{
mStepSize = 1;
}
else
{
mStepSize = maxZoomLevel - zoomLevel;
}
}
}
/**
* Is a given GeoPoint in the current projection of the map.
*
* @param eval
* @return
*/
protected boolean isGeoPointOnScreen(GeoPoint geopoint)
{
boolean onscreen = geopoint != null;
if (geopoint != null && mGeoTopLeft != null && mGeoBottumRight != null)
{
onscreen = onscreen && mGeoTopLeft.getLatitudeE6() > geopoint.getLatitudeE6();
onscreen = onscreen && mGeoBottumRight.getLatitudeE6() < geopoint.getLatitudeE6();
if (mGeoTopLeft.getLongitudeE6() < mGeoBottumRight.getLongitudeE6())
{
onscreen = onscreen && mGeoTopLeft.getLongitudeE6() < geopoint.getLongitudeE6();
onscreen = onscreen && mGeoBottumRight.getLongitudeE6() > geopoint.getLongitudeE6();
}
else
{
onscreen = onscreen && (mGeoTopLeft.getLongitudeE6() < geopoint.getLongitudeE6() || mGeoBottumRight.getLongitudeE6() > geopoint.getLongitudeE6());
}
}
return onscreen;
}
/**
* Is a given coordinates are on the screen
*
* @param eval
* @return
*/
protected boolean isOnScreen(int x, int y)
{
boolean onscreen = x > 0 && y > 0 && x < mWidth && y < mHeight;
return onscreen;
}
/**
* Calculates in which segment opposited to the projecting a geo point
* resides
*
* @param p1
* @return
*/
private int toSegment(GeoPoint p1)
{
// Log.d( TAG, String.format( "Comparing %s to points TL %s and BR %s", p1, mTopLeft, mBottumRight ));
int nr;
if (p1.getLongitudeE6() < mGeoTopLeft.getLongitudeE6()) // left
{
nr = 1;
}
else if (p1.getLongitudeE6() > mGeoBottumRight.getLongitudeE6()) // right
{
nr = 3;
}
else
// middle
{
nr = 2;
}
if (p1.getLatitudeE6() > mGeoTopLeft.getLatitudeE6()) // top
{
nr = nr + 0;
}
else if (p1.getLatitudeE6() < mGeoBottumRight.getLatitudeE6()) // bottom
{
nr = nr + 6;
}
else
// middle
{
nr = nr + 3;
}
return nr;
}
private boolean possibleScreenPass(GeoPoint fromGeo, GeoPoint toGeo)
{
boolean safe = true;
if (fromGeo != null && toGeo != null)
{
int from = toSegment(fromGeo);
int to = toSegment(toGeo);
switch (from)
{
case 1:
safe = to == 1 || to == 2 || to == 3 || to == 4 || to == 7;
break;
case 2:
safe = to == 1 || to == 2 || to == 3;
break;
case 3:
safe = to == 1 || to == 2 || to == 3 || to == 6 || to == 9;
break;
case 4:
safe = to == 1 || to == 4 || to == 7;
break;
case 5:
safe = false;
break;
case 6:
safe = to == 3 || to == 6 || to == 9;
break;
case 7:
safe = to == 1 || to == 4 || to == 7 || to == 8 || to == 9;
break;
case 8:
safe = to == 7 || to == 8 || to == 9;
break;
case 9:
safe = to == 3 || to == 6 || to == 7 || to == 8 || to == 9;
break;
default:
safe = false;
break;
}
// Log.d( TAG, String.format( "From %d to %d is safe: %s", from, to, safe ) );
}
return !safe;
}
public void setTrackColoringMethod(int coloring, double avgspeed, double avgHeight)
{
if (mTrackColoringMethod != coloring)
{
mTrackColoringMethod = coloring;
calculateTrack();
}
mAvgSpeed = avgspeed;
mAvgHeight = avgHeight;
}
/**
* For the current waypoint cursor returns the GeoPoint
*
* @return
*/
private GeoPoint extractGeoPoint()
{
int microLatitude = (int) (mWaypointsCursor.getDouble(0) * 1E6d);
int microLongitude = (int) (mWaypointsCursor.getDouble(1) * 1E6d);
return new GeoPoint(microLatitude, microLongitude);
}
/**
* @param startLocation
* @param endLocation
* @return speed in m/s between 2 locations
*/
private static double calculateSpeedBetweenLocations(Location startLocation, Location endLocation)
{
double speed = -1d;
if (startLocation != null && endLocation != null)
{
float distance = startLocation.distanceTo(endLocation);
float seconds = (endLocation.getTime() - startLocation.getTime()) / 1000f;
speed = distance / seconds;
// Log.d( TAG, "Found a speed of "+speed+ " over a distance of "+ distance+" in a time of "+seconds);
}
if (speed > 0)
{
return speed;
}
else
{
return -1d;
}
}
public static int extendPoint(int x1, int x2)
{
int diff = x2 - x1;
int next = x2 + diff;
return next;
}
private static double distanceInPoints(Point start, Point end)
{
int x = Math.abs(end.x - start.x);
int y = Math.abs(end.y - start.y);
return (double) Math.sqrt(x * x + y * y);
}
private boolean handleMediaTapList(List<Uri> tappedUri)
{
if (tappedUri.size() == 1)
{
return handleMedia(mLoggerMap.getActivity(), tappedUri.get(0));
}
else
{
BaseAdapter adapter = new MediaAdapter(mLoggerMap.getActivity(), tappedUri);
mLoggerMap.showMediaDialog(adapter);
return true;
}
}
public static boolean handleMedia(Context ctx, Uri mediaUri)
{
if (mediaUri.getScheme().equals("file"))
{
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
if (mediaUri.getLastPathSegment().endsWith("3gp"))
{
intent.setDataAndType(mediaUri, "video/3gpp");
ctx.startActivity(intent);
return true;
}
else if (mediaUri.getLastPathSegment().endsWith("jpg"))
{
//<scheme>://<authority><absolute path>
Uri.Builder builder = new Uri.Builder();
mediaUri = builder.scheme(mediaUri.getScheme()).authority(mediaUri.getAuthority()).path(mediaUri.getPath()).build();
intent.setDataAndType(mediaUri, "image/jpeg");
ctx.startActivity(intent);
return true;
}
else if (mediaUri.getLastPathSegment().endsWith("txt"))
{
intent.setDataAndType(mediaUri, "text/plain");
ctx.startActivity(intent);
return true;
}
}
else if (mediaUri.getScheme().equals("content"))
{
if (mediaUri.getAuthority().equals(GPStracking.AUTHORITY + ".string"))
{
String text = mediaUri.getLastPathSegment();
Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_LONG);
toast.show();
return true;
}
else if (mediaUri.getAuthority().equals("media"))
{
ctx.startActivity(new Intent(Intent.ACTION_VIEW, mediaUri));
return true;
}
}
return false;
}
public boolean commonOnTap(GeoPoint tappedGeoPoint)
{
List<Uri> tappedUri = new Vector<Uri>();
Point tappedPoint = new Point();
mLoggerMap.toPixels(tappedGeoPoint, tappedPoint);
for (MediaVO media : mMediaPath)
{
if (media.x < tappedPoint.x && tappedPoint.x < media.x + media.w && media.y < tappedPoint.y && tappedPoint.y < media.y + media.h)
{
tappedUri.add(media.uri);
}
}
if (tappedUri.size() > 0)
{
return handleMediaTapList(tappedUri);
}
else
{
if (mTrackColoringMethod == DRAW_DOTS)
{
DotVO tapped = null;
synchronized (mDotPath) // Switch the fresh path with the old Path object
{
int w = 25;
for (DotVO dot : mDotPath)
{
// Log.d( TAG, "Compare ("+dot.x+","+dot.y+") with tap ("+tappedPoint.x+","+tappedPoint.y+")" );
if (dot.x - w < tappedPoint.x && tappedPoint.x < dot.x + w && dot.y - w < tappedPoint.y && tappedPoint.y < dot.y + w)
{
if (tapped == null)
{
tapped = dot;
}
else
{
tapped = dot.distanceTo(tappedPoint) < tapped.distanceTo(tappedPoint) ? dot : tapped;
}
}
}
}
if (tapped != null)
{
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(mLoggerMap.getActivity().getApplicationContext());
String timetxt = timeFormat.format(new Date(tapped.time));
UnitsI18n units = new UnitsI18n(mLoggerMap.getActivity(), null);
double speed = units.conversionFromMetersPerSecond(tapped.speed);
String speedtxt = String.format("%.1f %s", speed, units.getSpeedUnit());
String text = mLoggerMap.getActivity().getString(R.string.time_and_speed, timetxt, speedtxt);
Toast toast = Toast.makeText(mLoggerMap.getActivity(), text, Toast.LENGTH_SHORT);
toast.show();
}
}
return false;
}
}
private static class MediaVO
{
@Override
public String toString()
{
return "MediaVO [bitmapKey=" + bitmapKey + ", uri=" + uri + ", geopoint=" + geopoint + ", x=" + x + ", y=" + y + ", w=" + w + ", h=" + h
+ ", waypointId=" + waypointId + "]";
}
public Integer bitmapKey;
public Uri uri;
public GeoPoint geopoint;
public int x;
public int y;
public int w;
public int h;
public long waypointId;
}
private static class DotVO
{
public long time;
public long speed;
public int x;
public int y;
public float radius;
public int distanceTo(Point tappedPoint)
{
return Math.abs(tappedPoint.x - this.x) + Math.abs(tappedPoint.y - this.y);
}
}
private class MediaAdapter extends BaseAdapter
{
private Context mContext;
private List<Uri> mTappedUri;
private int itemBackground;
public MediaAdapter(Context ctx, List<Uri> tappedUri)
{
mContext = ctx;
mTappedUri = tappedUri;
TypedArray a = mContext.obtainStyledAttributes(R.styleable.gallery);
itemBackground = a.getResourceId(R.styleable.gallery_android_galleryItemBackground, 0);
a.recycle();
}
@Override
public int getCount()
{
return mTappedUri.size();
}
@Override
public Object getItem(int position)
{
return mTappedUri.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(sBitmapCache.get(getResourceForMedia(mLoggerMap.getActivity().getResources(), mTappedUri.get(position))));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
public void setBitmapHolder(AsyncOverlay bitmapOverlay)
{
mAsyncOverlay = bitmapOverlay;
}
}
| Java |
package nl.sogeti.android.gpstracker.viewer.map.overlay;
import java.util.LinkedList;
import java.util.List;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.Log;
import com.google.android.maps.GeoPoint;
public class BitmapSegmentsOverlay extends AsyncOverlay
{
private static final String TAG = "GG.BitmapSegmentsOverlay";
List<SegmentRendering> mOverlays;
Handler mOverlayHandler;
public BitmapSegmentsOverlay(LoggerMap loggermap, Handler handler)
{
super(loggermap, handler);
mOverlays = new LinkedList<SegmentRendering>();
mOverlayHandler = handler;
}
@Override
synchronized protected void redrawOffscreen(Canvas asyncBuffer, LoggerMap loggermap)
{
for (SegmentRendering segment : mOverlays)
{
segment.draw(asyncBuffer);
}
}
@Override
public synchronized void scheduleRecalculation()
{
for (SegmentRendering segment : mOverlays)
{
segment.calculateMedia();
segment.calculateTrack();
}
}
@Override
synchronized protected boolean commonOnTap(GeoPoint tappedGeoPoint)
{
boolean handled = false;
for (SegmentRendering segment : mOverlays)
{
if (!handled)
{
handled = segment.commonOnTap(tappedGeoPoint);
}
}
return handled;
}
synchronized public void addSegment(SegmentRendering segment)
{
segment.setBitmapHolder(this);
mOverlays.add(segment);
}
synchronized public void clearSegments()
{
for (SegmentRendering segment : mOverlays)
{
segment.closeResources();
}
mOverlays.clear();
reset();
}
synchronized public void setTrackColoringMethod(int color, double speed, double height)
{
for (SegmentRendering segment : mOverlays)
{
segment.setTrackColoringMethod(color, speed, height);
}
scheduleRecalculation();
}
public int size()
{
return mOverlays.size();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Delivery Center Java
** Author: rene
** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*/
package nl.sogeti.android.gpstracker.viewer.map;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.SlidingIndicatorView;
import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.CloudmadeUtil;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.Overlay;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
/**
* ????
*
* @version $Id:$
* @author rene (c) Feb 26, 2012, Sogeti B.V.
*/
public class OsmLoggerMap extends Activity implements LoggerMap
{
protected static final String TAG = "OsmLoggerMap";
LoggerMapHelper mHelper;
private MapView mMapView;
private TextView[] mSpeedtexts;
private TextView mLastGPSSpeedView;
private TextView mLastGPSAltitudeView;
private TextView mDistanceView;
private MyLocationOverlay mMylocation;
private Projection mProjecton;
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate(Bundle load)
{
super.onCreate(load);
setContentView(R.layout.map_osm);
mMapView = (MapView) findViewById(R.id.myMapView);
TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03),
(TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) };
mSpeedtexts = speeds;
mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed);
mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude);
mDistanceView = (TextView) findViewById(R.id.currentDistance);
mHelper = new LoggerMapHelper(this);
mMapView.setBuiltInZoomControls(true);
mProjecton = mMapView.getProjection();
mHelper.onCreate(load);
mMylocation = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add( new Overlay(this)
{
@Override
protected void draw(Canvas arg0, MapView map, boolean arg2)
{
Projection projecton = map.getProjection();
mProjecton = projecton;
IGeoPoint gepoint = map.getMapCenter();
Point point = projecton.toPixels(gepoint, null);
Log.d(TAG, "Found center ("+gepoint.getLatitudeE6()+","+gepoint.getLongitudeE6()+") matching screen point ("+point.x+","+point.y+") ");
}
} );
}
@Override
protected void onResume()
{
super.onResume();
mHelper.onResume();
}
@Override
protected void onPause()
{
mHelper.onPause();
super.onPause();
}
@Override
protected void onDestroy()
{
mHelper.onDestroy();
super.onDestroy();
}
@Override
public void onNewIntent(Intent newIntent)
{
mHelper.onNewIntent(newIntent);
}
@Override
protected void onRestoreInstanceState(Bundle load)
{
if (load != null)
{
super.onRestoreInstanceState(load);
}
mHelper.onRestoreInstanceState(load);
}
@Override
protected void onSaveInstanceState(Bundle save)
{
super.onSaveInstanceState(save);
mHelper.onSaveInstanceState(save);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
mHelper.onCreateOptionsMenu(menu);
return result;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
mHelper.onPrepareOptionsMenu(menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
boolean handled = mHelper.onOptionsItemSelected(item);
if( !handled )
{
handled = super.onOptionsItemSelected(item);
}
return handled;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
mHelper.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean propagate = true;
switch (keyCode)
{
default:
propagate = mHelper.onKeyDown(keyCode, event);
if( propagate )
{
propagate = super.onKeyDown(keyCode, event);
}
break;
}
return propagate;
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = mHelper.onCreateDialog(id);
if( dialog == null )
{
dialog = super.onCreateDialog(id);
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
mHelper.onPrepareDialog(id, dialog);
super.onPrepareDialog(id, dialog);
}
/******************************/
/** Own methods **/
/******************************/
private void setTrafficOverlay(boolean b)
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.TRAFFIC, b);
editor.commit();
}
private void setSatelliteOverlay(boolean b)
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.SATELLITE, b);
editor.commit();
}
/******************************/
/** Loggermap methods **/
/******************************/
@Override
public void updateOverlays()
{
SharedPreferences sharedPreferences = mHelper.getPreferences();
int renderer = sharedPreferences.getInt(Constants.OSMBASEOVERLAY, 0);
switch( renderer )
{
case Constants.OSM_CLOUDMADE:
CloudmadeUtil.retrieveCloudmadeKey(this.getApplicationContext());
mMapView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES);
break;
case Constants.OSM_MAKNIK:
mMapView.setTileSource(TileSourceFactory.MAPNIK);
break;
case Constants.OSM_CYCLE:
mMapView.setTileSource(TileSourceFactory.CYCLEMAP);
break;
default:
break;
}
}
@Override
public void setDrawingCacheEnabled(boolean b)
{
findViewById(R.id.mapScreen).setDrawingCacheEnabled(true);
}
@Override
public Activity getActivity()
{
return this;
}
@Override
public void onLayerCheckedChanged(int checkedId, boolean isChecked)
{
switch (checkedId)
{
case R.id.layer_google_satellite:
setSatelliteOverlay(true);
break;
case R.id.layer_google_regular:
setSatelliteOverlay(false);
break;
case R.id.layer_traffic:
setTrafficOverlay(isChecked);
break;
default:
break;
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.TRAFFIC))
{
updateOverlays();
}
else if (key.equals(Constants.SATELLITE))
{
updateOverlays();
}
}
@Override
public Bitmap getDrawingCache()
{
return findViewById(R.id.mapScreen).getDrawingCache();
}
@Override
public void showMediaDialog(BaseAdapter mediaAdapter)
{
mHelper.showMediaDialog(mediaAdapter);
}
public void onDateOverlayChanged()
{
mMapView.postInvalidate();
}
@Override
public String getDataSourceId()
{
return LoggerMapHelper.GOOGLE_PROVIDER;
}
@Override
public boolean isOutsideScreen(GeoPoint lastPoint)
{
Point out = new Point();
mProjecton.toMapPixels(convertGeoPoint(lastPoint), out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < 0 || out.y < 0 || out.y > height || out.x > width);
}
@Override
public boolean isNearScreenEdge(GeoPoint lastPoint)
{
Point out = new Point();
mProjecton.toMapPixels(convertGeoPoint(lastPoint), out);
int height = this.mMapView.getHeight();
int width = this.mMapView.getWidth();
return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3);
}
@Override
public void executePostponedActions()
{
// NOOP for Google Maps
}
@Override
public void enableCompass()
{
mMylocation.enableCompass();
}
@Override
public void enableMyLocation()
{
mMylocation.enableMyLocation();
}
@Override
public void disableMyLocation()
{
mMylocation.disableMyLocation();
}
@Override
public void disableCompass()
{
mMylocation.disableCompass();
}
@Override
public void setZoom(int zoom)
{
mMapView.getController().setZoom(zoom);
}
@Override
public void animateTo(GeoPoint storedPoint)
{
mMapView.getController().animateTo(convertGeoPoint(storedPoint));
}
@Override
public int getZoomLevel()
{
return mMapView.getZoomLevel();
}
@Override
public GeoPoint getMapCenter()
{
return convertOSMGeoPoint(mMapView.getMapCenter());
}
@Override
public boolean zoomOut()
{
return mMapView.getController().zoomOut();
}
@Override
public boolean zoomIn()
{
return mMapView.getController().zoomIn();
}
@Override
public void postInvalidate()
{
mMapView.postInvalidate();
}
@Override
public void addOverlay(OverlayProvider overlay)
{
mMapView.getOverlays().add(overlay.getOSMOverlay());
}
@Override
public void clearAnimation()
{
mMapView.clearAnimation();
}
@Override
public void setCenter(GeoPoint lastPoint)
{
mMapView.getController().setCenter( convertGeoPoint(lastPoint));
}
@Override
public int getMaxZoomLevel()
{
return mMapView.getMaxZoomLevel();
}
@Override
public GeoPoint fromPixels(int x, int y)
{
IGeoPoint osmGeopoint = mProjecton.fromPixels(x, y);
GeoPoint geopoint = convertOSMGeoPoint(osmGeopoint);
return geopoint;
}
@Override
public void toPixels(GeoPoint geoPoint, Point screenPoint)
{
org.osmdroid.util.GeoPoint localGeopoint = convertGeoPoint(geoPoint);
mProjecton.toMapPixels( localGeopoint, screenPoint);
}
@Override
public boolean hasProjection()
{
return mProjecton != null;
}
@Override
public float metersToEquatorPixels(float float1)
{
return mProjecton.metersToEquatorPixels(float1);
}
@Override
public TextView[] getSpeedTextViews()
{
return mSpeedtexts;
}
@Override
public TextView getAltitideTextView()
{
return mLastGPSAltitudeView;
}
@Override
public TextView getSpeedTextView()
{
return mLastGPSSpeedView;
}
@Override
public TextView getDistanceTextView()
{
return mDistanceView;
}
static org.osmdroid.util.GeoPoint convertGeoPoint( GeoPoint point )
{
org.osmdroid.util.GeoPoint geopoint = new org.osmdroid.util.GeoPoint(point.getLatitudeE6(), point.getLongitudeE6());
return geopoint;
}
static GeoPoint convertOSMGeoPoint( IGeoPoint point )
{
return new GeoPoint(point.getLatitudeE6(), point.getLongitudeE6() );
}
@Override
public void clearOverlays()
{
mMapView.getOverlayManager().clear();
}
@Override
public SlidingIndicatorView getScaleIndicatorView()
{
return (SlidingIndicatorView) findViewById(R.id.scaleindicator);
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.LiveFolders;
/**
* Activity to build a data set to be shown in a live folder in a Android desktop
*
* @version $Id$
* @author rene (c) Mar 22, 2009, Sogeti B.V.
*/
public class TracksLiveFolder extends Activity
{
@Override
protected void onCreate( Bundle savedInstanceState )
{
this.setVisible( false );
super.onCreate( savedInstanceState );
final Intent intent = getIntent();
final String action = intent.getAction();
if( LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals( action ) )
{
final Intent baseAction = new Intent( Intent.ACTION_VIEW, GPStracking.Tracks.CONTENT_URI );
Uri liveData = Uri.withAppendedPath( GPStracking.CONTENT_URI, "live_folders/tracks" );
final Intent createLiveFolder = new Intent();
createLiveFolder.setData( liveData );
createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_NAME, getString(R.string.track_list) );
createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_ICON, Intent.ShortcutIconResource.fromContext( this, R.drawable.live ) );
createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST );
createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT, baseAction );
setResult( RESULT_OK, createLiveFolder );
}
else
{
setResult( RESULT_CANCELED );
}
finish();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.DescribeTrack;
import nl.sogeti.android.gpstracker.actions.Statistics;
import nl.sogeti.android.gpstracker.actions.tasks.GpxParser;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter;
import nl.sogeti.android.gpstracker.adapter.SectionedListAdapter;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder;
import nl.sogeti.android.gpstracker.db.DatabaseHelper;
import nl.sogeti.android.gpstracker.db.GPStracking;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.Pair;
import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Show a list view of all tracks, also doubles for showing search results
*
* @version $Id$
* @author rene (c) Jan 11, 2009, Sogeti B.V.
*/
public class TrackList extends ListActivity implements ProgressListener
{
private static final String TAG = "OGT.TrackList";
private static final int MENU_DETELE = Menu.FIRST + 0;
private static final int MENU_SHARE = Menu.FIRST + 1;
private static final int MENU_RENAME = Menu.FIRST + 2;
private static final int MENU_STATS = Menu.FIRST + 3;
private static final int MENU_SEARCH = Menu.FIRST + 4;
private static final int MENU_VACUUM = Menu.FIRST + 5;
private static final int MENU_PICKER = Menu.FIRST + 6;
private static final int MENU_BREADCRUMBS = Menu.FIRST + 7;
public static final int DIALOG_FILENAME = Menu.FIRST + 22;
private static final int DIALOG_RENAME = Menu.FIRST + 23;
private static final int DIALOG_DELETE = Menu.FIRST + 24;
private static final int DIALOG_VACUUM = Menu.FIRST + 25;
private static final int DIALOG_IMPORT = Menu.FIRST + 26;
private static final int DIALOG_INSTALL = Menu.FIRST + 27;
protected static final int DIALOG_ERROR = Menu.FIRST + 28;
private static final int PICKER_OI = Menu.FIRST + 29;
private static final int DESCRIBE = Menu.FIRST + 30;
private BreadcrumbsAdapter mBreadcrumbAdapter;
private EditText mTrackNameView;
private Uri mDialogTrackUri;
private String mDialogCurrentName = "";
private String mErrorDialogMessage;
private Exception mErrorDialogException;
private Runnable mImportAction;
private String mImportTrackName;
private String mErrorTask;
/**
* Progress listener for the background tasks uploading to gobreadcrumbs
*/
private ProgressListener mExportListener;
private int mPausePosition;
private BreadcrumbsService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
this.setContentView(R.layout.tracklist);
displayIntent(getIntent());
ListView listView = getListView();
listView.setItemsCanFocus(true);
// Add the context menu (the long press thing)
registerForContextMenu(listView);
if (savedInstanceState != null)
{
getListView().setSelection(savedInstanceState.getInt("POSITION"));
}
IntentFilter filter = new IntentFilter();
filter.addAction(BreadcrumbsService.NOTIFY_DATA_SET_CHANGED);
registerReceiver(mReceiver, filter);
Intent service = new Intent(this, BreadcrumbsService.class);
startService(service);
}
@Override
protected void onStart()
{
super.onStart();
Intent intent = new Intent(this, BreadcrumbsService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onResume()
{
if (mPausePosition != 0)
{
getListView().setSelection(mPausePosition);
}
super.onResume();
}
@Override
protected void onPause()
{
mPausePosition = getListView().getFirstVisiblePosition();
super.onPause();
}
@Override
protected void onStop()
{
if (mBound)
{
unbindService(mConnection);
mBound = false;
mService = null;
}
super.onStop();
}
@Override
protected void onDestroy()
{
if (isFinishing())
{
Intent service = new Intent(this, BreadcrumbsService.class);
stopService(service);
}
unregisterReceiver(mReceiver);
super.onDestroy();
}
@Override
public void onNewIntent(Intent newIntent)
{
displayIntent(newIntent);
}
/*
* (non-Javadoc)
* @see android.app.ListActivity#onRestoreInstanceState(android.os.Bundle)
*/
@Override
protected void onRestoreInstanceState(Bundle state)
{
super.onRestoreInstanceState(state);
mDialogTrackUri = state.getParcelable("URI");
mDialogCurrentName = state.getString("NAME");
mDialogCurrentName = mDialogCurrentName != null ? mDialogCurrentName : "";
getListView().setSelection(state.getInt("POSITION"));
}
/*
* (non-Javadoc)
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable("URI", mDialogTrackUri);
outState.putString("NAME", mDialogCurrentName);
outState.putInt("POSITION", getListView().getFirstVisiblePosition());
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
menu.add(ContextMenu.NONE, MENU_SEARCH, ContextMenu.NONE, android.R.string.search_go).setIcon(android.R.drawable.ic_search_category_default).setAlphabeticShortcut(SearchManager.MENU_KEY);
menu.add(ContextMenu.NONE, MENU_VACUUM, ContextMenu.NONE, R.string.menu_vacuum).setIcon(android.R.drawable.ic_menu_crop);
menu.add(ContextMenu.NONE, MENU_PICKER, ContextMenu.NONE, R.string.menu_picker).setIcon(android.R.drawable.ic_menu_add);
menu.add(ContextMenu.NONE, MENU_BREADCRUMBS, ContextMenu.NONE, R.string.dialog_breadcrumbsconnect).setIcon(android.R.drawable.ic_menu_revert);
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
boolean handled = false;
switch (item.getItemId())
{
case MENU_SEARCH:
onSearchRequested();
handled = true;
break;
case MENU_VACUUM:
showDialog(DIALOG_VACUUM);
break;
case MENU_PICKER:
try
{
Intent intent = new Intent("org.openintents.action.PICK_FILE");
intent.putExtra("org.openintents.extra.TITLE", getString(R.string.dialog_import_picker));
intent.putExtra("org.openintents.extra.BUTTON_TEXT", getString(R.string.menu_picker));
startActivityForResult(intent, PICKER_OI);
}
catch (ActivityNotFoundException e)
{
showDialog(DIALOG_INSTALL);
}
break;
case MENU_BREADCRUMBS:
mService.removeAuthentication();
mService.clearAllCache();
mService.collectBreadcrumbsOauthToken();
break;
default:
handled = super.onOptionsItemSelected(item);
}
return handled;
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick(listView, view, position, id);
Object item = listView.getItemAtPosition(position);
if (item instanceof String)
{
if (Constants.BREADCRUMBS_CONNECT.equals(item))
{
mService.collectBreadcrumbsOauthToken();
}
}
else if (item instanceof Pair< ? , ? >)
{
@SuppressWarnings("unchecked")
final Pair<Integer, Integer> track = (Pair<Integer, Integer>) item;
if (track.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE)
{
TextView tv = (TextView) view.findViewById(R.id.listitem_name);
mImportTrackName = tv.getText().toString();
mImportAction = new Runnable()
{
@Override
public void run()
{
mService.startDownloadTask(TrackList.this, TrackList.this, track);
}
};
showDialog(DIALOG_IMPORT);
}
}
else
{
Intent intent = new Intent();
Uri trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, id);
intent.setData(trackUri);
ComponentName caller = this.getCallingActivity();
if (caller != null)
{
setResult(RESULT_OK, intent);
finish();
}
else
{
intent.setClass(this, CommonLoggerMap.class);
startActivity(intent);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
if (menuInfo instanceof AdapterView.AdapterContextMenuInfo)
{
AdapterView.AdapterContextMenuInfo itemInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
TextView textView = (TextView) itemInfo.targetView.findViewById(R.id.listitem_name);
if (textView != null)
{
menu.setHeaderTitle(textView.getText());
}
Object listItem = getListAdapter().getItem(itemInfo.position);
if (listItem instanceof Cursor)
{
menu.add(0, MENU_STATS, 0, R.string.menu_statistics);
menu.add(0, MENU_SHARE, 0, R.string.menu_shareTrack);
menu.add(0, MENU_RENAME, 0, R.string.menu_renameTrack);
menu.add(0, MENU_DETELE, 0, R.string.menu_deleteTrack);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
boolean handled = false;
AdapterView.AdapterContextMenuInfo info;
try
{
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
}
catch (ClassCastException e)
{
Log.e(TAG, "Bad menuInfo", e);
return handled;
}
Object listItem = getListAdapter().getItem(info.position);
if (listItem instanceof Cursor)
{
Cursor cursor = (Cursor) listItem;
mDialogTrackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, cursor.getLong(0));
mDialogCurrentName = cursor.getString(1);
mDialogCurrentName = mDialogCurrentName != null ? mDialogCurrentName : "";
switch (item.getItemId())
{
case MENU_DETELE:
{
showDialog(DIALOG_DELETE);
handled = true;
break;
}
case MENU_SHARE:
{
Intent actionIntent = new Intent(Intent.ACTION_RUN);
actionIntent.setDataAndType(mDialogTrackUri, Tracks.CONTENT_ITEM_TYPE);
actionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(actionIntent, getString(R.string.share_track)));
handled = true;
break;
}
case MENU_RENAME:
{
showDialog(DIALOG_RENAME);
handled = true;
break;
}
case MENU_STATS:
{
Intent actionIntent = new Intent(this, Statistics.class);
actionIntent.setData(mDialogTrackUri);
startActivity(actionIntent);
handled = true;
break;
}
default:
handled = super.onContextItemSelected(item);
break;
}
}
return handled;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_RENAME:
LayoutInflater factory = LayoutInflater.from(this);
View view = factory.inflate(R.layout.namedialog, null);
mTrackNameView = (EditText) view.findViewById(R.id.nameField);
builder = new AlertDialog.Builder(this).setTitle(R.string.dialog_routename_title).setMessage(R.string.dialog_routename_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_okay, mRenameOnClickListener).setNegativeButton(R.string.btn_cancel, null).setView(view);
dialog = builder.create();
return dialog;
case DIALOG_DELETE:
builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_delete_title).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, mDeleteOnClickListener);
dialog = builder.create();
String messageFormat = this.getResources().getString(R.string.dialog_delete_message);
String message = String.format(messageFormat, "");
((AlertDialog) dialog).setMessage(message);
return dialog;
case DIALOG_VACUUM:
builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_vacuum_title).setMessage(R.string.dialog_vacuum_message).setIcon(android.R.drawable.ic_dialog_alert)
.setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, mVacuumOnClickListener);
dialog = builder.create();
return dialog;
case DIALOG_IMPORT:
builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_import_title).setMessage(getString(R.string.dialog_import_message, mImportTrackName))
.setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, mImportOnClickListener);
dialog = builder.create();
return dialog;
case DIALOG_INSTALL:
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_nooipicker).setMessage(R.string.dialog_nooipicker_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOiPickerDialogListener).setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
case DIALOG_ERROR:
builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage).setNeutralButton(android.R.string.cancel, null);
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog(id);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
super.onPrepareDialog(id, dialog);
AlertDialog alert;
String message;
switch (id)
{
case DIALOG_RENAME:
mTrackNameView.setText(mDialogCurrentName);
mTrackNameView.setSelection(0, mDialogCurrentName.length());
break;
case DIALOG_DELETE:
alert = (AlertDialog) dialog;
String messageFormat = this.getResources().getString(R.string.dialog_delete_message);
message = String.format(messageFormat, mDialogCurrentName);
alert.setMessage(message);
break;
case DIALOG_ERROR:
alert = (AlertDialog) dialog;
message = "Failed task:\n" + mErrorTask;
message += "\n\n";
message += "Reason:\n" + mErrorDialogMessage;
if (mErrorDialogException != null)
{
message += " (" + mErrorDialogException.getMessage() + ") ";
}
alert.setMessage(message);
break;
case DIALOG_IMPORT:
alert = (AlertDialog) dialog;
alert.setMessage(getString(R.string.dialog_import_message, mImportTrackName));
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_CANCELED)
{
switch (requestCode)
{
case PICKER_OI:
new GpxParser(TrackList.this, TrackList.this).execute(data.getData());
break;
case DESCRIBE:
Uri trackUri = data.getData();
String name;
if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME))
{
name = data.getExtras().getString(Constants.NAME);
}
else
{
name = "shareToGobreadcrumbs";
}
mService.startUploadTask(TrackList.this, mExportListener, trackUri, name);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
else
{
if (requestCode == DESCRIBE)
{
mBreadcrumbAdapter.notifyDataSetChanged();
}
}
}
private void displayIntent(Intent intent)
{
final String queryAction = intent.getAction();
final String orderby = Tracks.CREATION_TIME + " DESC";
Cursor tracksCursor = null;
if (Intent.ACTION_SEARCH.equals(queryAction))
{
// Got to SEARCH a query for tracks, make a list
tracksCursor = doSearchWithIntent(intent);
}
else if (Intent.ACTION_VIEW.equals(queryAction))
{
final Uri uri = intent.getData();
if ("content".equals(uri.getScheme()) && GPStracking.AUTHORITY.equals(uri.getAuthority()))
{
// Got to VIEW a single track, instead hand it of to the LoggerMap
Intent notificationIntent = new Intent(this, LoggerMap.class);
notificationIntent.setData(uri);
startActivity(notificationIntent);
finish();
}
else if (uri.getScheme().equals("file") || uri.getScheme().equals("content"))
{
mImportTrackName = uri.getLastPathSegment();
// Got to VIEW a GPX filename
mImportAction = new Runnable()
{
@Override
public void run()
{
new GpxParser(TrackList.this, TrackList.this).execute(uri);
}
};
showDialog(DIALOG_IMPORT);
tracksCursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby);
}
else
{
Log.e(TAG, "Unable to VIEW " + uri);
}
}
else
{
// Got to nothing, make a list of everything
tracksCursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby);
}
displayCursor(tracksCursor);
}
private void displayCursor(Cursor tracksCursor)
{
SectionedListAdapter sectionedAdapter = new SectionedListAdapter(this);
String[] fromColumns = new String[] { Tracks.NAME, Tracks.CREATION_TIME, Tracks._ID };
int[] toItems = new int[] { R.id.listitem_name, R.id.listitem_from, R.id.bcSyncedCheckBox };
SimpleCursorAdapter trackAdapter = new SimpleCursorAdapter(this, R.layout.trackitem, tracksCursor, fromColumns, toItems);
mBreadcrumbAdapter = new BreadcrumbsAdapter(this, mService);
sectionedAdapter.addSection("Local", trackAdapter);
sectionedAdapter.addSection("www.gobreadcrumbs.com", mBreadcrumbAdapter);
// Enrich the track adapter with Breadcrumbs adapter data
trackAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder()
{
@Override
public boolean setViewValue(View view, final Cursor cursor, int columnIndex)
{
if (columnIndex == 0)
{
final long trackId = cursor.getLong(0);
final String trackName = cursor.getString(1);
// Show the check if Breadcrumbs is online
final CheckBox checkbox = (CheckBox) view;
final ProgressBar progressbar = (ProgressBar) ((View) view.getParent()).findViewById(R.id.bcExportProgress);
if (mService != null && mService.isAuthorized())
{
checkbox.setVisibility(View.VISIBLE);
// Disable the checkbox if marked online
boolean isOnline = mService.isLocalTrackSynced(trackId);
checkbox.setEnabled(!isOnline);
// Check the checkbox if determined synced
boolean isSynced = mService.isLocalTrackSynced(trackId);
checkbox.setOnCheckedChangeListener(null);
checkbox.setChecked(isSynced);
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
// Start a description of the track
Intent namingIntent = new Intent(TrackList.this, DescribeTrack.class);
namingIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId));
namingIntent.putExtra(Constants.NAME, trackName);
mExportListener = new ProgressListener()
{
@Override
public void setIndeterminate(boolean indeterminate)
{
progressbar.setIndeterminate(indeterminate);
}
@Override
public void started()
{
checkbox.setVisibility(View.INVISIBLE);
progressbar.setVisibility(View.VISIBLE);
}
@Override
public void finished(Uri result)
{
checkbox.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.INVISIBLE);
progressbar.setIndeterminate(false);
}
@Override
public void setProgress(int value)
{
progressbar.setProgress(value);
}
@Override
public void showError(String task, String errorMessage, Exception exception)
{
TrackList.this.showError(task, errorMessage, exception);
}
};
startActivityForResult(namingIntent, DESCRIBE);
}
}
});
}
else
{
checkbox.setVisibility(View.INVISIBLE);
checkbox.setOnCheckedChangeListener(null);
}
return true;
}
return false;
}
});
setListAdapter(sectionedAdapter);
}
private Cursor doSearchWithIntent(final Intent queryIntent)
{
final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
Cursor cursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, "name LIKE ?", new String[] { "%" + queryString + "%" }, null);
return cursor;
}
/*******************************************************************/
/** ProgressListener interface and UI actions (non-Javadoc) **/
/*******************************************************************/
@Override
public void setIndeterminate(boolean indeterminate)
{
setProgressBarIndeterminate(indeterminate);
}
@Override
public void started()
{
setProgressBarVisibility(true);
setProgress(Window.PROGRESS_START);
}
@Override
public void finished(Uri result)
{
setProgressBarVisibility(false);
setProgressBarIndeterminate(false);
}
@Override
public void showError(String task, String errorDialogMessage, Exception errorDialogException)
{
mErrorTask = task;
mErrorDialogMessage = errorDialogMessage;
mErrorDialogException = errorDialogException;
Log.e(TAG, errorDialogMessage, errorDialogException);
if (!isFinishing())
{
showDialog(DIALOG_ERROR);
}
setProgressBarVisibility(false);
setProgressBarIndeterminate(false);
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
mBreadcrumbAdapter.setService(mService);
}
@Override
public void onServiceDisconnected(ComponentName arg0)
{
mBound = false;
mService = null;
}
};
private OnClickListener mDeleteOnClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
getContentResolver().delete(mDialogTrackUri, null, null);
}
};
private OnClickListener mRenameOnClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Log.d( TAG, "Context item selected: "+mDialogUri+" with name "+mDialogCurrentName );
String trackName = mTrackNameView.getText().toString();
ContentValues values = new ContentValues();
values.put(Tracks.NAME, trackName);
TrackList.this.getContentResolver().update(mDialogTrackUri, values, null, null);
}
};
private OnClickListener mVacuumOnClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
DatabaseHelper helper = new DatabaseHelper(TrackList.this);
helper.vacuum();
}
};
private OnClickListener mImportOnClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
mImportAction.run();
}
};
private final DialogInterface.OnClickListener mOiPickerDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager");
Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiAboutIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk");
oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiAboutIntent);
}
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (BreadcrumbsService.NOTIFY_DATA_SET_CHANGED.equals(intent.getAction()))
{
mBreadcrumbAdapter.updateItemList();
}
}
};
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.viewer;
import java.util.regex.Pattern;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
/**
* Controller for the settings dialog
*
* @version $Id: ApplicationPreferenceActivity.java 1146 2011-11-05 11:36:51Z
* rcgroot $
* @author rene (c) Jan 18, 2009, Sogeti B.V.
*/
public class ApplicationPreferenceActivity extends PreferenceActivity
{
public static final String STREAMBROADCAST_PREFERENCE = "streambroadcast_distance";
public static final String UNITS_IMPLEMENT_WIDTH_PREFERENCE = "units_implement_width";
public static final String CUSTOMPRECISIONDISTANCE_PREFERENCE = "customprecisiondistance";
public static final String CUSTOMPRECISIONTIME_PREFERENCE = "customprecisiontime";
public static final String PRECISION_PREFERENCE = "precision";
public static final String CUSTOMUPLOAD_BACKLOG = "CUSTOMUPLOAD_BACKLOG";
public static final String CUSTOMUPLOAD_URL = "CUSTOMUPLOAD_URL";
private EditTextPreference time;
private EditTextPreference distance;
private EditTextPreference implentWidth;
private EditTextPreference streambroadcast_distance;
private EditTextPreference custumupload_backlog;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings);
ListPreference precision = (ListPreference) findPreference(PRECISION_PREFERENCE);
time = (EditTextPreference) findPreference(CUSTOMPRECISIONTIME_PREFERENCE);
distance = (EditTextPreference) findPreference(CUSTOMPRECISIONDISTANCE_PREFERENCE);
implentWidth = (EditTextPreference) findPreference(UNITS_IMPLEMENT_WIDTH_PREFERENCE);
streambroadcast_distance = (EditTextPreference) findPreference(STREAMBROADCAST_PREFERENCE);
custumupload_backlog = (EditTextPreference) findPreference(CUSTOMUPLOAD_BACKLOG);
setEnabledCustomValues(precision.getValue());
precision.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
setEnabledCustomValues(newValue);
return true;
}
});
implentWidth.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String fpExpr = "\\d{1,4}([,\\.]\\d+)?";
return Pattern.matches(fpExpr, newValue.toString());
}
});
streambroadcast_distance.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String fpExpr = "\\d{1,5}";
boolean matches = Pattern.matches(fpExpr, newValue.toString());
if (matches)
{
Editor editor = getPreferenceManager().getSharedPreferences().edit();
double value = new UnitsI18n(ApplicationPreferenceActivity.this).conversionFromLocalToMeters(Integer.parseInt(newValue.toString()));
editor.putFloat("streambroadcast_distance_meter", (float) value);
editor.commit();
}
return matches;
}
});
custumupload_backlog.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
String fpExpr = "\\d{1,3}";
return Pattern.matches(fpExpr, newValue.toString());
}
});
}
private void setEnabledCustomValues(Object newValue)
{
boolean customPresicion = Integer.toString(Constants.LOGGING_CUSTOM).equals(newValue);
time.setEnabled(customPresicion);
distance.setEnabled(customPresicion);
}
}
| Java |
/* Copyright (c) 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.gdata.util.common.base;
import static com.google.gdata.util.common.base.Preconditions.checkNotNull;
import java.io.IOException;
/**
* An {@link Escaper} that converts literal text into a format safe for
* inclusion in a particular context (such as an XML document). Typically (but
* not always), the inverse process of "unescaping" the text is performed
* automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one
* very important difference. A CharEscaper can only process Java
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in
* isolation and may not cope when it encounters surrogate pairs. This class
* facilitates the correct escaping of all Unicode characters.
*
* <p>As there are important reasons, including potential security issues, to
* handle Unicode correctly if you are considering implementing a new escaper
* you should favor using UnicodeEscaper wherever possible.
*
* <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe
* when used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers extend this class and implement
* the {@link #escape(int)} method.
*
*
*/
public abstract class UnicodeEscaper implements Escaper {
/** The amount of padding (chars) to use when growing the escape buffer. */
private static final int DEST_PAD = 32;
/**
* Returns the escaped form of the given Unicode code point, or {@code null}
* if this code point does not need to be escaped. When called as part of an
* escaping operation, the given code point is guaranteed to be in the range
* {@code 0 <= cp <= Character#MAX_CODE_POINT}.
*
* <p>If an empty array is returned, this effectively strips the input
* character from the resulting text.
*
* <p>If the character does not need to be escaped, this method should return
* {@code null}, rather than an array containing the character representation
* of the code point. This enables the escaping algorithm to perform more
* efficiently.
*
* <p>If the implementation of this method cannot correctly handle a
* particular code point then it should either throw an appropriate runtime
* exception or return a suitable replacement character. It must never
* silently discard invalid input as this may constitute a security risk.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was
* needed
*/
protected abstract char[] escape(int cp);
/**
* Scans a sub-sequence of characters from a given {@link CharSequence},
* returning the index of the next character that requires escaping.
*
* <p><b>Note:</b> When implementing an escaper, it is a good idea to override
* this method for efficiency. The base class implementation determines
* successive Unicode code points and invokes {@link #escape(int)} for each of
* them. If the semantics of your escaper are such that code points in the
* supplementary range are either all escaped or all unescaped, this method
* can be implemented more efficiently using {@link CharSequence#charAt(int)}.
*
* <p>Note however that if your escaper does not escape characters in the
* supplementary range, you should either continue to validate the correctness
* of any surrogate characters encountered or provide a clear warning to users
* that your escaper does not validate its input.
*
* <p>See {@link PercentEscaper} for an example.
*
* @param csq a sequence of characters
* @param start the index of the first character to be scanned
* @param end the index immediately after the last character to be scanned
* @throws IllegalArgumentException if the scanned sub-sequence of {@code csq}
* contains invalid surrogate pairs
*/
protected int nextEscapeIndex(CharSequence csq, int start, int end) {
int index = start;
while (index < end) {
int cp = codePointAt(csq, index, end);
if (cp < 0 || escape(cp) != null) {
break;
}
index += Character.isSupplementaryCodePoint(cp) ? 2 : 1;
}
return index;
}
/**
* Returns the escaped form of a given literal string.
*
* <p>If you are escaping input in arbitrary successive chunks, then it is not
* generally safe to use this method. If an input string ends with an
* unmatched high surrogate character, then this method will throw
* {@link IllegalArgumentException}. You should either ensure your input is
* valid <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before
* calling this method or use an escaped {@link Appendable} (as returned by
* {@link #escape(Appendable)}) which can cope with arbitrarily split input.
*
* <p><b>Note:</b> When implementing an escaper it is a good idea to override
* this method for efficiency by inlining the implementation of
* {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for
* {@link PercentEscaper} more than doubled the performance for unescaped
* strings (as measured by {@link CharEscapersBenchmark}).
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
public String escape(String string) {
int end = string.length();
int index = nextEscapeIndex(string, 0, end);
return index == end ? string : escapeSlow(string, index);
}
/**
* Returns the escaped form of a given literal string, starting at the given
* index. This method is called by the {@link #escape(String)} method when it
* discovers that escaping is required. It is protected to allow subclasses
* to override the fastpath escaping function to inline their escaping test.
* See {@link CharEscaperBuilder} for an example usage.
*
* <p>This method is not reentrant and may only be invoked by the top level
* {@link #escape(String)} method.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = DEST_TL.get();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, index, end);
if (cp < 0) {
throw new IllegalArgumentException(
"Trailing high surrogate at end of input");
}
char[] escaped = escape(cp);
if (escaped != null) {
int charsSkipped = index - unescapedChunkStart;
// This is the size needed to add the replacement, not the full
// size needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + escaped.length;
if (dest.length < sizeNeeded) {
int destLength = sizeNeeded + (end - index) + DEST_PAD;
dest = growBuffer(dest, destIndex, destLength);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(unescapedChunkStart, index, dest, destIndex);
destIndex += charsSkipped;
}
if (escaped.length > 0) {
System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
destIndex += escaped.length;
}
}
unescapedChunkStart
= index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
index = nextEscapeIndex(s, unescapedChunkStart, end);
}
// Process trailing unescaped characters - no need to account for escaped
// length or padding the allocation.
int charsSkipped = end - unescapedChunkStart;
if (charsSkipped > 0) {
int endIndex = destIndex + charsSkipped;
if (dest.length < endIndex) {
dest = growBuffer(dest, destIndex, endIndex);
}
s.getChars(unescapedChunkStart, end, dest, destIndex);
destIndex = endIndex;
}
return new String(dest, 0, destIndex);
}
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Unlike {@link #escape(String)} it is permitted to append arbitrarily
* split input to this Appendable, including input that is split over a
* surrogate pair. In this case the pending high surrogate character will not
* be processed until the corresponding low surrogate is appended. This means
* that a trailing high surrogate character at the end of the input cannot be
* detected and will be silently ignored. This is unavoidable since the
* Appendable interface has no {@code close()} method, and it is impossible to
* determine when the last characters have been appended.
*
* <p>The methods of the returned object will propagate any exceptions thrown
* by the underlying {@code Appendable}.
*
* <p>For well formed <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* the escaping behavior is identical to that of {@link #escape(String)} and
* the following code is equivalent to (but much slower than)
* {@code escaper.escape(string)}: <pre>{@code
*
* StringBuilder sb = new StringBuilder();
* escaper.escape(sb).append(string);
* return sb.toString();}</pre>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it
* @throws NullPointerException if {@code out} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*
*/
public Appendable escape(final Appendable out) {
checkNotNull(out);
return new Appendable() {
int pendingHighSurrogate = -1;
char[] decodedChars = new char[2];
public Appendable append(CharSequence csq) throws IOException {
return append(csq, 0, csq.length());
}
public Appendable append(CharSequence csq, int start, int end)
throws IOException {
int index = start;
if (index < end) {
// This is a little subtle: index must never reference the middle of a
// surrogate pair but unescapedChunkStart can. The first time we enter
// the loop below it is possible that index != unescapedChunkStart.
int unescapedChunkStart = index;
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
char c = csq.charAt(index++);
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got " + c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
// Emit the escaped character and adjust unescapedChunkStart to
// skip the low surrogate we have consumed.
outputChars(escaped, escaped.length);
unescapedChunkStart += 1;
} else {
// Emit pending high surrogate (unescaped) but do not modify
// unescapedChunkStart as we must still emit the low surrogate.
out.append((char) pendingHighSurrogate);
}
pendingHighSurrogate = -1;
}
while (true) {
// Find and append the next subsequence of unescaped characters.
index = nextEscapeIndex(csq, index, end);
if (index > unescapedChunkStart) {
out.append(csq, unescapedChunkStart, index);
}
if (index == end) {
break;
}
// If we are not finished, calculate the next code point.
int cp = codePointAt(csq, index, end);
if (cp < 0) {
// Our sequence ended half way through a surrogate pair so just
// record the state and exit.
pendingHighSurrogate = -cp;
break;
}
// Escape the code point and output the characters.
char[] escaped = escape(cp);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
// This shouldn't really happen if nextEscapeIndex is correct but
// we should cope with false positives.
int len = Character.toChars(cp, decodedChars, 0);
outputChars(decodedChars, len);
}
// Update our index past the escaped character and continue.
index += (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
unescapedChunkStart = index;
}
}
return this;
}
public Appendable append(char c) throws IOException {
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got '" + c +
"' with value " + (int) c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append((char) pendingHighSurrogate);
out.append(c);
}
pendingHighSurrogate = -1;
} else if (Character.isHighSurrogate(c)) {
// This is the start of a (split) surrogate pair.
pendingHighSurrogate = c;
} else {
if (Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c +
"' with value " + (int) c);
}
// This is a normal (non surrogate) char.
char[] escaped = escape(c);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append(c);
}
}
return this;
}
private void outputChars(char[] chars, int len) throws IOException {
for (int n = 0; n < len; n++) {
out.append(chars[n]);
}
}
};
}
/**
* Returns the Unicode code point of the character at the given index.
*
* <p>Unlike {@link Character#codePointAt(CharSequence, int)} or
* {@link String#codePointAt(int)} this method will never fail silently when
* encountering an invalid surrogate pair.
*
* <p>The behaviour of this method is as follows:
* <ol>
* <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
* <li><b>If the character at the specified index is not a surrogate, it is
* returned.</b>
* <li>If the first character was a high surrogate value, then an attempt is
* made to read the next character.
* <ol>
* <li><b>If the end of the sequence was reached, the negated value of
* the trailing high surrogate is returned.</b>
* <li><b>If the next character was a valid low surrogate, the code point
* value of the high/low surrogate pair is returned.</b>
* <li>If the next character was not a low surrogate value, then
* {@link IllegalArgumentException} is thrown.
* </ol>
* <li>If the first character was a low surrogate value,
* {@link IllegalArgumentException} is thrown.
* </ol>
*
* @param seq the sequence of characters from which to decode the code point
* @param index the index of the first character to decode
* @param end the index beyond the last valid character to decode
* @return the Unicode code point for the given index or the negated value of
* the trailing high surrogate character at the end of the sequence
*/
protected static final int codePointAt(CharSequence seq, int index, int end) {
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE ||
c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '" + c2 +
"' with value " + (int) c2 + " at index " + index);
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c1 +
"' with value " + (int) c1 + " at index " + (index - 1));
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
}
/**
* Helper method to grow the character buffer as needed, this only happens
* once in a while so it's ok if it's in a method call. If the index passed
* in is 0 then no copying will be done.
*/
private static final char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
/**
* A thread-local destination buffer to keep us from creating new buffers.
* The starting size is 1024 characters. If we grow past this we don't
* put it back in the threadlocal, we just keep going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
}
| Java |
/*
* Copyright (C) 2007 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.gdata.util.common.base;
import java.util.Collection;
import java.util.NoSuchElementException;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
*
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
*
* Note that the sense of the expression is inverted; with {@code Preconditions}
* you declare what you expect to be <i>true</i>, just as you do with an
* <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html">
* {@code assert}</a> or a JUnit {@code assertTrue()} call.
*
* <p>Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link
* UnsupportedOperationException} and others -- are used to signal that the
* <i>calling method</i> has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps <i>ever</i>. Postcondition or other invariant failures should not
* throw these types of exceptions.
*
* <p><b>Note:</b> The methods of the {@code Preconditions} class are highly
* unusual in one way: they are <i>supposed to</i> throw exceptions, and promise
* in their specifications to do so even when given perfectly valid input. That
* is, {@code null} is a valid parameter to the method {@link
* #checkNotNull(Object)} -- and technically this parameter could be even marked
* as {@link Nullable} -- yet the method will still throw an exception anyway,
* because that's what its contract says to do.
*
* <p>This class may be used with the Google Web Toolkit (GWT).
*
*
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException();
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(
T iterable, Object errorMessage) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable,
String errorMessageTemplate, Object... errorMessageArgs) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return iterable;
}
private static boolean containsOrIsNull(Iterable<?> iterable) {
if (iterable == null) {
return true;
}
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(null);
} catch (NullPointerException e) {
// A NPE implies that the collection doesn't contain null.
return false;
}
} else {
for (Object element : iterable) {
if (element == null) {
return true;
}
}
return false;
}
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size) {
checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(
format("%s (%s) must not be negative", desc, index));
}
if (index >= size) {
throw new IndexOutOfBoundsException(
format("%s (%s) must be less than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size) {
checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be negative", desc, index));
}
if (index > size) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be greater than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
* in an array, list or string of size {@code size}, and are in order. A
* position index may range from zero to {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an
* array, list or string
* @param end a user-supplied index identifying a ending position in an array,
* list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is
* greater than {@code size}, or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
checkPositionIndex(start, size, "start index");
checkPositionIndex(end, size, "end index");
if (end < start) {
throw new IndexOutOfBoundsException(format(
"end index (%s) must not be less than start index (%s)", end, start));
}
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
// VisibleForTesting
static String format(String template, Object... args) {
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
}
| Java |
/* Copyright (c) 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.gdata.util.common.base;
/**
* An object that converts literal text into a format safe for inclusion in a
* particular context (such as an XML document). Typically (but not always), the
* inverse process of "unescaping" the text is performed automatically by the
* relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p>An {@code Escaper} instance is required to be stateless, and safe when
* used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers, use {@link
* CharEscaperBuilder}, or extend {@link CharEscaper} or {@code UnicodeEscaper}.
*
*
*/
public interface Escaper {
/**
* Returns the escaped form of a given literal string.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed
* UTF-16 or cannot be escaped for any other reason
*/
public String escape(String string);
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it.
*/
public Appendable escape(Appendable out);
}
| Java |
/* Copyright (c) 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.gdata.util.common.base;
/**
* A {@code UnicodeEscaper} that escapes some set of Java characters using
* the URI percent encoding scheme. The set of safe characters (those which
* remain unescaped) can be specified on construction.
*
* <p>For details on escaping URIs for use in web pages, see section 2.4 of
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>In most cases this class should not need to be used directly. If you
* have no special requirements for escaping your URIs, you should use either
* {@link CharEscapers#uriEscaper()} or
* {@link CharEscapers#uriEscaper(boolean)}.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>Any additionally specified safe characters remain the same.
* <li>If {@code plusForSpace} was specified, the space character " " is
* converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal representation
* of the byte value.
* </ul>
*
* <p>RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!",
* "~", "*", "'", "(" and ")". It goes on to state:
*
* <p><i>Unreserved characters can be escaped without changing the semantics
* of the URI, but this should not be done unless the URI is being used
* in a context that does not allow the unescaped character to appear.</i>
*
* <p>For performance reasons the only currently supported character encoding of
* this class is UTF-8.
*
* <p><b>Note</b>: This escaper produces uppercase hexidecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
*
*/
public class PercentEscaper extends UnicodeEscaper {
/**
* A string of safe characters that mimics the behavior of
* {@link java.net.URLEncoder}.
*
*/
public static final String SAFECHARS_URLENCODER = "-_.*";
/**
* A string of characters that do not need to be encoded when used in URI
* path segments, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;=";
/**
* A string of characters that do not need to be encoded when used in URI
* query strings, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEQUERYSTRINGCHARS_URLENCODER
= "-_.!~*'()@:$,;/?:";
// In some uri escapers spaces are escaped to '+'
private static final char[] URI_ESCAPED_SPACE = { '+' };
private static final char[] UPPER_HEX_DIGITS =
"0123456789ABCDEF".toCharArray();
/**
* If true we should convert space to the {@code +} character.
*/
private final boolean plusForSpace;
/**
* An array of flags where for any {@code char c} if {@code safeOctets[c]} is
* true then {@code c} should remain unmodified in the output. If
* {@code c > safeOctets.length} then it should be escaped.
*/
private final boolean[] safeOctets;
/**
* Constructs a URI escaper with the specified safe characters and optional
* handling of the space character.
*
* @param safeChars a non null string specifying additional safe characters
* for this escaper (the ranges 0..9, a..z and A..Z are always safe and
* should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +}
* rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
*/
public PercentEscaper(String safeChars, boolean plusForSpace) {
// Avoid any misunderstandings about the behavior of this escaper
if (safeChars.matches(".*[0-9A-Za-z].*")) {
throw new IllegalArgumentException(
"Alphanumeric characters are always 'safe' and should not be " +
"explicitly specified");
}
// Avoid ambiguous parameters. Safe characters are never modified so if
// space is a safe character then setting plusForSpace is meaningless.
if (plusForSpace && safeChars.contains(" ")) {
throw new IllegalArgumentException(
"plusForSpace cannot be specified when space is a 'safe' character");
}
if (safeChars.contains("%")) {
throw new IllegalArgumentException(
"The '%' character cannot be specified as 'safe'");
}
this.plusForSpace = plusForSpace;
this.safeOctets = createSafeOctets(safeChars);
}
/**
* Creates a boolean[] with entries corresponding to the character values
* for 0-9, A-Z, a-z and those specified in safeChars set to true. The array
* is as small as is required to hold the given character information.
*/
private static boolean[] createSafeOctets(String safeChars) {
int maxChar = 'z';
char[] safeCharArray = safeChars.toCharArray();
for (char c : safeCharArray) {
maxChar = Math.max(c, maxChar);
}
boolean[] octets = new boolean[maxChar + 1];
for (int c = '0'; c <= '9'; c++) {
octets[c] = true;
}
for (int c = 'A'; c <= 'Z'; c++) {
octets[c] = true;
}
for (int c = 'a'; c <= 'z'; c++) {
octets[c] = true;
}
for (char c : safeCharArray) {
octets[c] = true;
}
return octets;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~760ns to ~400ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
protected int nextEscapeIndex(CharSequence csq, int index, int end) {
for (; index < end; index++) {
char c = csq.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
break;
}
}
return index;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~400ns to ~170ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
return escapeSlow(s, index);
}
}
return s;
}
/**
* Escapes the given Unicode code point in UTF-8.
*/
@Override
protected char[] escape(int cp) {
// We should never get negative values here but if we do it will throw an
// IndexOutOfBoundsException, so at least it will get spotted.
if (cp < safeOctets.length && safeOctets[cp]) {
return null;
} else if (cp == ' ' && plusForSpace) {
return URI_ESCAPED_SPACE;
} else if (cp <= 0x7F) {
// Single byte UTF-8 characters
// Start with "%--" and fill in the blanks
char[] dest = new char[3];
dest[0] = '%';
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
dest[1] = UPPER_HEX_DIGITS[cp >>> 4];
return dest;
} else if (cp <= 0x7ff) {
// Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff]
// Start with "%--%--" and fill in the blanks
char[] dest = new char[6];
dest[0] = '%';
dest[3] = '%';
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[1] = UPPER_HEX_DIGITS[0xC | cp];
return dest;
} else if (cp <= 0xffff) {
// Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff]
// Start with "%E-%--%--" and fill in the blanks
char[] dest = new char[9];
dest[0] = '%';
dest[1] = 'E';
dest[3] = '%';
dest[6] = '%';
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp];
return dest;
} else if (cp <= 0x10ffff) {
char[] dest = new char[12];
// Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff]
// Start with "%F-%--%--%--" and fill in the blanks
dest[0] = '%';
dest[1] = 'F';
dest[3] = '%';
dest[6] = '%';
dest[9] = '%';
dest[11] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0x7];
return dest;
} else {
// If this ever happens it is due to bug in UnicodeEscaper, not bad input.
throw new IllegalArgumentException(
"Invalid unicode character value " + cp);
}
}
}
| Java |
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oauth.signpost.http.HttpRequest;
public class HttpURLConnectionRequestAdapter implements HttpRequest {
protected HttpURLConnection connection;
public HttpURLConnectionRequestAdapter(HttpURLConnection connection) {
this.connection = connection;
}
public String getMethod() {
return connection.getRequestMethod();
}
public String getRequestUrl() {
return connection.getURL().toExternalForm();
}
public void setRequestUrl(String url) {
// can't do
}
public void setHeader(String name, String value) {
connection.setRequestProperty(name, value);
}
public String getHeader(String name) {
return connection.getRequestProperty(name);
}
public Map<String, String> getAllHeaders() {
Map<String, List<String>> origHeaders = connection.getRequestProperties();
Map<String, String> headers = new HashMap<String, String>(origHeaders.size());
for (String name : origHeaders.keySet()) {
List<String> values = origHeaders.get(name);
if (!values.isEmpty()) {
headers.put(name, values.get(0));
}
}
return headers;
}
public InputStream getMessagePayload() throws IOException {
return null;
}
public String getContentType() {
return connection.getRequestProperty("Content-Type");
}
public HttpURLConnection unwrap() {
return connection;
}
}
| Java |
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import oauth.signpost.http.HttpResponse;
public class HttpURLConnectionResponseAdapter implements HttpResponse {
private HttpURLConnection connection;
public HttpURLConnectionResponseAdapter(HttpURLConnection connection) {
this.connection = connection;
}
public InputStream getContent() throws IOException {
return connection.getInputStream();
}
public int getStatusCode() throws IOException {
return connection.getResponseCode();
}
public String getReasonPhrase() throws Exception {
return connection.getResponseMessage();
}
public Object unwrap() {
return connection;
}
}
| Java |
/*
* Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost.basic;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import oauth.signpost.AbstractOAuthProvider;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* This default implementation uses {@link java.net.HttpURLConnection} type GET
* requests to receive tokens from a service provider.
*
* @author Matthias Kaeppler
*/
public class DefaultOAuthProvider extends AbstractOAuthProvider {
private static final long serialVersionUID = 1L;
public DefaultOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
}
protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException,
IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection();
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Length", "0");
return new HttpURLConnectionRequestAdapter(connection);
}
protected HttpResponse sendRequest(HttpRequest request) throws IOException {
HttpURLConnection connection = (HttpURLConnection) request.unwrap();
connection.connect();
return new HttpURLConnectionResponseAdapter(connection);
}
@Override
protected void closeConnection(HttpRequest request, HttpResponse response) {
HttpURLConnection connection = (HttpURLConnection) request.unwrap();
if (connection != null) {
connection.disconnect();
}
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.basic;
import java.net.HttpURLConnection;
import oauth.signpost.AbstractOAuthConsumer;
import oauth.signpost.http.HttpRequest;
/**
* The default implementation for an OAuth consumer. Only supports signing
* {@link java.net.HttpURLConnection} type requests.
*
* @author Matthias Kaeppler
*/
public class DefaultOAuthConsumer extends AbstractOAuthConsumer {
private static final long serialVersionUID = 1L;
public DefaultOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
@Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof HttpURLConnection)) {
throw new IllegalArgumentException(
"The default consumer expects requests of type java.net.HttpURLConnection");
}
return new HttpURLConnectionRequestAdapter((HttpURLConnection) request);
}
}
| Java |
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import oauth.signpost.http.HttpRequest;
public class UrlStringRequestAdapter implements HttpRequest {
private String url;
public UrlStringRequestAdapter(String url) {
this.url = url;
}
public String getMethod() {
return "GET";
}
public String getRequestUrl() {
return url;
}
public void setRequestUrl(String url) {
this.url = url;
}
public void setHeader(String name, String value) {
}
public String getHeader(String name) {
return null;
}
public Map<String, String> getAllHeaders() {
return Collections.emptyMap();
}
public InputStream getMessagePayload() throws IOException {
return null;
}
public String getContentType() {
return null;
}
public Object unwrap() {
return url;
}
}
| Java |
package oauth.signpost.exception;
@SuppressWarnings("serial")
public abstract class OAuthException extends Exception {
public OAuthException(String message) {
super(message);
}
public OAuthException(Throwable cause) {
super(cause);
}
public OAuthException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthMessageSignerException extends OAuthException {
public OAuthMessageSignerException(String message) {
super(message);
}
public OAuthMessageSignerException(Exception cause) {
super(cause);
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthNotAuthorizedException extends OAuthException {
private static final String ERROR = "Authorization failed (server replied with a 401). "
+ "This can happen if the consumer key was not correct or "
+ "the signatures did not match.";
private String responseBody;
public OAuthNotAuthorizedException() {
super(ERROR);
}
public OAuthNotAuthorizedException(String responseBody) {
super(ERROR);
this.responseBody = responseBody;
}
public String getResponseBody() {
return responseBody;
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthExpectationFailedException extends OAuthException {
public OAuthExpectationFailedException(String message) {
super(message);
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthCommunicationException extends OAuthException {
private String responseBody;
public OAuthCommunicationException(Exception cause) {
super("Communication with the service provider failed: "
+ cause.getLocalizedMessage(), cause);
}
public OAuthCommunicationException(String message, String responseBody) {
super(message);
this.responseBody = responseBody;
}
public String getResponseBody() {
return responseBody;
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import oauth.signpost.basic.UrlStringRequestAdapter;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
import oauth.signpost.signature.HmacSha1MessageSigner;
import oauth.signpost.signature.OAuthMessageSigner;
import oauth.signpost.signature.QueryStringSigningStrategy;
import oauth.signpost.signature.SigningStrategy;
/**
* ABC for consumer implementations. If you're developing a custom consumer you
* will probably inherit from this class to save you a lot of work.
*
* @author Matthias Kaeppler
*/
public abstract class AbstractOAuthConsumer implements OAuthConsumer {
private static final long serialVersionUID = 1L;
private String consumerKey, consumerSecret;
private String token;
private OAuthMessageSigner messageSigner;
private SigningStrategy signingStrategy;
// these are params that may be passed to the consumer directly (i.e.
// without going through the request object)
private HttpParameters additionalParameters;
// these are the params which will be passed to the message signer
private HttpParameters requestParameters;
private boolean sendEmptyTokens;
public AbstractOAuthConsumer(String consumerKey, String consumerSecret) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
setMessageSigner(new HmacSha1MessageSigner());
setSigningStrategy(new AuthorizationHeaderSigningStrategy());
}
public void setMessageSigner(OAuthMessageSigner messageSigner) {
this.messageSigner = messageSigner;
messageSigner.setConsumerSecret(consumerSecret);
}
public void setSigningStrategy(SigningStrategy signingStrategy) {
this.signingStrategy = signingStrategy;
}
public void setAdditionalParameters(HttpParameters additionalParameters) {
this.additionalParameters = additionalParameters;
}
public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
if (consumerKey == null) {
throw new OAuthExpectationFailedException("consumer key not set");
}
if (consumerSecret == null) {
throw new OAuthExpectationFailedException("consumer secret not set");
}
requestParameters = new HttpParameters();
try {
if (additionalParameters != null) {
requestParameters.putAll(additionalParameters, false);
}
collectHeaderParameters(request, requestParameters);
collectQueryParameters(request, requestParameters);
collectBodyParameters(request, requestParameters);
// add any OAuth params that haven't already been set
completeOAuthParameters(requestParameters);
requestParameters.remove(OAuth.OAUTH_SIGNATURE);
} catch (IOException e) {
throw new OAuthCommunicationException(e);
}
String signature = messageSigner.sign(request, requestParameters);
OAuth.debugOut("signature", signature);
signingStrategy.writeSignature(signature, request, requestParameters);
OAuth.debugOut("Auth header", request.getHeader("Authorization"));
OAuth.debugOut("Request URL", request.getRequestUrl());
return request;
}
public HttpRequest sign(Object request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
return sign(wrap(request));
}
public String sign(String url) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
HttpRequest request = new UrlStringRequestAdapter(url);
// switch to URL signing
SigningStrategy oldStrategy = this.signingStrategy;
this.signingStrategy = new QueryStringSigningStrategy();
sign(request);
// revert to old strategy
this.signingStrategy = oldStrategy;
return request.getRequestUrl();
}
/**
* Adapts the given request object to a Signpost {@link HttpRequest}. How
* this is done depends on the consumer implementation.
*
* @param request
* the native HTTP request instance
* @return the adapted request
*/
protected abstract HttpRequest wrap(Object request);
public void setTokenWithSecret(String token, String tokenSecret) {
this.token = token;
messageSigner.setTokenSecret(tokenSecret);
}
public String getToken() {
return token;
}
public String getTokenSecret() {
return messageSigner.getTokenSecret();
}
public String getConsumerKey() {
return this.consumerKey;
}
public String getConsumerSecret() {
return this.consumerSecret;
}
/**
* <p>
* Helper method that adds any OAuth parameters to the given request
* parameters which are missing from the current request but required for
* signing. A good example is the oauth_nonce parameter, which is typically
* not provided by the client in advance.
* </p>
* <p>
* It's probably not a very good idea to override this method. If you want
* to generate different nonces or timestamps, override
* {@link #generateNonce()} or {@link #generateTimestamp()} instead.
* </p>
*
* @param out
* the request parameter which should be completed
*/
protected void completeOAuthParameters(HttpParameters out) {
if (!out.containsKey(OAuth.OAUTH_CONSUMER_KEY)) {
out.put(OAuth.OAUTH_CONSUMER_KEY, consumerKey, true);
}
if (!out.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
out.put(OAuth.OAUTH_SIGNATURE_METHOD, messageSigner.getSignatureMethod(), true);
}
if (!out.containsKey(OAuth.OAUTH_TIMESTAMP)) {
out.put(OAuth.OAUTH_TIMESTAMP, generateTimestamp(), true);
}
if (!out.containsKey(OAuth.OAUTH_NONCE)) {
out.put(OAuth.OAUTH_NONCE, generateNonce(), true);
}
if (!out.containsKey(OAuth.OAUTH_VERSION)) {
out.put(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0, true);
}
if (!out.containsKey(OAuth.OAUTH_TOKEN)) {
if (token != null && !token.equals("") || sendEmptyTokens) {
out.put(OAuth.OAUTH_TOKEN, token, true);
}
}
}
public HttpParameters getRequestParameters() {
return requestParameters;
}
public void setSendEmptyTokens(boolean enable) {
this.sendEmptyTokens = enable;
}
/**
* Collects OAuth Authorization header parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectHeaderParameters(HttpRequest request, HttpParameters out) {
HttpParameters headerParams = OAuth.oauthHeaderToParamsMap(request.getHeader(OAuth.HTTP_AUTHORIZATION_HEADER));
out.putAll(headerParams, false);
}
/**
* Collects x-www-form-urlencoded body parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectBodyParameters(HttpRequest request, HttpParameters out)
throws IOException {
// collect x-www-form-urlencoded body params
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith(OAuth.FORM_ENCODED)) {
InputStream payload = request.getMessagePayload();
out.putAll(OAuth.decodeForm(payload), true);
}
}
/**
* Collects HTTP GET query string parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectQueryParameters(HttpRequest request, HttpParameters out) {
String url = request.getRequestUrl();
int q = url.indexOf('?');
if (q >= 0) {
// Combine the URL query string with the other parameters:
out.putAll(OAuth.decodeForm(url.substring(q + 1)), true);
}
}
protected String generateTimestamp() {
return Long.toString(System.currentTimeMillis() / 1000L);
}
protected String generateNonce() {
return Long.toString(new Random().nextLong());
}
}
| Java |
package oauth.signpost;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* Provides hooks into the token request handling procedure executed by
* {@link OAuthProvider}.
*
* @author Matthias Kaeppler
*/
public interface OAuthProviderListener {
/**
* Called after the request has been created and default headers added, but
* before the request has been signed.
*
* @param request
* the request to be sent
* @throws Exception
*/
void prepareRequest(HttpRequest request) throws Exception;
/**
* Called after the request has been signed, but before it's being sent.
*
* @param request
* the request to be sent
* @throws Exception
*/
void prepareSubmission(HttpRequest request) throws Exception;
/**
* Called when the server response has been received. You can implement this
* to manually handle the response data.
*
* @param request
* the request that was sent
* @param response
* the response that was received
* @return returning true means you have handled the response, and the
* provider will return immediately. Return false to let the event
* propagate and let the provider execute its default response
* handling.
* @throws Exception
*/
boolean onResponseReceived(HttpRequest request, HttpResponse response) throws Exception;
}
| Java |
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler
*
* 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 oauth.signpost;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import oauth.signpost.http.HttpParameters;
import com.google.gdata.util.common.base.PercentEscaper;
public class OAuth {
public static final String VERSION_1_0 = "1.0";
public static final String ENCODING = "UTF-8";
public static final String FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String HTTP_AUTHORIZATION_HEADER = "Authorization";
public static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
public static final String OAUTH_TOKEN = "oauth_token";
public static final String OAUTH_TOKEN_SECRET = "oauth_token_secret";
public static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
public static final String OAUTH_SIGNATURE = "oauth_signature";
public static final String OAUTH_TIMESTAMP = "oauth_timestamp";
public static final String OAUTH_NONCE = "oauth_nonce";
public static final String OAUTH_VERSION = "oauth_version";
public static final String OAUTH_CALLBACK = "oauth_callback";
public static final String OAUTH_CALLBACK_CONFIRMED = "oauth_callback_confirmed";
public static final String OAUTH_VERIFIER = "oauth_verifier";
/**
* Pass this value as the callback "url" upon retrieving a request token if
* your application cannot receive callbacks (e.g. because it's a desktop
* app). This will tell the service provider that verification happens
* out-of-band, which basically means that it will generate a PIN code (the
* OAuth verifier) and display that to your user. You must obtain this code
* from your user and pass it to
* {@link OAuthProvider#retrieveAccessToken(OAuthConsumer, String)} in order
* to complete the token handshake.
*/
public static final String OUT_OF_BAND = "oob";
private static final PercentEscaper percentEncoder = new PercentEscaper(
"-._~", false);
public static String percentEncode(String s) {
if (s == null) {
return "";
}
return percentEncoder.escape(s);
}
public static String percentDecode(String s) {
try {
if (s == null) {
return "";
}
return URLDecoder.decode(s, ENCODING);
// This implements http://oauth.pbwiki.com/FlexibleDecoding
} catch (java.io.UnsupportedEncodingException wow) {
throw new RuntimeException(wow.getMessage(), wow);
}
}
/**
* Construct a x-www-form-urlencoded document containing the given sequence
* of name/value pairs. Use OAuth percent encoding (not exactly the encoding
* mandated by x-www-form-urlencoded).
*/
public static <T extends Map.Entry<String, String>> void formEncode(Collection<T> parameters,
OutputStream into) throws IOException {
if (parameters != null) {
boolean first = true;
for (Map.Entry<String, String> entry : parameters) {
if (first) {
first = false;
} else {
into.write('&');
}
into.write(percentEncode(safeToString(entry.getKey())).getBytes());
into.write('=');
into.write(percentEncode(safeToString(entry.getValue())).getBytes());
}
}
}
/**
* Construct a x-www-form-urlencoded document containing the given sequence
* of name/value pairs. Use OAuth percent encoding (not exactly the encoding
* mandated by x-www-form-urlencoded).
*/
public static <T extends Map.Entry<String, String>> String formEncode(Collection<T> parameters)
throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
formEncode(parameters, b);
return new String(b.toByteArray());
}
/** Parse a form-urlencoded document. */
public static HttpParameters decodeForm(String form) {
HttpParameters params = new HttpParameters();
if (isEmpty(form)) {
return params;
}
for (String nvp : form.split("\\&")) {
int equals = nvp.indexOf('=');
String name;
String value;
if (equals < 0) {
name = percentDecode(nvp);
value = null;
} else {
name = percentDecode(nvp.substring(0, equals));
value = percentDecode(nvp.substring(equals + 1));
}
params.put(name, value);
}
return params;
}
public static HttpParameters decodeForm(InputStream content)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
return decodeForm(sb.toString());
}
/**
* Construct a Map containing a copy of the given parameters. If several
* parameters have the same name, the Map will contain the first value,
* only.
*/
public static <T extends Map.Entry<String, String>> Map<String, String> toMap(Collection<T> from) {
HashMap<String, String> map = new HashMap<String, String>();
if (from != null) {
for (Map.Entry<String, String> entry : from) {
String key = entry.getKey();
if (!map.containsKey(key)) {
map.put(key, entry.getValue());
}
}
}
return map;
}
public static final String safeToString(Object from) {
return (from == null) ? null : from.toString();
}
public static boolean isEmpty(String str) {
return (str == null) || (str.length() == 0);
}
/**
* Appends a list of key/value pairs to the given URL, e.g.:
*
* <pre>
* String url = OAuth.addQueryParameters("http://example.com?a=1", b, 2, c, 3);
* </pre>
*
* which yields:
*
* <pre>
* http://example.com?a=1&b=2&c=3
* </pre>
*
* All parameters will be encoded according to OAuth's percent encoding
* rules.
*
* @param url
* the URL
* @param kvPairs
* the list of key/value pairs
* @return
*/
public static String addQueryParameters(String url, String... kvPairs) {
String queryDelim = url.contains("?") ? "&" : "?";
StringBuilder sb = new StringBuilder(url + queryDelim);
for (int i = 0; i < kvPairs.length; i += 2) {
if (i > 0) {
sb.append("&");
}
sb.append(OAuth.percentEncode(kvPairs[i]) + "="
+ OAuth.percentEncode(kvPairs[i + 1]));
}
return sb.toString();
}
public static String addQueryParameters(String url, Map<String, String> params) {
String[] kvPairs = new String[params.size() * 2];
int idx = 0;
for (String key : params.keySet()) {
kvPairs[idx] = key;
kvPairs[idx + 1] = params.get(key);
idx += 2;
}
return addQueryParameters(url, kvPairs);
}
/**
* Builds an OAuth header from the given list of header fields. All
* parameters starting in 'oauth_*' will be percent encoded.
*
* <pre>
* String authHeader = OAuth.prepareOAuthHeader("realm", "http://example.com", "oauth_token", "x%y");
* </pre>
*
* which yields:
*
* <pre>
* OAuth realm="http://example.com", oauth_token="x%25y"
* </pre>
*
* @param kvPairs
* the list of key/value pairs
* @return a string eligible to be used as an OAuth HTTP Authorization
* header.
*/
public static String prepareOAuthHeader(String... kvPairs) {
StringBuilder sb = new StringBuilder("OAuth ");
for (int i = 0; i < kvPairs.length; i += 2) {
if (i > 0) {
sb.append(", ");
}
String value = kvPairs[i].startsWith("oauth_") ? OAuth
.percentEncode(kvPairs[i + 1]) : kvPairs[i + 1];
sb.append(OAuth.percentEncode(kvPairs[i]) + "=\"" + value + "\"");
}
return sb.toString();
}
public static HttpParameters oauthHeaderToParamsMap(String oauthHeader) {
HttpParameters params = new HttpParameters();
if (oauthHeader == null || !oauthHeader.startsWith("OAuth ")) {
return params;
}
oauthHeader = oauthHeader.substring("OAuth ".length());
String[] elements = oauthHeader.split(",");
for (String keyValuePair : elements) {
String[] keyValue = keyValuePair.split("=");
params.put(keyValue[0].trim(), keyValue[1].replace("\"", "").trim());
}
return params;
}
/**
* Helper method to concatenate a parameter and its value to a pair that can
* be used in an HTTP header. This method percent encodes both parts before
* joining them.
*
* @param name
* the OAuth parameter name, e.g. oauth_token
* @param value
* the OAuth parameter value, e.g. 'hello oauth'
* @return a name/value pair, e.g. oauth_token="hello%20oauth"
*/
public static String toHeaderElement(String name, String value) {
return OAuth.percentEncode(name) + "=\"" + OAuth.percentEncode(value) + "\"";
}
public static void debugOut(String key, String value) {
if (System.getProperty("debug") != null) {
System.out.println("[SIGNPOST] " + key + ": " + value);
}
}
}
| Java |
/*
* Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* ABC for all provider implementations. If you're writing a custom provider,
* you will probably inherit from this class, since it takes a lot of work from
* you.
*
* @author Matthias Kaeppler
*/
public abstract class AbstractOAuthProvider implements OAuthProvider {
private static final long serialVersionUID = 1L;
private String requestTokenEndpointUrl;
private String accessTokenEndpointUrl;
private String authorizationWebsiteUrl;
private HttpParameters responseParameters;
private Map<String, String> defaultHeaders;
private boolean isOAuth10a;
private transient OAuthProviderListener listener;
public AbstractOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
this.requestTokenEndpointUrl = requestTokenEndpointUrl;
this.accessTokenEndpointUrl = accessTokenEndpointUrl;
this.authorizationWebsiteUrl = authorizationWebsiteUrl;
this.responseParameters = new HttpParameters();
this.defaultHeaders = new HashMap<String, String>();
}
public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException {
// invalidate current credentials, if any
consumer.setTokenWithSecret(null, null);
// 1.0a expects the callback to be sent while getting the request token.
// 1.0 service providers would simply ignore this parameter.
retrieveToken(consumer, requestTokenEndpointUrl, OAuth.OAUTH_CALLBACK, callbackUrl);
String callbackConfirmed = responseParameters.getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED);
responseParameters.remove(OAuth.OAUTH_CALLBACK_CONFIRMED);
isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed);
// 1.0 service providers expect the callback as part of the auth URL,
// Do not send when 1.0a.
if (isOAuth10a) {
return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN,
consumer.getToken());
} else {
return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN,
consumer.getToken(), OAuth.OAUTH_CALLBACK, callbackUrl);
}
}
public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException {
if (consumer.getToken() == null || consumer.getTokenSecret() == null) {
throw new OAuthExpectationFailedException(
"Authorized request token or token secret not set. "
+ "Did you retrieve an authorized request token before?");
}
if (isOAuth10a && oauthVerifier != null) {
retrieveToken(consumer, accessTokenEndpointUrl, OAuth.OAUTH_VERIFIER, oauthVerifier);
} else {
retrieveToken(consumer, accessTokenEndpointUrl);
}
}
/**
* <p>
* Implemented by subclasses. The responsibility of this method is to
* contact the service provider at the given endpoint URL and fetch a
* request or access token. What kind of token is retrieved solely depends
* on the URL being used.
* </p>
* <p>
* Correct implementations of this method must guarantee the following
* post-conditions:
* <ul>
* <li>the {@link OAuthConsumer} passed to this method must have a valid
* {@link OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by
* calling {@link OAuthConsumer#setTokenWithSecret(String, String)}</li>
* <li>{@link #getResponseParameters()} must return the set of query
* parameters served by the service provider in the token response, with all
* OAuth specific parameters being removed</li>
* </ul>
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param endpointUrl
* the URL at which the service provider serves the OAuth token that
* is to be fetched
* @param additionalParameters
* you can pass parameters here (typically OAuth parameters such as
* oauth_callback or oauth_verifier) which will go directly into the
* signer, i.e. you don't have to put them into the request first,
* just so the consumer pull them out again. Pass them sequentially
* in key/value order.
* @throws OAuthMessageSignerException
* if signing the token request fails
* @throws OAuthCommunicationException
* if a network communication error occurs
* @throws OAuthNotAuthorizedException
* if the server replies 401 - Unauthorized
* @throws OAuthExpectationFailedException
* if an expectation has failed, e.g. because the server didn't
* reply in the expected format
*/
protected void retrieveToken(OAuthConsumer consumer, String endpointUrl,
String... additionalParameters) throws OAuthMessageSignerException,
OAuthCommunicationException, OAuthNotAuthorizedException,
OAuthExpectationFailedException {
Map<String, String> defaultHeaders = getRequestHeaders();
if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) {
throw new OAuthExpectationFailedException("Consumer key or secret not set");
}
HttpRequest request = null;
HttpResponse response = null;
try {
request = createRequest(endpointUrl);
for (String header : defaultHeaders.keySet()) {
request.setHeader(header, defaultHeaders.get(header));
}
if (additionalParameters != null) {
HttpParameters httpParams = new HttpParameters();
httpParams.putAll(additionalParameters, true);
consumer.setAdditionalParameters(httpParams);
}
if (this.listener != null) {
this.listener.prepareRequest(request);
}
consumer.sign(request);
if (this.listener != null) {
this.listener.prepareSubmission(request);
}
response = sendRequest(request);
int statusCode = response.getStatusCode();
boolean requestHandled = false;
if (this.listener != null) {
requestHandled = this.listener.onResponseReceived(request, response);
}
if (requestHandled) {
return;
}
if (statusCode >= 300) {
handleUnexpectedResponse(statusCode, response);
}
HttpParameters responseParams = OAuth.decodeForm(response.getContent());
String token = responseParams.getFirst(OAuth.OAUTH_TOKEN);
String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
responseParams.remove(OAuth.OAUTH_TOKEN);
responseParams.remove(OAuth.OAUTH_TOKEN_SECRET);
setResponseParameters(responseParams);
if (token == null || secret == null) {
throw new OAuthExpectationFailedException(
"Request token or token secret not set in server reply. "
+ "The service provider you use is probably buggy.");
}
consumer.setTokenWithSecret(token, secret);
} catch (OAuthNotAuthorizedException e) {
throw e;
} catch (OAuthExpectationFailedException e) {
throw e;
} catch (Exception e) {
throw new OAuthCommunicationException(e);
} finally {
try {
closeConnection(request, response);
} catch (Exception e) {
throw new OAuthCommunicationException(e);
}
}
}
protected void handleUnexpectedResponse(int statusCode, HttpResponse response) throws Exception {
if (response == null) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent()));
StringBuilder responseBody = new StringBuilder();
String line = reader.readLine();
while (line != null) {
responseBody.append(line);
line = reader.readLine();
}
switch (statusCode) {
case 401:
throw new OAuthNotAuthorizedException(responseBody.toString());
default:
throw new OAuthCommunicationException("Service provider responded in error: "
+ statusCode + " (" + response.getReasonPhrase() + ")", responseBody.toString());
}
}
/**
* Overrride this method if you want to customize the logic for building a
* request object for the given endpoint URL.
*
* @param endpointUrl
* the URL to which the request will go
* @return the request object
* @throws Exception
* if something breaks
*/
protected abstract HttpRequest createRequest(String endpointUrl) throws Exception;
/**
* Override this method if you want to customize the logic for how the given
* request is sent to the server.
*
* @param request
* the request to send
* @return the response to the request
* @throws Exception
* if something breaks
*/
protected abstract HttpResponse sendRequest(HttpRequest request) throws Exception;
/**
* Called when the connection is being finalized after receiving the
* response. Use this to do any cleanup / resource freeing.
*
* @param request
* the request that has been sent
* @param response
* the response that has been received
* @throws Exception
* if something breaks
*/
protected void closeConnection(HttpRequest request, HttpResponse response) throws Exception {
// NOP
}
public HttpParameters getResponseParameters() {
return responseParameters;
}
/**
* Returns a single query parameter as served by the service provider in a
* token reply. You must call {@link #setResponseParameters} with the set of
* parameters before using this method.
*
* @param key
* the parameter name
* @return the parameter value
*/
protected String getResponseParameter(String key) {
return responseParameters.getFirst(key);
}
public void setResponseParameters(HttpParameters parameters) {
this.responseParameters = parameters;
}
public void setOAuth10a(boolean isOAuth10aProvider) {
this.isOAuth10a = isOAuth10aProvider;
}
public boolean isOAuth10a() {
return isOAuth10a;
}
public String getRequestTokenEndpointUrl() {
return this.requestTokenEndpointUrl;
}
public String getAccessTokenEndpointUrl() {
return this.accessTokenEndpointUrl;
}
public String getAuthorizationWebsiteUrl() {
return this.authorizationWebsiteUrl;
}
public void setRequestHeader(String header, String value) {
defaultHeaders.put(header, value);
}
public Map<String, String> getRequestHeaders() {
return defaultHeaders;
}
public void setListener(OAuthProviderListener listener) {
this.listener = listener;
}
public void removeListener(OAuthProviderListener listener) {
this.listener = null;
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost;
import java.io.Serializable;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
import oauth.signpost.signature.HmacSha1MessageSigner;
import oauth.signpost.signature.OAuthMessageSigner;
import oauth.signpost.signature.PlainTextMessageSigner;
import oauth.signpost.signature.QueryStringSigningStrategy;
import oauth.signpost.signature.SigningStrategy;
/**
* <p>
* Exposes a simple interface to sign HTTP requests using a given OAuth token
* and secret. Refer to {@link OAuthProvider} how to retrieve a valid token and
* token secret.
* </p>
* <p>
* HTTP messages are signed as follows:
* <p>
*
* <pre>
* // exchange the arguments with the actual token/secret pair
* OAuthConsumer consumer = new DefaultOAuthConsumer("1234", "5678");
*
* URL url = new URL("http://example.com/protected.xml");
* HttpURLConnection request = (HttpURLConnection) url.openConnection();
*
* consumer.sign(request);
*
* request.connect();
* </pre>
*
* </p>
* </p>
*
* @author Matthias Kaeppler
*/
public interface OAuthConsumer extends Serializable {
/**
* Sets the message signer that should be used to generate the OAuth
* signature.
*
* @param messageSigner
* the signer
* @see HmacSha1MessageSigner
* @see PlainTextMessageSigner
*/
public void setMessageSigner(OAuthMessageSigner messageSigner);
/**
* Allows you to add parameters (typically OAuth parameters such as
* oauth_callback or oauth_verifier) which will go directly into the signer,
* i.e. you don't have to put them into the request first. The consumer's
* {@link SigningStrategy} will then take care of writing them to the
* correct part of the request before it is sent. Note that these parameters
* are expected to already be percent encoded -- they will be simply merged
* as-is.
*
* @param additionalParameters
* the parameters
*/
public void setAdditionalParameters(HttpParameters additionalParameters);
/**
* Defines which strategy should be used to write a signature to an HTTP
* request.
*
* @param signingStrategy
* the strategy
* @see AuthorizationHeaderSigningStrategy
* @see QueryStringSigningStrategy
*/
public void setSigningStrategy(SigningStrategy signingStrategy);
/**
* <p>
* Causes the consumer to always include the oauth_token parameter to be
* sent, even if blank. If you're seeing 401s during calls to
* {@link OAuthProvider#retrieveRequestToken}, try setting this to true.
* </p>
*
* @param enable
* true or false
*/
public void setSendEmptyTokens(boolean enable);
/**
* Signs the given HTTP request by writing an OAuth signature (and other
* required OAuth parameters) to it. Where these parameters are written
* depends on the current {@link SigningStrategy}.
*
* @param request
* the request to sign
* @return the request object passed as an argument
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* <p>
* Signs the given HTTP request by writing an OAuth signature (and other
* required OAuth parameters) to it. Where these parameters are written
* depends on the current {@link SigningStrategy}.
* </p>
* This method accepts HTTP library specific request objects; the consumer
* implementation must ensure that only those request types are passed which
* it supports.
*
* @param request
* the request to sign
* @return the request object passed as an argument
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public HttpRequest sign(Object request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* <p>
* "Signs" the given URL by appending all OAuth parameters to it which are
* required for message signing. The assumed HTTP method is GET.
* Essentially, this is equivalent to signing an HTTP GET request, but it
* can be useful if your application requires clickable links to protected
* resources, i.e. when your application does not have access to the actual
* request that is being sent.
* </p>
*
* @param url
* the input URL. May have query parameters.
* @return the input URL, with all necessary OAuth parameters attached as a
* query string. Existing query parameters are preserved.
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public String sign(String url) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Sets the OAuth token and token secret used for message signing.
*
* @param token
* the token
* @param tokenSecret
* the token secret
*/
public void setTokenWithSecret(String token, String tokenSecret);
public String getToken();
public String getTokenSecret();
public String getConsumerKey();
public String getConsumerSecret();
/**
* Returns all parameters collected from the HTTP request during message
* signing (this means the return value may be NULL before a call to
* {@link #sign}), plus all required OAuth parameters that were added
* because the request didn't contain them beforehand. In other words, this
* is the exact set of parameters that were used for creating the message
* signature.
*
* @return the request parameters used for message signing
*/
public HttpParameters getRequestParameters();
}
| Java |
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler
*
* 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 oauth.signpost.http;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import oauth.signpost.OAuth;
/**
* A multi-map of HTTP request parameters. Each key references a
* {@link SortedSet} of parameters collected from the request during message
* signing. Parameter values are sorted as per {@linkplain http
* ://oauth.net/core/1.0a/#anchor13}. Every key/value pair will be
* percent-encoded upon insertion. This class has special semantics tailored to
* being useful for message signing; it's not a general purpose collection class
* to handle request parameters.
*
* @author Matthias Kaeppler
*/
@SuppressWarnings("serial")
public class HttpParameters implements Map<String, SortedSet<String>>, Serializable {
private TreeMap<String, SortedSet<String>> wrappedMap = new TreeMap<String, SortedSet<String>>();
public SortedSet<String> put(String key, SortedSet<String> value) {
return wrappedMap.put(key, value);
}
public SortedSet<String> put(String key, SortedSet<String> values, boolean percentEncode) {
if (percentEncode) {
remove(key);
for (String v : values) {
put(key, v, true);
}
return get(key);
} else {
return wrappedMap.put(key, values);
}
}
/**
* Convenience method to add a single value for the parameter specified by
* 'key'.
*
* @param key
* the parameter name
* @param value
* the parameter value
* @return the value
*/
public String put(String key, String value) {
return put(key, value, false);
}
/**
* Convenience method to add a single value for the parameter specified by
* 'key'.
*
* @param key
* the parameter name
* @param value
* the parameter value
* @param percentEncode
* whether key and value should be percent encoded before being
* inserted into the map
* @return the value
*/
public String put(String key, String value, boolean percentEncode) {
SortedSet<String> values = wrappedMap.get(key);
if (values == null) {
values = new TreeSet<String>();
wrappedMap.put(percentEncode ? OAuth.percentEncode(key) : key, values);
}
if (value != null) {
value = percentEncode ? OAuth.percentEncode(value) : value;
values.add(value);
}
return value;
}
/**
* Convenience method to allow for storing null values. {@link #put} doesn't
* allow null values, because that would be ambiguous.
*
* @param key
* the parameter name
* @param nullString
* can be anything, but probably... null?
* @return null
*/
public String putNull(String key, String nullString) {
return put(key, nullString);
}
public void putAll(Map<? extends String, ? extends SortedSet<String>> m) {
wrappedMap.putAll(m);
}
public void putAll(Map<? extends String, ? extends SortedSet<String>> m, boolean percentEncode) {
if (percentEncode) {
for (String key : m.keySet()) {
put(key, m.get(key), true);
}
} else {
wrappedMap.putAll(m);
}
}
public void putAll(String[] keyValuePairs, boolean percentEncode) {
for (int i = 0; i < keyValuePairs.length - 1; i += 2) {
this.put(keyValuePairs[i], keyValuePairs[i + 1], percentEncode);
}
}
/**
* Convenience method to merge a Map<String, List<String>>.
*
* @param m
* the map
*/
public void putMap(Map<String, List<String>> m) {
for (String key : m.keySet()) {
SortedSet<String> vals = get(key);
if (vals == null) {
vals = new TreeSet<String>();
put(key, vals);
}
vals.addAll(m.get(key));
}
}
public SortedSet<String> get(Object key) {
return wrappedMap.get(key);
}
/**
* Convenience method for {@link #getFirst(key, false)}.
*
* @param key
* the parameter name (must be percent encoded if it contains unsafe
* characters!)
* @return the first value found for this parameter
*/
public String getFirst(Object key) {
return getFirst(key, false);
}
/**
* Returns the first value from the set of all values for the given
* parameter name. If the key passed to this method contains special
* characters, you MUST first percent encode it using
* {@link OAuth#percentEncode(String)}, otherwise the lookup will fail
* (that's because upon storing values in this map, keys get
* percent-encoded).
*
* @param key
* the parameter name (must be percent encoded if it contains unsafe
* characters!)
* @param percentDecode
* whether the value being retrieved should be percent decoded
* @return the first value found for this parameter
*/
public String getFirst(Object key, boolean percentDecode) {
SortedSet<String> values = wrappedMap.get(key);
if (values == null || values.isEmpty()) {
return null;
}
String value = values.first();
return percentDecode ? OAuth.percentDecode(value) : value;
}
/**
* Concatenates all values for the given key to a list of key/value pairs
* suitable for use in a URL query string.
*
* @param key
* the parameter name
* @return the query string
*/
public String getAsQueryString(Object key) {
StringBuilder sb = new StringBuilder();
key = OAuth.percentEncode((String) key);
Set<String> values = wrappedMap.get(key);
if (values == null) {
return key + "=";
}
Iterator<String> iter = values.iterator();
while (iter.hasNext()) {
sb.append(key + "=" + iter.next());
if (iter.hasNext()) {
sb.append("&");
}
}
return sb.toString();
}
public String getAsHeaderElement(String key) {
String value = getFirst(key);
if (value == null) {
return null;
}
return key + "=\"" + value + "\"";
}
public boolean containsKey(Object key) {
return wrappedMap.containsKey(key);
}
public boolean containsValue(Object value) {
for (Set<String> values : wrappedMap.values()) {
if (values.contains(value)) {
return true;
}
}
return false;
}
public int size() {
int count = 0;
for (String key : wrappedMap.keySet()) {
count += wrappedMap.get(key).size();
}
return count;
}
public boolean isEmpty() {
return wrappedMap.isEmpty();
}
public void clear() {
wrappedMap.clear();
}
public SortedSet<String> remove(Object key) {
return wrappedMap.remove(key);
}
public Set<String> keySet() {
return wrappedMap.keySet();
}
public Collection<SortedSet<String>> values() {
return wrappedMap.values();
}
public Set<java.util.Map.Entry<String, SortedSet<String>>> entrySet() {
return wrappedMap.entrySet();
}
}
| Java |
package oauth.signpost.http;
import java.io.IOException;
import java.io.InputStream;
public interface HttpResponse {
int getStatusCode() throws IOException;
String getReasonPhrase() throws Exception;
InputStream getContent() throws IOException;
/**
* Returns the underlying response object, in case you need to work on it
* directly.
*
* @return the wrapped response object
*/
Object unwrap();
}
| Java |
package oauth.signpost.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.HttpURLConnectionRequestAdapter;
/**
* A concise description of an HTTP request. Contains methods to access all
* those parts of an HTTP request which Signpost needs to sign a message. If you
* want to extend Signpost to sign a different kind of HTTP request than those
* currently supported, you'll have to write an adapter which implements this
* interface and a custom {@link OAuthConsumer} which performs the wrapping.
*
* @see HttpURLConnectionRequestAdapter
* @author Matthias Kaeppler
*/
public interface HttpRequest {
String getMethod();
String getRequestUrl();
void setRequestUrl(String url);
void setHeader(String name, String value);
String getHeader(String name);
Map<String, String> getAllHeaders();
InputStream getMessagePayload() throws IOException;
String getContentType();
/**
* Returns the wrapped request object, in case you must work directly on it.
*
* @return the wrapped request object
*/
Object unwrap();
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.signature;
import java.io.IOException;
import java.io.Serializable;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
import org.apache.commons.codec.binary.Base64;
public abstract class OAuthMessageSigner implements Serializable {
private static final long serialVersionUID = 4445779788786131202L;
private transient Base64 base64;
private String consumerSecret;
private String tokenSecret;
public OAuthMessageSigner() {
this.base64 = new Base64();
}
public abstract String sign(HttpRequest request, HttpParameters requestParameters)
throws OAuthMessageSignerException;
public abstract String getSignatureMethod();
public String getConsumerSecret() {
return consumerSecret;
}
public String getTokenSecret() {
return tokenSecret;
}
public void setConsumerSecret(String consumerSecret) {
this.consumerSecret = consumerSecret;
}
public void setTokenSecret(String tokenSecret) {
this.tokenSecret = tokenSecret;
}
protected byte[] decodeBase64(String s) {
return base64.decode(s.getBytes());
}
protected String base64Encode(byte[] b) {
return new String(base64.encode(b));
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.base64 = new Base64();
}
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.signature;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
@SuppressWarnings("serial")
public class HmacSha1MessageSigner extends OAuthMessageSigner {
private static final String MAC_NAME = "HmacSHA1";
@Override
public String getSignatureMethod() {
return "HMAC-SHA1";
}
@Override
public String sign(HttpRequest request, HttpParameters requestParams)
throws OAuthMessageSignerException {
try {
String keyString = OAuth.percentEncode(getConsumerSecret()) + '&'
+ OAuth.percentEncode(getTokenSecret());
byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
Mac mac = Mac.getInstance(MAC_NAME);
mac.init(key);
String sbs = new SignatureBaseString(request, requestParams).generate();
OAuth.debugOut("SBS", sbs);
byte[] text = sbs.getBytes(OAuth.ENCODING);
return base64Encode(mac.doFinal(text)).trim();
} catch (GeneralSecurityException e) {
throw new OAuthMessageSignerException(e);
} catch (UnsupportedEncodingException e) {
throw new OAuthMessageSignerException(e);
}
}
}
| Java |
package oauth.signpost.signature;
import java.io.Serializable;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
/**
* <p>
* Defines how an OAuth signature string is written to a request.
* </p>
* <p>
* Unlike {@link OAuthMessageSigner}, which is concerned with <i>how</i> to
* generate a signature, this class is concered with <i>where</i> to write it
* (e.g. HTTP header or query string).
* </p>
*
* @author Matthias Kaeppler
*/
public interface SigningStrategy extends Serializable {
/**
* Writes an OAuth signature and all remaining required parameters to an
* HTTP message.
*
* @param signature
* the signature to write
* @param request
* the request to sign
* @param requestParameters
* the request parameters
* @return whatever has been written to the request, e.g. an Authorization
* header field
*/
String writeSignature(String signature, HttpRequest request, HttpParameters requestParameters);
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
@SuppressWarnings("serial")
public class PlainTextMessageSigner extends OAuthMessageSigner {
@Override
public String getSignatureMethod() {
return "PLAINTEXT";
}
@Override
public String sign(HttpRequest request, HttpParameters requestParams)
throws OAuthMessageSignerException {
return OAuth.percentEncode(getConsumerSecret()) + '&'
+ OAuth.percentEncode(getTokenSecret());
}
}
| Java |
/*
* Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost.signature;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
public class SignatureBaseString {
private HttpRequest request;
private HttpParameters requestParameters;
/**
* Constructs a new SBS instance that will operate on the given request
* object and parameter set.
*
* @param request
* the HTTP request
* @param requestParameters
* the set of request parameters from the Authorization header, query
* string and form body
*/
public SignatureBaseString(HttpRequest request, HttpParameters requestParameters) {
this.request = request;
this.requestParameters = requestParameters;
}
/**
* Builds the signature base string from the data this instance was
* configured with.
*
* @return the signature base string
* @throws OAuthMessageSignerException
*/
public String generate() throws OAuthMessageSignerException {
try {
String normalizedUrl = normalizeRequestUrl();
String normalizedParams = normalizeRequestParameters();
return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&'
+ OAuth.percentEncode(normalizedParams);
} catch (Exception e) {
throw new OAuthMessageSignerException(e);
}
}
public String normalizeRequestUrl() throws URISyntaxException {
URI uri = new URI(request.getRequestUrl());
String scheme = uri.getScheme().toLowerCase();
String authority = uri.getAuthority().toLowerCase();
boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
|| (scheme.equals("https") && uri.getPort() == 443);
if (dropPort) {
// find the last : in the authority
int index = authority.lastIndexOf(":");
if (index >= 0) {
authority = authority.substring(0, index);
}
}
String path = uri.getRawPath();
if (path == null || path.length() <= 0) {
path = "/"; // conforms to RFC 2616 section 3.2.2
}
// we know that there is no query and no fragment here.
return scheme + "://" + authority + path;
}
/**
* Normalizes the set of request parameters this instance was configured
* with, as per OAuth spec section 9.1.1.
*
* @param parameters
* the set of request parameters
* @return the normalized params string
* @throws IOException
*/
public String normalizeRequestParameters() throws IOException {
if (requestParameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<String> iter = requestParameters.keySet().iterator();
for (int i = 0; iter.hasNext(); i++) {
String param = iter.next();
if (OAuth.OAUTH_SIGNATURE.equals(param) || "realm".equals(param)) {
continue;
}
if (i > 0) {
sb.append("&");
}
sb.append(requestParameters.getAsQueryString(param));
}
return sb.toString();
}
}
| Java |
package oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
/**
* Writes to the HTTP Authorization header field.
*
* @author Matthias Kaeppler
*/
public class AuthorizationHeaderSigningStrategy implements SigningStrategy {
private static final long serialVersionUID = 1L;
public String writeSignature(String signature, HttpRequest request,
HttpParameters requestParameters) {
StringBuilder sb = new StringBuilder();
sb.append("OAuth ");
if (requestParameters.containsKey("realm")) {
sb.append(requestParameters.getAsHeaderElement("realm"));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TOKEN));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CALLBACK));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERIFIER));
sb.append(", ");
}
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CONSUMER_KEY));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERSION));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_SIGNATURE_METHOD));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TIMESTAMP));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_NONCE));
sb.append(", ");
sb.append(OAuth.toHeaderElement(OAuth.OAUTH_SIGNATURE, signature));
String header = sb.toString();
request.setHeader(OAuth.HTTP_AUTHORIZATION_HEADER, header);
return header;
}
}
| Java |
package oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
/**
* Writes to a URL query string. <strong>Note that this currently ONLY works
* when signing a URL directly, not with HTTP request objects.</strong> That's
* because most HTTP request implementations do not allow the client to change
* the URL once the request has been instantiated, so there is no way to append
* parameters to it.
*
* @author Matthias Kaeppler
*/
public class QueryStringSigningStrategy implements SigningStrategy {
private static final long serialVersionUID = 1L;
public String writeSignature(String signature, HttpRequest request,
HttpParameters requestParameters) {
// add the signature
StringBuilder sb = new StringBuilder(OAuth.addQueryParameters(request.getRequestUrl(),
OAuth.OAUTH_SIGNATURE, signature));
// add the optional OAuth parameters
if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TOKEN));
}
if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CALLBACK));
}
if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERIFIER));
}
// add the remaining OAuth params
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CONSUMER_KEY));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERSION));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_SIGNATURE_METHOD));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TIMESTAMP));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_NONCE));
String signedUrl = sb.toString();
request.setRequestUrl(signedUrl);
return signedUrl;
}
}
| Java |
/*
* Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost;
import java.io.Serializable;
import java.util.Map;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
/**
* <p>
* Supplies an interface that can be used to retrieve request and access tokens
* from an OAuth 1.0(a) service provider. A provider object requires an
* {@link OAuthConsumer} to sign the token request message; after a token has
* been retrieved, the consumer is automatically updated with the token and the
* corresponding secret.
* </p>
* <p>
* To initiate the token exchange, create a new provider instance and configure
* it with the URLs the service provider exposes for requesting tokens and
* resource authorization, e.g.:
* </p>
*
* <pre>
* OAuthProvider provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
* "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
* </pre>
* <p>
* Depending on the HTTP library you use, you may need a different provider
* type, refer to the website documentation for how to do that.
* </p>
* <p>
* To receive a request token which the user must authorize, you invoke it using
* a consumer instance and a callback URL:
* </p>
* <p>
*
* <pre>
* String url = provider.retrieveRequestToken(consumer, "http://www.example.com/callback");
* </pre>
*
* </p>
* <p>
* That url must be opened in a Web browser, where the user can grant access to
* the resources in question. If that succeeds, the service provider will
* redirect to the callback URL and append the blessed request token.
* </p>
* <p>
* That token must now be exchanged for an access token, as such:
* </p>
* <p>
*
* <pre>
* provider.retrieveAccessToken(consumer, nullOrVerifierCode);
* </pre>
*
* </p>
* <p>
* where nullOrVerifierCode is either null if your provided a callback URL in
* the previous step, or the pin code issued by the service provider to the user
* if the request was out-of-band (cf. {@link OAuth#OUT_OF_BAND}.
* </p>
* <p>
* The consumer used during token handshakes is now ready for signing.
* </p>
*
* @see DefaultOAuthProvider
* @see DefaultOAuthConsumer
* @see OAuthProviderListener
*/
public interface OAuthProvider extends Serializable {
/**
* Queries the service provider for a request token.
* <p>
* <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid
* consumer key and consumer secret already set.
* </p>
* <p>
* <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an
* unauthorized request token and token secret set.
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param callbackUrl
* Pass an actual URL if your app can receive callbacks and you want
* to get informed about the result of the authorization process.
* Pass {@link OAuth.OUT_OF_BAND} if the service provider implements
* OAuth 1.0a and your app cannot receive callbacks. Pass null if the
* service provider implements OAuth 1.0 and your app cannot receive
* callbacks. Please note that some services (among them Twitter)
* will fail authorization if you pass a callback URL but register
* your application as a desktop app (which would only be able to
* handle OOB requests).
* @return The URL to which the user must be sent in order to authorize the
* consumer. It includes the unauthorized request token (and in the
* case of OAuth 1.0, the callback URL -- 1.0a clients send along
* with the token request).
* @throws OAuthMessageSignerException
* if signing the request failed
* @throws OAuthNotAuthorizedException
* if the service provider rejected the consumer
* @throws OAuthExpectationFailedException
* if required parameters were not correctly set by the consumer or
* service provider
* @throws OAuthCommunicationException
* if server communication failed
*/
public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Queries the service provider for an access token.
* <p>
* <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid
* consumer key, consumer secret, authorized request token and token secret
* already set.
* </p>
* <p>
* <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an
* access token and token secret set.
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param oauthVerifier
* <b>NOTE: Only applies to service providers implementing OAuth
* 1.0a. Set to null if the service provider is still using OAuth
* 1.0.</b> The verification code issued by the service provider
* after the the user has granted the consumer authorization. If the
* callback method provided in the previous step was
* {@link OAuth.OUT_OF_BAND}, then you must ask the user for this
* value. If your app has received a callback, the verfication code
* was passed as part of that request instead.
* @throws OAuthMessageSignerException
* if signing the request failed
* @throws OAuthNotAuthorizedException
* if the service provider rejected the consumer
* @throws OAuthExpectationFailedException
* if required parameters were not correctly set by the consumer or
* service provider
* @throws OAuthCommunicationException
* if server communication failed
*/
public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Any additional non-OAuth parameters returned in the response body of a
* token request can be obtained through this method. These parameters will
* be preserved until the next token request is issued. The return value is
* never null.
*/
public HttpParameters getResponseParameters();
/**
* Subclasses must use this setter to preserve any non-OAuth query
* parameters contained in the server response. It's the caller's
* responsibility that any OAuth parameters be removed beforehand.
*
* @param parameters
* the map of query parameters served by the service provider in the
* token response
*/
public void setResponseParameters(HttpParameters parameters);
/**
* Use this method to set custom HTTP headers to be used for the requests
* which are sent to retrieve tokens. @deprecated THIS METHOD HAS BEEN
* DEPRECATED. Use {@link OAuthProviderListener} to customize requests.
*
* @param header
* The header name (e.g. 'WWW-Authenticate')
* @param value
* The header value (e.g. 'realm=www.example.com')
*/
@Deprecated
public void setRequestHeader(String header, String value);
/**
* @deprecated THIS METHOD HAS BEEN DEPRECATED. Use
* {@link OAuthProviderListener} to customize requests.
* @return all request headers set via {@link #setRequestHeader}
*/
@Deprecated
public Map<String, String> getRequestHeaders();
/**
* @param isOAuth10aProvider
* set to true if the service provider supports OAuth 1.0a. Note that
* you need only call this method if you reconstruct a provider
* object in between calls to retrieveRequestToken() and
* retrieveAccessToken() (i.e. if the object state isn't preserved).
* If instead those two methods are called on the same provider
* instance, this flag will be deducted automatically based on the
* server response during retrieveRequestToken(), so you can simply
* ignore this method.
*/
public void setOAuth10a(boolean isOAuth10aProvider);
/**
* @return true if the service provider supports OAuth 1.0a. Note that the
* value returned here is only meaningful after you have already
* performed the token handshake, otherwise there is no way to
* determine what version of the OAuth protocol the service provider
* implements.
*/
public boolean isOAuth10a();
public String getRequestTokenEndpointUrl();
public String getAccessTokenEndpointUrl();
public String getAuthorizationWebsiteUrl();
public void setListener(OAuthProviderListener listener);
public void removeListener(OAuthProviderListener listener);
}
| Java |
/* Copyright (c) 2009 Matthias Kaeppler
*
* 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 oauth.signpost.commonshttp;
import oauth.signpost.AbstractOAuthConsumer;
import oauth.signpost.http.HttpRequest;
/**
* Supports signing HTTP requests of type {@link org.apache.ogt.http.HttpRequest}.
*
* @author Matthias Kaeppler
*/
public class CommonsHttpOAuthConsumer extends AbstractOAuthConsumer {
private static final long serialVersionUID = 1L;
public CommonsHttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
@Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof org.apache.ogt.http.HttpRequest)) {
throw new IllegalArgumentException(
"This consumer expects requests of type "
+ org.apache.ogt.http.HttpRequest.class.getCanonicalName());
}
return new HttpRequestAdapter((org.apache.ogt.http.client.methods.HttpUriRequest) request);
}
}
| Java |
package oauth.signpost.commonshttp;
import java.io.IOException;
import java.io.InputStream;
import oauth.signpost.http.HttpResponse;
public class HttpResponseAdapter implements HttpResponse {
private org.apache.ogt.http.HttpResponse response;
public HttpResponseAdapter(org.apache.ogt.http.HttpResponse response) {
this.response = response;
}
public InputStream getContent() throws IOException {
return response.getEntity().getContent();
}
public int getStatusCode() throws IOException {
return response.getStatusLine().getStatusCode();
}
public String getReasonPhrase() throws Exception {
return response.getStatusLine().getReasonPhrase();
}
public Object unwrap() {
return response;
}
}
| Java |
/*
* Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost.commonshttp;
import java.io.IOException;
import oauth.signpost.AbstractOAuthProvider;
import oauth.signpost.http.HttpRequest;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This implementation uses the Apache Commons {@link HttpClient} 4.x HTTP
* implementation to fetch OAuth tokens from a service provider. Android users
* should use this provider implementation in favor of the default one, since
* the latter is known to cause problems with Android's Apache Harmony
* underpinnings.
*
* @author Matthias Kaeppler
*/
public class CommonsHttpOAuthProvider extends AbstractOAuthProvider {
private static final long serialVersionUID = 1L;
private transient HttpClient httpClient;
public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
this.httpClient = new DefaultHttpClient();
}
public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl, HttpClient httpClient) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
this.httpClient = httpClient;
}
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
protected HttpRequest createRequest(String endpointUrl) throws Exception {
HttpPost request = new HttpPost(endpointUrl);
return new HttpRequestAdapter(request);
}
@Override
protected oauth.signpost.http.HttpResponse sendRequest(HttpRequest request) throws Exception {
HttpResponse response = httpClient.execute((HttpUriRequest) request.unwrap());
return new HttpResponseAdapter(response);
}
@Override
protected void closeConnection(HttpRequest request, oauth.signpost.http.HttpResponse response)
throws Exception {
if (response != null) {
HttpEntity entity = ((HttpResponse) response.unwrap()).getEntity();
if (entity != null) {
try {
// free the connection
entity.consumeContent();
} catch (IOException e) {
// this means HTTP keep-alive is not possible
e.printStackTrace();
}
}
}
}
}
| Java |
package oauth.signpost.commonshttp;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.client.methods.HttpUriRequest;
public class HttpRequestAdapter implements oauth.signpost.http.HttpRequest {
private HttpUriRequest request;
private HttpEntity entity;
public HttpRequestAdapter(HttpUriRequest request) {
this.request = request;
if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest) request).getEntity();
}
}
public String getMethod() {
return request.getRequestLine().getMethod();
}
public String getRequestUrl() {
return request.getURI().toString();
}
public void setRequestUrl(String url) {
throw new RuntimeException(new UnsupportedOperationException());
}
public String getHeader(String name) {
Header header = request.getFirstHeader(name);
if (header == null) {
return null;
}
return header.getValue();
}
public void setHeader(String name, String value) {
request.setHeader(name, value);
}
public Map<String, String> getAllHeaders() {
Header[] origHeaders = request.getAllHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
for (Header h : origHeaders) {
headers.put(h.getName(), h.getValue());
}
return headers;
}
public String getContentType() {
if (entity == null) {
return null;
}
Header header = entity.getContentType();
if (header == null) {
return null;
}
return header.getValue();
}
public InputStream getMessagePayload() throws IOException {
if (entity == null) {
return null;
}
return entity.getContent();
}
public Object unwrap() {
return request;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URI;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class Benchmark {
public static void main(String[] args) throws Exception {
String ns = System.getProperty("hc.benchmark.n-requests", "200000");
String nc = System.getProperty("hc.benchmark.concurrent", "100");
String cls = System.getProperty("hc.benchmark.content-len", "2048");
int n = Integer.parseInt(ns);
int c = Integer.parseInt(nc);
int contentLen = Integer.parseInt(cls);
SocketConnector connector = new SocketConnector();
connector.setPort(0);
connector.setRequestBufferSize(12 * 1024);
connector.setResponseBufferSize(12 * 1024);
connector.setAcceptors(2);
connector.setAcceptQueueSize(c);
QueuedThreadPool threadpool = new QueuedThreadPool();
threadpool.setMinThreads(c);
threadpool.setMaxThreads(2000);
Server server = new Server();
server.addConnector(connector);
server.setThreadPool(threadpool);
server.setHandler(new RandomDataHandler());
server.start();
int port = connector.getLocalPort();
// Sleep a little
Thread.sleep(2000);
TestHttpAgent[] agents = new TestHttpAgent[] {
new TestHttpClient3(),
new TestHttpJRE(),
new TestHttpCore(),
new TestHttpClient4(),
new TestJettyHttpClient(),
new TestNingHttpClient()
};
byte[] content = new byte[contentLen];
int r = Math.abs(content.hashCode());
for (int i = 0; i < content.length; i++) {
content[i] = (byte) ((r + i) % 96 + 32);
}
URI target1 = new URI("http", null, "localhost", port, "/rnd", "c=" + contentLen, null);
URI target2 = new URI("http", null, "localhost", port, "/echo", null, null);
try {
for (TestHttpAgent agent: agents) {
agent.init();
try {
System.out.println("=================================");
System.out.println("HTTP agent: " + agent.getClientName());
System.out.println("---------------------------------");
System.out.println(n + " GET requests");
System.out.println("---------------------------------");
long startTime1 = System.currentTimeMillis();
Stats stats1 = agent.get(target1, n, c);
long finishTime1 = System.currentTimeMillis();
Stats.printStats(target1, startTime1, finishTime1, stats1);
System.out.println("---------------------------------");
System.out.println(n + " POST requests");
System.out.println("---------------------------------");
long startTime2 = System.currentTimeMillis();
Stats stats2 = agent.post(target2, content, n, c);
long finishTime2 = System.currentTimeMillis();
Stats.printStats(target2, startTime2, finishTime2, stats2);
} finally {
agent.shutdown();
}
agent.init();
System.out.println("---------------------------------");
}
} finally {
server.stop();
}
server.join();
}
static class RandomDataHandler extends AbstractHandler {
public RandomDataHandler() {
super();
}
public void handle(
final String target,
final Request baseRequest,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
if (target.equals("/rnd")) {
rnd(request, response);
} else if (target.equals("/echo")) {
echo(request, response);
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Writer writer = response.getWriter();
writer.write("Target not found: " + target);
writer.flush();
}
}
private void rnd(
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
int count = 100;
String s = request.getParameter("c");
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatus(500);
Writer writer = response.getWriter();
writer.write("Invalid query format: " + request.getQueryString());
writer.flush();
return;
}
response.setStatus(200);
response.setContentLength(count);
OutputStream outstream = response.getOutputStream();
byte[] tmp = new byte[1024];
int r = Math.abs(tmp.hashCode());
int remaining = count;
while (remaining > 0) {
int chunk = Math.min(tmp.length, remaining);
for (int i = 0; i < chunk; i++) {
tmp[i] = (byte) ((r + i) % 96 + 32);
}
outstream.write(tmp, 0, chunk);
remaining -= chunk;
}
outstream.flush();
}
private void echo(
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
ByteArrayOutputStream2 buffer = new ByteArrayOutputStream2();
InputStream instream = request.getInputStream();
if (instream != null) {
IO.copy(instream, buffer);
buffer.flush();
}
byte[] content = buffer.getBuf();
response.setStatus(200);
response.setContentLength(content.length);
OutputStream outstream = response.getOutputStream();
outstream.write(content);
outstream.flush();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class TestHttpJRE implements TestHttpAgent {
public TestHttpJRE() {
super();
}
public void init() {
}
public void shutdown() {
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
System.setProperty("http.maxConnections", Integer.toString(c));
URL target = targetURI.toURL();
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, target, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final URL target;
private final byte[] content;
WorkerThread(final Stats stats, final URL target, final byte[] content) {
super();
this.stats = stats;
this.target = target;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
while (!this.stats.isComplete()) {
long contentLen = 0;
try {
HttpURLConnection conn = (HttpURLConnection) this.target.openConnection();
conn.setReadTimeout(15000);
if (this.content != null) {
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(this.content.length);
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
try {
out.write(this.content);
out.flush ();
} finally {
out.close();
}
}
InputStream instream = conn.getInputStream();
if (instream != null) {
try {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
} finally {
instream.close();
}
}
if (conn.getResponseCode() == 200) {
this.stats.success(contentLen);
} else {
this.stats.failure(contentLen);
}
} catch (IOException ex) {
this.stats.failure(contentLen);
}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "JRE HTTP " + System.getProperty("java.version");
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpJRE test = new TestHttpJRE();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.net.URI;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.Request;
public class TestNingHttpClient implements TestHttpAgent {
private AsyncHttpClient client;
public TestNingHttpClient() {
super();
}
public void init() throws Exception {
}
public void shutdown() throws Exception {
this.client.close();
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
if (this.client != null) {
this.client.close();
}
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setAllowPoolingConnection(true)
.setCompressionEnabled(false)
.setMaximumConnectionsPerHost(c)
.setMaximumConnectionsTotal(2000)
.setRequestTimeoutInMs(15000)
.build();
this.client = new AsyncHttpClient(config);
Stats stats = new Stats(n, c);
for (int i = 0; i < n; i++) {
Request request;
if (content == null) {
request = this.client.prepareGet(targetURI.toASCIIString())
.build();
} else {
request = this.client.preparePost(targetURI.toASCIIString())
.setBody(content)
.build();
}
try {
this.client.executeRequest(request, new SimpleAsyncHandler(stats));
} catch (IOException ex) {
}
}
stats.waitFor();
return stats;
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "Ning Async HTTP client 1.4.0";
}
static class SimpleAsyncHandler implements AsyncHandler<Object> {
private final Stats stats;
private int status = 0;
private long contentLen = 0;
SimpleAsyncHandler(final Stats stats) {
super();
this.stats = stats;
}
public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
this.status = responseStatus.getStatusCode();
return STATE.CONTINUE;
}
public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
return STATE.CONTINUE;
}
public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception {
this.contentLen += bodyPart.getBodyPartBytes().length;
return STATE.CONTINUE;
}
public Object onCompleted() throws Exception {
if (this.status == 200) {
this.stats.success(this.contentLen);
} else {
this.stats.failure(this.contentLen);
}
return STATE.CONTINUE;
}
public void onThrowable(final Throwable t) {
this.stats.failure(this.contentLen);
}
};
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestNingHttpClient test = new TestNingHttpClient();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class TestHttpClient3 implements TestHttpAgent {
private final MultiThreadedHttpConnectionManager mgr;
private final HttpClient httpclient;
public TestHttpClient3() {
super();
this.mgr = new MultiThreadedHttpConnectionManager();
this.httpclient = new HttpClient(this.mgr);
this.httpclient.getParams().setVersion(
HttpVersion.HTTP_1_1);
this.httpclient.getParams().setBooleanParameter(
HttpMethodParams.USE_EXPECT_CONTINUE, false);
this.httpclient.getHttpConnectionManager().getParams()
.setStaleCheckingEnabled(false);
this.httpclient.getParams().setSoTimeout(15000);
HttpMethodRetryHandler retryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(final HttpMethod httpmethod, final IOException ex, int count) {
return false;
}
};
this.httpclient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); }
public void init() {
}
public void shutdown() {
this.mgr.shutdown();
}
Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
this.mgr.getParams().setMaxTotalConnections(2000);
this.mgr.getParams().setDefaultMaxConnectionsPerHost(c);
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, target, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final URI target;
private final byte[] content;
WorkerThread(final Stats stats, final URI target, final byte[] content) {
super();
this.stats = stats;
this.target = target;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
while (!this.stats.isComplete()) {
HttpMethod httpmethod;
if (this.content == null) {
GetMethod httpget = new GetMethod(target.toASCIIString());
httpmethod = httpget;
} else {
PostMethod httppost = new PostMethod(target.toASCIIString());
httppost.setRequestEntity(new ByteArrayRequestEntity(content));
httpmethod = httppost;
}
long contentLen = 0;
try {
httpclient.executeMethod(httpmethod);
InputStream instream = httpmethod.getResponseBodyAsStream();
if (instream != null) {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
}
this.stats.success(contentLen);
} catch (IOException ex) {
this.stats.failure(contentLen);
} finally {
httpmethod.releaseConnection();
}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "Apache HttpClient 3.1";
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpClient3 test = new TestHttpClient3();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.net.URI;
public class Stats {
private final int expectedCount;
private final int concurrency;
private int successCount = 0;
private int failureCount = 0;
private long contentLen = 0;
private long totalContentLen = 0;
public Stats(int expectedCount, int concurrency) {
super();
this.expectedCount = expectedCount;
this.concurrency = concurrency;
}
public synchronized boolean isComplete() {
return this.successCount + this.failureCount >= this.expectedCount;
}
public synchronized void success(long contentLen) {
if (isComplete()) return;
this.successCount++;
this.contentLen = contentLen;
this.totalContentLen += contentLen;
notifyAll();
}
public synchronized void failure(long contentLen) {
if (isComplete()) return;
this.failureCount++;
this.contentLen = contentLen;
this.totalContentLen += contentLen;
notifyAll();
}
public int getConcurrency() {
return this.concurrency;
}
public synchronized int getSuccessCount() {
return successCount;
}
public synchronized int getFailureCount() {
return failureCount;
}
public void setFailureCount(int failureCount) {
this.failureCount = failureCount;
}
public synchronized long getContentLen() {
return contentLen;
}
public synchronized long getTotalContentLen() {
return totalContentLen;
}
public synchronized void waitFor() throws InterruptedException {
while (!isComplete()) {
wait();
}
}
public static void printStats(
final URI targetURI, long startTime, long finishTime, final Stats stats) {
float totalTimeSec = (float) (finishTime - startTime) / 1000;
float reqsPerSec = (float) stats.getSuccessCount() / totalTimeSec;
float timePerReqMs = (float) (finishTime - startTime) / (float) stats.getSuccessCount();
System.out.print("Document URI:\t\t");
System.out.println(targetURI);
System.out.print("Document Length:\t");
System.out.print(stats.getContentLen());
System.out.println(" bytes");
System.out.println();
System.out.print("Concurrency level:\t");
System.out.println(stats.getConcurrency());
System.out.print("Time taken for tests:\t");
System.out.print(totalTimeSec);
System.out.println(" seconds");
System.out.print("Complete requests:\t");
System.out.println(stats.getSuccessCount());
System.out.print("Failed requests:\t");
System.out.println(stats.getFailureCount());
System.out.print("Content transferred:\t");
System.out.print(stats.getTotalContentLen());
System.out.println(" bytes");
System.out.print("Requests per second:\t");
System.out.print(reqsPerSec);
System.out.println(" [#/sec] (mean)");
System.out.print("Time per request:\t");
System.out.print(timePerReqMs);
System.out.println(" [ms] (mean)");
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.net.URI;
public interface TestHttpAgent {
void init() throws Exception;
void shutdown() throws Exception;
String getClientName();
Stats get(URI target, int n, int c) throws Exception;
Stats post(URI target, byte[] content, int n, int c) throws Exception;
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URI;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.VersionInfo;
public class TestHttpCore implements TestHttpAgent {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public TestHttpCore() {
super();
this.params = new SyncBasicHttpParams();
this.params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
this.params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
false);
this.params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,
false);
this.params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
8 * 1024);
this.params.setIntParameter(HttpConnectionParams.SO_TIMEOUT,
15000);
this.httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent()
}, null);
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void init() {
}
public void shutdown() {
}
Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
HttpHost targetHost = new HttpHost(target.getHost(), target.getPort());
StringBuilder buffer = new StringBuilder();
buffer.append(target.getPath());
if (target.getQuery() != null) {
buffer.append("?");
buffer.append(target.getQuery());
}
String requestUri = buffer.toString();
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, targetHost, requestUri, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final HttpHost targetHost;
private final String requestUri;
private final byte[] content;
WorkerThread(final Stats stats,
final HttpHost targetHost, final String requestUri, final byte[] content) {
super();
this.stats = stats;
this.targetHost = targetHost;
this.requestUri = requestUri;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
HttpContext context = new BasicHttpContext();
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
try {
while (!this.stats.isComplete()) {
HttpRequest request;
if (this.content == null) {
BasicHttpRequest httpget = new BasicHttpRequest("GET", this.requestUri);
request = httpget;
} else {
BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST",
this.requestUri);
httppost.setEntity(new ByteArrayEntity(this.content));
request = httppost;
}
long contentLen = 0;
try {
if (!conn.isOpen()) {
Socket socket = new Socket(
this.targetHost.getHostName(),
this.targetHost.getPort() > 0 ? this.targetHost.getPort() : 80);
conn.bind(socket, params);
}
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
httpexecutor.postProcess(response, httpproc, context);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
contentLen = 0;
if (instream != null) {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
}
} finally {
instream.close();
}
}
if (!connStrategy.keepAlive(response, context)) {
conn.close();
}
for (HeaderIterator it = request.headerIterator(); it.hasNext();) {
it.next();
it.remove();
}
this.stats.success(contentLen);
} catch (IOException ex) {
this.stats.failure(contentLen);
} catch (HttpException ex) {
this.stats.failure(contentLen);
}
}
} finally {
try {
conn.shutdown();
} catch (IOException ignore) {}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http",
Thread.currentThread().getContextClassLoader());
return "Apache HttpCore 4 (ver: " +
((vinfo != null) ? vinfo.getRelease() : VersionInfo.UNAVAILABLE) + ")";
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpCore test = new TestHttpCore();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.VersionInfo;
public class TestHttpClient4 implements TestHttpAgent {
private final ThreadSafeClientConnManager mgr;
private final DefaultHttpClient httpclient;
public TestHttpClient4() {
super();
HttpParams params = new SyncBasicHttpParams();
params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
false);
params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,
false);
params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
8 * 1024);
params.setIntParameter(HttpConnectionParams.SO_TIMEOUT,
15000);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
this.mgr = new ThreadSafeClientConnManager(schemeRegistry);
this.httpclient = new DefaultHttpClient(this.mgr, params);
this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(
final IOException exception, int executionCount, final HttpContext context) {
return false;
}
});
}
public void init() {
}
public void shutdown() {
this.mgr.shutdown();
}
Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
this.mgr.setMaxTotal(2000);
this.mgr.setDefaultMaxPerRoute(c);
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, target, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final URI target;
private final byte[] content;
WorkerThread(final Stats stats, final URI target, final byte[] content) {
super();
this.stats = stats;
this.target = target;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
while (!this.stats.isComplete()) {
HttpUriRequest request;
if (this.content == null) {
HttpGet httpget = new HttpGet(target);
request = httpget;
} else {
HttpPost httppost = new HttpPost(target);
httppost.setEntity(new ByteArrayEntity(content));
request = httppost;
}
long contentLen = 0;
try {
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
contentLen = 0;
if (instream != null) {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
}
} finally {
instream.close();
}
}
this.stats.success(contentLen);
} catch (IOException ex) {
this.stats.failure(contentLen);
request.abort();
}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n ,c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http.client",
Thread.currentThread().getContextClassLoader());
return "Apache HttpClient 4 (ver: " +
((vinfo != null) ? vinfo.getRelease() : VersionInfo.UNAVAILABLE) + ")";
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpClient4 test = new TestHttpClient4();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.benchmark;
import java.io.IOException;
import java.net.URI;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.server.Server;
public class TestJettyHttpClient implements TestHttpAgent {
private final HttpClient client;
public TestJettyHttpClient() {
super();
this.client = new HttpClient();
this.client.setRequestBufferSize(8 * 1024);
this.client.setResponseBufferSize(8 * 1024);
this.client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
this.client.setTimeout(15000);
}
public void init() throws Exception {
this.client.start();
}
public void shutdown() throws Exception {
this.client.stop();
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
this.client.setMaxConnectionsPerAddress(c);
Stats stats = new Stats(n, c);
for (int i = 0; i < n; i++) {
SimpleHttpExchange exchange = new SimpleHttpExchange(stats);
exchange.setURL(targetURI.toASCIIString());
if (content != null) {
exchange.setMethod("POST");
exchange.setRequestContent(new ByteArrayBuffer(content));
}
try {
this.client.send(exchange);
} catch (IOException ex) {
}
}
stats.waitFor();
return stats;
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "Jetty " + Server.getVersion();
}
static class SimpleHttpExchange extends HttpExchange {
private final Stats stats;
private int status = 0;
private long contentLen = 0;
SimpleHttpExchange(final Stats stats) {
super();
this.stats = stats;
}
protected void onResponseStatus(
final Buffer version, int status, final Buffer reason) throws IOException {
this.status = status;
super.onResponseStatus(version, status, reason);
}
@Override
protected void onResponseContent(final Buffer content) throws IOException {
byte[] tmp = new byte[content.length()];
content.get(tmp, 0, tmp.length);
this.contentLen += tmp.length;
super.onResponseContent(content);
}
@Override
protected void onResponseComplete() throws IOException {
if (this.status == 200) {
this.stats.success(this.contentLen);
} else {
this.stats.failure(this.contentLen);
}
super.onResponseComplete();
}
@Override
protected void onConnectionFailed(final Throwable x) {
this.stats.failure(this.contentLen);
super.onConnectionFailed(x);
}
@Override
protected void onException(final Throwable x) {
this.stats.failure(this.contentLen);
super.onException(x);
}
};
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestJettyHttpClient test = new TestJettyHttpClient();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.params.HttpParams;
@Deprecated
class SchemeSocketFactoryAdaptor implements SchemeSocketFactory {
private final SocketFactory factory;
SchemeSocketFactoryAdaptor(final SocketFactory factory) {
super();
this.factory = factory;
}
public Socket connectSocket(
final Socket sock,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
String host = remoteAddress.getHostName();
int port = remoteAddress.getPort();
InetAddress local = null;
int localPort = 0;
if (localAddress != null) {
local = localAddress.getAddress();
localPort = localAddress.getPort();
}
return this.factory.connectSocket(sock, host, port, local, localPort, params);
}
public Socket createSocket(final HttpParams params) throws IOException {
return this.factory.createSocket();
}
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
return this.factory.isSecure(sock);
}
public SocketFactory getFactory() {
return this.factory;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (obj instanceof SchemeSocketFactoryAdaptor) {
return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory);
} else {
return this.factory.equals(obj);
}
}
@Override
public int hashCode() {
return this.factory.hashCode();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
@Deprecated
class SocketFactoryAdaptor implements SocketFactory {
private final SchemeSocketFactory factory;
SocketFactoryAdaptor(final SchemeSocketFactory factory) {
super();
this.factory = factory;
}
public Socket createSocket() throws IOException {
HttpParams params = new BasicHttpParams();
return this.factory.createSocket(params);
}
public Socket connectSocket(
final Socket socket,
final String host, int port,
final InetAddress localAddress, int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetSocketAddress local = null;
if (localAddress != null || localPort > 0) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
local = new InetSocketAddress(localAddress, localPort);
}
InetAddress remoteAddress = InetAddress.getByName(host);
InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
return this.factory.connectSocket(socket, remote, local, params);
}
public boolean isSecure(final Socket socket) throws IllegalArgumentException {
return this.factory.isSecure(socket);
}
public SchemeSocketFactory getFactory() {
return this.factory;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (obj instanceof SocketFactoryAdaptor) {
return this.factory.equals(((SocketFactoryAdaptor)obj).factory);
} else {
return this.factory.equals(obj);
}
}
@Override
public int hashCode() {
return this.factory.hashCode();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.util.Locale;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.util.LangUtils;
/**
* Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified
* by lowercase names. Supported schemes are typically collected in a {@link SchemeRegistry
* SchemeRegistry}.
* <p>
* For example, to configure support for "https://" URLs, you could write code like the following:
* <pre>
* Scheme https = new Scheme("https", 443, new MySecureSocketFactory());
* SchemeRegistry.DEFAULT.register(https);
* </pre>
*
* @since 4.0
*/
@Immutable
public final class Scheme {
/** The name of this scheme, in lowercase. (e.g. http, https) */
private final String name;
/** The socket factory for this scheme */
private final SchemeSocketFactory socketFactory;
/** The default port for this scheme */
private final int defaultPort;
/** Indicates whether this scheme allows for layered connections */
private final boolean layered;
/** A string representation, for {@link #toString toString}. */
private String stringRep;
/*
* This is used to cache the result of the toString() method
* Since the method always generates the same value, there's no
* need to synchronize, and it does not affect immutability.
*/
/**
* Creates a new scheme.
* Whether the created scheme allows for layered connections
* depends on the class of <code>factory</code>.
*
* @param name the scheme name, for example "http".
* The name will be converted to lowercase.
* @param port the default port for this scheme
* @param factory the factory for creating sockets for communication
* with this scheme
*
* @since 4.1
*/
public Scheme(final String name, final int port, final SchemeSocketFactory factory) {
if (name == null) {
throw new IllegalArgumentException("Scheme name may not be null");
}
if ((port <= 0) || (port > 0xffff)) {
throw new IllegalArgumentException("Port is invalid: " + port);
}
if (factory == null) {
throw new IllegalArgumentException("Socket factory may not be null");
}
this.name = name.toLowerCase(Locale.ENGLISH);
this.socketFactory = factory;
this.defaultPort = port;
this.layered = factory instanceof LayeredSchemeSocketFactory;
}
/**
* Creates a new scheme.
* Whether the created scheme allows for layered connections
* depends on the class of <code>factory</code>.
*
* @param name the scheme name, for example "http".
* The name will be converted to lowercase.
* @param factory the factory for creating sockets for communication
* with this scheme
* @param port the default port for this scheme
*
* @deprecated Use {@link #Scheme(String, int, SchemeSocketFactory)}
*/
@Deprecated
public Scheme(final String name,
final SocketFactory factory,
final int port) {
if (name == null) {
throw new IllegalArgumentException
("Scheme name may not be null");
}
if (factory == null) {
throw new IllegalArgumentException
("Socket factory may not be null");
}
if ((port <= 0) || (port > 0xffff)) {
throw new IllegalArgumentException
("Port is invalid: " + port);
}
this.name = name.toLowerCase(Locale.ENGLISH);
if (factory instanceof LayeredSocketFactory) {
this.socketFactory = new LayeredSchemeSocketFactoryAdaptor(
(LayeredSocketFactory) factory);
this.layered = true;
} else {
this.socketFactory = new SchemeSocketFactoryAdaptor(factory);
this.layered = false;
}
this.defaultPort = port;
}
/**
* Obtains the default port.
*
* @return the default port for this scheme
*/
public final int getDefaultPort() {
return defaultPort;
}
/**
* Obtains the socket factory.
* If this scheme is {@link #isLayered layered}, the factory implements
* {@link LayeredSocketFactory LayeredSocketFactory}.
*
* @return the socket factory for this scheme
*
* @deprecated Use {@link #getSchemeSocketFactory()}
*/
@Deprecated
public final SocketFactory getSocketFactory() {
if (this.socketFactory instanceof SchemeSocketFactoryAdaptor) {
return ((SchemeSocketFactoryAdaptor) this.socketFactory).getFactory();
} else {
if (this.layered) {
return new LayeredSocketFactoryAdaptor(
(LayeredSchemeSocketFactory) this.socketFactory);
} else {
return new SocketFactoryAdaptor(this.socketFactory);
}
}
}
/**
* Obtains the socket factory.
* If this scheme is {@link #isLayered layered}, the factory implements
* {@link LayeredSocketFactory LayeredSchemeSocketFactory}.
*
* @return the socket factory for this scheme
*
* @since 4.1
*/
public final SchemeSocketFactory getSchemeSocketFactory() {
return this.socketFactory;
}
/**
* Obtains the scheme name.
*
* @return the name of this scheme, in lowercase
*/
public final String getName() {
return name;
}
/**
* Indicates whether this scheme allows for layered connections.
*
* @return <code>true</code> if layered connections are possible,
* <code>false</code> otherwise
*/
public final boolean isLayered() {
return layered;
}
/**
* Resolves the correct port for this scheme.
* Returns the given port if it is valid, the default port otherwise.
*
* @param port the port to be resolved,
* a negative number to obtain the default port
*
* @return the given port or the defaultPort
*/
public final int resolvePort(int port) {
return port <= 0 ? defaultPort : port;
}
/**
* Return a string representation of this object.
*
* @return a human-readable string description of this scheme
*/
@Override
public final String toString() {
if (stringRep == null) {
StringBuilder buffer = new StringBuilder();
buffer.append(this.name);
buffer.append(':');
buffer.append(Integer.toString(this.defaultPort));
stringRep = buffer.toString();
}
return stringRep;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) return true;
if (obj instanceof Scheme) {
Scheme that = (Scheme) obj;
return this.name.equals(that.name)
&& this.defaultPort == that.defaultPort
&& this.layered == that.layered;
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.defaultPort);
hash = LangUtils.hashCode(hash, this.name);
hash = LangUtils.hashCode(hash, this.layered);
return hash;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
@Deprecated
class LayeredSocketFactoryAdaptor extends SocketFactoryAdaptor implements LayeredSocketFactory {
private final LayeredSchemeSocketFactory factory;
LayeredSocketFactoryAdaptor(final LayeredSchemeSocketFactory factory) {
super(factory);
this.factory = factory;
}
public Socket createSocket(
final Socket socket,
final String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return this.factory.createLayeredSocket(socket, host, port, autoClose);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.params.HttpParams;
/**
* A factory for creating, initializing and connecting sockets.
* The factory encapsulates the logic for establishing a socket connection.
*
* @since 4.0
*
* @deprecated use {@link SchemeSocketFactory}
*/
@Deprecated
public interface SocketFactory {
/**
* Creates a new, unconnected socket.
* The socket should subsequently be passed to
* {@link #connectSocket connectSocket}.
*
* @return a new socket
*
* @throws IOException if an I/O error occurs while creating the socket
*/
Socket createSocket()
throws IOException;
/**
* Connects a socket to the given host.
*
* @param sock the socket to connect, as obtained from
* {@link #createSocket createSocket}.
* <code>null</code> indicates that a new socket
* should be created and connected.
* @param host the host to connect to
* @param port the port to connect to on the host
* @param localAddress the local address to bind the socket to, or
* <code>null</code> for any
* @param localPort the port on the local machine,
* 0 or a negative number for any
* @param params additional {@link HttpParams parameters} for connecting
*
* @return the connected socket. The returned object may be different
* from the <code>sock</code> argument if this factory supports
* a layered protocol.
*
* @throws IOException if an I/O error occurs
* @throws UnknownHostException if the IP address of the target host
* can not be determined
* @throws ConnectTimeoutException if the socket cannot be connected
* within the time limit defined in the <code>params</code>
*/
Socket connectSocket(
Socket sock,
String host,
int port,
InetAddress localAddress,
int localPort,
HttpParams params
) throws IOException, UnknownHostException, ConnectTimeoutException;
/**
* Checks whether a socket provides a secure connection.
* The socket must be {@link #connectSocket connected}
* by this factory.
* The factory will <i>not</i> perform I/O operations
* in this method.
* <br/>
* As a rule of thumb, plain sockets are not secure and
* TLS/SSL sockets are secure. However, there may be
* application specific deviations. For example, a plain
* socket to a host in the same intranet ("trusted zone")
* could be considered secure. On the other hand, a
* TLS/SSL socket could be considered insecure based on
* the cipher suite chosen for the connection.
*
* @param sock the connected socket to check
*
* @return <code>true</code> if the connection of the socket
* should be considered secure, or
* <code>false</code> if it should not
*
* @throws IllegalArgumentException
* if the argument is invalid, for example because it is
* not a connected socket or was created by a different
* socket factory.
* Note that socket factories are <i>not</i> required to
* check these conditions, they may simply return a default
* value when called with an invalid socket argument.
*/
boolean isSecure(Socket sock)
throws IllegalArgumentException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* A {@link SocketFactory SocketFactory} for layered sockets (SSL/TLS).
* See there for things to consider when implementing a socket factory.
*
* @since 4.0
*
* @deprecated use {@link SchemeSocketFactory}
*/
@Deprecated
public interface LayeredSocketFactory extends SocketFactory {
/**
* Returns a socket connected to the given host that is layered over an
* existing socket. Used primarily for creating secure sockets through
* proxies.
*
* @param socket the existing socket
* @param host the host name/IP
* @param port the port on the host
* @param autoClose a flag for closing the underling socket when the created
* socket is closed
*
* @return Socket a new socket
*
* @throws IOException if an I/O error occurs while creating the socket
* @throws UnknownHostException if the IP address of the host cannot be
* determined
*/
Socket createSocket(
Socket socket,
String host,
int port,
boolean autoClose
) throws IOException, UnknownHostException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* The default class for creating plain (unencrypted) sockets.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* </ul>
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
@Immutable
public class PlainSocketFactory implements SocketFactory, SchemeSocketFactory {
private final HostNameResolver nameResolver;
/**
* Gets the default factory.
*
* @return the default factory
*/
public static PlainSocketFactory getSocketFactory() {
return new PlainSocketFactory();
}
@Deprecated
public PlainSocketFactory(final HostNameResolver nameResolver) {
super();
this.nameResolver = nameResolver;
}
public PlainSocketFactory() {
super();
this.nameResolver = null;
}
/**
* @param params Optional parameters. Parameters passed to this method will have no effect.
* This method will create a unconnected instance of {@link Socket} class
* using default constructor.
*
* @since 4.1
*/
public Socket createSocket(final HttpParams params) {
return new Socket();
}
public Socket createSocket() {
return new Socket();
}
/**
* @since 4.1
*/
public Socket connectSocket(
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params) throws IOException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Socket sock = socket;
if (sock == null) {
sock = createSocket();
}
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
try {
sock.setSoTimeout(soTimeout);
sock.connect(remoteAddress, connTimeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
return sock;
}
/**
* Checks whether a socket connection is secure.
* This factory creates plain socket connections
* which are not considered secure.
*
* @param sock the connected socket
*
* @return <code>false</code>
*
* @throws IllegalArgumentException if the argument is invalid
*/
public final boolean isSecure(Socket sock)
throws IllegalArgumentException {
if (sock == null) {
throw new IllegalArgumentException("Socket may not be null.");
}
// This check is performed last since it calls a method implemented
// by the argument object. getClass() is final in java.lang.Object.
if (sock.isClosed()) {
throw new IllegalArgumentException("Socket is closed.");
}
return false;
}
/**
* @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
*/
@Deprecated
public Socket connectSocket(
final Socket socket,
final String host, int port,
final InetAddress localAddress, int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetSocketAddress local = null;
if (localAddress != null || localPort > 0) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
local = new InetSocketAddress(localAddress, localPort);
}
InetAddress remoteAddress;
if (this.nameResolver != null) {
remoteAddress = this.nameResolver.resolve(host);
} else {
remoteAddress = InetAddress.getByName(host);
}
InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
return connectSocket(socket, remote, local, params);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.params.HttpParams;
/**
* A factory for creating, initializing and connecting sockets. The factory encapsulates the logic
* for establishing a socket connection.
*
* @since 4.1
*/
public interface SchemeSocketFactory {
/**
* Creates a new, unconnected socket. The socket should subsequently be passed to
* {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}.
*
* @param params Optional {@link HttpParams parameters}. In most cases these parameters
* will not be required and will have no effect, as usually socket
* initialization should take place in the
* {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
* method. However, in rare cases one may want to pass additional parameters
* to this method in order to create a customized {@link Socket} instance,
* for instance bound to a SOCKS proxy server.
*
* @return a new socket
*
* @throws IOException if an I/O error occurs while creating the socket
*/
Socket createSocket(HttpParams params) throws IOException;
/**
* Connects a socket to the target host with the given remote address.
*
* @param sock the socket to connect, as obtained from
* {@link #createSocket(HttpParams) createSocket}.
* <code>null</code> indicates that a new socket
* should be created and connected.
* @param remoteAddress the remote address to connect to
* @param localAddress the local address to bind the socket to, or
* <code>null</code> for any
* @param params additional {@link HttpParams parameters} for connecting
*
* @return the connected socket. The returned object may be different
* from the <code>sock</code> argument if this factory supports
* a layered protocol.
*
* @throws IOException if an I/O error occurs
* @throws UnknownHostException if the IP address of the target host
* can not be determined
* @throws ConnectTimeoutException if the socket cannot be connected
* within the time limit defined in the <code>params</code>
*/
Socket connectSocket(
Socket sock,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException;
/**
* Checks whether a socket provides a secure connection. The socket must be
* {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams) connected}
* by this factory. The factory will <i>not</i> perform I/O operations in this method.
* <p>
* As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However,
* there may be application specific deviations. For example, a plain socket to a host in the
* same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL
* socket could be considered insecure based on the cipher suite chosen for the connection.
*
* @param sock the connected socket to check
*
* @return <code>true</code> if the connection of the socket
* should be considered secure, or
* <code>false</code> if it should not
*
* @throws IllegalArgumentException
* if the argument is invalid, for example because it is
* not a connected socket or was created by a different
* socket factory.
* Note that socket factories are <i>not</i> required to
* check these conditions, they may simply return a default
* value when called with an invalid socket argument.
*/
boolean isSecure(Socket sock) throws IllegalArgumentException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
/**
* Hostname to IP address resolver.
*
* @since 4.0
*
* @deprecated Do not use
*/
@Deprecated
public interface HostNameResolver {
/**
* Resolves given hostname to its IP address
*
* @param hostname the hostname.
* @return IP address.
* @throws IOException
*/
InetAddress resolve (String hostname) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
@Deprecated
class LayeredSchemeSocketFactoryAdaptor extends SchemeSocketFactoryAdaptor
implements LayeredSchemeSocketFactory {
private final LayeredSocketFactory factory;
LayeredSchemeSocketFactoryAdaptor(final LayeredSocketFactory factory) {
super(factory);
this.factory = factory;
}
public Socket createLayeredSocket(
final Socket socket,
final String target, int port,
boolean autoClose) throws IOException, UnknownHostException {
return this.factory.createSocket(socket, target, port, autoClose);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.ThreadSafe;
/**
* A set of supported protocol {@link Scheme}s.
* Schemes are identified by lowercase names.
*
* @since 4.0
*/
@ThreadSafe
public final class SchemeRegistry {
/** The available schemes in this registry. */
private final ConcurrentHashMap<String,Scheme> registeredSchemes;
/**
* Creates a new, empty scheme registry.
*/
public SchemeRegistry() {
super();
registeredSchemes = new ConcurrentHashMap<String,Scheme>();
}
/**
* Obtains a scheme by name.
*
* @param name the name of the scheme to look up (in lowercase)
*
* @return the scheme, never <code>null</code>
*
* @throws IllegalStateException
* if the scheme with the given name is not registered
*/
public final Scheme getScheme(String name) {
Scheme found = get(name);
if (found == null) {
throw new IllegalStateException
("Scheme '"+name+"' not registered.");
}
return found;
}
/**
* Obtains the scheme for a host.
* Convenience method for <code>getScheme(host.getSchemeName())</pre>
*
* @param host the host for which to obtain the scheme
*
* @return the scheme for the given host, never <code>null</code>
*
* @throws IllegalStateException
* if a scheme with the respective name is not registered
*/
public final Scheme getScheme(HttpHost host) {
if (host == null) {
throw new IllegalArgumentException("Host must not be null.");
}
return getScheme(host.getSchemeName());
}
/**
* Obtains a scheme by name, if registered.
*
* @param name the name of the scheme to look up (in lowercase)
*
* @return the scheme, or
* <code>null</code> if there is none by this name
*/
public final Scheme get(String name) {
if (name == null)
throw new IllegalArgumentException("Name must not be null.");
// leave it to the caller to use the correct name - all lowercase
//name = name.toLowerCase();
Scheme found = registeredSchemes.get(name);
return found;
}
/**
* Registers a scheme.
* The scheme can later be retrieved by its name
* using {@link #getScheme(String) getScheme} or {@link #get get}.
*
* @param sch the scheme to register
*
* @return the scheme previously registered with that name, or
* <code>null</code> if none was registered
*/
public final Scheme register(Scheme sch) {
if (sch == null)
throw new IllegalArgumentException("Scheme must not be null.");
Scheme old = registeredSchemes.put(sch.getName(), sch);
return old;
}
/**
* Unregisters a scheme.
*
* @param name the name of the scheme to unregister (in lowercase)
*
* @return the unregistered scheme, or
* <code>null</code> if there was none
*/
public final Scheme unregister(String name) {
if (name == null)
throw new IllegalArgumentException("Name must not be null.");
// leave it to the caller to use the correct name - all lowercase
//name = name.toLowerCase();
Scheme gone = registeredSchemes.remove(name);
return gone;
}
/**
* Obtains the names of the registered schemes.
*
* @return List containing registered scheme names.
*/
public final List<String> getSchemeNames() {
return new ArrayList<String>(registeredSchemes.keySet());
}
/**
* Populates the internal collection of registered {@link Scheme protocol schemes}
* with the content of the map passed as a parameter.
*
* @param map protocol schemes
*/
public void setItems(final Map<String, Scheme> map) {
if (map == null) {
return;
}
registeredSchemes.clear();
registeredSchemes.putAll(map);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.scheme;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* A {@link SocketFactory SocketFactory} for layered sockets (SSL/TLS).
* See there for things to consider when implementing a socket factory.
*
* @since 4.1
*/
public interface LayeredSchemeSocketFactory extends SchemeSocketFactory {
/**
* Returns a socket connected to the given host that is layered over an
* existing socket. Used primarily for creating secure sockets through
* proxies.
*
* @param socket the existing socket
* @param target the name of the target host.
* @param port the port to connect to on the target host
* @param autoClose a flag for closing the underling socket when the created
* socket is closed
*
* @return Socket a new socket
*
* @throws IOException if an I/O error occurs while creating the socket
* @throws UnknownHostException if the IP address of the host cannot be
* determined
*/
Socket createLayeredSocket(
Socket socket,
String target,
int port,
boolean autoClose
) throws IOException, UnknownHostException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.io.InterruptedIOException;
import org.apache.ogt.http.annotation.Immutable;
/**
* A timeout while connecting to an HTTP server or waiting for an
* available connection from an HttpConnectionManager.
*
*
* @since 4.0
*/
@Immutable
public class ConnectTimeoutException extends InterruptedIOException {
private static final long serialVersionUID = -4816682903149535989L;
/**
* Creates a ConnectTimeoutException with a <tt>null</tt> detail message.
*/
public ConnectTimeoutException() {
super();
}
/**
* Creates a ConnectTimeoutException with the specified detail message.
*
* @param message The exception detail message
*/
public ConnectTimeoutException(final String message) {
super(message);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Interface for deciding how long a connection can remain
* idle before being reused.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*/
public interface ConnectionKeepAliveStrategy {
/**
* Returns the duration of time which this connection can be safely kept
* idle. If the connection is left idle for longer than this period of time,
* it MUST not reused. A value of 0 or less may be returned to indicate that
* there is no suitable suggestion.
*
* When coupled with a {@link ConnectionReuseStrategy}, if
* {@link ConnectionReuseStrategy#keepAlive(HttpResponse, HttpContext)}
* returns true, this allows you to control how long the reuse will last. If
* keepAlive returns false, this should have no meaningful impact
*
* @param response
* The last response received over the connection.
* @param context
* the context in which the connection is being used.
*
* @return the duration in ms for which it is safe to keep the connection
* idle, or <=0 if no suggested duration.
*/
long getKeepAliveDuration(HttpResponse response, HttpContext context);
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.net.ConnectException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.Immutable;
/**
* A {@link ConnectException} that specifies the {@link HttpHost} that was
* being connected to.
*
* @since 4.0
*/
@Immutable
public class HttpHostConnectException extends ConnectException {
private static final long serialVersionUID = -3194482710275220224L;
private final HttpHost host;
public HttpHostConnectException(final HttpHost host, final ConnectException cause) {
super("Connection to " + host + " refused");
this.host = host;
initCause(cause);
}
public HttpHost getHost() {
return this.host;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import javax.net.ssl.SSLException;
import org.apache.ogt.http.annotation.Immutable;
/**
* The Strict HostnameVerifier works the same way as Sun Java 1.4, Sun
* Java 5, Sun Java 6-rc. It's also pretty close to IE6. This
* implementation appears to be compliant with RFC 2818 for dealing with
* wildcards.
* <p/>
* The hostname must match either the first CN, or any of the subject-alts.
* A wildcard can occur in the CN, and in any of the subject-alts. The
* one divergence from IE6 is how we only check the first CN. IE6 allows
* a match against any of the CNs present. We decided to follow in
* Sun Java 1.4's footsteps and only check the first CN. (If you need
* to check all the CN's, feel free to write your own implementation!).
* <p/>
* A wildcard such as "*.foo.com" matches only subdomains in the same
* level, for example "a.foo.com". It does not match deeper subdomains
* such as "a.b.foo.com".
*
*
* @since 4.0
*/
@Immutable
public class StrictHostnameVerifier extends AbstractVerifier {
public final void verify(
final String host,
final String[] cns,
final String[] subjectAlts) throws SSLException {
verify(host, cns, subjectAlts, true);
}
@Override
public final String toString() {
return "STRICT";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import org.apache.ogt.http.annotation.Immutable;
/**
* The ALLOW_ALL HostnameVerifier essentially turns hostname verification
* off. This implementation is a no-op, and never throws the SSLException.
*
*
* @since 4.0
*/
@Immutable
public class AllowAllHostnameVerifier extends AbstractVerifier {
public final void verify(
final String host,
final String[] cns,
final String[] subjectAlts) {
// Allow everything - so never blowup.
}
@Override
public final String toString() {
return "ALLOW_ALL";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import javax.net.ssl.SSLException;
import org.apache.ogt.http.annotation.Immutable;
/**
* The HostnameVerifier that works the same way as Curl and Firefox.
* <p/>
* The hostname must match either the first CN, or any of the subject-alts.
* A wildcard can occur in the CN, and in any of the subject-alts.
* <p/>
* The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard
* (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains,
* including "a.b.foo.com".
*
*
* @since 4.0
*/
@Immutable
public class BrowserCompatHostnameVerifier extends AbstractVerifier {
public final void verify(
final String host,
final String[] cns,
final String[] subjectAlts) throws SSLException {
verify(host, cns, subjectAlts, false);
}
@Override
public final String toString() {
return "BROWSER_COMPATIBLE";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* A trust strategy that accepts self-signed certificates as trusted. Verification of all other
* certificates is done by the trust manager configured in the SSL context.
*
* @since 4.1
*/
public class TrustSelfSignedStrategy implements TrustStrategy {
public boolean isTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
return chain.length == 1;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.cert.X509Certificate;
/**
* Interface for checking if a hostname matches the names stored inside the
* server's X.509 certificate. This interface extends
* {@link javax.net.ssl.HostnameVerifier}, but it is recommended to use
* methods added by X509HostnameVerifier.
*
* @since 4.0
*/
public interface X509HostnameVerifier extends HostnameVerifier {
/**
* Verifies that the host name is an acceptable match with the server's
* authentication scheme based on the given {@link SSLSocket}.
*
* @param host the host.
* @param ssl the SSL socket.
* @throws IOException if an I/O error occurs or the verification process
* fails.
*/
void verify(String host, SSLSocket ssl) throws IOException;
/**
* Verifies that the host name is an acceptable match with the server's
* authentication scheme based on the given {@link X509Certificate}.
*
* @param host the host.
* @param cert the certificate.
* @throws SSLException if the verification process fails.
*/
void verify(String host, X509Certificate cert) throws SSLException;
/**
* Checks to see if the supplied hostname matches any of the supplied CNs
* or "DNS" Subject-Alts. Most implementations only look at the first CN,
* and ignore any additional CNs. Most implementations do look at all of
* the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
* according to RFC 2818.
*
* @param cns CN fields, in order, as extracted from the X.509
* certificate.
* @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
* from the X.509 certificate.
* @param host The hostname to verify.
* @throws SSLException if the verification process fails.
*/
void verify(String host, String[] cns, String[] subjectAlts)
throws SSLException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* @since 4.1
*/
class TrustManagerDecorator implements X509TrustManager {
private final X509TrustManager trustManager;
private final TrustStrategy trustStrategy;
TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {
super();
this.trustManager = trustManager;
this.trustStrategy = trustStrategy;
}
public void checkClientTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
this.trustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
if (!this.trustStrategy.isTrusted(chain, authType)) {
this.trustManager.checkServerTrusted(chain, authType);
}
}
public X509Certificate[] getAcceptedIssuers() {
return this.trustManager.getAcceptedIssuers();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* A strategy to establish trustworthiness of certificates without consulting the trust manager
* configured in the actual SSL context. This interface can be used to override the standard
* JSSE certificate verification process.
*
* @since 4.1
*/
public interface TrustStrategy {
/**
* Determines whether the certificate chain can be trusted without consulting the trust manager
* configured in the actual SSL context. This method can be used to override the standard JSSE
* certificate verification process.
* <p>
* Please note that, if this method returns <code>false</code>, the trust manager configured
* in the actual SSL context can still clear the certificate as trusted.
*
* @param chain the peer certificate chain
* @param authType the authentication type based on the client certificate
* @return <code>true</code> if the certificate can be trusted without verification by
* the trust manager, <code>false</code> otherwise.
* @throws CertificateException thrown if the certificate is not trusted or invalid.
*/
boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.HostNameResolver;
import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory;
import org.apache.ogt.http.conn.scheme.LayeredSocketFactory;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
/**
* Layered socket factory for TLS/SSL connections.
* <p>
* SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of
* trusted certificates and to authenticate to the HTTPS server using a private key.
* <p>
* SSLSocketFactory will enable server authentication when supplied with
* a {@link KeyStore trust-store} file containing one or several trusted certificates. The client
* secure socket will reject the connection during the SSL session handshake if the target HTTPS
* server attempts to authenticate itself with a non-trusted certificate.
* <p>
* Use JDK keytool utility to import a trusted certificate and generate a trust-store file:
* <pre>
* keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
* </pre>
* <p>
* In special cases the standard trust verification process can be bypassed by using a custom
* {@link TrustStrategy}. This interface is primarily intended for allowing self-signed
* certificates to be accepted as trusted without having to add them to the trust-store file.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* </ul>
* <p>
* SSLSocketFactory will enable client authentication when supplied with
* a {@link KeyStore key-store} file containing a private key/public certificate
* pair. The client secure socket will use the private key to authenticate
* itself to the target HTTPS server during the SSL session handshake if
* requested to do so by the server.
* The target HTTPS server will in its turn verify the certificate presented
* by the client in order to establish client's authenticity
* <p>
* Use the following sequence of actions to generate a key-store file
* </p>
* <ul>
* <li>
* <p>
* Use JDK keytool utility to generate a new key
* <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
* For simplicity use the same password for the key as that of the key-store
* </p>
* </li>
* <li>
* <p>
* Issue a certificate signing request (CSR)
* <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
* </p>
* </li>
* <li>
* <p>
* Send the certificate request to the trusted Certificate Authority for signature.
* One may choose to act as her own CA and sign the certificate request using a PKI
* tool, such as OpenSSL.
* </p>
* </li>
* <li>
* <p>
* Import the trusted CA root certificate
* <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre>
* </p>
* </li>
* <li>
* <p>
* Import the PKCS#7 file containg the complete certificate chain
* <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre>
* </p>
* </li>
* <li>
* <p>
* Verify the content the resultant keystore file
* <pre>keytool -list -v -keystore my.keystore</pre>
* </p>
* </li>
* </ul>
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
@ThreadSafe
public class SSLSocketFactory implements LayeredSchemeSocketFactory, LayeredSocketFactory {
public static final String TLS = "TLS";
public static final String SSL = "SSL";
public static final String SSLV2 = "SSLv2";
public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
= new AllowAllHostnameVerifier();
public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
= new BrowserCompatHostnameVerifier();
public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER
= new StrictHostnameVerifier();
/**
* Gets the default factory, which uses the default JVM settings for secure
* connections.
*
* @return the default factory
*/
public static SSLSocketFactory getSocketFactory() {
return new SSLSocketFactory();
}
private final javax.net.ssl.SSLSocketFactory socketfactory;
private final HostNameResolver nameResolver;
// TODO: make final
private volatile X509HostnameVerifier hostnameVerifier;
private static SSLContext createSSLContext(
String algorithm,
final KeyStore keystore,
final String keystorePassword,
final KeyStore truststore,
final SecureRandom random,
final TrustStrategy trustStrategy)
throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
if (algorithm == null) {
algorithm = TLS;
}
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null);
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(truststore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
if (trustmanagers != null && trustStrategy != null) {
for (int i = 0; i < trustmanagers.length; i++) {
TrustManager tm = trustmanagers[i];
if (tm instanceof X509TrustManager) {
trustmanagers[i] = new TrustManagerDecorator(
(X509TrustManager) tm, trustStrategy);
}
}
}
SSLContext sslcontext = SSLContext.getInstance(algorithm);
sslcontext.init(keymanagers, trustmanagers, random);
return sslcontext;
}
private static SSLContext createDefaultSSLContext() {
try {
return createSSLContext(TLS, null, null, null, null, null);
} catch (Exception ex) {
throw new IllegalStateException("Failure initializing default SSL context", ex);
}
}
/**
* @deprecated Use {@link #SSLSocketFactory(String, KeyStore, String, KeyStore, SecureRandom, X509HostnameVerifier)}
*/
@Deprecated
public SSLSocketFactory(
final String algorithm,
final KeyStore keystore,
final String keystorePassword,
final KeyStore truststore,
final SecureRandom random,
final HostNameResolver nameResolver)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(createSSLContext(
algorithm, keystore, keystorePassword, truststore, random, null),
nameResolver);
}
/**
* @since 4.1
*/
public SSLSocketFactory(
String algorithm,
final KeyStore keystore,
final String keystorePassword,
final KeyStore truststore,
final SecureRandom random,
final X509HostnameVerifier hostnameVerifier)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(createSSLContext(
algorithm, keystore, keystorePassword, truststore, random, null),
hostnameVerifier);
}
/**
* @since 4.1
*/
public SSLSocketFactory(
String algorithm,
final KeyStore keystore,
final String keystorePassword,
final KeyStore truststore,
final SecureRandom random,
final TrustStrategy trustStrategy,
final X509HostnameVerifier hostnameVerifier)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(createSSLContext(
algorithm, keystore, keystorePassword, truststore, random, trustStrategy),
hostnameVerifier);
}
public SSLSocketFactory(
final KeyStore keystore,
final String keystorePassword,
final KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(TLS, keystore, keystorePassword, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
public SSLSocketFactory(
final KeyStore keystore,
final String keystorePassword)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{
this(TLS, keystore, keystorePassword, null, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
public SSLSocketFactory(
final KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(TLS, null, null, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
/**
* @since 4.1
*/
public SSLSocketFactory(
final TrustStrategy trustStrategy,
final X509HostnameVerifier hostnameVerifier)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(TLS, null, null, null, null, trustStrategy, hostnameVerifier);
}
/**
* @since 4.1
*/
public SSLSocketFactory(
final TrustStrategy trustStrategy)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(TLS, null, null, null, null, trustStrategy, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
public SSLSocketFactory(final SSLContext sslContext) {
this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
/**
* @deprecated Use {@link #SSLSocketFactory(SSLContext)}
*/
@Deprecated
public SSLSocketFactory(
final SSLContext sslContext, final HostNameResolver nameResolver) {
super();
this.socketfactory = sslContext.getSocketFactory();
this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
this.nameResolver = nameResolver;
}
/**
* @since 4.1
*/
public SSLSocketFactory(
final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
super();
this.socketfactory = sslContext.getSocketFactory();
this.hostnameVerifier = hostnameVerifier;
this.nameResolver = null;
}
private SSLSocketFactory() {
this(createDefaultSSLContext());
}
/**
* @param params Optional parameters. Parameters passed to this method will have no effect.
* This method will create a unconnected instance of {@link Socket} class.
* @since 4.1
*/
public Socket createSocket(final HttpParams params) throws IOException {
return this.socketfactory.createSocket();
}
@Deprecated
public Socket createSocket() throws IOException {
return this.socketfactory.createSocket();
}
/**
* @since 4.1
*/
public Socket connectSocket(
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Socket sock = socket != null ? socket : new Socket();
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
try {
sock.setSoTimeout(soTimeout);
sock.connect(remoteAddress, connTimeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
SSLSocket sslsock;
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
sslsock = (SSLSocket) sock;
} else {
sslsock = (SSLSocket) this.socketfactory.createSocket(
sock, remoteAddress.getHostName(), remoteAddress.getPort(), true);
}
if (this.hostnameVerifier != null) {
try {
this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock);
// verifyHostName() didn't blowup - good!
} catch (IOException iox) {
// close the socket before re-throwing the exception
try { sslsock.close(); } catch (Exception x) { /*ignore*/ }
throw iox;
}
}
return sslsock;
}
/**
* Checks whether a socket connection is secure.
* This factory creates TLS/SSL socket connections
* which, by default, are considered secure.
* <br/>
* Derived classes may override this method to perform
* runtime checks, for example based on the cypher suite.
*
* @param sock the connected socket
*
* @return <code>true</code>
*
* @throws IllegalArgumentException if the argument is invalid
*/
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
if (sock == null) {
throw new IllegalArgumentException("Socket may not be null");
}
// This instanceof check is in line with createSocket() above.
if (!(sock instanceof SSLSocket)) {
throw new IllegalArgumentException("Socket not created by this factory");
}
// This check is performed last since it calls the argument object.
if (sock.isClosed()) {
throw new IllegalArgumentException("Socket is closed");
}
return true;
}
/**
* @since 4.1
*/
public Socket createLayeredSocket(
final Socket socket,
final String host,
final int port,
final boolean autoClose) throws IOException, UnknownHostException {
SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
socket,
host,
port,
autoClose
);
if (this.hostnameVerifier != null) {
this.hostnameVerifier.verify(host, sslSocket);
}
// verifyHostName() didn't blowup - good!
return sslSocket;
}
@Deprecated
public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
if ( hostnameVerifier == null ) {
throw new IllegalArgumentException("Hostname verifier may not be null");
}
this.hostnameVerifier = hostnameVerifier;
}
public X509HostnameVerifier getHostnameVerifier() {
return this.hostnameVerifier;
}
/**
* @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
*/
@Deprecated
public Socket connectSocket(
final Socket socket,
final String host, int port,
final InetAddress localAddress, int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetSocketAddress local = null;
if (localAddress != null || localPort > 0) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
local = new InetSocketAddress(localAddress, localPort);
}
InetAddress remoteAddress;
if (this.nameResolver != null) {
remoteAddress = this.nameResolver.resolve(host);
} else {
remoteAddress = InetAddress.getByName(host);
}
InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
return connectSocket(socket, remote, local, params);
}
/**
* @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)}
*/
@Deprecated
public Socket createSocket(
final Socket socket,
final String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return createLayeredSocket(socket, host, port, autoClose);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.util.InetAddressUtils;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
/**
* Abstract base class for all standard {@link X509HostnameVerifier}
* implementations.
*
* @since 4.0
*/
@Immutable
public abstract class AbstractVerifier implements X509HostnameVerifier {
/**
* This contains a list of 2nd-level domains that aren't allowed to
* have wildcards when combined with country-codes.
* For example: [*.co.uk].
* <p/>
* The [*.co.uk] problem is an interesting one. Should we just hope
* that CA's would never foolishly allow such a certificate to happen?
* Looks like we're the only implementation guarding against this.
* Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
*/
private final static String[] BAD_COUNTRY_2LDS =
{ "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
"lg", "ne", "net", "or", "org" };
static {
// Just in case developer forgot to manually sort the array. :-)
Arrays.sort(BAD_COUNTRY_2LDS);
}
public AbstractVerifier() {
super();
}
public final void verify(String host, SSLSocket ssl)
throws IOException {
if(host == null) {
throw new NullPointerException("host to verify is null");
}
SSLSession session = ssl.getSession();
if(session == null) {
// In our experience this only happens under IBM 1.4.x when
// spurious (unrelated) certificates show up in the server'
// chain. Hopefully this will unearth the real problem:
InputStream in = ssl.getInputStream();
in.available();
/*
If you're looking at the 2 lines of code above because
you're running into a problem, you probably have two
options:
#1. Clean up the certificate chain that your server
is presenting (e.g. edit "/etc/apache2/server.crt"
or wherever it is your server's certificate chain
is defined).
OR
#2. Upgrade to an IBM 1.5.x or greater JVM, or switch
to a non-IBM JVM.
*/
// If ssl.getInputStream().available() didn't cause an
// exception, maybe at least now the session is available?
session = ssl.getSession();
if(session == null) {
// If it's still null, probably a startHandshake() will
// unearth the real problem.
ssl.startHandshake();
// Okay, if we still haven't managed to cause an exception,
// might as well go for the NPE. Or maybe we're okay now?
session = ssl.getSession();
}
}
Certificate[] certs = session.getPeerCertificates();
X509Certificate x509 = (X509Certificate) certs[0];
verify(host, x509);
}
public final boolean verify(String host, SSLSession session) {
try {
Certificate[] certs = session.getPeerCertificates();
X509Certificate x509 = (X509Certificate) certs[0];
verify(host, x509);
return true;
}
catch(SSLException e) {
return false;
}
}
public final void verify(String host, X509Certificate cert)
throws SSLException {
String[] cns = getCNs(cert);
String[] subjectAlts = getSubjectAlts(cert, host);
verify(host, cns, subjectAlts);
}
public final void verify(final String host, final String[] cns,
final String[] subjectAlts,
final boolean strictWithSubDomains)
throws SSLException {
// Build the list of names we're going to check. Our DEFAULT and
// STRICT implementations of the HostnameVerifier only use the
// first CN provided. All other CNs are ignored.
// (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
LinkedList<String> names = new LinkedList<String>();
if(cns != null && cns.length > 0 && cns[0] != null) {
names.add(cns[0]);
}
if(subjectAlts != null) {
for (String subjectAlt : subjectAlts) {
if (subjectAlt != null) {
names.add(subjectAlt);
}
}
}
if(names.isEmpty()) {
String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
throw new SSLException(msg);
}
// StringBuilder for building the error message.
StringBuilder buf = new StringBuilder();
// We're can be case-insensitive when comparing the host we used to
// establish the socket to the hostname in the certificate.
String hostName = host.trim().toLowerCase(Locale.ENGLISH);
boolean match = false;
for(Iterator<String> it = names.iterator(); it.hasNext();) {
// Don't trim the CN, though!
String cn = it.next();
cn = cn.toLowerCase(Locale.ENGLISH);
// Store CN in StringBuilder in case we need to report an error.
buf.append(" <");
buf.append(cn);
buf.append('>');
if(it.hasNext()) {
buf.append(" OR");
}
// The CN better have at least two dots if it wants wildcard
// action. It also can't be [*.co.uk] or [*.co.jp] or
// [*.org.uk], etc...
boolean doWildcard = cn.startsWith("*.") &&
cn.lastIndexOf('.') >= 0 &&
acceptableCountryWildcard(cn) &&
!isIPAddress(host);
if(doWildcard) {
match = hostName.endsWith(cn.substring(1));
if(match && strictWithSubDomains) {
// If we're in strict mode, then [*.foo.com] is not
// allowed to match [a.b.foo.com]
match = countDots(hostName) == countDots(cn);
}
} else {
match = hostName.equals(cn);
}
if(match) {
break;
}
}
if(!match) {
throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
}
}
public static boolean acceptableCountryWildcard(String cn) {
int cnLen = cn.length();
if(cnLen >= 7 && cnLen <= 9) {
// Look for the '.' in the 3rd-last position:
if(cn.charAt(cnLen - 3) == '.') {
// Trim off the [*.] and the [.XX].
String s = cn.substring(2, cnLen - 3);
// And test against the sorted array of bad 2lds:
int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
return x < 0;
}
}
return true;
}
public static String[] getCNs(X509Certificate cert) {
LinkedList<String> cnList = new LinkedList<String>();
/*
Sebastian Hauer's original StrictSSLProtocolSocketFactory used
getName() and had the following comment:
Parses a X.500 distinguished name for the value of the
"Common Name" field. This is done a bit sloppy right
now and should probably be done a bit more according to
<code>RFC 2253</code>.
I've noticed that toString() seems to do a better job than
getName() on these X500Principal objects, so I'm hoping that
addresses Sebastian's concern.
For example, getName() gives me this:
1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
whereas toString() gives me this:
EMAILADDRESS=juliusdavies@cucbc.com
Looks like toString() even works with non-ascii domain names!
I tested it with "花子.co.jp" and it worked fine.
*/
String subjectPrincipal = cert.getSubjectX500Principal().toString();
StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
while(st.hasMoreTokens()) {
String tok = st.nextToken();
int x = tok.indexOf("CN=");
if(x >= 0) {
cnList.add(tok.substring(x + 3));
}
}
if(!cnList.isEmpty()) {
String[] cns = new String[cnList.size()];
cnList.toArray(cns);
return cns;
} else {
return null;
}
}
/**
* Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
* Returns null if there aren't any.
*
* @param cert X509Certificate
* @param hostname
* @return Array of SubjectALT DNS or IP names stored in the certificate.
*/
private static String[] getSubjectAlts(
final X509Certificate cert, final String hostname) {
int subjectType;
if (isIPAddress(hostname)) {
subjectType = 7;
} else {
subjectType = 2;
}
LinkedList<String> subjectAltList = new LinkedList<String>();
Collection<List<?>> c = null;
try {
c = cert.getSubjectAlternativeNames();
}
catch(CertificateParsingException cpe) {
Logger.getLogger(AbstractVerifier.class.getName())
.log(Level.FINE, "Error parsing certificate.", cpe);
}
if(c != null) {
for (List<?> aC : c) {
List<?> list = aC;
int type = ((Integer) list.get(0)).intValue();
if (type == subjectType) {
String s = (String) list.get(1);
subjectAltList.add(s);
}
}
}
if(!subjectAltList.isEmpty()) {
String[] subjectAlts = new String[subjectAltList.size()];
subjectAltList.toArray(subjectAlts);
return subjectAlts;
} else {
return null;
}
}
/**
* Extracts the array of SubjectAlt DNS names from an X509Certificate.
* Returns null if there aren't any.
* <p/>
* Note: Java doesn't appear able to extract international characters
* from the SubjectAlts. It can only extract international characters
* from the CN field.
* <p/>
* (Or maybe the version of OpenSSL I'm using to test isn't storing the
* international characters correctly in the SubjectAlts?).
*
* @param cert X509Certificate
* @return Array of SubjectALT DNS names stored in the certificate.
*/
public static String[] getDNSSubjectAlts(X509Certificate cert) {
return getSubjectAlts(cert, null);
}
/**
* Counts the number of dots "." in a string.
* @param s string to count dots from
* @return number of dots
*/
public static int countDots(final String s) {
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '.') {
count++;
}
}
return count;
}
private static boolean isIPAddress(final String hostname) {
return hostname != null &&
(InetAddressUtils.isIPv4Address(hostname) ||
InetAddressUtils.isIPv6Address(hostname));
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.params.HttpParams;
/**
* A factory for creating new {@link ClientConnectionManager} instances.
*
*
* @since 4.0
*/
public interface ClientConnectionManagerFactory {
ClientConnectionManager newInstance(
HttpParams params,
SchemeRegistry schemeRegistry);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.params.HttpParams;
/**
* A client-side connection that relies on outside logic to connect sockets to the
* appropriate hosts. It can be operated directly by an application, or through an
* {@link ClientConnectionOperator operator}.
*
* @since 4.0
*/
public interface OperatedClientConnection extends HttpClientConnection, HttpInetConnection {
/**
* Obtains the target host for this connection.
* If the connection is to a proxy but not tunnelled, this is
* the proxy. If the connection is tunnelled through a proxy,
* this is the target of the tunnel.
* <br/>
* The return value is well-defined only while the connection is open.
* It may change even while the connection is open,
* because of an {@link #update update}.
*
* @return the host to which this connection is opened
*/
HttpHost getTargetHost();
/**
* Indicates whether this connection is secure.
* The return value is well-defined only while the connection is open.
* It may change even while the connection is open,
* because of an {@link #update update}.
*
* @return <code>true</code> if this connection is secure,
* <code>false</code> otherwise
*/
boolean isSecure();
/**
* Obtains the socket for this connection.
* The return value is well-defined only while the connection is open.
* It may change even while the connection is open,
* because of an {@link #update update}.
*
* @return the socket for communicating with the
* {@link #getTargetHost target host}
*/
Socket getSocket();
/**
* Signals that this connection is in the process of being open.
* <p>
* By calling this method, the connection can be re-initialized
* with a new Socket instance before {@link #openCompleted} is called.
* This enabled the connection to close that socket if
* {@link org.apache.ogt.http.HttpConnection#shutdown shutdown}
* is called before it is fully open. Closing an unconnected socket
* will interrupt a thread that is blocked on the connect.
* Otherwise, that thread will either time out on the connect,
* or it returns successfully and then opens this connection
* which was just shut down.
* <p>
* This method can be called multiple times if the connection
* is layered over another protocol. <b>Note:</b> This method
* will <i>not</i> close the previously used socket. It is
* the caller's responsibility to close that socket if it is
* no longer required.
* <p>
* The caller must invoke {@link #openCompleted} in order to complete
* the process.
*
* @param sock the unconnected socket which is about to
* be connected.
* @param target the target host of this connection
*/
void opening(Socket sock, HttpHost target)
throws IOException;
/**
* Signals that the connection has been successfully open.
* An attempt to call this method on an open connection will cause
* an exception.
*
* @param secure <code>true</code> if this connection is secure, for
* example if an <code>SSLSocket</code> is used, or
* <code>false</code> if it is not secure
* @param params parameters for this connection. The parameters will
* be used when creating dependent objects, for example
* to determine buffer sizes.
*/
void openCompleted(boolean secure, HttpParams params)
throws IOException;
/**
* Updates this connection.
* A connection can be updated only while it is open.
* Updates are used for example when a tunnel has been established,
* or when a TLS/SSL connection has been layered on top of a plain
* socket connection.
* <br/>
* <b>Note:</b> Updating the connection will <i>not</i> close the
* previously used socket. It is the caller's responsibility to close
* that socket if it is no longer required.
*
* @param sock the new socket for communicating with the target host,
* or <code>null</code> to continue using the old socket.
* If <code>null</code> is passed, helper objects that
* depend on the socket should be re-used. In that case,
* some changes in the parameters will not take effect.
* @param target the new target host of this connection
* @param secure <code>true</code> if this connection is now secure,
* <code>false</code> if it is not secure
* @param params new parameters for this connection
*/
void update(Socket sock, HttpHost target,
boolean secure, HttpParams params)
throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* ClientConnectionOperator represents a strategy for creating
* {@link OperatedClientConnection} instances and updating the underlying
* {@link Socket} of those objects. Implementations will most likely make use
* of {@link SchemeSocketFactory}s to create {@link Socket} instances.
* <p>
* The methods in this interface allow the creation of plain and layered
* sockets. Creating a tunnelled connection through a proxy, however,
* is not within the scope of the operator.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*/
public interface ClientConnectionOperator {
/**
* Creates a new connection that can be operated.
*
* @return a new, unopened connection for use with this operator
*/
OperatedClientConnection createConnection();
/**
* Opens a connection to the given target host.
*
* @param conn the connection to open
* @param target the target host to connect to
* @param local the local address to route from, or
* <code>null</code> for the default
* @param context the context for the connection
* @param params the parameters for the connection
*
* @throws IOException in case of a problem
*/
void openConnection(OperatedClientConnection conn,
HttpHost target,
InetAddress local,
HttpContext context,
HttpParams params)
throws IOException;
/**
* Updates a connection with a layered secure connection.
* The typical use of this method is to update a tunnelled plain
* connection (HTTP) to a secure TLS/SSL connection (HTTPS).
*
* @param conn the open connection to update
* @param target the target host for the updated connection.
* The connection must already be open or tunnelled
* to the host and port, but the scheme of the target
* will be used to create a layered connection.
* @param context the context for the connection
* @param params the parameters for the updated connection
*
* @throws IOException in case of a problem
*/
void updateSecureConnection(OperatedClientConnection conn,
HttpHost target,
HttpContext context,
HttpParams params)
throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import javax.net.ssl.SSLSession;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* Interface to access routing information of a client side connection.
*
* @since 4.1
*/
public interface HttpRoutedConnection extends HttpInetConnection {
/**
* Indicates whether this connection is secure.
* The return value is well-defined only while the connection is open.
* It may change even while the connection is open.
*
* @return <code>true</code> if this connection is secure,
* <code>false</code> otherwise
*/
boolean isSecure();
/**
* Obtains the current route of this connection.
*
* @return the route established so far, or
* <code>null</code> if not connected
*/
HttpRoute getRoute();
/**
* Obtains the SSL session of the underlying connection, if any.
* If this connection is open, and the underlying socket is an
* {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of
* that socket is obtained. This is a potentially blocking operation.
* <br/>
* <b>Note:</b> Whether the underlying socket is an SSL socket
* can not necessarily be determined via {@link #isSecure}.
* Plain sockets may be considered secure, for example if they are
* connected to a known host in the same network segment.
* On the other hand, SSL sockets may be considered insecure,
* for example depending on the chosen cipher suite.
*
* @return the underlying SSL session if available,
* <code>null</code> otherwise
*/
SSLSession getSSLSession();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSession;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A client-side connection with advanced connection logic.
* Instances are typically obtained from a connection manager.
*
* @since 4.0
*/
public interface ManagedClientConnection extends
HttpClientConnection, HttpRoutedConnection, ConnectionReleaseTrigger {
/**
* Indicates whether this connection is secure.
* The return value is well-defined only while the connection is open.
* It may change even while the connection is open.
*
* @return <code>true</code> if this connection is secure,
* <code>false</code> otherwise
*/
boolean isSecure();
/**
* Obtains the current route of this connection.
*
* @return the route established so far, or
* <code>null</code> if not connected
*/
HttpRoute getRoute();
/**
* Obtains the SSL session of the underlying connection, if any.
* If this connection is open, and the underlying socket is an
* {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of
* that socket is obtained. This is a potentially blocking operation.
* <br/>
* <b>Note:</b> Whether the underlying socket is an SSL socket
* can not necessarily be determined via {@link #isSecure}.
* Plain sockets may be considered secure, for example if they are
* connected to a known host in the same network segment.
* On the other hand, SSL sockets may be considered insecure,
* for example depending on the chosen cipher suite.
*
* @return the underlying SSL session if available,
* <code>null</code> otherwise
*/
SSLSession getSSLSession();
/**
* Opens this connection according to the given route.
*
* @param route the route along which to open. It will be opened to
* the first proxy if present, or directly to the target.
* @param context the context for opening this connection
* @param params the parameters for opening this connection
*
* @throws IOException in case of a problem
*/
void open(HttpRoute route, HttpContext context, HttpParams params)
throws IOException;
/**
* Indicates that a tunnel to the target has been established.
* The route is the one previously passed to {@link #open open}.
* Subsequently, {@link #layerProtocol layerProtocol} can be called
* to layer the TLS/SSL protocol on top of the tunnelled connection.
* <br/>
* <b>Note:</b> In HttpClient 3, a call to the corresponding method
* would automatically trigger the layering of the TLS/SSL protocol.
* This is not the case anymore, you can establish a tunnel without
* layering a new protocol over the connection.
*
* @param secure <code>true</code> if the tunnel should be considered
* secure, <code>false</code> otherwise
* @param params the parameters for tunnelling this connection
*
* @throws IOException in case of a problem
*/
void tunnelTarget(boolean secure, HttpParams params)
throws IOException;
/**
* Indicates that a tunnel to an intermediate proxy has been established.
* This is used exclusively for so-called <i>proxy chains</i>, where
* a request has to pass through multiple proxies before reaching the
* target. In that case, all proxies but the last need to be tunnelled
* when establishing the connection. Tunnelling of the last proxy to the
* target is optional and would be indicated via {@link #tunnelTarget}.
*
* @param next the proxy to which the tunnel was established.
* This is <i>not</i> the proxy <i>through</i> which
* the tunnel was established, but the new end point
* of the tunnel. The tunnel does <i>not</i> yet
* reach to the target, use {@link #tunnelTarget}
* to indicate an end-to-end tunnel.
* @param secure <code>true</code> if the connection should be
* considered secure, <code>false</code> otherwise
* @param params the parameters for tunnelling this connection
*
* @throws IOException in case of a problem
*/
void tunnelProxy(HttpHost next, boolean secure, HttpParams params)
throws IOException;
/**
* Layers a new protocol on top of a {@link #tunnelTarget tunnelled}
* connection. This is typically used to create a TLS/SSL connection
* through a proxy.
* The route is the one previously passed to {@link #open open}.
* It is not guaranteed that the layered connection is
* {@link #isSecure secure}.
*
* @param context the context for layering on top of this connection
* @param params the parameters for layering on top of this connection
*
* @throws IOException in case of a problem
*/
void layerProtocol(HttpContext context, HttpParams params)
throws IOException;
/**
* Marks this connection as being in a reusable communication state.
* The checkpoints for reuseable communication states (in the absence
* of pipelining) are before sending a request and after receiving
* the response in its entirety.
* The connection will automatically clear the checkpoint when
* used for communication. A call to this method indicates that
* the next checkpoint has been reached.
* <br/>
* A reusable communication state is necessary but not sufficient
* for the connection to be reused.
* A {@link #getRoute route} mismatch, the connection being closed,
* or other circumstances might prevent reuse.
*/
void markReusable();
/**
* Marks this connection as not being in a reusable state.
* This can be used immediately before releasing this connection
* to prevent its reuse. Reasons for preventing reuse include
* error conditions and the evaluation of a
* {@link org.apache.ogt.http.ConnectionReuseStrategy reuse strategy}.
* <br/>
* <b>Note:</b>
* It is <i>not</i> necessary to call here before writing to
* or reading from this connection. Communication attempts will
* automatically unmark the state as non-reusable. It can then
* be switched back using {@link #markReusable markReusable}.
*/
void unmarkReusable();
/**
* Indicates whether this connection is in a reusable communication state.
* See {@link #markReusable markReusable} and
* {@link #unmarkReusable unmarkReusable} for details.
*
* @return <code>true</code> if this connection is marked as being in
* a reusable communication state,
* <code>false</code> otherwise
*/
boolean isMarkedReusable();
/**
* Assigns a state object to this connection. Connection managers may make
* use of the connection state when allocating persistent connections.
*
* @param state The state object
*/
void setState(Object state);
/**
* Returns the state object associated with this connection.
*
* @return The state object
*/
Object getState();
/**
* Sets the duration that this connection can remain idle before it is
* reused. The connection should not be used again if this time elapses. The
* idle duration must be reset after each request sent over this connection.
* The elapsed time starts counting when the connection is released, which
* is typically after the headers (and any response body, if present) is
* fully consumed.
*/
void setIdleDuration(long duration, TimeUnit unit);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import java.net.InetAddress;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.params.HttpAbstractParamBean;
import org.apache.ogt.http.params.HttpParams;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate connection routing parameters
* using Java Beans conventions.
*
* @since 4.0
*/
@NotThreadSafe
public class ConnRouteParamBean extends HttpAbstractParamBean {
public ConnRouteParamBean (final HttpParams params) {
super(params);
}
/** @see ConnRoutePNames#DEFAULT_PROXY */
public void setDefaultProxy (final HttpHost defaultProxy) {
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, defaultProxy);
}
/** @see ConnRoutePNames#LOCAL_ADDRESS */
public void setLocalAddress (final InetAddress address) {
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, address);
}
/** @see ConnRoutePNames#FORCED_ROUTE */
public void setForcedRoute (final HttpRoute route) {
params.setParameter(ConnRoutePNames.FORCED_ROUTE, route);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
/**
* Parameter names for connection routing.
*
* @since 4.0
*/
public interface ConnRoutePNames {
/**
* Parameter for the default proxy.
* The default value will be used by some
* {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner}
* implementations, in particular the default implementation.
* <p>
* This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}.
* </p>
*/
public static final String DEFAULT_PROXY = "http.route.default-proxy";
/**
* Parameter for the local address.
* On machines with multiple network interfaces, this parameter
* can be used to select the network interface from which the
* connection originates.
* It will be interpreted by the standard
* {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner}
* implementations, in particular the default implementation.
* <p>
* This parameter expects a value of type {@link java.net.InetAddress}.
* </p>
*/
public static final String LOCAL_ADDRESS = "http.route.local-address";
/**
* Parameter for an forced route.
* The forced route will be interpreted by the standard
* {@link org.apache.ogt.http.conn.routing.HttpRoutePlanner HttpRoutePlanner}
* implementations.
* Instead of computing a route, the given forced route will be
* returned, even if it points to the wrong target host.
* <p>
* This parameter expects a value of type
* {@link org.apache.ogt.http.conn.routing.HttpRoute HttpRoute}.
* </p>
*/
public static final String FORCED_ROUTE = "http.route.forced-route";
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* An adaptor for manipulating HTTP connection management
* parameters in {@link HttpParams}.
*
* @since 4.0
*
* @see ConnManagerPNames
*/
@Deprecated
@Immutable
public final class ConnManagerParams implements ConnManagerPNames {
/** The default maximum number of connections allowed overall */
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;
/**
* Returns the timeout in milliseconds used when retrieving a
* {@link org.apache.ogt.http.conn.ManagedClientConnection} from the
* {@link org.apache.ogt.http.conn.ClientConnectionManager}.
*
* @return timeout in milliseconds.
*
* @deprecated use {@link HttpConnectionParams#getConnectionTimeout(HttpParams)}
*/
@Deprecated
public static long getTimeout(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(TIMEOUT, 0);
}
/**
* Sets the timeout in milliseconds used when retrieving a
* {@link org.apache.ogt.http.conn.ManagedClientConnection} from the
* {@link org.apache.ogt.http.conn.ClientConnectionManager}.
*
* @param timeout the timeout in milliseconds
*
* @deprecated use {@link HttpConnectionParams#setConnectionTimeout(HttpParams, int)}
*/
@Deprecated
public static void setTimeout(final HttpParams params, long timeout) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(TIMEOUT, timeout);
}
/** The default maximum number of connections allowed per host */
private static final ConnPerRoute DEFAULT_CONN_PER_ROUTE = new ConnPerRoute() {
public int getMaxForRoute(HttpRoute route) {
return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE;
}
};
/**
* Sets lookup interface for maximum number of connections allowed per route.
*
* @param params HTTP parameters
* @param connPerRoute lookup interface for maximum number of connections allowed
* per route
*
* @deprecated use {@link ThreadSafeClientConnManager#setMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute, int)}
*/
@Deprecated
public static void setMaxConnectionsPerRoute(final HttpParams params,
final ConnPerRoute connPerRoute) {
if (params == null) {
throw new IllegalArgumentException
("HTTP parameters must not be null.");
}
params.setParameter(MAX_CONNECTIONS_PER_ROUTE, connPerRoute);
}
/**
* Returns lookup interface for maximum number of connections allowed per route.
*
* @param params HTTP parameters
*
* @return lookup interface for maximum number of connections allowed per route.
*
* @deprecated use {@link ThreadSafeClientConnManager#getMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute)}
*/
@Deprecated
public static ConnPerRoute getMaxConnectionsPerRoute(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException
("HTTP parameters must not be null.");
}
ConnPerRoute connPerRoute = (ConnPerRoute) params.getParameter(MAX_CONNECTIONS_PER_ROUTE);
if (connPerRoute == null) {
connPerRoute = DEFAULT_CONN_PER_ROUTE;
}
return connPerRoute;
}
/**
* Sets the maximum number of connections allowed.
*
* @param params HTTP parameters
* @param maxTotalConnections The maximum number of connections allowed.
*
* @deprecated use {@link ThreadSafeClientConnManager#setMaxTotal(int)}
*/
@Deprecated
public static void setMaxTotalConnections(
final HttpParams params,
int maxTotalConnections) {
if (params == null) {
throw new IllegalArgumentException
("HTTP parameters must not be null.");
}
params.setIntParameter(MAX_TOTAL_CONNECTIONS, maxTotalConnections);
}
/**
* Gets the maximum number of connections allowed.
*
* @param params HTTP parameters
*
* @return The maximum number of connections allowed.
*
* @deprecated use {@link ThreadSafeClientConnManager#getMaxTotal()}
*/
@Deprecated
public static int getMaxTotalConnections(
final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException
("HTTP parameters must not be null.");
}
return params.getIntParameter(MAX_TOTAL_CONNECTIONS, DEFAULT_MAX_TOTAL_CONNECTIONS);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
/**
* Parameter names for HTTP client connections.
*
* @since 4.0
*/
public interface ConnConnectionPNames {
/**
* Defines the maximum number of ignorable lines before we expect
* a HTTP response's status line.
* <p>
* With HTTP/1.1 persistent connections, the problem arises that
* broken scripts could return a wrong Content-Length
* (there are more bytes sent than specified).
* Unfortunately, in some cases, this cannot be detected after the
* bad response, but only before the next one.
* So HttpClient must be able to skip those surplus lines this way.
* </p>
* <p>
* This parameter expects a value of type {@link Integer}.
* 0 disallows all garbage/empty lines before the status line.
* Use {@link java.lang.Integer#MAX_VALUE} for unlimited number.
* </p>
*/
public static final String MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.params.HttpAbstractParamBean;
import org.apache.ogt.http.params.HttpParams;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate connection manager parameters
* using Java Beans conventions.
*
* @since 4.0
*/
@NotThreadSafe
@Deprecated
public class ConnManagerParamBean extends HttpAbstractParamBean {
public ConnManagerParamBean (final HttpParams params) {
super(params);
}
public void setTimeout (final long timeout) {
params.setLongParameter(ConnManagerPNames.TIMEOUT, timeout);
}
/** @see ConnManagerPNames#MAX_TOTAL_CONNECTIONS */
@Deprecated
public void setMaxTotalConnections (final int maxConnections) {
params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, maxConnections);
}
/** @see ConnManagerPNames#MAX_CONNECTIONS_PER_ROUTE */
@Deprecated
public void setConnectionsPerRoute(final ConnPerRouteBean connPerRoute) {
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, connPerRoute);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.params.CoreConnectionPNames;
/**
* Parameter names for connection managers in HttpConn.
*
* @since 4.0
*/
@Deprecated
public interface ConnManagerPNames {
/**
* Defines the timeout in milliseconds used when retrieving an instance of
* {@link org.apache.ogt.http.conn.ManagedClientConnection} from the
* {@link org.apache.ogt.http.conn.ClientConnectionManager}.
* <p>
* This parameter expects a value of type {@link Long}.
* <p>
* @deprecated use {@link CoreConnectionPNames#CONNECTION_TIMEOUT}
*/
@Deprecated
public static final String TIMEOUT = "http.conn-manager.timeout";
/**
* Defines the maximum number of connections per route.
* This limit is interpreted by client connection managers
* and applies to individual manager instances.
* <p>
* This parameter expects a value of type {@link ConnPerRoute}.
* <p>
* @deprecated use {@link ThreadSafeClientConnManager#setMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute, int)},
* {@link ThreadSafeClientConnManager#getMaxForRoute(org.apache.ogt.http.conn.routing.HttpRoute)}
*/
@Deprecated
public static final String MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route";
/**
* Defines the maximum number of connections in total.
* This limit is interpreted by client connection managers
* and applies to individual manager instances.
* <p>
* This parameter expects a value of type {@link Integer}.
* <p>
* @deprecated use {@link ThreadSafeClientConnManager#setMaxTotal(int)},
* {@link ThreadSafeClientConnManager#getMaxTotal()}
*/
@Deprecated
public static final String MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.params.HttpAbstractParamBean;
import org.apache.ogt.http.params.HttpParams;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate HTTP client connection parameters
* using Java Beans conventions.
*
* @since 4.0
*/
@NotThreadSafe
public class ConnConnectionParamBean extends HttpAbstractParamBean {
public ConnConnectionParamBean (final HttpParams params) {
super(params);
}
/**
* @see ConnConnectionPNames#MAX_STATUS_LINE_GARBAGE
*/
public void setMaxStatusLineGarbage (final int maxStatusLineGarbage) {
params.setIntParameter(ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE, maxStatusLineGarbage);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* This class maintains a map of HTTP routes to maximum number of connections allowed
* for those routes. This class can be used by pooling
* {@link org.apache.ogt.http.conn.ClientConnectionManager connection managers} for
* a fine-grained control of connections on a per route basis.
*
* @since 4.0
*/
@ThreadSafe
public final class ConnPerRouteBean implements ConnPerRoute {
/** The default maximum number of connections allowed per host */
public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; // Per RFC 2616 sec 8.1.4
private final ConcurrentHashMap<HttpRoute, Integer> maxPerHostMap;
private volatile int defaultMax;
public ConnPerRouteBean(int defaultMax) {
super();
this.maxPerHostMap = new ConcurrentHashMap<HttpRoute, Integer>();
setDefaultMaxPerRoute(defaultMax);
}
public ConnPerRouteBean() {
this(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
}
/**
* @deprecated Use {@link #getDefaultMaxPerRoute()} instead
*/
@Deprecated
public int getDefaultMax() {
return this.defaultMax;
}
/**
* @since 4.1
*/
public int getDefaultMaxPerRoute() {
return this.defaultMax;
}
public void setDefaultMaxPerRoute(int max) {
if (max < 1) {
throw new IllegalArgumentException
("The maximum must be greater than 0.");
}
this.defaultMax = max;
}
public void setMaxForRoute(final HttpRoute route, int max) {
if (route == null) {
throw new IllegalArgumentException
("HTTP route may not be null.");
}
if (max < 1) {
throw new IllegalArgumentException
("The maximum must be greater than 0.");
}
this.maxPerHostMap.put(route, Integer.valueOf(max));
}
public int getMaxForRoute(final HttpRoute route) {
if (route == null) {
throw new IllegalArgumentException
("HTTP route may not be null.");
}
Integer max = this.maxPerHostMap.get(route);
if (max != null) {
return max.intValue();
} else {
return this.defaultMax;
}
}
public void setMaxForRoutes(final Map<HttpRoute, Integer> map) {
if (map == null) {
return;
}
this.maxPerHostMap.clear();
this.maxPerHostMap.putAll(map);
}
@Override
public String toString() {
return this.maxPerHostMap.toString();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* This interface is intended for looking up maximum number of connections
* allowed for a given route. This class can be used by pooling
* {@link org.apache.ogt.http.conn.ClientConnectionManager connection managers} for
* a fine-grained control of connections on a per route basis.
*
* @since 4.0
*/
public interface ConnPerRoute {
int getMaxForRoute(HttpRoute route);
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.params;
import java.net.InetAddress;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.params.HttpParams;
/**
* An adaptor for manipulating HTTP routing parameters
* in {@link HttpParams}.
*
* @since 4.0
*/
@Immutable
public class ConnRouteParams implements ConnRoutePNames {
/**
* A special value indicating "no host".
* This relies on a nonsense scheme name to avoid conflicts
* with actual hosts. Note that this is a <i>valid</i> host.
*/
public static final HttpHost NO_HOST =
new HttpHost("127.0.0.255", 0, "no-host"); // Immutable
/**
* A special value indicating "no route".
* This is a route with {@link #NO_HOST} as the target.
*/
public static final HttpRoute NO_ROUTE = new HttpRoute(NO_HOST); // Immutable
/** Disabled default constructor. */
private ConnRouteParams() {
// no body
}
/**
* Obtains the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
* parameter value.
* {@link #NO_HOST} will be mapped to <code>null</code>,
* to allow unsetting in a hierarchy.
*
* @param params the parameters in which to look up
*
* @return the default proxy set in the argument parameters, or
* <code>null</code> if not set
*/
public static HttpHost getDefaultProxy(HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
HttpHost proxy = (HttpHost)
params.getParameter(DEFAULT_PROXY);
if ((proxy != null) && NO_HOST.equals(proxy)) {
// value is explicitly unset
proxy = null;
}
return proxy;
}
/**
* Sets the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
* parameter value.
*
* @param params the parameters in which to set the value
* @param proxy the value to set, may be <code>null</code>.
* Note that {@link #NO_HOST} will be mapped to
* <code>null</code> by {@link #getDefaultProxy},
* to allow for explicit unsetting in hierarchies.
*/
public static void setDefaultProxy(HttpParams params,
HttpHost proxy) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
params.setParameter(DEFAULT_PROXY, proxy);
}
/**
* Obtains the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
* parameter value.
* {@link #NO_ROUTE} will be mapped to <code>null</code>,
* to allow unsetting in a hierarchy.
*
* @param params the parameters in which to look up
*
* @return the forced route set in the argument parameters, or
* <code>null</code> if not set
*/
public static HttpRoute getForcedRoute(HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
HttpRoute route = (HttpRoute)
params.getParameter(FORCED_ROUTE);
if ((route != null) && NO_ROUTE.equals(route)) {
// value is explicitly unset
route = null;
}
return route;
}
/**
* Sets the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
* parameter value.
*
* @param params the parameters in which to set the value
* @param route the value to set, may be <code>null</code>.
* Note that {@link #NO_ROUTE} will be mapped to
* <code>null</code> by {@link #getForcedRoute},
* to allow for explicit unsetting in hierarchies.
*/
public static void setForcedRoute(HttpParams params,
HttpRoute route) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
params.setParameter(FORCED_ROUTE, route);
}
/**
* Obtains the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
* parameter value.
* There is no special value that would automatically be mapped to
* <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4,
* :: for IPv6) to override a specific local address in a hierarchy.
*
* @param params the parameters in which to look up
*
* @return the local address set in the argument parameters, or
* <code>null</code> if not set
*/
public static InetAddress getLocalAddress(HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
InetAddress local = (InetAddress)
params.getParameter(LOCAL_ADDRESS);
// no explicit unsetting
return local;
}
/**
* Sets the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
* parameter value.
*
* @param params the parameters in which to set the value
* @param local the value to set, may be <code>null</code>
*/
public static void setLocalAddress(HttpParams params,
InetAddress local) {
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
params.setParameter(LOCAL_ADDRESS, local);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn;
import java.util.concurrent.TimeUnit;
/**
* Encapsulates a request for a {@link ManagedClientConnection}.
*
* @since 4.0
*/
public interface ClientConnectionRequest {
/**
* Obtains a connection within a given time.
* This method will block until a connection becomes available,
* the timeout expires, or the connection manager is
* {@link ClientConnectionManager#shutdown() shut down}.
* Timeouts are handled with millisecond precision.
*
* If {@link #abortRequest()} is called while this is blocking or
* before this began, an {@link InterruptedException} will
* be thrown.
*
* @param timeout the timeout, 0 or negative for no timeout
* @param tunit the unit for the <code>timeout</code>,
* may be <code>null</code> only if there is no timeout
*
* @return a connection that can be used to communicate
* along the given route
*
* @throws ConnectionPoolTimeoutException
* in case of a timeout
* @throws InterruptedException
* if the calling thread is interrupted while waiting
*/
ManagedClientConnection getConnection(long timeout, TimeUnit tunit)
throws InterruptedException, ConnectionPoolTimeoutException;
/**
* Aborts the call to {@link #getConnection(long, TimeUnit)},
* causing it to throw an {@link InterruptedException}.
*/
void abortRequest();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.routing;
import java.net.InetAddress;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.util.LangUtils;
/**
* Helps tracking the steps in establishing a route.
*
* @since 4.0
*/
@NotThreadSafe
public final class RouteTracker implements RouteInfo, Cloneable {
/** The target host to connect to. */
private final HttpHost targetHost;
/**
* The local address to connect from.
* <code>null</code> indicates that the default should be used.
*/
private final InetAddress localAddress;
// the attributes above are fixed at construction time
// now follow attributes that indicate the established route
/** Whether the first hop of the route is established. */
private boolean connected;
/** The proxy chain, if any. */
private HttpHost[] proxyChain;
/** Whether the the route is tunnelled end-to-end through proxies. */
private TunnelType tunnelled;
/** Whether the route is layered over a tunnel. */
private LayerType layered;
/** Whether the route is secure. */
private boolean secure;
/**
* Creates a new route tracker.
* The target and origin need to be specified at creation time.
*
* @param target the host to which to route
* @param local the local address to route from, or
* <code>null</code> for the default
*/
public RouteTracker(HttpHost target, InetAddress local) {
if (target == null) {
throw new IllegalArgumentException("Target host may not be null.");
}
this.targetHost = target;
this.localAddress = local;
this.tunnelled = TunnelType.PLAIN;
this.layered = LayerType.PLAIN;
}
/**
* Creates a new tracker for the given route.
* Only target and origin are taken from the route,
* everything else remains to be tracked.
*
* @param route the route to track
*/
public RouteTracker(HttpRoute route) {
this(route.getTargetHost(), route.getLocalAddress());
}
/**
* Tracks connecting to the target.
*
* @param secure <code>true</code> if the route is secure,
* <code>false</code> otherwise
*/
public final void connectTarget(boolean secure) {
if (this.connected) {
throw new IllegalStateException("Already connected.");
}
this.connected = true;
this.secure = secure;
}
/**
* Tracks connecting to the first proxy.
*
* @param proxy the proxy connected to
* @param secure <code>true</code> if the route is secure,
* <code>false</code> otherwise
*/
public final void connectProxy(HttpHost proxy, boolean secure) {
if (proxy == null) {
throw new IllegalArgumentException("Proxy host may not be null.");
}
if (this.connected) {
throw new IllegalStateException("Already connected.");
}
this.connected = true;
this.proxyChain = new HttpHost[]{ proxy };
this.secure = secure;
}
/**
* Tracks tunnelling to the target.
*
* @param secure <code>true</code> if the route is secure,
* <code>false</code> otherwise
*/
public final void tunnelTarget(boolean secure) {
if (!this.connected) {
throw new IllegalStateException("No tunnel unless connected.");
}
if (this.proxyChain == null) {
throw new IllegalStateException("No tunnel without proxy.");
}
this.tunnelled = TunnelType.TUNNELLED;
this.secure = secure;
}
/**
* Tracks tunnelling to a proxy in a proxy chain.
* This will extend the tracked proxy chain, but it does not mark
* the route as tunnelled. Only end-to-end tunnels are considered there.
*
* @param proxy the proxy tunnelled to
* @param secure <code>true</code> if the route is secure,
* <code>false</code> otherwise
*/
public final void tunnelProxy(HttpHost proxy, boolean secure) {
if (proxy == null) {
throw new IllegalArgumentException("Proxy host may not be null.");
}
if (!this.connected) {
throw new IllegalStateException("No tunnel unless connected.");
}
if (this.proxyChain == null) {
throw new IllegalStateException("No proxy tunnel without proxy.");
}
// prepare an extended proxy chain
HttpHost[] proxies = new HttpHost[this.proxyChain.length+1];
System.arraycopy(this.proxyChain, 0,
proxies, 0, this.proxyChain.length);
proxies[proxies.length-1] = proxy;
this.proxyChain = proxies;
this.secure = secure;
}
/**
* Tracks layering a protocol.
*
* @param secure <code>true</code> if the route is secure,
* <code>false</code> otherwise
*/
public final void layerProtocol(boolean secure) {
// it is possible to layer a protocol over a direct connection,
// although this case is probably not considered elsewhere
if (!this.connected) {
throw new IllegalStateException
("No layered protocol unless connected.");
}
this.layered = LayerType.LAYERED;
this.secure = secure;
}
public final HttpHost getTargetHost() {
return this.targetHost;
}
public final InetAddress getLocalAddress() {
return this.localAddress;
}
public final int getHopCount() {
int hops = 0;
if (this.connected) {
if (proxyChain == null)
hops = 1;
else
hops = proxyChain.length + 1;
}
return hops;
}
public final HttpHost getHopTarget(int hop) {
if (hop < 0)
throw new IllegalArgumentException
("Hop index must not be negative: " + hop);
final int hopcount = getHopCount();
if (hop >= hopcount) {
throw new IllegalArgumentException
("Hop index " + hop +
" exceeds tracked route length " + hopcount +".");
}
HttpHost result = null;
if (hop < hopcount-1)
result = this.proxyChain[hop];
else
result = this.targetHost;
return result;
}
public final HttpHost getProxyHost() {
return (this.proxyChain == null) ? null : this.proxyChain[0];
}
public final boolean isConnected() {
return this.connected;
}
public final TunnelType getTunnelType() {
return this.tunnelled;
}
public final boolean isTunnelled() {
return (this.tunnelled == TunnelType.TUNNELLED);
}
public final LayerType getLayerType() {
return this.layered;
}
public final boolean isLayered() {
return (this.layered == LayerType.LAYERED);
}
public final boolean isSecure() {
return this.secure;
}
/**
* Obtains the tracked route.
* If a route has been tracked, it is {@link #isConnected connected}.
* If not connected, nothing has been tracked so far.
*
* @return the tracked route, or
* <code>null</code> if nothing has been tracked so far
*/
public final HttpRoute toRoute() {
return !this.connected ?
null : new HttpRoute(this.targetHost, this.localAddress,
this.proxyChain, this.secure,
this.tunnelled, this.layered);
}
/**
* Compares this tracked route to another.
*
* @param o the object to compare with
*
* @return <code>true</code> if the argument is the same tracked route,
* <code>false</code>
*/
@Override
public final boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof RouteTracker))
return false;
RouteTracker that = (RouteTracker) o;
return
// Do the cheapest checks first
(this.connected == that.connected) &&
(this.secure == that.secure) &&
(this.tunnelled == that.tunnelled) &&
(this.layered == that.layered) &&
LangUtils.equals(this.targetHost, that.targetHost) &&
LangUtils.equals(this.localAddress, that.localAddress) &&
LangUtils.equals(this.proxyChain, that.proxyChain);
}
/**
* Generates a hash code for this tracked route.
* Route trackers are modifiable and should therefore not be used
* as lookup keys. Use {@link #toRoute toRoute} to obtain an
* unmodifiable representation of the tracked route.
*
* @return the hash code
*/
@Override
public final int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.targetHost);
hash = LangUtils.hashCode(hash, this.localAddress);
if (this.proxyChain != null) {
for (int i = 0; i < this.proxyChain.length; i++) {
hash = LangUtils.hashCode(hash, this.proxyChain[i]);
}
}
hash = LangUtils.hashCode(hash, this.connected);
hash = LangUtils.hashCode(hash, this.secure);
hash = LangUtils.hashCode(hash, this.tunnelled);
hash = LangUtils.hashCode(hash, this.layered);
return hash;
}
/**
* Obtains a description of the tracked route.
*
* @return a human-readable representation of the tracked route
*/
@Override
public final String toString() {
StringBuilder cab = new StringBuilder(50 + getHopCount()*30);
cab.append("RouteTracker[");
if (this.localAddress != null) {
cab.append(this.localAddress);
cab.append("->");
}
cab.append('{');
if (this.connected)
cab.append('c');
if (this.tunnelled == TunnelType.TUNNELLED)
cab.append('t');
if (this.layered == LayerType.LAYERED)
cab.append('l');
if (this.secure)
cab.append('s');
cab.append("}->");
if (this.proxyChain != null) {
for (int i=0; i<this.proxyChain.length; i++) {
cab.append(this.proxyChain[i]);
cab.append("->");
}
}
cab.append(this.targetHost);
cab.append(']');
return cab.toString();
}
// default implementation of clone() is sufficient
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.routing;
import org.apache.ogt.http.annotation.Immutable;
/**
* Basic implementation of an {@link HttpRouteDirector HttpRouteDirector}.
* This implementation is stateless and therefore thread-safe.
*
* @since 4.0
*/
@Immutable
public class BasicRouteDirector implements HttpRouteDirector {
/**
* Provides the next step.
*
* @param plan the planned route
* @param fact the currently established route, or
* <code>null</code> if nothing is established
*
* @return one of the constants defined in this class, indicating
* either the next step to perform, or success, or failure.
* 0 is for success, a negative value for failure.
*/
public int nextStep(RouteInfo plan, RouteInfo fact) {
if (plan == null) {
throw new IllegalArgumentException
("Planned route may not be null.");
}
int step = UNREACHABLE;
if ((fact == null) || (fact.getHopCount() < 1))
step = firstStep(plan);
else if (plan.getHopCount() > 1)
step = proxiedStep(plan, fact);
else
step = directStep(plan, fact);
return step;
} // nextStep
/**
* Determines the first step to establish a route.
*
* @param plan the planned route
*
* @return the first step
*/
protected int firstStep(RouteInfo plan) {
return (plan.getHopCount() > 1) ?
CONNECT_PROXY : CONNECT_TARGET;
}
/**
* Determines the next step to establish a direct connection.
*
* @param plan the planned route
* @param fact the currently established route
*
* @return one of the constants defined in this class, indicating
* either the next step to perform, or success, or failure
*/
protected int directStep(RouteInfo plan, RouteInfo fact) {
if (fact.getHopCount() > 1)
return UNREACHABLE;
if (!plan.getTargetHost().equals(fact.getTargetHost()))
return UNREACHABLE;
// If the security is too low, we could now suggest to layer
// a secure protocol on the direct connection. Layering on direct
// connections has not been supported in HttpClient 3.x, we don't
// consider it here until there is a real-life use case for it.
// Should we tolerate if security is better than planned?
// (plan.isSecure() && !fact.isSecure())
if (plan.isSecure() != fact.isSecure())
return UNREACHABLE;
// Local address has to match only if the plan specifies one.
if ((plan.getLocalAddress() != null) &&
!plan.getLocalAddress().equals(fact.getLocalAddress())
)
return UNREACHABLE;
return COMPLETE;
}
/**
* Determines the next step to establish a connection via proxy.
*
* @param plan the planned route
* @param fact the currently established route
*
* @return one of the constants defined in this class, indicating
* either the next step to perform, or success, or failure
*/
protected int proxiedStep(RouteInfo plan, RouteInfo fact) {
if (fact.getHopCount() <= 1)
return UNREACHABLE;
if (!plan.getTargetHost().equals(fact.getTargetHost()))
return UNREACHABLE;
final int phc = plan.getHopCount();
final int fhc = fact.getHopCount();
if (phc < fhc)
return UNREACHABLE;
for (int i=0; i<fhc-1; i++) {
if (!plan.getHopTarget(i).equals(fact.getHopTarget(i)))
return UNREACHABLE;
}
// now we know that the target matches and proxies so far are the same
if (phc > fhc)
return TUNNEL_PROXY; // need to extend the proxy chain
// proxy chain and target are the same, check tunnelling and layering
if ((fact.isTunnelled() && !plan.isTunnelled()) ||
(fact.isLayered() && !plan.isLayered()))
return UNREACHABLE;
if (plan.isTunnelled() && !fact.isTunnelled())
return TUNNEL_TARGET;
if (plan.isLayered() && !fact.isLayered())
return LAYER_PROTOCOL;
// tunnel and layering are the same, remains to check the security
// Should we tolerate if security is better than planned?
// (plan.isSecure() && !fact.isSecure())
if (plan.isSecure() != fact.isSecure())
return UNREACHABLE;
return COMPLETE;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.