code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ecomdev.openvpn.api; import android.os.Parcel; import android.os.Parcelable; public class APIVpnProfile implements Parcelable { public final String mUUID; public final String mName; public final boolean mUserEditable; public APIVpnProfile(Parcel in) { mUUID = in.readString(); mName = in.readString(); mUserEditable = in.readInt() != 0; } public APIVpnProfile(String uuidString, String name, boolean userEditable) { mUUID=uuidString; mName = name; mUserEditable=userEditable; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mUUID); dest.writeString(mName); if(mUserEditable) dest.writeInt(0); else dest.writeInt(1); } public static final Parcelable.Creator<APIVpnProfile> CREATOR = new Parcelable.Creator<APIVpnProfile>() { public APIVpnProfile createFromParcel(Parcel in) { return new APIVpnProfile(in); } public APIVpnProfile[] newArray(int size) { return new APIVpnProfile[size]; } }; }
Java
package com.ecomdev.openvpn.api; import java.io.IOException; import java.io.StringReader; import java.lang.ref.WeakReference; import java.util.LinkedList; import java.util.List; import android.annotation.TargetApi; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.VpnService; import android.os.*; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ConfigParser; import com.ecomdev.openvpn.core.ConfigParser.ConfigParseError; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import com.ecomdev.openvpn.core.VpnStatus.StateListener; import com.ecomdev.openvpn.core.OpenVpnService; import com.ecomdev.openvpn.core.OpenVpnService.LocalBinder; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.core.VPNLaunchHelper; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) public class ExternalOpenVPNService extends Service implements StateListener { private static final int SEND_TOALL = 0; final RemoteCallbackList<IOpenVPNStatusCallback> mCallbacks = new RemoteCallbackList<IOpenVPNStatusCallback>(); private OpenVpnService mService; private ExternalAppDatabase mExtAppDb; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { mService = null; } }; @Override public void onCreate() { super.onCreate(); VpnStatus.addStateListener(this); mExtAppDb = new ExternalAppDatabase(this); Intent intent = new Intent(getBaseContext(), OpenVpnService.class); intent.setAction(OpenVpnService.START_SERVICE); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); mHandler.setService(this); } private final IOpenVPNAPIService.Stub mBinder = new IOpenVPNAPIService.Stub() { private void checkOpenVPNPermission() throws SecurityRemoteException { PackageManager pm = getPackageManager(); for (String apppackage : mExtAppDb.getExtAppList()) { ApplicationInfo app; try { app = pm.getApplicationInfo(apppackage, 0); if (Binder.getCallingUid() == app.uid) { return; } } catch (NameNotFoundException e) { // App not found. Remove it from the list mExtAppDb.removeApp(apppackage); } } throw new SecurityException("Unauthorized OpenVPN API Caller"); } @Override public List<APIVpnProfile> getProfiles() throws RemoteException { checkOpenVPNPermission(); ProfileManager pm = ProfileManager.getInstance(getBaseContext()); List<APIVpnProfile> profiles = new LinkedList<APIVpnProfile>(); for (VpnProfile vp : pm.getProfiles()) profiles.add(new APIVpnProfile(vp.getUUIDString(), vp.mName, vp.mUserEditable)); return profiles; } @Override public void startProfile(String profileUUID) throws RemoteException { checkOpenVPNPermission(); Intent shortVPNIntent = new Intent(Intent.ACTION_MAIN); shortVPNIntent.setClass(getBaseContext(), com.ecomdev.openvpn.LaunchVPN.class); shortVPNIntent.putExtra(com.ecomdev.openvpn.LaunchVPN.EXTRA_KEY, profileUUID); shortVPNIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(shortVPNIntent); } public void startVPN(String inlineconfig) throws RemoteException { checkOpenVPNPermission(); ConfigParser cp = new ConfigParser(); try { cp.parseConfig(new StringReader(inlineconfig)); VpnProfile vp = cp.convertProfile(); if (vp.checkProfile(getApplicationContext()) != R.string.no_error_found) throw new RemoteException(getString(vp.checkProfile(getApplicationContext()))); ProfileManager.setTemporaryProfile(vp); VPNLaunchHelper.startOpenVpn(vp, getBaseContext()); } catch (IOException e) { throw new RemoteException(e.getMessage()); } catch (ConfigParseError e) { throw new RemoteException(e.getMessage()); } } @Override public boolean addVPNProfile(String name, String config) throws RemoteException { checkOpenVPNPermission(); ConfigParser cp = new ConfigParser(); try { cp.parseConfig(new StringReader(config)); VpnProfile vp = cp.convertProfile(); vp.mName = name; ProfileManager pm = ProfileManager.getInstance(getBaseContext()); pm.addProfile(vp); } catch (IOException e) { VpnStatus.logException(e); return false; } catch (ConfigParseError e) { VpnStatus.logException(e); return false; } return true; } @Override public Intent prepare(String packagename) { if (new ExternalAppDatabase(ExternalOpenVPNService.this).isAllowed(packagename)) return null; Intent intent = new Intent(); intent.setClass(ExternalOpenVPNService.this, ConfirmDialog.class); return intent; } @Override public Intent prepareVPNService() throws RemoteException { checkOpenVPNPermission(); if (VpnService.prepare(ExternalOpenVPNService.this) == null) return null; else return new Intent(getBaseContext(), GrantPermissionsActivity.class); } @Override public void registerStatusCallback(IOpenVPNStatusCallback cb) throws RemoteException { checkOpenVPNPermission(); if (cb != null) { cb.newStatus(mMostRecentState.vpnUUID, mMostRecentState.state, mMostRecentState.logmessage, mMostRecentState.level.name()); mCallbacks.register(cb); } } @Override public void unregisterStatusCallback(IOpenVPNStatusCallback cb) throws RemoteException { checkOpenVPNPermission(); if (cb != null) mCallbacks.unregister(cb); } @Override public void disconnect() throws RemoteException { checkOpenVPNPermission(); if (mService != null && mService.getManagement() != null) mService.getManagement().stopVPN(); } @Override public void pause() throws RemoteException { checkOpenVPNPermission(); if (mService != null) mService.userPause(true); } @Override public void resume() throws RemoteException { checkOpenVPNPermission(); if (mService != null) mService.userPause(false); } }; private UpdateMessage mMostRecentState; @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onDestroy() { super.onDestroy(); mCallbacks.kill(); unbindService(mConnection); VpnStatus.removeStateListener(this); } class UpdateMessage { public String state; public String logmessage; public ConnectionStatus level; public String vpnUUID; public UpdateMessage(String state, String logmessage, ConnectionStatus level) { this.state = state; this.logmessage = logmessage; this.level = level; } } @Override public void updateState(String state, String logmessage, int resid, ConnectionStatus level) { mMostRecentState = new UpdateMessage(state, logmessage, level); if (ProfileManager.getLastConnectedVpn() != null) mMostRecentState.vpnUUID = ProfileManager.getLastConnectedVpn().getUUIDString(); Message msg = mHandler.obtainMessage(SEND_TOALL, mMostRecentState); msg.sendToTarget(); } private static final OpenVPNServiceHandler mHandler = new OpenVPNServiceHandler(); static class OpenVPNServiceHandler extends Handler { WeakReference<ExternalOpenVPNService> service = null; private void setService(ExternalOpenVPNService eos) { service = new WeakReference<ExternalOpenVPNService>(eos); } @Override public void handleMessage(Message msg) { RemoteCallbackList<IOpenVPNStatusCallback> callbacks; switch (msg.what) { case SEND_TOALL: if (service == null || service.get() == null) return; callbacks = service.get().mCallbacks; // Broadcast to all clients the new value. final int N = callbacks.beginBroadcast(); for (int i = 0; i < N; i++) { try { sendUpdate(callbacks.getBroadcastItem(i), (UpdateMessage) msg.obj); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing // the dead object for us. } } callbacks.finishBroadcast(); break; } } private void sendUpdate(IOpenVPNStatusCallback broadcastItem, UpdateMessage um) throws RemoteException { broadcastItem.newStatus(um.vpnUUID, um.state, um.logmessage, um.level.name()); } } }
Java
package com.ecomdev.openvpn; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.preference.PreferenceManager; import android.security.KeyChain; import android.security.KeyChainException; import android.util.Base64; import com.ecomdev.openvpn.core.NativeUtils; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.core.OpenVpnService; import com.ecomdev.openvpn.core.X509Utils; import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemWriter; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Locale; import java.util.UUID; import java.util.Vector; public class VpnProfile implements Serializable { // Note that this class cannot be moved to core where it belongs since // the profile loading depends on it being here // The Serializable documentation mentions that class name change are possible // but the how is unclear // transient public static final long MAX_EMBED_FILE_SIZE = 2048*1024; // 2048kB // Don't change this, not all parts of the program use this constant public static final String EXTRA_PROFILEUUID = "com.ecomdev.openvpn.profileUUID"; public static final String INLINE_TAG = "[[INLINE]]"; public static final String MINIVPN = "miniopenvpn"; private static final long serialVersionUID = 7085688938959334563L; private static final String OVPNCONFIGFILE = "android.conf"; public static final int MAXLOGLEVEL = 4; public static final int CURRENT_PROFILE_VERSION = 2; public static String DEFAULT_DNS1 = "8.8.8.8"; public static String DEFAULT_DNS2 = "8.8.4.4"; public transient String mTransientPW = null; public transient String mTransientPCKS12PW = null; public static final int TYPE_CERTIFICATES = 0; public static final int TYPE_PKCS12 = 1; public static final int TYPE_KEYSTORE = 2; public static final int TYPE_USERPASS = 3; public static final int TYPE_STATICKEYS = 4; public static final int TYPE_USERPASS_CERTIFICATES = 5; public static final int TYPE_USERPASS_PKCS12 = 6; public static final int TYPE_USERPASS_KEYSTORE = 7; public static final int X509_VERIFY_TLSREMOTE = 0; public static final int X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING = 1; public static final int X509_VERIFY_TLSREMOTE_DN = 2; public static final int X509_VERIFY_TLSREMOTE_RDN = 3; public static final int X509_VERIFY_TLSREMOTE_RDN_PREFIX = 4; // variable named wrong and should haven beeen transient // but needs to keep wrong name to guarante loading of old // profiles public transient boolean profileDleted = false; public int mAuthenticationType = TYPE_KEYSTORE; public String mName; public String mAlias; public String mClientCertFilename; public String mTLSAuthDirection = ""; public String mTLSAuthFilename; public String mClientKeyFilename; public String mCaFilename; public boolean mUseLzo = true; public String mServerPort = "1194"; public boolean mUseUdp = true; public String mPKCS12Filename; public String mPKCS12Password; public boolean mUseTLSAuth = false; public String mServerName = "openvpn.ecomdev.com"; public String mDNS1 = DEFAULT_DNS1; public String mDNS2 = DEFAULT_DNS2; public String mIPv4Address; public String mIPv6Address; public boolean mOverrideDNS = false; public String mSearchDomain = "ecomdev.com"; public boolean mUseDefaultRoute = true; public boolean mUsePull = true; public String mCustomRoutes; public boolean mCheckRemoteCN = false; public boolean mExpectTLSCert = true; public String mRemoteCN = ""; public String mPassword = ""; public String mUsername = ""; public boolean mRoutenopull = false; public boolean mUseRandomHostname = false; public boolean mUseFloat = false; public boolean mUseCustomConfig = false; public String mCustomConfigOptions = ""; public String mVerb = "1"; //ignored public String mCipher = ""; public boolean mNobind = false; public boolean mUseDefaultRoutev6 = true; public String mCustomRoutesv6 = ""; public String mKeyPassword = ""; public boolean mPersistTun = false; public String mConnectRetryMax = "5"; public String mConnectRetry = "5"; public boolean mUserEditable = true; public String mAuth = ""; public int mX509AuthType = X509_VERIFY_TLSREMOTE_RDN; private transient PrivateKey mPrivateKey; // Public attributes, since I got mad with getter/setter // set members to default values private UUID mUuid; public boolean mAllowLocalLAN; private int mProfileVersion; public String mExcludedRoutes; public String mExcludedRoutesv6; public int mPing = -1; public VpnProfile(String name) { mUuid = UUID.randomUUID(); mName = name; mProfileVersion = CURRENT_PROFILE_VERSION; } public static String openVpnEscape(String unescaped) { if (unescaped == null) return null; String escapedString = unescaped.replace("\\", "\\\\"); escapedString = escapedString.replace("\"", "\\\""); escapedString = escapedString.replace("\n", "\\n"); if (escapedString.equals(unescaped) && !escapedString.contains(" ") && !escapedString.contains("#")) return unescaped; else return '"' + escapedString + '"'; } public void clearDefaults() { mServerName = "unknown"; mUsePull = false; mUseLzo = false; mUseDefaultRoute = false; mUseDefaultRoutev6 = false; mExpectTLSCert = false; mPersistTun = false; mAllowLocalLAN = true; } public UUID getUUID() { return mUuid; } public String getName() { if (mName==null) return "No profile name"; return mName; } public void upgradeProfile(){ if(mProfileVersion< 2) { /* default to the behaviour the OS used */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) mAllowLocalLAN = true; else mAllowLocalLAN = false; } mProfileVersion= CURRENT_PROFILE_VERSION; } public String getConfigFile(Context context, boolean configForOvpn3) { File cacheDir = context.getCacheDir(); String cfg = ""; // Enable managment interface cfg += "# Enables connection to GUI\n"; cfg += "management "; cfg += cacheDir.getAbsolutePath() + "/" + "mgmtsocket"; cfg += " unix\n"; cfg += "management-client\n"; // Not needed, see updated man page in 2.3 //cfg += "management-signal\n"; cfg += "management-query-passwords\n"; cfg += "management-hold\n\n"; cfg += getVersionEnvString(context); cfg += "machine-readable-output\n"; boolean useTLSClient = (mAuthenticationType != TYPE_STATICKEYS); if (useTLSClient && mUsePull) cfg += "client\n"; else if (mUsePull) cfg += "pull\n"; else if (useTLSClient) cfg += "tls-client\n"; //cfg += "verb " + mVerb + "\n"; cfg += "verb " + MAXLOGLEVEL + "\n"; if (mConnectRetryMax == null) { mConnectRetryMax = "5"; } if (!mConnectRetryMax.equals("-1")) cfg += "connect-retry-max " + mConnectRetryMax + "\n"; if (mConnectRetry == null) mConnectRetry = "5"; cfg += "connect-retry " + mConnectRetry + "\n"; cfg += "resolv-retry 60\n"; // We cannot use anything else than tun cfg += "dev tun\n"; // Server Address cfg += "remote "; cfg += mServerName; cfg += " "; cfg += mServerPort; if (mUseUdp) cfg += " udp\n"; else cfg += " tcp-client\n"; switch (mAuthenticationType) { case VpnProfile.TYPE_USERPASS_CERTIFICATES: cfg += "auth-user-pass\n"; case VpnProfile.TYPE_CERTIFICATES: // Ca cfg += insertFileData("ca", mCaFilename); // Client Cert + Key cfg += insertFileData("key", mClientKeyFilename); cfg += insertFileData("cert", mClientCertFilename); break; case VpnProfile.TYPE_USERPASS_PKCS12: cfg += "auth-user-pass\n"; case VpnProfile.TYPE_PKCS12: cfg += insertFileData("pkcs12", mPKCS12Filename); break; case VpnProfile.TYPE_USERPASS_KEYSTORE: cfg += "auth-user-pass\n"; case VpnProfile.TYPE_KEYSTORE: if (!configForOvpn3) { String[] ks = getKeyStoreCertificates(context); cfg += "### From Keystore ####\n"; if (ks != null) { cfg += "<ca>\n" + ks[0] + "\n</ca>\n"; if (ks[1] != null) cfg += "<extra-certs>\n" + ks[1] + "\n</extra-certs>\n"; cfg += "<cert>\n" + ks[2] + "\n</cert>\n"; cfg += "management-external-key\n"; } else { cfg += context.getString(R.string.keychain_access) + "\n"; if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) if (!mAlias.matches("^[a-zA-Z0-9]$")) cfg += context.getString(R.string.jelly_keystore_alphanumeric_bug) + "\n"; } } break; case VpnProfile.TYPE_USERPASS: cfg += "auth-user-pass\n"; cfg += insertFileData("ca", mCaFilename); } if (mUseLzo) { cfg += "comp-lzo\n"; } if (mUseTLSAuth) { if (mAuthenticationType == TYPE_STATICKEYS) cfg += insertFileData("secret", mTLSAuthFilename); else cfg += insertFileData("tls-auth", mTLSAuthFilename); if (nonNull(mTLSAuthDirection)) { cfg += "key-direction "; cfg += mTLSAuthDirection; cfg += "\n"; } } if (!mUsePull) { if (nonNull(mIPv4Address)) cfg += "ifconfig " + cidrToIPAndNetmask(mIPv4Address) + "\n"; if (nonNull(mIPv6Address)) cfg += "ifconfig-ipv6 " + mIPv6Address + "\n"; } if (mUsePull && mRoutenopull) cfg += "route-nopull\n"; String routes = ""; int numroutes = 0; if (mUseDefaultRoute) routes += "route 0.0.0.0 0.0.0.0 vpn_gateway\n"; else { for (String route : getCustomRoutes(mCustomRoutes)) { routes += "route " + route + " vpn_gateway\n"; numroutes++; } for (String route: getCustomRoutes(mExcludedRoutes)) { routes += "route " + route + " net_gateway"; } } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mAllowLocalLAN) cfg+="redirect-private block-local\n"; else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && mAllowLocalLAN) cfg+="redirect-private unblock-local\n"; if (mUseDefaultRoutev6) cfg += "route-ipv6 ::/0\n"; else for (String route : getCustomRoutesv6(mCustomRoutesv6)) { routes += "route-ipv6 " + route + "\n"; numroutes++; } // Round number to next 100 if (numroutes > 90) { numroutes = ((numroutes / 100) + 1) * 100; cfg += "# A lot of routes are set, increase max-routes\n"; cfg += "max-routes " + numroutes + "\n"; } cfg += routes; if (mOverrideDNS || !mUsePull) { if (nonNull(mDNS1)) cfg += "dhcp-option DNS " + mDNS1 + "\n"; if (nonNull(mDNS2)) cfg += "dhcp-option DNS " + mDNS2 + "\n"; if (nonNull(mSearchDomain)) cfg += "dhcp-option DOMAIN " + mSearchDomain + "\n"; } if (mNobind) cfg += "nobind\n"; // Authentication if (mAuthenticationType != TYPE_STATICKEYS) { if (mCheckRemoteCN) { if (mRemoteCN == null || mRemoteCN.equals("")) cfg += "verify-x509-name " + mServerName + " name\n"; else switch (mX509AuthType) { // 2.2 style x509 checks case X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING: cfg += "compat-names no-remapping\n"; case X509_VERIFY_TLSREMOTE: cfg += "tls-remote " + openVpnEscape(mRemoteCN) + "\n"; break; case X509_VERIFY_TLSREMOTE_RDN: cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + " name\n"; break; case X509_VERIFY_TLSREMOTE_RDN_PREFIX: cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + " name-prefix\n"; break; case X509_VERIFY_TLSREMOTE_DN: cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + "\n"; break; } } if (mExpectTLSCert) cfg += "remote-cert-tls server\n"; } if (nonNull(mCipher)) { cfg += "cipher " + mCipher + "\n"; } if (nonNull(mAuth)) { cfg += "auth " + mAuth + "\n"; } // Obscure Settings dialog if (mUseRandomHostname) cfg += "#my favorite options :)\nremote-random-hostname\n"; if (mUseFloat) cfg += "float\n"; if (mPersistTun) { cfg += "persist-tun\n"; cfg += "# persist-tun also enables pre resolving to avoid DNS resolve problem\n"; cfg += "preresolve\n"; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean usesystemproxy = prefs.getBoolean("usesystemproxy", true); if (usesystemproxy) { cfg += "# Use system proxy setting\n"; cfg += "management-query-proxy\n"; } if (mUseCustomConfig) { cfg += "# Custom configuration options\n"; cfg += "# You are on your on own here :)\n"; cfg += mCustomConfigOptions; cfg += "\n"; } return cfg; } private String getVersionEnvString(Context c) { String version = "unknown"; try { PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); version = packageinfo.versionName; } catch (PackageManager.NameNotFoundException e) { VpnStatus.logException(e); } return String.format(Locale.US, "setenv IV_GUI_VER \"%s %s\"\n", c.getPackageName(), version); } //! Put inline data inline and other data as normal escaped filename private String insertFileData(String cfgentry, String filedata) { if (filedata == null) { // TODO: generate good error return String.format("%s %s\n", cfgentry, "missing"); } else if (filedata.startsWith(VpnProfile.INLINE_TAG)) { String datawoheader = filedata.substring(VpnProfile.INLINE_TAG.length()); return String.format(Locale.ENGLISH, "<%s>\n%s\n</%s>\n", cfgentry, datawoheader, cfgentry); } else { return String.format(Locale.ENGLISH, "%s %s\n", cfgentry, openVpnEscape(filedata)); } } private boolean nonNull(String val) { if (val == null || val.equals("")) return false; else return true; } private Collection<String> getCustomRoutes(String routes) { Vector<String> cidrRoutes = new Vector<String>(); if (routes == null) { // No routes set, return empty vector return cidrRoutes; } for (String route : routes.split("[\n \t]")) { if (!route.equals("")) { String cidrroute = cidrToIPAndNetmask(route); if (cidrroute == null) return null; cidrRoutes.add(cidrroute); } } return cidrRoutes; } private Collection<String> getCustomRoutesv6(String routes) { Vector<String> cidrRoutes = new Vector<String>(); if (routes == null) { // No routes set, return empty vector return cidrRoutes; } for (String route : routes.split("[\n \t]")) { if (!route.equals("")) { cidrRoutes.add(route); } } return cidrRoutes; } private String cidrToIPAndNetmask(String route) { String[] parts = route.split("/"); // No /xx, assume /32 as netmask if (parts.length == 1) parts = (route + "/32").split("/"); if (parts.length != 2) return null; int len; try { len = Integer.parseInt(parts[1]); } catch (NumberFormatException ne) { return null; } if (len < 0 || len > 32) return null; long nm = 0xffffffffl; nm = (nm << (32 - len)) & 0xffffffffl; String netmask = String.format(Locale.ENGLISH, "%d.%d.%d.%d", (nm & 0xff000000) >> 24, (nm & 0xff0000) >> 16, (nm & 0xff00) >> 8, nm & 0xff); return parts[0] + " " + netmask; } private String[] buildOpenvpnArgv(File cacheDir) { Vector<String> args = new Vector<String>(); // Add fixed paramenters //args.add("/data/data/com.ecomdev.openvpn/lib/openvpn"); args.add(cacheDir.getAbsolutePath() + "/" + VpnProfile.MINIVPN); args.add("--config"); args.add(cacheDir.getAbsolutePath() + "/" + OVPNCONFIGFILE); return args.toArray(new String[args.size()]); } public Intent prepareIntent(Context context) { String prefix = context.getPackageName(); Intent intent = new Intent(context, OpenVpnService.class); if (mAuthenticationType == VpnProfile.TYPE_KEYSTORE || mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) { if (getKeyStoreCertificates(context) == null) return null; } intent.putExtra(prefix + ".ARGV", buildOpenvpnArgv(context.getCacheDir())); intent.putExtra(prefix + ".profileUUID", mUuid.toString()); ApplicationInfo info = context.getApplicationInfo(); intent.putExtra(prefix + ".nativelib", info.nativeLibraryDir); try { FileWriter cfg = new FileWriter(context.getCacheDir().getAbsolutePath() + "/" + OVPNCONFIGFILE); cfg.write(getConfigFile(context, false)); cfg.flush(); cfg.close(); } catch (IOException e) { VpnStatus.logException(e); } return intent; } String[] getKeyStoreCertificates(Context context) { return getKeyStoreCertificates(context, 5); } class NoCertReturnedException extends Exception { public NoCertReturnedException (String msg) { super(msg); } } synchronized String[] getKeyStoreCertificates(Context context,int tries) { PrivateKey privateKey = null; X509Certificate[] cachain; Exception exp=null; try { privateKey = KeyChain.getPrivateKey(context, mAlias); mPrivateKey = privateKey; String keystoreChain = null; cachain = KeyChain.getCertificateChain(context, mAlias); if(cachain == null) throw new NoCertReturnedException("No certificate returned from Keystore"); if (cachain.length <= 1 && !nonNull(mCaFilename)) { VpnStatus.logMessage(VpnStatus.LogLevel.ERROR, "", context.getString(R.string.keychain_nocacert)); } else { StringWriter ksStringWriter = new StringWriter(); PemWriter pw = new PemWriter(ksStringWriter); for (int i = 1; i < cachain.length; i++) { X509Certificate cert = cachain[i]; pw.writeObject(new PemObject("CERTIFICATE", cert.getEncoded())); } pw.close(); keystoreChain = ksStringWriter.toString(); } String caout = null; if (nonNull(mCaFilename)) { try { Certificate cacert = X509Utils.getCertificateFromFile(mCaFilename); StringWriter caoutWriter = new StringWriter(); PemWriter pw = new PemWriter(caoutWriter); pw.writeObject(new PemObject("CERTIFICATE", cacert.getEncoded())); pw.close(); caout= caoutWriter.toString(); } catch (Exception e) { VpnStatus.logError("Could not read CA certificate" + e.getLocalizedMessage()); } } StringWriter certout = new StringWriter(); if (cachain.length >= 1) { X509Certificate usercert = cachain[0]; PemWriter upw = new PemWriter(certout); upw.writeObject(new PemObject("CERTIFICATE", usercert.getEncoded())); upw.close(); } String user = certout.toString(); String ca, extra; if(caout==null) { ca =keystoreChain; extra=null; } else { ca = caout; extra=keystoreChain; } return new String[]{ca, extra, user}; } catch (InterruptedException e) { exp=e; } catch (FileNotFoundException e) { exp=e; } catch (CertificateException e) { exp=e; } catch (IOException e) { exp=e; } catch (KeyChainException e) { exp=e; } catch (NoCertReturnedException e) { exp =e; } catch (IllegalArgumentException e) { exp =e; } catch (AssertionError e) { if (tries ==0) return null; VpnStatus.logError(String.format("Failure getting Keystore Keys (%s), retrying",e.getLocalizedMessage())); try { Thread.sleep(3000); } catch (InterruptedException e1) { VpnStatus.logException(e1); } return getKeyStoreCertificates(context, tries-1); } if (exp != null) { exp.printStackTrace(); VpnStatus.logError(R.string.keyChainAccessError, exp.getLocalizedMessage()); VpnStatus.logError(R.string.keychain_access); if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) { if (!mAlias.matches("^[a-zA-Z0-9]$")) { VpnStatus.logError(R.string.jelly_keystore_alphanumeric_bug); } } } return null; } //! Return an error if somethign is wrong public int checkProfile(Context context) { if (mAuthenticationType == TYPE_KEYSTORE || mAuthenticationType == TYPE_USERPASS_KEYSTORE) { if (mAlias == null) return R.string.no_keystore_cert_selected; } if (!mUsePull || mAuthenticationType == TYPE_STATICKEYS) { if (mIPv4Address == null || cidrToIPAndNetmask(mIPv4Address) == null) return R.string.ipv4_format_error; } if (!mUseDefaultRoute && (getCustomRoutes(mCustomRoutes) == null || getCustomRoutes(mExcludedRoutes) ==null)) return R.string.custom_route_format_error; // Everything okay return R.string.no_error_found; } //! Openvpn asks for a "Private Key", this should be pkcs12 key // public String getPasswordPrivateKey() { if (mTransientPCKS12PW != null) { String pwcopy = mTransientPCKS12PW; mTransientPCKS12PW = null; return pwcopy; } switch (mAuthenticationType) { case TYPE_PKCS12: case TYPE_USERPASS_PKCS12: return mPKCS12Password; case TYPE_CERTIFICATES: case TYPE_USERPASS_CERTIFICATES: return mKeyPassword; case TYPE_USERPASS: case TYPE_STATICKEYS: default: return null; } } boolean isUserPWAuth() { switch (mAuthenticationType) { case TYPE_USERPASS: case TYPE_USERPASS_CERTIFICATES: case TYPE_USERPASS_KEYSTORE: case TYPE_USERPASS_PKCS12: return true; default: return false; } } public boolean requireTLSKeyPassword() { if (!nonNull(mClientKeyFilename)) return false; String data = ""; if (mClientKeyFilename.startsWith(INLINE_TAG)) data = mClientKeyFilename; else { char[] buf = new char[2048]; FileReader fr; try { fr = new FileReader(mClientKeyFilename); int len = fr.read(buf); while (len > 0) { data += new String(buf, 0, len); len = fr.read(buf); } fr.close(); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } } if (data.contains("Proc-Type: 4,ENCRYPTED")) return true; else if (data.contains("-----BEGIN ENCRYPTED PRIVATE KEY-----")) return true; else return false; } public int needUserPWInput() { if ((mAuthenticationType == TYPE_PKCS12 || mAuthenticationType == TYPE_USERPASS_PKCS12) && (mPKCS12Password == null || mPKCS12Password.equals(""))) { if (mTransientPCKS12PW == null) return R.string.pkcs12_file_encryption_key; } if (mAuthenticationType == TYPE_CERTIFICATES || mAuthenticationType == TYPE_USERPASS_CERTIFICATES) { if (requireTLSKeyPassword() && !nonNull(mKeyPassword)) if (mTransientPCKS12PW == null) { return R.string.private_key_password; } } if (isUserPWAuth() && !(nonNull(mUsername) && (nonNull(mPassword) || mTransientPW != null))) { return R.string.password; } return 0; } public String getPasswordAuth() { if (mTransientPW != null) { String pwcopy = mTransientPW; mTransientPW = null; return pwcopy; } else { return mPassword; } } // Used by the Array Adapter @Override public String toString() { return mName; } public String getUUIDString() { return mUuid.toString(); } public PrivateKey getKeystoreKey() { return mPrivateKey; } public String getSignedData(String b64data) { PrivateKey privkey = getKeystoreKey(); Exception err; byte[] data = Base64.decode(b64data, Base64.DEFAULT); // The Jelly Bean *evil* Hack // 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) { return processSignJellyBeans(privkey, data); } try { Cipher rsasinger = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); rsasinger.init(Cipher.ENCRYPT_MODE, privkey); byte[] signed_bytes = rsasinger.doFinal(data); return Base64.encodeToString(signed_bytes, Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { err = e; } catch (InvalidKeyException e) { err = e; } catch (NoSuchPaddingException e) { err = e; } catch (IllegalBlockSizeException e) { err = e; } catch (BadPaddingException e) { err = e; } VpnStatus.logError(R.string.error_rsa_sign, err.getClass().toString(), err.getLocalizedMessage()); return null; } private String processSignJellyBeans(PrivateKey privkey, byte[] data) { Exception err; try { Method getKey = privkey.getClass().getSuperclass().getDeclaredMethod("getOpenSSLKey"); getKey.setAccessible(true); // Real object type is OpenSSLKey Object opensslkey = getKey.invoke(privkey); getKey.setAccessible(false); Method getPkeyContext = opensslkey.getClass().getDeclaredMethod("getPkeyContext"); // integer pointer to EVP_pkey getPkeyContext.setAccessible(true); int pkey = (Integer) getPkeyContext.invoke(opensslkey); getPkeyContext.setAccessible(false); // 112 with TLS 1.2 (172 back with 4.3), 36 with TLS 1.0 byte[] signed_bytes = NativeUtils.rsasign(data, pkey); return Base64.encodeToString(signed_bytes, Base64.NO_WRAP); } catch (NoSuchMethodException e) { err = e; } catch (IllegalArgumentException e) { err = e; } catch (IllegalAccessException e) { err = e; } catch (InvocationTargetException e) { err = e; } catch (InvalidKeyException e) { err = e; } VpnStatus.logError(R.string.error_rsa_sign, err.getClass().toString(), err.getLocalizedMessage()); return null; } }
Java
package com.ecomdev.openvpn; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.ecomdev.openvpn.core.ProfileManager; public class OnBootReceiver extends BroadcastReceiver { // Debug: am broadcast -a android.intent.action.BOOT_COMPLETED @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { VpnProfile bootProfile = ProfileManager.getOnBootProfile(context); if(bootProfile != null) { launchVPN(bootProfile, context); } } } void launchVPN(VpnProfile profile, Context context) { Intent startVpnIntent = new Intent(Intent.ACTION_MAIN); startVpnIntent.setClass(context, LaunchVPN.class); startVpnIntent.putExtra(LaunchVPN.EXTRA_KEY,profile.getUUIDString()); startVpnIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startVpnIntent.putExtra(LaunchVPN.EXTRA_HIDELOG, true); context.startActivity(startVpnIntent); } }
Java
package com.ecomdev.openvpn; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Binder; import android.os.IBinder; import com.ecomdev.openvpn.fragments.Utils; /** * Created by ymka on 03.08.14. */ public class DemoService extends Service { private final LocalBinder mBinder = new LocalBinder(); private UpdateTimeListener mListener; @Override public IBinder onBind(Intent intent) { return mBinder; } public void setListener(UpdateTimeListener listener) { mListener = listener; } public void updateTime() { final int demoHours = getResources().getInteger(R.integer.demoTime); //hours in milliseconds int demoTime = demoHours * 60 * 60 * 1000; SharedPreferences preferences = getSharedPreferences(Constants.sMAIN_SHARED_PREFERENCE, MODE_PRIVATE); long startDemoTime = preferences.getLong(Constants.sPREF_START_DEMO_TIME, 0); boolean isTimePassed = Utils.isDifferenceNotExceed(System.currentTimeMillis(), startDemoTime, demoTime); if (isTimePassed) { preferences.edit().putBoolean(Constants.sPREF_IS_TIMEOUT, true); Intent intent = new Intent(getApplicationContext(), UpdateDemoTimeReceiver.class); PendingIntent broadcast = PendingIntent.getBroadcast(getApplicationContext(), Constants.sUPDATE_DEMO_TIME_RECEIVER_NUM, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(broadcast); mListener.timeOut(); } else { preferences.edit().putInt(Constants.sPREF_LEFT_HOURS, demoHours - 1); mListener.updateDemoHours(); } } public class LocalBinder extends Binder { public DemoService getService() { return DemoService.this; } } public interface UpdateTimeListener { public void updateDemoHours(); public void timeOut(); } }
Java
package com.ecomdev.openvpn.views; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.util.Pair; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; public class RemoteCNPreference extends DialogPreference { private Spinner mSpinner; private EditText mEditText; private int mDNType; private String mDn; private TextView mRemoteTLSNote; //private ScrollView mScrollView; public RemoteCNPreference(Context context, AttributeSet attrs) { super(context, attrs); setDialogLayoutResource(R.layout.tlsremote); } @Override protected void onBindDialogView(View view) { super.onBindDialogView(view); mEditText = (EditText) view.findViewById(R.id.tlsremotecn); mSpinner = (Spinner) view.findViewById(R.id.x509verifytype); mRemoteTLSNote = (TextView) view.findViewById(R.id.tlsremotenote); //mScrollView = (ScrollView) view.findViewById(R.id.tlsremotescroll); if(mDn!=null) mEditText.setText(mDn); populateSpinner(); } public String getCNText() { return mDn; } public int getAuthtype() { return mDNType; } public void setDN(String dn) { mDn = dn; if(mEditText!=null) mEditText.setText(dn); } public void setAuthType(int x509authtype) { mDNType = x509authtype; if (mSpinner!=null) populateSpinner(); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { String dn = mEditText.getText().toString(); int authtype = getAuthTypeFromSpinner(); if (callChangeListener(new Pair<Integer, String>(authtype, dn))) { mDn = dn; mDNType = authtype; } } } private void populateSpinner() { ArrayAdapter<String> authtypes = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item); authtypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); authtypes.add(getContext().getString(R.string.complete_dn)); authtypes.add(getContext().getString(R.string.rdn)); authtypes.add(getContext().getString(R.string.rdn_prefix)); if ((mDNType == VpnProfile.X509_VERIFY_TLSREMOTE || mDNType == VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING) && !(mDn==null || "".equals(mDn))) { authtypes.add(getContext().getString(R.string.tls_remote_deprecated)); mRemoteTLSNote.setVisibility(View.VISIBLE); } else { mRemoteTLSNote.setVisibility(View.GONE); } mSpinner.setAdapter(authtypes); mSpinner.setSelection(getSpinnerPositionFromAuthTYPE()); } private int getSpinnerPositionFromAuthTYPE() { switch (mDNType) { case VpnProfile.X509_VERIFY_TLSREMOTE_DN: return 0; case VpnProfile.X509_VERIFY_TLSREMOTE_RDN: return 1; case VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX: return 2; case VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING: case VpnProfile.X509_VERIFY_TLSREMOTE: if (mDn==null || "".equals(mDn)) return 1; else return 3; default: return 0; } } private int getAuthTypeFromSpinner() { int pos = mSpinner.getSelectedItemPosition(); switch (pos) { case 0: return VpnProfile.X509_VERIFY_TLSREMOTE_DN; case 1: return VpnProfile.X509_VERIFY_TLSREMOTE_RDN; case 2: return VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX; case 3: // This is the tls-remote entry, only visible if mDntype is a // tls-remote type return mDNType; default: return VpnProfile.X509_VERIFY_TLSREMOTE; } } }
Java
package com.ecomdev.openvpn.views; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.ViewConfiguration; import android.widget.SeekBar; public class SeekBarTicks extends SeekBar { private Paint mTickPaint; private float mTickHeight; private float tickHeightRatio = 0.6f; public SeekBarTicks(Context context, AttributeSet attrs) { super (context, attrs); initTicks (context, attrs, android.R.attr.seekBarStyle); } public SeekBarTicks(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initTicks (context, attrs, defStyle); /*mTickHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tickHeightDP, ctx.getResources().getDisplayMetrics()); */ } private void initTicks(Context context, AttributeSet attrs, int defStyle) { TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.secondaryProgress }, defStyle, 0); int tickColor = a.getColor(0, android.R.color.black); mTickPaint = new Paint(); mTickPaint.setColor( context.getResources().getColor(tickColor)); a.recycle(); } @Override protected synchronized void onDraw(Canvas canvas) { drawTicks(canvas); super.onDraw(canvas); } private void drawTicks(Canvas canvas) { final int available = getWidth() - getPaddingLeft() - getPaddingRight(); final int availableHeight = getHeight() - getPaddingBottom() - getPaddingTop(); int extrapadding = (int) ((availableHeight- (availableHeight * tickHeightRatio))/2); int tickSpacing = available / (getMax() ); for (int i = 1; i < getMax(); i++) { final float x = getPaddingLeft() + i * tickSpacing; canvas.drawLine(x, getPaddingTop()+extrapadding, x, getHeight()-getPaddingBottom()-extrapadding, mTickPaint); } } }
Java
package com.ecomdev.openvpn.views; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.activities.FileSelect; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.core.X509Utils; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.ecomdev.openvpn.fragments.Utils; import java.io.*; import static android.os.Build.*; public class FileSelectLayout extends LinearLayout implements OnClickListener { public void parseResponse(Intent data, Context c) { if (VERSION.SDK_INT < VERSION_CODES.KITKAT) { String fileData = data.getStringExtra(FileSelect.RESULT_DATA); setData(fileData, c); } else if (data != null) { try { String newData = Utils.getStringFromFilePickerResult(fileType,data,c); if (newData!=null) setData(VpnProfile.INLINE_TAG + newData, c); } catch (IOException e) { VpnStatus.logException(e); } } } public interface FileSelectCallback { String getString(int res); void startActivityForResult(Intent startFC, int mTaskId); } private boolean mIsCertificate; private TextView mDataView; private String mData; private FileSelectCallback mFragment; private int mTaskId; private Button mSelectButton; private Utils.FileType fileType; private String mTitle; private boolean mShowClear; private TextView mDataDetails; public FileSelectLayout(Context context, AttributeSet attrset) { super(context, attrset); TypedArray ta = context.obtainStyledAttributes(attrset, R.styleable.FileSelectLayout); setupViews(ta.getString(R.styleable.FileSelectLayout_title), ta.getBoolean(R.styleable.FileSelectLayout_certificate, true)); ta.recycle(); } public FileSelectLayout (Context context, String title, boolean isCerticate) { super(context); setupViews(title, isCerticate); } private void setupViews(String title, boolean isCertificate) { inflate(getContext(), R.layout.file_select, this); mTitle = title; mIsCertificate = isCertificate; TextView tview = (TextView) findViewById(R.id.file_title); tview.setText(mTitle); mDataView = (TextView) findViewById(R.id.file_selected_item); mDataDetails = (TextView) findViewById(R.id.file_selected_description); mSelectButton = (Button) findViewById(R.id.file_select_button); mSelectButton.setOnClickListener(this); } public void setCaller(FileSelectCallback fragment, int i, Utils.FileType ft) { mTaskId = i; mFragment = fragment; fileType = ft; } public void getCertificateFileDialog() { Intent startFC = new Intent(getContext(), FileSelect.class); startFC.putExtra(FileSelect.START_DATA, mData); startFC.putExtra(FileSelect.WINDOW_TITLE, mTitle); if (fileType == Utils.FileType.PKCS12) startFC.putExtra(FileSelect.DO_BASE64_ENCODE, true); if (mShowClear) startFC.putExtra(FileSelect.SHOW_CLEAR_BUTTON, true); mFragment.startActivityForResult(startFC, mTaskId); } public String getData() { return mData; } public void setData(String data, Context c) { mData = data; if (data == null) { mDataView.setText(mFragment.getString(R.string.no_data)); mDataDetails.setText(""); } else { if (mData.startsWith(VpnProfile.INLINE_TAG)) mDataView.setText(R.string.inline_file_data); else mDataView.setText(data); if (mIsCertificate) mDataDetails.setText(X509Utils.getCertificateFriendlyName(c, data)); } } @Override public void onClick(View v) { if (v == mSelectButton) { if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { Intent startFilePicker = Utils.getFilePickerIntent(fileType); mFragment.startActivityForResult(startFilePicker, mTaskId); } else { getCertificateFileDialog(); } } } public void setShowClear() { mShowClear = true; } }
Java
package com.ecomdev.openvpn; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.ContentProvider; import android.content.ContentProvider.PipeDataWriter; import android.content.ContentValues; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.OpenableColumns; import android.util.Log; import com.ecomdev.openvpn.core.VpnStatus; /** * A very simple content provider that can serve arbitrary asset files from * our .apk. */ public class FileProvider extends ContentProvider implements PipeDataWriter<InputStream> { @Override public boolean onCreate() { return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { File dumpfile = getFileFromURI(uri); MatrixCursor c = new MatrixCursor(projection); Object[] row = new Object[projection.length]; int i=0; for (String r:projection) { if(r.equals(OpenableColumns.SIZE)) row[i] = dumpfile.length(); if(r.equals(OpenableColumns.DISPLAY_NAME)) row[i] = dumpfile.getName(); i++; } c.addRow(row); return c; } catch (FileNotFoundException e) { VpnStatus.logException(e); return null; } } @Override public Uri insert(Uri uri, ContentValues values) { // Don't support inserts. return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Don't support deletes. return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Don't support updates. return 0; } @Override public String getType(Uri uri) { // For this sample, assume all files are .apks. return "application/octet-stream"; } @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { File dumpfile = getFileFromURI(uri); try { InputStream is = new FileInputStream(dumpfile); // Start a new thread that pipes the stream data back to the caller. return new AssetFileDescriptor( openPipeHelper(uri, null, null, is, this), 0, dumpfile.length()); } catch (IOException e) { throw new FileNotFoundException("Unable to open minidump " + uri); } } private File getFileFromURI(Uri uri) throws FileNotFoundException { // Try to open an asset with the given name. String path = uri.getPath(); if(path.startsWith("/")) path = path.replaceFirst("/", ""); // I think this already random enough, no need for magic secure cookies // 1f9563a4-a1f5-2165-255f2219-111823ef.dmp if (!path.matches("^[0-9a-z-.]*(dmp|dmp.log)$")) throw new FileNotFoundException("url not in expect format " + uri); File cachedir = getContext().getCacheDir(); return new File(cachedir,path); } @Override public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, Bundle opts, InputStream args) { // Transfer data from the asset to the pipe the client is reading. byte[] buffer = new byte[8192]; int n; FileOutputStream fout = new FileOutputStream(output.getFileDescriptor()); try { while ((n=args.read(buffer)) >= 0) { fout.write(buffer, 0, n); } } catch (IOException e) { Log.i("OpenVPNFileProvider", "Failed transferring", e); } finally { try { args.close(); } catch (IOException e) { } try { fout.close(); } catch (IOException e) { } } } }
Java
package com.ecomdev.openvpn.core; import android.Manifest.permission; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.VpnService; import android.os.*; import android.os.Handler.Callback; import android.preference.PreferenceManager; import android.text.TextUtils; import com.ecomdev.openvpn.activities.DisconnectVPN; import com.ecomdev.openvpn.activities.LogWindow; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.VpnStatus.ByteCountListener; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import com.ecomdev.openvpn.core.VpnStatus.StateListener; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Locale; import java.util.Vector; import static com.ecomdev.openvpn.core.NetworkSpace.*; import static com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus.*; public class OpenVpnService extends VpnService implements StateListener, Callback, ByteCountListener { public static final String START_SERVICE = "com.ecomdev.openvpn.START_SERVICE"; public static final String START_SERVICE_STICKY = "com.ecomdev.openvpn.START_SERVICE_STICKY"; public static final String ALWAYS_SHOW_NOTIFICATION = "com.ecomdev.openvpn.NOTIFICATION_ALWAYS_VISIBLE"; public static final String DISCONNECT_VPN = "com.ecomdev.openvpn.DISCONNECT_VPN"; private static final String PAUSE_VPN = "com.ecomdev.openvpn.PAUSE_VPN"; private static final String RESUME_VPN = "com.ecomdev.openvpn.RESUME_VPN"; private static final int OPENVPN_STATUS = 1; private static boolean mNotificationAlwaysVisible = false; private final Vector<String> mDnslist = new Vector<String>(); private final NetworkSpace mRoutes = new NetworkSpace(); private final NetworkSpace mRoutesv6 = new NetworkSpace(); private final IBinder mBinder = new LocalBinder(); private Thread mProcessThread = null; private VpnProfile mProfile; private String mDomain = null; private CIDRIP mLocalIP = null; private int mMtu; private String mLocalIPv6 = null; private DeviceStateReceiver mDeviceStateReceiver; private boolean mDisplayBytecount = false; private boolean mStarting = false; private long mConnecttime; private boolean mOvpn3 = false; private OpenVPNManagement mManagement; private String mLastTunCfg; private String mRemoteGW; // From: http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java public static String humanReadableByteCount(long bytes, boolean mbit) { if (mbit) bytes = bytes * 8; int unit = mbit ? 1000 : 1024; if (bytes < unit) return bytes + (mbit ? " bit" : " B"); int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (mbit ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (mbit ? "" : ""); if (mbit) return String.format(Locale.getDefault(), "%.1f %sbit", bytes / Math.pow(unit, exp), pre); else return String.format(Locale.getDefault(), "%.1f %sB", bytes / Math.pow(unit, exp), pre); } @Override public IBinder onBind(Intent intent) { String action = intent.getAction(); if (action != null && action.equals(START_SERVICE)) return mBinder; else return super.onBind(intent); } @Override public void onRevoke() { mManagement.stopVPN(); endVpnService(); } // Similar to revoke but do not try to stop process public void processDied() { endVpnService(); } private void endVpnService() { mProcessThread = null; VpnStatus.removeByteCountListener(this); unregisterDeviceStateReceiver(); ProfileManager.setConntectedVpnProfileDisconnected(this); if (!mStarting) { stopForeground(!mNotificationAlwaysVisible); if (!mNotificationAlwaysVisible) { stopSelf(); VpnStatus.removeStateListener(this); } } } private void showNotification(String msg, String tickerText, boolean lowpriority, long when, ConnectionStatus status) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = getIconByConnectionStatus(status); android.app.Notification.Builder nbuilder = new Notification.Builder(this); if (mProfile != null) nbuilder.setContentTitle(getString(R.string.notifcation_title, mProfile.mName)); else nbuilder.setContentTitle(getString(R.string.notifcation_title_notconnect)); nbuilder.setContentText(msg); nbuilder.setOnlyAlertOnce(true); nbuilder.setOngoing(true); nbuilder.setContentIntent(getLogPendingIntent()); nbuilder.setSmallIcon(icon); if (when != 0) nbuilder.setWhen(when); // Try to set the priority available since API 16 (Jellybean) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) jbNotificationExtras(lowpriority, nbuilder); if (tickerText != null && !tickerText.equals("")) nbuilder.setTicker(tickerText); @SuppressWarnings("deprecation") Notification notification = nbuilder.getNotification(); mNotificationManager.notify(OPENVPN_STATUS, notification); startForeground(OPENVPN_STATUS, notification); } private int getIconByConnectionStatus(ConnectionStatus level) { switch (level) { case LEVEL_CONNECTED: return R.drawable.ic_stat_vpn; case LEVEL_AUTH_FAILED: case LEVEL_NONETWORK: case LEVEL_NOTCONNECTED: return R.drawable.ic_stat_vpn_offline; case LEVEL_CONNECTING_NO_SERVER_REPLY_YET: case LEVEL_WAITING_FOR_USER_INPUT: return R.drawable.ic_stat_vpn_outline; case LEVEL_CONNECTING_SERVER_REPLIED: return R.drawable.ic_stat_vpn_empty_halo; case LEVEL_VPNPAUSED: return android.R.drawable.ic_media_pause; case UNKNOWN_LEVEL: default: return R.drawable.ic_stat_vpn; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void jbNotificationExtras(boolean lowpriority, android.app.Notification.Builder nbuilder) { try { if (lowpriority) { Method setpriority = nbuilder.getClass().getMethod("setPriority", int.class); // PRIORITY_MIN == -2 setpriority.invoke(nbuilder, -2); Method setUsesChronometer = nbuilder.getClass().getMethod("setUsesChronometer", boolean.class); setUsesChronometer.invoke(nbuilder, true); } Intent disconnectVPN = new Intent(this, DisconnectVPN.class); disconnectVPN.setAction(DISCONNECT_VPN); PendingIntent disconnectPendingIntent = PendingIntent.getActivity(this, 0, disconnectVPN, 0); nbuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.cancel_connection), disconnectPendingIntent); Intent pauseVPN = new Intent(this, OpenVpnService.class); if (mDeviceStateReceiver == null || !mDeviceStateReceiver.isUserPaused()) { pauseVPN.setAction(PAUSE_VPN); PendingIntent pauseVPNPending = PendingIntent.getService(this, 0, pauseVPN, 0); nbuilder.addAction(android.R.drawable.ic_media_pause, getString(R.string.pauseVPN), pauseVPNPending); } else { pauseVPN.setAction(RESUME_VPN); PendingIntent resumeVPNPending = PendingIntent.getService(this, 0, pauseVPN, 0); nbuilder.addAction(android.R.drawable.ic_media_play, getString(R.string.resumevpn), resumeVPNPending); } //ignore exception } catch (NoSuchMethodException nsm) { VpnStatus.logException(nsm); } catch (IllegalArgumentException e) { VpnStatus.logException(e); } catch (IllegalAccessException e) { VpnStatus.logException(e); } catch (InvocationTargetException e) { VpnStatus.logException(e); } } PendingIntent getLogPendingIntent() { // Let the configure Button show the Log Intent intent = new Intent(getBaseContext(), LogWindow.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); PendingIntent startLW = PendingIntent.getActivity(this, 0, intent, 0); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); return startLW; } synchronized void registerDeviceStateReceiver(OpenVPNManagement magnagement) { // Registers BroadcastReceiver to track network connection changes. IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); mDeviceStateReceiver = new DeviceStateReceiver(magnagement); registerReceiver(mDeviceStateReceiver, filter); VpnStatus.addByteCountListener(mDeviceStateReceiver); } synchronized void unregisterDeviceStateReceiver() { if (mDeviceStateReceiver != null) try { VpnStatus.removeByteCountListener(mDeviceStateReceiver); this.unregisterReceiver(mDeviceStateReceiver); } catch (IllegalArgumentException iae) { // I don't know why this happens: // java.lang.IllegalArgumentException: Receiver not registered: com.ecomdev.openvpn.NetworkSateReceiver@41a61a10 // Ignore for now ... iae.printStackTrace(); } mDeviceStateReceiver = null; } public void userPause(boolean shouldBePaused) { if (mDeviceStateReceiver != null) mDeviceStateReceiver.userPause(shouldBePaused); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getBooleanExtra(ALWAYS_SHOW_NOTIFICATION, false)) mNotificationAlwaysVisible = true; VpnStatus.addStateListener(this); VpnStatus.addByteCountListener(this); if (intent != null && PAUSE_VPN.equals(intent.getAction())) { if (mDeviceStateReceiver != null) mDeviceStateReceiver.userPause(true); return START_NOT_STICKY; } if (intent != null && RESUME_VPN.equals(intent.getAction())) { if (mDeviceStateReceiver != null) mDeviceStateReceiver.userPause(false); return START_NOT_STICKY; } if (intent != null && START_SERVICE.equals(intent.getAction())) return START_NOT_STICKY; if (intent != null && START_SERVICE_STICKY.equals(intent.getAction())) { return START_REDELIVER_INTENT; } assert (intent != null); // Extract information from the intent. String prefix = getPackageName(); String[] argv = intent.getStringArrayExtra(prefix + ".ARGV"); String nativelibdir = intent.getStringExtra(prefix + ".nativelib"); String profileUUID = intent.getStringExtra(prefix + ".profileUUID"); mProfile = ProfileManager.get(this, profileUUID); String startTitle = getString(R.string.start_vpn_title, mProfile.mName); String startTicker = getString(R.string.start_vpn_ticker, mProfile.mName); showNotification(startTitle, startTicker, false, 0, LEVEL_CONNECTING_NO_SERVER_REPLY_YET); // Set a flag that we are starting a new VPN mStarting = true; // Stop the previous session by interrupting the thread. if (mManagement != null && mManagement.stopVPN()) // an old was asked to exit, wait 1s try { Thread.sleep(1000); } catch (InterruptedException e) { } if (mProcessThread != null) { mProcessThread.interrupt(); try { Thread.sleep(1000); } catch (InterruptedException e) { } } // An old running VPN should now be exited mStarting = false; // Start a new session by creating a new thread. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mOvpn3 = prefs.getBoolean("ovpn3", false); mOvpn3 = false; // Open the Management Interface if (!mOvpn3) { // start a Thread that handles incoming messages of the managment socket OpenVpnManagementThread ovpnManagementThread = new OpenVpnManagementThread(mProfile, this); if (ovpnManagementThread.openManagementInterface(this)) { Thread mSocketManagerThread = new Thread(ovpnManagementThread, "OpenVPNManagementThread"); mSocketManagerThread.start(); mManagement = ovpnManagementThread; VpnStatus.logInfo("started Socket Thread"); } else { return START_NOT_STICKY; } } Runnable processThread; if (mOvpn3) { OpenVPNManagement mOpenVPN3 = instantiateOpenVPN3Core(); processThread = (Runnable) mOpenVPN3; mManagement = mOpenVPN3; } else { HashMap<String, String> env = new HashMap<String, String>(); processThread = new OpenVPNThread(this, argv, env, nativelibdir); } mProcessThread = new Thread(processThread, "OpenVPNProcessThread"); mProcessThread.start(); if (mDeviceStateReceiver != null) unregisterDeviceStateReceiver(); registerDeviceStateReceiver(mManagement); ProfileManager.setConnectedVpnProfile(this, mProfile); return START_NOT_STICKY; } private OpenVPNManagement instantiateOpenVPN3Core() { return null; } @Override public void onDestroy() { if (mProcessThread != null) { mManagement.stopVPN(); mProcessThread.interrupt(); } if (mDeviceStateReceiver != null) { this.unregisterReceiver(mDeviceStateReceiver); } // Just in case unregister for state VpnStatus.removeStateListener(this); } private String getTunConfigString() { // The format of the string is not important, only that // two identical configurations produce the same result String cfg = "TUNCFG UNQIUE STRING ips:"; if (mLocalIP != null) cfg += mLocalIP.toString(); if (mLocalIPv6 != null) cfg += mLocalIPv6.toString(); cfg += "routes: " + TextUtils.join("|", mRoutes.getNetworks(true)) + TextUtils.join("|", mRoutesv6.getNetworks(true)); cfg += "excl. routes:" + TextUtils.join("|", mRoutes.getNetworks(false)) + TextUtils.join("|", mRoutesv6.getNetworks(false)); cfg += "dns: " + TextUtils.join("|", mDnslist); cfg += "domain: " + mDomain; cfg += "mtu: " + mMtu; return cfg; } public ParcelFileDescriptor openTun() { Builder builder = new Builder(); if (mLocalIP == null && mLocalIPv6 == null) { VpnStatus.logError(getString(R.string.opentun_no_ipaddr)); return null; } if (mLocalIP != null) { try { builder.addAddress(mLocalIP.mIp, mLocalIP.len); } catch (IllegalArgumentException iae) { VpnStatus.logError(R.string.dns_add_error, mLocalIP, iae.getLocalizedMessage()); return null; } } if (mLocalIPv6 != null) { String[] ipv6parts = mLocalIPv6.split("/"); try { builder.addAddress(ipv6parts[0], Integer.parseInt(ipv6parts[1])); } catch (IllegalArgumentException iae) { VpnStatus.logError(R.string.ip_add_error, mLocalIPv6, iae.getLocalizedMessage()); return null; } } for (String dns : mDnslist) { try { builder.addDnsServer(dns); } catch (IllegalArgumentException iae) { VpnStatus.logError(R.string.dns_add_error, dns, iae.getLocalizedMessage()); } } builder.setMtu(mMtu); for (NetworkSpace.ipAddress route : mRoutes.getPositiveIPList()) { try { builder.addRoute(route.getIPv4Address(), route.networkMask); } catch (IllegalArgumentException ia) { VpnStatus.logError(getString(R.string.route_rejected) + route + " " + ia.getLocalizedMessage()); } } for (NetworkSpace.ipAddress route6 : mRoutesv6.getPositiveIPList()) { try { builder.addRoute(route6.getIPv6Address(), route6.networkMask); } catch (IllegalArgumentException ia) { VpnStatus.logError(getString(R.string.route_rejected) + route6 + " " + ia.getLocalizedMessage()); } } if (mDomain != null) builder.addSearchDomain(mDomain); VpnStatus.logInfo(R.string.last_openvpn_tun_config); VpnStatus.logInfo(R.string.local_ip_info, mLocalIP.mIp, mLocalIP.len, mLocalIPv6, mMtu); VpnStatus.logInfo(R.string.dns_server_info, TextUtils.join(", ", mDnslist), mDomain); VpnStatus.logInfo(R.string.routes_info_incl, TextUtils.join(", ", mRoutes.getNetworks(true)), TextUtils.join(", ", mRoutesv6.getNetworks(true))); VpnStatus.logInfo(R.string.routes_info_excl, TextUtils.join(", ", mRoutes.getNetworks(false)),TextUtils.join(", ", mRoutesv6.getNetworks(false))); VpnStatus.logDebug(R.string.routes_debug, TextUtils.join(", ", mRoutes.getPositiveIPList()), TextUtils.join(", ", mRoutesv6.getPositiveIPList())); String session = mProfile.mName; if (mLocalIP != null && mLocalIPv6 != null) session = getString(R.string.session_ipv6string, session, mLocalIP, mLocalIPv6); else if (mLocalIP != null) session = getString(R.string.session_ipv4string, session, mLocalIP); builder.setSession(session); // No DNS Server, log a warning if (mDnslist.size() == 0) VpnStatus.logInfo(R.string.warn_no_dns); mLastTunCfg = getTunConfigString(); // Reset information mDnslist.clear(); mRoutes.clear(); mRoutesv6.clear(); mLocalIP = null; mLocalIPv6 = null; mDomain = null; builder.setConfigureIntent(getLogPendingIntent()); try { return builder.establish(); } catch (Exception e) { VpnStatus.logError(R.string.tun_open_error); VpnStatus.logError(getString(R.string.error) + e.getLocalizedMessage()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) { VpnStatus.logError(R.string.tun_error_helpful); } return null; } } public void addDNS(String dns) { mDnslist.add(dns); } public void setDomain(String domain) { if (mDomain == null) { mDomain = domain; } } public void addRoute (String dest, String mask, String gateway, String device) { CIDRIP route = new CIDRIP(dest, mask); boolean include = isAndroidTunDevice(device); NetworkSpace.ipAddress gatewayIP = new NetworkSpace.ipAddress(new CIDRIP(gateway, 32),false); NetworkSpace.ipAddress localNet = new NetworkSpace.ipAddress(mLocalIP,true); if (localNet.containsNet(gatewayIP)) include=true; if (gateway!= null && (gateway.equals("255.255.255.255") || gateway.equals(mRemoteGW))) include=true; if (route.len == 32 && !mask.equals("255.255.255.255")) { VpnStatus.logWarning(R.string.route_not_cidr, dest, mask); } if (route.normalise()) VpnStatus.logWarning(R.string.route_not_netip, dest, route.len, route.mIp); mRoutes.addIP(route, include); } public void addRoutev6(String network, String device) { String[] v6parts = network.split("/"); boolean included = isAndroidTunDevice(device); // Tun is opened after ROUTE6, no device name may be present try { Inet6Address ip = (Inet6Address) InetAddress.getAllByName(v6parts[0])[0]; int mask = Integer.parseInt(v6parts[1]); mRoutesv6.addIPv6(ip, mask, included); } catch (UnknownHostException e) { VpnStatus.logException(e); } } private boolean isAndroidTunDevice(String device) { return device!=null && (device.startsWith("tun") || "(null)".equals(device) || "vpnservice-tun".equals(device)); } public void setMtu(int mtu) { mMtu = mtu; } public void setLocalIP(CIDRIP cdrip) { mLocalIP = cdrip; } public void setLocalIP(String local, String netmask, int mtu, String mode) { mLocalIP = new CIDRIP(local, netmask); mMtu = mtu; if (mLocalIP.len == 32 && !netmask.equals("255.255.255.255")) { // get the netmask as IP long netint = CIDRIP.getInt(netmask); if (Math.abs(netint - mLocalIP.getInt()) == 1) { if ("net30".equals(mode)) mLocalIP.len = 30; else mLocalIP.len = 31; } else { VpnStatus.logWarning(R.string.ip_not_cidr, local, netmask, mode); } } if ("p2p".equals(mode)) mRemoteGW=netmask; else mRemoteGW=null; } public void setLocalIPv6(String ipv6addr) { mLocalIPv6 = ipv6addr; } @Override public void updateState(String state, String logmessage, int resid, ConnectionStatus level) { // If the process is not running, ignore any state, // Notification should be invisible in this state doSendBroadcast(state, level); if (mProcessThread == null && !mNotificationAlwaysVisible) return; // Display byte count only after being connected { if (level == LEVEL_WAITING_FOR_USER_INPUT) { // The user is presented a dialog of some kind, no need to inform the user // with a notifcation return; } else if (level == LEVEL_CONNECTED) { mDisplayBytecount = true; mConnecttime = System.currentTimeMillis(); } else { mDisplayBytecount = false; } // Other notifications are shown, // This also mean we are no longer connected, ignore bytecount messages until next // CONNECTED String ticker = getString(resid); showNotification(getString(resid) + " " + logmessage, ticker, false, 0, level); } } private void doSendBroadcast(String state, ConnectionStatus level) { Intent vpnstatus = new Intent(); vpnstatus.setAction("com.ecomdev.openvpn.VPN_STATUS"); vpnstatus.putExtra("status", level.toString()); vpnstatus.putExtra("detailstatus", state); sendBroadcast(vpnstatus, permission.ACCESS_NETWORK_STATE); } @Override public void updateByteCount(long in, long out, long diffIn, long diffOut) { if (mDisplayBytecount) { String netstat = String.format(getString(R.string.statusline_bytecount), humanReadableByteCount(in, false), humanReadableByteCount(diffIn / OpenVPNManagement.mBytecountInterval, true), humanReadableByteCount(out, false), humanReadableByteCount(diffOut / OpenVPNManagement.mBytecountInterval, true)); boolean lowpriority = !mNotificationAlwaysVisible; showNotification(netstat, null, lowpriority, mConnecttime, LEVEL_CONNECTED); } } @Override public boolean handleMessage(Message msg) { Runnable r = msg.getCallback(); if (r != null) { r.run(); return true; } else { return false; } } public OpenVPNManagement getManagement() { return mManagement; } public String getTunReopenStatus() { String currentConfiguration = getTunConfigString(); if (currentConfiguration.equals(mLastTunCfg)) return "NOACTION"; else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) return "OPEN_AFTER_CLOSE"; else return "OPEN_BEFORE_CLOSE"; } public class LocalBinder extends Binder { public OpenVpnService getService() { // Return this instance of LocalService so clients can call public methods return OpenVpnService.this; } } }
Java
package com.ecomdev.openvpn.core; import java.security.InvalidKeyException; public class NativeUtils { public static native byte[] rsasign(byte[] input,int pkey) throws InvalidKeyException; static native void jniclose(int fdint); static { System.loadLibrary("stlport_shared"); System.loadLibrary("opvpnutil"); } }
Java
package com.ecomdev.openvpn.core; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.preference.PreferenceManager; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.VpnStatus.ByteCountListener; import java.util.LinkedList; import static com.ecomdev.openvpn.core.OpenVPNManagement.pauseReason; public class DeviceStateReceiver extends BroadcastReceiver implements ByteCountListener { private int lastNetwork = -1; private OpenVPNManagement mManagement; // Window time in s private final int TRAFFIC_WINDOW = 60; // Data traffic limit in bytes private final long TRAFFIC_LIMIT = 64 * 1024; connectState network = connectState.DISCONNECTED; connectState screen = connectState.SHOULDBECONNECTED; connectState userpause = connectState.SHOULDBECONNECTED; private String lastStateMsg = null; enum connectState { SHOULDBECONNECTED, PENDINGDISCONNECT, DISCONNECTED } static class Datapoint { private Datapoint(long t, long d) { timestamp = t; data = d; } long timestamp; long data; } LinkedList<Datapoint> trafficdata = new LinkedList<DeviceStateReceiver.Datapoint>(); @Override public void updateByteCount(long in, long out, long diffIn, long diffOut) { if (screen != connectState.PENDINGDISCONNECT) return; long total = diffIn + diffOut; trafficdata.add(new Datapoint(System.currentTimeMillis(), total)); while (trafficdata.getFirst().timestamp <= (System.currentTimeMillis() - TRAFFIC_WINDOW * 1000)) { trafficdata.removeFirst(); } long windowtraffic = 0; for (Datapoint dp : trafficdata) windowtraffic += dp.data; if (windowtraffic < TRAFFIC_LIMIT) { screen = connectState.DISCONNECTED; VpnStatus.logInfo(R.string.screenoff_pause, OpenVpnService.humanReadableByteCount(TRAFFIC_LIMIT, false), TRAFFIC_WINDOW); mManagement.pause(getPauseReason()); } } public void userPause(boolean pause) { if (pause) { userpause = connectState.DISCONNECTED; // Check if we should disconnect mManagement.pause(getPauseReason()); } else { boolean wereConnected = shouldBeConnected(); userpause = connectState.SHOULDBECONNECTED; if (shouldBeConnected() && !wereConnected) mManagement.resume(); else // Update the reason why we currently paused mManagement.pause(getPauseReason()); } } public DeviceStateReceiver(OpenVPNManagement magnagement) { super(); mManagement = magnagement; } @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { networkStateChange(context); } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { boolean screenOffPause = prefs.getBoolean("screenoff", false); if (screenOffPause) { if (!ProfileManager.getLastConnectedVpn().mPersistTun) VpnStatus.logError(R.string.screen_nopersistenttun); screen = connectState.PENDINGDISCONNECT; fillTrafficData(); if (network == connectState.DISCONNECTED || userpause == connectState.DISCONNECTED) screen = connectState.DISCONNECTED; } } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) { // Network was disabled because screen off boolean connected = shouldBeConnected(); screen = connectState.SHOULDBECONNECTED; /* should be connected has changed because the screen is on now, connect the VPN */ if (shouldBeConnected() != connected) mManagement.resume(); else if (!shouldBeConnected()) /*Update the reason why we are still paused */ mManagement.pause(getPauseReason()); } } private void fillTrafficData() { trafficdata.add(new Datapoint(System.currentTimeMillis(), TRAFFIC_LIMIT)); } public void networkStateChange(Context context) { NetworkInfo networkInfo = getCurrentNetworkInfo(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean sendusr1 = prefs.getBoolean("netchangereconnect", true); String netstatestring; if (networkInfo == null) { netstatestring = "not connected"; } else { String subtype = networkInfo.getSubtypeName(); if (subtype == null) subtype = ""; String extrainfo = networkInfo.getExtraInfo(); if (extrainfo == null) extrainfo = ""; /* if(networkInfo.getType()==android.net.ConnectivityManager.TYPE_WIFI) { WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiinfo = wifiMgr.getConnectionInfo(); extrainfo+=wifiinfo.getBSSID(); subtype += wifiinfo.getNetworkId(); }*/ netstatestring = String.format("%2$s %4$s to %1$s %3$s", networkInfo.getTypeName(), networkInfo.getDetailedState(), extrainfo, subtype); } if (networkInfo != null && networkInfo.getState() == State.CONNECTED) { int newnet = networkInfo.getType(); network = connectState.SHOULDBECONNECTED; if (sendusr1 && lastNetwork != newnet) { if (screen == connectState.PENDINGDISCONNECT) screen = connectState.DISCONNECTED; if (shouldBeConnected()) { if (lastNetwork == -1) { mManagement.resume(); } else { mManagement.reconnect(); } } lastNetwork = newnet; } } else if (networkInfo == null) { // Not connected, stop openvpn, set last connected network to no network lastNetwork = -1; if (sendusr1) { network = connectState.DISCONNECTED; // Set screen state to be disconnected if disconnect pending if (screen == connectState.PENDINGDISCONNECT) screen = connectState.DISCONNECTED; mManagement.pause(getPauseReason()); } } if (!netstatestring.equals(lastStateMsg)) VpnStatus.logInfo(R.string.netstatus, netstatestring); lastStateMsg = netstatestring; } public boolean isUserPaused() { return userpause == connectState.DISCONNECTED; } private boolean shouldBeConnected() { return (screen == connectState.SHOULDBECONNECTED && userpause == connectState.SHOULDBECONNECTED && network == connectState.SHOULDBECONNECTED); } private pauseReason getPauseReason() { if (userpause == connectState.DISCONNECTED) return pauseReason.userPause; if (screen == connectState.DISCONNECTED) return pauseReason.screenOff; if (network == connectState.DISCONNECTED) return pauseReason.noNetwork; return pauseReason.userPause; } private NetworkInfo getCurrentNetworkInfo(Context context) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return conn.getActiveNetworkInfo(); } }
Java
package com.ecomdev.openvpn.core; import java.util.Locale; class CIDRIP { String mIp; int len; public CIDRIP(String ip, String mask) { mIp = ip; long netmask = getInt(mask); // Add 33. bit to ensure the loop terminates netmask += 1l << 32; int lenZeros = 0; while ((netmask & 0x1) == 0) { lenZeros++; netmask = netmask >> 1; } // Check if rest of netmask is only 1s if (netmask != (0x1ffffffffl >> lenZeros)) { // Asume no CIDR, set /32 len = 32; } else { len = 32 - lenZeros; } } public CIDRIP(String address, int prefix_length) { len = prefix_length; mIp = address; } @Override public String toString() { return String.format(Locale.ENGLISH, "%s/%d", mIp, len); } public boolean normalise() { long ip = getInt(mIp); long newip = ip & (0xffffffffl << (32 - len)); if (newip != ip) { mIp = String.format("%d.%d.%d.%d", (newip & 0xff000000) >> 24, (newip & 0xff0000) >> 16, (newip & 0xff00) >> 8, newip & 0xff); return true; } else { return false; } } static long getInt(String ipaddr) { String[] ipt = ipaddr.split("\\."); long ip = 0; ip += Long.parseLong(ipt[0]) << 24; ip += Integer.parseInt(ipt[1]) << 16; ip += Integer.parseInt(ipt[2]) << 8; ip += Integer.parseInt(ipt[3]); return ip; } public long getInt() { return getInt(mIp); } }
Java
package com.ecomdev.openvpn.core; import android.util.Log; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import com.ecomdev.openvpn.core.VpnStatus.LogItem; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OpenVPNThread implements Runnable { private static final String DUMP_PATH_STRING = "Dump path: "; private static final String TAG = "OpenVPN"; public static final int M_FATAL = (1 << 4); public static final int M_NONFATAL = (1 << 5); public static final int M_WARN = (1 << 6); public static final int M_DEBUG = (1 << 7); private String[] mArgv; private Process mProcess; private String mNativeDir; private OpenVpnService mService; private String mDumpPath; private Map<String, String> mProcessEnv; public OpenVPNThread(OpenVpnService service,String[] argv, Map<String,String> processEnv, String nativelibdir) { mArgv = argv; mNativeDir = nativelibdir; mService = service; mProcessEnv = processEnv; } public void stopProcess() { mProcess.destroy(); } @Override public void run() { try { Log.i(TAG, "Starting openvpn"); startOpenVPNThreadArgs(mArgv, mProcessEnv); Log.i(TAG, "Giving up"); } catch (Exception e) { VpnStatus.logException("Starting OpenVPN Thread" ,e); Log.e(TAG, "OpenVPNThread Got " + e.toString()); } finally { int exitvalue = 0; try { if (mProcess!=null) exitvalue = mProcess.waitFor(); } catch ( IllegalThreadStateException ite) { VpnStatus.logError("Illegal Thread state: " + ite.getLocalizedMessage()); } catch (InterruptedException ie) { VpnStatus.logError("InterruptedException: " + ie.getLocalizedMessage()); } if( exitvalue != 0) VpnStatus.logError("Process exited with exit value " + exitvalue); VpnStatus.updateStateString("NOPROCESS", "No process running.", R.string.state_noprocess, ConnectionStatus.LEVEL_NOTCONNECTED); if(mDumpPath!=null) { try { BufferedWriter logout = new BufferedWriter(new FileWriter(mDumpPath + ".log")); SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.GERMAN); for(LogItem li : VpnStatus.getlogbuffer()){ String time = timeformat.format(new Date(li.getLogtime())); logout.write(time +" " + li.getString(mService) + "\n"); } logout.close(); VpnStatus.logError(R.string.minidump_generated); } catch (IOException e) { VpnStatus.logError("Writing minidump log: " + e.getLocalizedMessage()); } } mService.processDied(); Log.i(TAG, "Exiting"); } } private void startOpenVPNThreadArgs(String[] argv, Map<String, String> env) { LinkedList<String> argvlist = new LinkedList<String>(); Collections.addAll(argvlist, argv); ProcessBuilder pb = new ProcessBuilder(argvlist); // Hack O rama String lbpath = genLibraryPath(argv, pb); pb.environment().put("LD_LIBRARY_PATH", lbpath); // Add extra variables for(Entry<String,String> e:env.entrySet()){ pb.environment().put(e.getKey(), e.getValue()); } pb.redirectErrorStream(true); try { mProcess = pb.start(); // Close the output, since we don't need it mProcess.getOutputStream().close(); InputStream in = mProcess.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while(true) { String logline = br.readLine(); if(logline==null) return; if (logline.startsWith(DUMP_PATH_STRING)) mDumpPath = logline.substring(DUMP_PATH_STRING.length()); // 1380308330.240114 18000002 Send to HTTP proxy: 'X-Online-Host: bla.blabla.com' Pattern p = Pattern.compile("(\\d+).(\\d+) ([0-9a-f])+ (.*)"); Matcher m = p.matcher(logline); if(m.matches()) { int flags = Integer.parseInt(m.group(3),16); String msg = m.group(4); int logLevel = flags & 0x0F; VpnStatus.LogLevel logStatus = VpnStatus.LogLevel.INFO; if ((flags & M_FATAL) != 0) logStatus = VpnStatus.LogLevel.ERROR; else if ((flags & M_NONFATAL)!=0) logStatus = VpnStatus.LogLevel.WARNING; else if ((flags & M_WARN)!=0) logStatus = VpnStatus.LogLevel.WARNING; else if ((flags & M_DEBUG)!=0) logStatus = VpnStatus.LogLevel.VERBOSE; if (msg.startsWith("MANAGEMENT: CMD")) logLevel = Math.max(4, logLevel); VpnStatus.logMessageOpenVPN(logStatus,logLevel,msg); } else { VpnStatus.logInfo("P:" + logline); } } } catch (IOException e) { VpnStatus.logException("Error reading from output of OpenVPN process" , e); stopProcess(); } } private String genLibraryPath(String[] argv, ProcessBuilder pb) { // Hack until I find a good way to get the real library path String applibpath = argv[0].replace("/cache/" + VpnProfile.MINIVPN , "/lib"); String lbpath = pb.environment().get("LD_LIBRARY_PATH"); if(lbpath==null) lbpath = applibpath; else lbpath = lbpath + ":" + applibpath; if (!applibpath.equals(mNativeDir)) { lbpath = lbpath + ":" + mNativeDir; } return lbpath; } }
Java
package com.ecomdev.openvpn.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.content.Intent; import android.os.Build; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; public class VPNLaunchHelper { static private boolean writeMiniVPN(Context context) { File mvpnout = new File(context.getCacheDir(),VpnProfile.MINIVPN); if (mvpnout.exists() && mvpnout.canExecute()) return true; IOException e2 = null; try { InputStream mvpn; try { mvpn = context.getAssets().open("minivpn." + Build.CPU_ABI); } catch (IOException errabi) { VpnStatus.logInfo("Failed getting assets for archicture " + Build.CPU_ABI); e2=errabi; mvpn = context.getAssets().open("minivpn." + Build.CPU_ABI2); } FileOutputStream fout = new FileOutputStream(mvpnout); byte buf[]= new byte[4096]; int lenread = mvpn.read(buf); while(lenread> 0) { fout.write(buf, 0, lenread); lenread = mvpn.read(buf); } fout.close(); if(!mvpnout.setExecutable(true)) { VpnStatus.logError("Failed to set minivpn executable"); return false; } return true; } catch (IOException e) { if(e2!=null) VpnStatus.logException(e2); VpnStatus.logException(e); return false; } } public static void startOpenVpn(VpnProfile startprofile, Context context) { if(!writeMiniVPN(context)) { VpnStatus.logError("Error writing minivpn binary"); return; } VpnStatus.logInfo(R.string.building_configration); Intent startVPN = startprofile.prepareIntent(context); if(startVPN!=null) context.startService(startVPN); } }
Java
package com.ecomdev.openvpn.core; import android.content.Context; import android.text.TextUtils; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemReader; import javax.security.auth.x500.X500Principal; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Hashtable; public class X509Utils { public static Certificate getCertificateFromFile(String certfilename) throws FileNotFoundException, CertificateException { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); InputStream inStream; if(certfilename.startsWith(VpnProfile.INLINE_TAG)) { // The java certifcate reader is ... kind of stupid // It does NOT ignore chars before the --BEGIN ... int subIndex = certfilename.indexOf("-----BEGIN CERTIFICATE-----"); subIndex = Math.max(0,subIndex); inStream = new ByteArrayInputStream(certfilename.substring(subIndex).getBytes()); } else { inStream = new FileInputStream(certfilename); } return certFact.generateCertificate(inStream); } public static PemObject readPemObjectFromFile (String keyfilename) throws IOException { Reader inStream; if(keyfilename.startsWith(VpnProfile.INLINE_TAG)) inStream = new StringReader(keyfilename.replace(VpnProfile.INLINE_TAG,"")); else inStream = new FileReader(new File(keyfilename)); PemReader pr = new PemReader(inStream); PemObject r = pr.readPemObject(); pr.close(); return r; } public static String getCertificateFriendlyName (Context c, String filename) { if(!TextUtils.isEmpty(filename)) { try { X509Certificate cert = (X509Certificate) getCertificateFromFile(filename); return getCertificateFriendlyName(cert); } catch (Exception e) { VpnStatus.logError("Could not read certificate" + e.getLocalizedMessage()); } } return c.getString(R.string.cannotparsecert); } public static String getCertificateFriendlyName(X509Certificate cert) { X500Principal principal = cert.getSubjectX500Principal(); byte[] encodedSubject = principal.getEncoded(); String friendlyName=null; /* Hack so we do not have to ship a whole Spongy/bouncycastle */ Exception exp=null; try { Class X509NameClass = Class.forName("com.android.org.bouncycastle.asn1.x509.X509Name"); Method getInstance = X509NameClass.getMethod("getInstance",Object.class); Hashtable defaultSymbols = (Hashtable) X509NameClass.getField("DefaultSymbols").get(X509NameClass); if (!defaultSymbols.containsKey("1.2.840.113549.1.9.1")) defaultSymbols.put("1.2.840.113549.1.9.1","eMail"); Object subjectName = getInstance.invoke(X509NameClass, encodedSubject); Method toString = X509NameClass.getMethod("toString",boolean.class,Hashtable.class); friendlyName= (String) toString.invoke(subjectName,true,defaultSymbols); } catch (ClassNotFoundException e) { exp =e ; } catch (NoSuchMethodException e) { exp =e; } catch (InvocationTargetException e) { exp =e; } catch (IllegalAccessException e) { exp =e; } catch (NoSuchFieldException e) { exp =e; } if (exp!=null) VpnStatus.logException("Getting X509 Name from certificate", exp); /* Fallback if the reflection method did not work */ if(friendlyName==null) friendlyName = principal.getName(); // Really evil hack to decode email address // See: http://code.google.com/p/android/issues/detail?id=21531 String[] parts = friendlyName.split(","); for (int i=0;i<parts.length;i++){ String part = parts[i]; if (part.startsWith("1.2.840.113549.1.9.1=#16")) { parts[i] = "email=" + ia5decode(part.replace("1.2.840.113549.1.9.1=#16", "")); } } friendlyName = TextUtils.join(",", parts); return friendlyName; } public static boolean isPrintableChar(char c) { Character.UnicodeBlock block = Character.UnicodeBlock.of( c ); return (!Character.isISOControl(c)) && block != null && block != Character.UnicodeBlock.SPECIALS; } private static String ia5decode(String ia5string) { String d = ""; for (int i=1;i<ia5string.length();i=i+2) { String hexstr = ia5string.substring(i-1,i+1); char c = (char) Integer.parseInt(hexstr,16); if (isPrintableChar(c)) { d+=c; } else if (i==1 && (c==0x12 || c==0x1b)) { ; // ignore } else { d += "\\x" + hexstr; } } return d; } }
Java
package com.ecomdev.openvpn.core; import android.annotation.TargetApi; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.RestrictionEntry; import android.os.Build; import android.os.Bundle; import java.util.ArrayList; import com.ecomdev.openvpn.R; /** * Created by arne on 25.07.13. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class GetRestrictionReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { final PendingResult result = goAsync(); new Thread() { @Override public void run() { final Bundle extras = new Bundle(); ArrayList<RestrictionEntry> restrictionEntries = initRestrictions(context); extras.putParcelableArrayList(Intent.EXTRA_RESTRICTIONS_LIST, restrictionEntries); result.setResult(Activity.RESULT_OK,null,extras); result.finish(); } }.run(); } private ArrayList<RestrictionEntry> initRestrictions(Context context) { ArrayList<RestrictionEntry> restrictions = new ArrayList<RestrictionEntry>(); RestrictionEntry allowChanges = new RestrictionEntry("allow_changes",false); allowChanges.setTitle(context.getString(R.string.allow_vpn_changes)); restrictions.add(allowChanges); return restrictions; } }
Java
package com.ecomdev.openvpn.core; import android.content.Context; import android.content.SharedPreferences; import android.net.LocalServerSocket; import android.net.LocalSocket; import android.net.LocalSocketAddress; import android.os.ParcelFileDescriptor; import android.preference.PreferenceManager; import android.util.Log; import org.jetbrains.annotations.NotNull; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.LinkedList; import java.util.Locale; import java.util.Vector; public class OpenVpnManagementThread implements Runnable, OpenVPNManagement { private static final String TAG = "openvpn"; private LocalSocket mSocket; private VpnProfile mProfile; private OpenVpnService mOpenVPNService; private LinkedList<FileDescriptor> mFDList=new LinkedList<FileDescriptor>(); private LocalServerSocket mServerSocket; private boolean mReleaseHold=true; private boolean mWaitingForRelease=false; private long mLastHoldRelease=0; private static Vector<OpenVpnManagementThread> active=new Vector<OpenVpnManagementThread>(); private LocalSocket mServerSocketLocal; private pauseReason lastPauseReason = pauseReason.noNetwork; public OpenVpnManagementThread(VpnProfile profile, OpenVpnService openVpnService) { mProfile = profile; mOpenVPNService = openVpnService; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(openVpnService); boolean managemeNetworkState = prefs.getBoolean("netchangereconnect", true); if(managemeNetworkState) mReleaseHold=false; } public boolean openManagementInterface(@NotNull Context c) { // Could take a while to open connection int tries=8; String socketName = (c.getCacheDir().getAbsolutePath() + "/" + "mgmtsocket"); // The mServerSocketLocal is transferred to the LocalServerSocket, ignore warning mServerSocketLocal = new LocalSocket(); while(tries > 0 && !mServerSocketLocal.isConnected()) { try { mServerSocketLocal.bind(new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.FILESYSTEM)); } catch (IOException e) { // wait 300 ms before retrying try { Thread.sleep(300); } catch (InterruptedException e1) { } } tries--; } try { mServerSocket = new LocalServerSocket(mServerSocketLocal.getFileDescriptor()); return true; } catch (IOException e) { VpnStatus.logException(e); } return false; } public void managmentCommand(String cmd) { try { if(mSocket!=null && mSocket.getOutputStream() !=null) { mSocket.getOutputStream().write(cmd.getBytes()); mSocket.getOutputStream().flush(); } }catch (IOException e) { // Ignore socket stack traces } } @Override public void run() { byte [] buffer =new byte[2048]; // mSocket.setSoTimeout(5); // Setting a timeout cannot be that bad String pendingInput=""; active.add(this); try { // Wait for a client to connect mSocket= mServerSocket.accept(); InputStream instream = mSocket.getInputStream(); // Close the management socket after client connected mServerSocket.close(); // Closing one of the two sockets also closes the other //mServerSocketLocal.close(); while(true) { int numbytesread = instream.read(buffer); if(numbytesread==-1) return; FileDescriptor[] fds = null; try { fds = mSocket.getAncillaryFileDescriptors(); } catch (IOException e) { VpnStatus.logException("Error reading fds from socket", e); } if(fds!=null){ Collections.addAll(mFDList, fds); } String input = new String(buffer,0,numbytesread,"UTF-8"); pendingInput += input; pendingInput=processInput(pendingInput); } } catch (IOException e) { if (!e.getMessage().equals("socket closed")) VpnStatus.logException(e); } active.remove(this); } //! Hack O Rama 2000! private void protectFileDescriptor(FileDescriptor fd) { Exception exp; try { Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$"); int fdint = (Integer) getInt.invoke(fd); // You can even get more evil by parsing toString() and extract the int from that :) mOpenVPNService.protect(fdint); //ParcelFileDescriptor pfd = ParcelFileDescriptor.fromFd(fdint); //pfd.close(); NativeUtils.jniclose(fdint); return; } catch (NoSuchMethodException e) { exp =e; } catch (IllegalArgumentException e) { exp =e; } catch (IllegalAccessException e) { exp =e; } catch (InvocationTargetException e) { exp =e; } catch (NullPointerException e) { exp =e; } Log.d("Openvpn", "Failed to retrieve fd from socket: " + fd); VpnStatus.logException("Failed to retrieve fd from socket (" + fd + ")" , exp); } private String processInput(String pendingInput) { while(pendingInput.contains("\n")) { String[] tokens = pendingInput.split("\\r?\\n", 2); processCommand(tokens[0]); if(tokens.length == 1) // No second part, newline was at the end pendingInput=""; else pendingInput=tokens[1]; } return pendingInput; } private void processCommand(String command) { //Log.i(TAG, "Line from managment" + command); if (command.startsWith(">") && command.contains(":")) { String[] parts = command.split(":",2); String cmd = parts[0].substring(1); String argument = parts[1]; if(cmd.equals("INFO")) { /* Ignore greeting from management */ return; }else if (cmd.equals("PASSWORD")) { processPWCommand(argument); } else if (cmd.equals("HOLD")) { handleHold(); } else if (cmd.equals("NEED-OK")) { processNeedCommand(argument); } else if (cmd.equals("BYTECOUNT")){ processByteCount(argument); } else if (cmd.equals("STATE")) { processState(argument); } else if (cmd.equals("PROXY")) { processProxyCMD(argument); } else if (cmd.equals("LOG")) { processLogMessage(argument); } else if (cmd.equals("RSA_SIGN")) { processSignCommand(argument); } else { VpnStatus.logWarning("MGMT: Got unrecognized command" + command); Log.i(TAG, "Got unrecognized command" + command); } } else if (command.startsWith("SUCCESS:")) { /* Ignore this kind of message too */ return; } else { Log.i(TAG, "Got unrecognized line from managment" + command); VpnStatus.logWarning("MGMT: Got unrecognized line from management:" + command); } } private void processLogMessage(String argument) { String[] args = argument.split(",",4); // 0 unix time stamp // 1 log level N,I,E etc. /* (b) zero or more message flags in a single string: I -- informational F -- fatal error N -- non-fatal error W -- warning D -- debug, and */ // 2 log message Log.d("OpenVPN", argument); VpnStatus.LogLevel level; if (args[1].equals("I")) { level = VpnStatus.LogLevel.INFO; } else if (args[1].equals("W")) { level = VpnStatus.LogLevel.WARNING; } else if (args[1].equals("D")) { level = VpnStatus.LogLevel.VERBOSE; } else if (args[1].equals("F")) { level = VpnStatus.LogLevel.ERROR; } else { level = VpnStatus.LogLevel.INFO; } int ovpnlevel = Integer.parseInt(args[2]) & 0x0F; String msg = args[3]; if (msg.startsWith("MANAGEMENT: CMD")) ovpnlevel = Math.max(4, ovpnlevel); VpnStatus.logMessageOpenVPN(level,ovpnlevel, msg); } private void handleHold() { if(mReleaseHold) { releaseHoldCmd(); } else { mWaitingForRelease=true; VpnStatus.updateStatePause(lastPauseReason); } } private void releaseHoldCmd() { if ((System.currentTimeMillis()- mLastHoldRelease) < 5000) { try { Thread.sleep(3000); } catch (InterruptedException e) { } } mWaitingForRelease=false; mLastHoldRelease = System.currentTimeMillis(); managmentCommand("hold release\n"); managmentCommand("bytecount " + mBytecountInterval + "\n"); managmentCommand("state on\n"); //managmentCommand("log on all\n"); } public void releaseHold() { mReleaseHold=true; if(mWaitingForRelease) releaseHoldCmd(); } private void processProxyCMD(String argument) { String[] args = argument.split(",",3); SocketAddress proxyaddr = ProxyDetection.detectProxy(mProfile); if(args.length >= 2) { String proto = args[1]; if(proto.equals("UDP")) { proxyaddr=null; } } if(proxyaddr instanceof InetSocketAddress ){ InetSocketAddress isa = (InetSocketAddress) proxyaddr; VpnStatus.logInfo(R.string.using_proxy, isa.getHostName(), isa.getPort()); String proxycmd = String.format(Locale.ENGLISH,"proxy HTTP %s %d\n", isa.getHostName(),isa.getPort()); managmentCommand(proxycmd); } else { managmentCommand("proxy NONE\n"); } } private void processState(String argument) { String[] args = argument.split(",",3); String currentstate = args[1]; if(args[2].equals(",,")) VpnStatus.updateStateString(currentstate, ""); else VpnStatus.updateStateString(currentstate, args[2]); } private void processByteCount(String argument) { // >BYTECOUNT:{BYTES_IN},{BYTES_OUT} int comma = argument.indexOf(','); long in = Long.parseLong(argument.substring(0, comma)); long out = Long.parseLong(argument.substring(comma+1)); VpnStatus.updateByteCount(in, out); } private void processNeedCommand(String argument) { int p1 =argument.indexOf('\''); int p2 = argument.indexOf('\'',p1+1); String needed = argument.substring(p1+1, p2); String extra = argument.split(":",2)[1]; String status = "ok"; if (needed.equals("PROTECTFD")) { FileDescriptor fdtoprotect = mFDList.pollFirst(); protectFileDescriptor(fdtoprotect); } else if (needed.equals("DNSSERVER")) { mOpenVPNService.addDNS(extra); }else if (needed.equals("DNSDOMAIN")){ mOpenVPNService.setDomain(extra); } else if (needed.equals("ROUTE")) { String[] routeparts = extra.split(" "); if(routeparts.length>3) { assert(routeparts[3].equals("dev")); mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]); } else { mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null); } } else if (needed.equals("ROUTE6")) { String[] routeparts = extra.split(" "); mOpenVPNService.addRoutev6(routeparts[0],routeparts[1]); } else if (needed.equals("IFCONFIG")) { String[] ifconfigparts = extra.split(" "); int mtu = Integer.parseInt(ifconfigparts[2]); mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1],mtu,ifconfigparts[3]); } else if (needed.equals("IFCONFIG6")) { mOpenVPNService.setLocalIPv6(extra); } else if (needed.equals("PERSIST_TUN_ACTION")) { // check if tun cfg stayed the same status = mOpenVPNService.getTunReopenStatus(); } else if (needed.equals("OPENTUN")) { if(sendTunFD(needed,extra)) return; else status="cancel"; // This not nice or anything but setFileDescriptors accepts only FilDescriptor class :( } else { Log.e(TAG,"Unkown needok command " + argument); return; } String cmd = String.format("needok '%s' %s\n", needed, status); managmentCommand(cmd); } private boolean sendTunFD (String needed, String extra) { Exception exp; if(!extra.equals("tun")) { // We only support tun VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!",extra)); return false; } ParcelFileDescriptor pfd = mOpenVPNService.openTun(); if(pfd==null) return false; Method setInt; int fdint = pfd.getFd(); try { setInt = FileDescriptor.class.getDeclaredMethod("setInt$",int.class); FileDescriptor fdtosend = new FileDescriptor(); setInt.invoke(fdtosend,fdint); FileDescriptor[] fds = {fdtosend}; mSocket.setFileDescriptorsForSend(fds); // Trigger a send so we can close the fd on our side of the channel // The API documentation fails to mention that it will not reset the file descriptor to // be send and will happily send the file descriptor on every write ... String cmd = String.format("needok '%s' %s\n", needed, "ok"); managmentCommand(cmd); // Set the FileDescriptor to null to stop this mad behavior mSocket.setFileDescriptorsForSend(null); pfd.close(); return true; } catch (NoSuchMethodException e) { exp =e; } catch (IllegalArgumentException e) { exp =e; } catch (IllegalAccessException e) { exp =e; } catch (InvocationTargetException e) { exp =e; } catch (IOException e) { exp =e; } VpnStatus.logException("Could not send fd over socket" , exp); return false; } private void processPWCommand(String argument) { //argument has the form Need 'Private Key' password // or ">PASSWORD:Verification Failed: '%s' ['%s']" String needed; try{ int p1 = argument.indexOf('\''); int p2 = argument.indexOf('\'',p1+1); needed = argument.substring(p1+1, p2); if (argument.startsWith("Verification Failed")) { proccessPWFailed(needed, argument.substring(p2+1)); return; } } catch (StringIndexOutOfBoundsException sioob) { VpnStatus.logError("Could not parse management Password command: " + argument); return; } String pw=null; if(needed.equals("Private Key")) { pw = mProfile.getPasswordPrivateKey(); } else if (needed.equals("Auth")) { String usercmd = String.format("username '%s' %s\n", needed, VpnProfile.openVpnEscape(mProfile.mUsername)); managmentCommand(usercmd); pw = mProfile.getPasswordAuth(); } if(pw!=null) { String cmd = String.format("password '%s' %s\n", needed, VpnProfile.openVpnEscape(pw)); managmentCommand(cmd); } else { VpnStatus.logError(String.format("Openvpn requires Authentication type '%s' but no password/key information available", needed)); } } private void proccessPWFailed(String needed, String args) { VpnStatus.updateStateString("AUTH_FAILED", needed + args, R.string.state_auth_failed, ConnectionStatus.LEVEL_AUTH_FAILED); } private static boolean stopOpenVPN() { boolean sendCMD=false; for (OpenVpnManagementThread mt: active){ mt.managmentCommand("signal SIGINT\n"); sendCMD=true; try { if(mt.mSocket !=null) mt.mSocket.close(); } catch (IOException e) { // Ignore close error on already closed socket } } return sendCMD; } public void signalusr1() { mReleaseHold=false; if(!mWaitingForRelease) managmentCommand("signal SIGUSR1\n"); else // If signalusr1 is called updateDemoHours the state string // if there is another for stopping VpnStatus.updateStatePause(lastPauseReason); } public void reconnect() { signalusr1(); releaseHold(); } private void processSignCommand(String b64data) { String signed_string = mProfile.getSignedData(b64data); if(signed_string==null) { managmentCommand("rsa-sig\n"); managmentCommand("\nEND\n"); stopOpenVPN(); return; } managmentCommand("rsa-sig\n"); managmentCommand(signed_string); managmentCommand("\nEND\n"); } @Override public void pause (pauseReason reason) { lastPauseReason = reason; signalusr1(); } @Override public void resume() { releaseHold(); /* Reset the reason why we are disconnected */ lastPauseReason = pauseReason.noNetwork; } @Override public boolean stopVPN() { return stopOpenVPN(); } }
Java
package com.ecomdev.openvpn.core; public interface OpenVPNManagement { enum pauseReason { noNetwork, userPause, screenOff } int mBytecountInterval =2; void reconnect(); void pause(pauseReason reason); void resume(); boolean stopVPN(); }
Java
package com.ecomdev.openvpn.core;/* * This software is provided 'as-is', without any express or implied * warranty. In no event will Google be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, as long as the origin is not misrepresented. */ import android.os.Build; import android.os.Process; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; /** * Fixes for the output of the default PRNG having low entropy. * * The fixes need to be applied via {@link #apply()} before any use of Java * Cryptography Architecture primitives. A good place to invoke them is in the * application's {@code onCreate}. */ public final class PRNGFixes { private static final int VERSION_CODE_JELLY_BEAN = 16; private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18; private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial(); /** Hidden constructor to prevent instantiation. */ private PRNGFixes() {} /** * Applies all fixes. * * @throws SecurityException if a fix is needed but could not be applied. */ public static void apply() { applyOpenSSLFix(); installLinuxPRNGSecureRandom(); } /** * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the * fix is not needed. * * @throws SecurityException if the fix is needed but could not be applied. */ private static void applyOpenSSLFix() throws SecurityException { if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN) || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) { // No need to apply the fix return; } try { // Mix in the device- and invocation-specific seed. Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto") .getMethod("RAND_seed", byte[].class) .invoke(null, generateSeed()); // Mix output of Linux PRNG into OpenSSL's PRNG int bytesRead = (Integer) Class.forName( "org.apache.harmony.xnet.provider.jsse.NativeCrypto") .getMethod("RAND_load_file", String.class, long.class) .invoke(null, "/dev/urandom", 1024); if (bytesRead != 1024) { throw new IOException( "Unexpected number of bytes read from Linux PRNG: " + bytesRead); } } catch (Exception e) { throw new SecurityException("Failed to seed OpenSSL PRNG", e); } } /** * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the * default. Does nothing if the implementation is already the default or if * there is not need to install the implementation. * * @throws SecurityException if the fix is needed but could not be applied. */ private static void installLinuxPRNGSecureRandom() throws SecurityException { if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) { // No need to apply the fix return; } // Install a Linux PRNG-based SecureRandom implementation as the // default, if not yet installed. Provider[] secureRandomProviders = Security.getProviders("SecureRandom.SHA1PRNG"); if ((secureRandomProviders == null) || (secureRandomProviders.length < 1) || (!LinuxPRNGSecureRandomProvider.class.equals( secureRandomProviders[0].getClass()))) { Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1); } // Assert that new SecureRandom() and // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed // by the Linux PRNG-based SecureRandom implementation. SecureRandom rng1 = new SecureRandom(); if (!LinuxPRNGSecureRandomProvider.class.equals( rng1.getProvider().getClass())) { throw new SecurityException( "new SecureRandom() backed by wrong Provider: " + rng1.getProvider().getClass()); } SecureRandom rng2; try { rng2 = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new SecurityException("SHA1PRNG not available", e); } if (!LinuxPRNGSecureRandomProvider.class.equals( rng2.getProvider().getClass())) { throw new SecurityException( "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong" + " Provider: " + rng2.getProvider().getClass()); } } /** * {@code Provider} of {@code SecureRandom} engines which pass through * all requests to the Linux PRNG. */ private static class LinuxPRNGSecureRandomProvider extends Provider { public LinuxPRNGSecureRandomProvider() { super("LinuxPRNG", 1.0, "A Linux-specific random number provider that uses" + " /dev/urandom"); // Although /dev/urandom is not a SHA-1 PRNG, some apps // explicitly request a SHA1PRNG SecureRandom and we thus need to // prevent them from getting the default implementation whose output // may have low entropy. put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName()); put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); } } /** * {@link SecureRandomSpi} which passes all requests to the Linux PRNG * ({@code /dev/urandom}). */ public static class LinuxPRNGSecureRandom extends SecureRandomSpi { /* * IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed * are passed through to the Linux PRNG (/dev/urandom). Instances of * this class seed themselves by mixing in the current time, PID, UID, * build fingerprint, and hardware serial number (where available) into * Linux PRNG. * * Concurrency: Read requests to the underlying Linux PRNG are * serialized (on sLock) to ensure that multiple threads do not get * duplicated PRNG output. */ private static final File URANDOM_FILE = new File("/dev/urandom"); private static final Object sLock = new Object(); /** * Input stream for reading from Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static DataInputStream sUrandomIn; /** * Output stream for writing to Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static OutputStream sUrandomOut; /** * Whether this engine instance has been seeded. This is needed because * each instance needs to seed itself if the client does not explicitly * seed it. */ private boolean mSeeded; @Override protected void engineSetSeed(byte[] bytes) { try { OutputStream out; synchronized (sLock) { out = getUrandomOutputStream(); } out.write(bytes); out.flush(); } catch (IOException e) { // On a small fraction of devices /dev/urandom is not writable. // Log and ignore. Log.w(PRNGFixes.class.getSimpleName(), "Failed to mix seed into " + URANDOM_FILE); } finally { mSeeded = true; } } @Override protected void engineNextBytes(byte[] bytes) { if (!mSeeded) { // Mix in the device- and invocation-specific seed. engineSetSeed(generateSeed()); } try { DataInputStream in; synchronized (sLock) { in = getUrandomInputStream(); } synchronized (in) { in.readFully(bytes); } } catch (IOException e) { throw new SecurityException( "Failed to read from " + URANDOM_FILE, e); } } @Override protected byte[] engineGenerateSeed(int size) { byte[] seed = new byte[size]; engineNextBytes(seed); return seed; } private DataInputStream getUrandomInputStream() { synchronized (sLock) { if (sUrandomIn == null) { // NOTE: Consider inserting a BufferedInputStream between // DataInputStream and FileInputStream if you need higher // PRNG output performance and can live with future PRNG // output being pulled into this process prematurely. try { sUrandomIn = new DataInputStream( new FileInputStream(URANDOM_FILE)); } catch (IOException e) { throw new SecurityException("Failed to open " + URANDOM_FILE + " for reading", e); } } return sUrandomIn; } } private OutputStream getUrandomOutputStream() throws IOException { synchronized (sLock) { if (sUrandomOut == null) { sUrandomOut = new FileOutputStream(URANDOM_FILE); } return sUrandomOut; } } } /** * Generates a device- and invocation-specific seed to be mixed into the * Linux PRNG. */ private static byte[] generateSeed() { try { ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream(); DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer); seedBufferOut.writeLong(System.currentTimeMillis()); seedBufferOut.writeLong(System.nanoTime()); seedBufferOut.writeInt(Process.myPid()); seedBufferOut.writeInt(Process.myUid()); seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL); seedBufferOut.close(); return seedBuffer.toByteArray(); } catch (IOException e) { throw new SecurityException("Failed to generate seed", e); } } /** * Gets the hardware serial number of this device. * * @return serial number or {@code null} if not available. */ private static String getDeviceSerialNumber() { // We're using the Reflection API because Build.SERIAL is only available // since API Level 9 (Gingerbread, Android 2.3). try { return (String) Build.class.getField("SERIAL").get(null); } catch (Exception ignored) { return null; } } private static byte[] getBuildFingerprintAndDeviceSerial() { StringBuilder result = new StringBuilder(); String fingerprint = Build.FINGERPRINT; if (fingerprint != null) { result.append(fingerprint); } String serial = getDeviceSerialNumber(); if (serial != null) { result.append(serial); } try { return result.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding not supported"); } } }
Java
package com.ecomdev.openvpn.core; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; public class ProxyDetection { static SocketAddress detectProxy(VpnProfile vp) { // Construct a new url with https as protocol try { URL url = new URL(String.format("https://%s:%s",vp.mServerName,vp.mServerPort)); Proxy proxy = getFirstProxy(url); if(proxy==null) return null; SocketAddress addr = proxy.address(); if (addr instanceof InetSocketAddress) { return addr; } } catch (MalformedURLException e) { VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage()); } catch (URISyntaxException e) { VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage()); } return null; } static Proxy getFirstProxy(URL url) throws URISyntaxException { System.setProperty("java.net.useSystemProxies", "true"); List<Proxy> proxylist = ProxySelector.getDefault().select(url.toURI()); if (proxylist != null) { for (Proxy proxy: proxylist) { SocketAddress addr = proxy.address(); if (addr != null) { return proxy; } } } return null; } }
Java
package com.ecomdev.openvpn.core; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import com.ecomdev.openvpn.R; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.FormatFlagsConversionMismatchException; import java.util.LinkedList; import java.util.Locale; import java.util.UnknownFormatConversionException; import java.util.Vector; public class VpnStatus { public static LinkedList<LogItem> logbuffer; private static Vector<LogListener> logListener; private static Vector<StateListener> stateListener; private static Vector<ByteCountListener> byteCountListener; private static String mLaststatemsg=""; private static String mLaststate = "NOPROCESS"; private static int mLastStateresid=R.string.state_noprocess; private static long mlastByteCount[]={0,0,0,0}; public static void logException(LogLevel ll, String context, Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); LogItem li; if (context !=null) { li = new LogItem(ll, R.string.unhandled_exception_context, e.getMessage(), sw.toString(), context); } else { li = new LogItem(ll, R.string.unhandled_exception, e.getMessage(), sw.toString()); } newLogItem(li); } public static void logException(Exception e) { logException(LogLevel.ERROR, null, e); } public static void logException(String context, Exception e) { logException(LogLevel.ERROR, context, e); } private static final int MAXLOGENTRIES = 1000; public static final String MANAGMENT_PREFIX = "M:"; public enum ConnectionStatus { LEVEL_CONNECTED, LEVEL_VPNPAUSED, LEVEL_CONNECTING_SERVER_REPLIED, LEVEL_CONNECTING_NO_SERVER_REPLY_YET, LEVEL_NONETWORK, LEVEL_NOTCONNECTED, LEVEL_AUTH_FAILED, LEVEL_WAITING_FOR_USER_INPUT, UNKNOWN_LEVEL } public enum LogLevel { INFO(2), ERROR(-2), WARNING(1), VERBOSE(3), DEBUG(4); protected int mValue; LogLevel(int value) { mValue = value; } public int getInt() { return mValue; } public static LogLevel getEnumByValue(int value) { switch (value) { case 1: return INFO; case 2: return ERROR; case 3: return WARNING; case 4: return DEBUG; default: return null; } } } // keytool -printcert -jarfile com.ecomdev.openvpn_85.apk public static final byte[] officalkey = {-58, -42, -44, -106, 90, -88, -87, -88, -52, -124, 84, 117, 66, 79, -112, -111, -46, 86, -37, 109}; public static final byte[] officaldebugkey = {-99, -69, 45, 71, 114, -116, 82, 66, -99, -122, 50, -70, -56, -111, 98, -35, -65, 105, 82, 43}; public static final byte[] amazonkey = {-116, -115, -118, -89, -116, -112, 120, 55, 79, -8, -119, -23, 106, -114, -85, -56, -4, 105, 26, -57}; public static final byte[] fdroidkey = {-92, 111, -42, -46, 123, -96, -60, 79, -27, -31, 49, 103, 11, -54, -68, -27, 17, 2, 121, 104}; private static ConnectionStatus mLastLevel=ConnectionStatus.LEVEL_NOTCONNECTED; static { logbuffer = new LinkedList<LogItem>(); logListener = new Vector<VpnStatus.LogListener>(); stateListener = new Vector<VpnStatus.StateListener>(); byteCountListener = new Vector<VpnStatus.ByteCountListener>(); logInformation(); } public static class LogItem implements Parcelable { private Object [] mArgs = null; private String mMessage = null; private int mRessourceId; // Default log priority LogLevel mLevel = LogLevel.INFO; private long logtime = System.currentTimeMillis(); private int mVerbosityLevel = -1; private LogItem(int ressourceId, Object[] args) { mRessourceId = ressourceId; mArgs = args; } public LogItem(LogLevel level, int verblevel, String message) { mMessage=message; mLevel = level; mVerbosityLevel = verblevel; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeArray(mArgs); dest.writeString(mMessage); dest.writeInt(mRessourceId); dest.writeInt(mLevel.getInt()); dest.writeInt(mVerbosityLevel); dest.writeLong(logtime); } public LogItem(Parcel in) { mArgs = in.readArray(Object.class.getClassLoader()); mMessage = in.readString(); mRessourceId = in.readInt(); mLevel = LogLevel.getEnumByValue(in.readInt()); mVerbosityLevel = in.readInt(); logtime = in.readLong(); } public static final Parcelable.Creator<LogItem> CREATOR = new Parcelable.Creator<LogItem>() { public LogItem createFromParcel(Parcel in) { return new LogItem(in); } public LogItem[] newArray(int size) { return new LogItem[size]; } }; public LogItem(LogLevel loglevel,int ressourceId, Object... args) { mRessourceId = ressourceId; mArgs =args; mLevel = loglevel; } public LogItem(LogLevel loglevel, String msg) { mLevel = loglevel; mMessage = msg; } public LogItem(LogLevel loglevel, int ressourceId) { mRessourceId =ressourceId; mLevel = loglevel; } public String getString(Context c) { try { if(mMessage !=null) { return mMessage; } else { if(c!=null) { if(mRessourceId==R.string.mobile_info) return getMobileInfoString(c); if(mArgs == null) return c.getString(mRessourceId); else return c.getString(mRessourceId,mArgs); } else { String str = String.format(Locale.ENGLISH,"Log (no context) resid %d", mRessourceId); if(mArgs !=null) for(Object o:mArgs) str += "|" + o.toString(); return str; } } } catch (UnknownFormatConversionException e) { if (c != null) throw new UnknownFormatConversionException(e.getLocalizedMessage() + getString(null)); else throw e; } catch (java.util.FormatFlagsConversionMismatchException e) { if (c != null) throw new FormatFlagsConversionMismatchException(e.getLocalizedMessage() + getString(null),e.getConversion()); else throw e; } } public LogLevel getLogLevel() { return mLevel; } // The lint is wrong here @SuppressLint("StringFormatMatches") private String getMobileInfoString(Context c) { c.getPackageManager(); String apksign="error getting package signature"; String version="error getting version"; try { Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray())); MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); if (Arrays.equals(digest, officalkey)) apksign = c.getString(R.string.official_build); else if (Arrays.equals(digest, officaldebugkey)) apksign = c.getString(R.string.debug_build); else if (Arrays.equals(digest, amazonkey)) apksign = "amazon version"; else if (Arrays.equals(digest, fdroidkey)) apksign = "F-Droid built and signed version"; else apksign = c.getString(R.string.built_by,cert.getSubjectX500Principal().getName()); PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0); version = packageinfo.versionName; } catch (NameNotFoundException e) { } catch (CertificateException e) { } catch (NoSuchAlgorithmException e) { } Object[] argsext = Arrays.copyOf(mArgs, mArgs.length+2); argsext[argsext.length-1]=apksign; argsext[argsext.length-2]=version; return c.getString(R.string.mobile_info_extended, argsext); } public long getLogtime() { return logtime; } public int getVerbosityLevel() { if (mVerbosityLevel==-1) { // Hack: // For message not from OpenVPN, report the status level as log level return mLevel.getInt(); } return mVerbosityLevel; } } public interface LogListener { void newLog(LogItem logItem); } public interface StateListener { void updateState(String state, String logmessage, int localizedResId, ConnectionStatus level); } public interface ByteCountListener { void updateByteCount(long in, long out, long diffIn, long diffOut); } public synchronized static void logMessage(LogLevel level,String prefix, String message) { newLogItem(new LogItem(level, prefix + message)); } public synchronized static void clearLog() { logbuffer.clear(); logInformation(); } private static void logInformation() { logInfo(R.string.mobile_info,Build.MODEL, Build.BOARD,Build.BRAND,Build.VERSION.SDK_INT); } public synchronized static void addLogListener(LogListener ll){ logListener.add(ll); } public synchronized static void removeLogListener(LogListener ll) { logListener.remove(ll); } public synchronized static void addByteCountListener(ByteCountListener bcl) { bcl.updateByteCount(mlastByteCount[0], mlastByteCount[1], mlastByteCount[2], mlastByteCount[3]); byteCountListener.add(bcl); } public synchronized static void removeByteCountListener(ByteCountListener bcl) { byteCountListener.remove(bcl); } public synchronized static void addStateListener(StateListener sl){ if(!stateListener.contains(sl)){ stateListener.add(sl); if(mLaststate!=null) sl.updateState(mLaststate, mLaststatemsg, mLastStateresid, mLastLevel); } } private static int getLocalizedState(String state){ if (state.equals("CONNECTING")) return R.string.state_connecting; else if (state.equals("WAIT")) return R.string.state_wait; else if (state.equals("AUTH")) return R.string.state_auth; else if (state.equals("GET_CONFIG")) return R.string.state_get_config; else if (state.equals("ASSIGN_IP")) return R.string.state_assign_ip; else if (state.equals("ADD_ROUTES")) return R.string.state_add_routes; else if (state.equals("CONNECTED")) return R.string.state_connected; else if (state.equals("DISCONNECTED")) return R.string.state_disconnected; else if (state.equals("RECONNECTING")) return R.string.state_reconnecting; else if (state.equals("EXITING")) return R.string.state_exiting; else if (state.equals("RESOLVE")) return R.string.state_resolve; else if (state.equals("TCP_CONNECT")) return R.string.state_tcp_connect; else return R.string.unknown_state; } public static void updateStatePause(OpenVPNManagement.pauseReason pauseReason) { switch (pauseReason) { case noNetwork: VpnStatus.updateStateString("NONETWORK", "", R.string.state_nonetwork, ConnectionStatus.LEVEL_NONETWORK); break; case screenOff: VpnStatus.updateStateString("SCREENOFF", "", R.string.state_screenoff, ConnectionStatus.LEVEL_VPNPAUSED); break; case userPause: VpnStatus.updateStateString("USERPAUSE", "", R.string.state_userpause, ConnectionStatus.LEVEL_VPNPAUSED); break; } } private static ConnectionStatus getLevel(String state){ String[] noreplyet = {"CONNECTING","WAIT", "RECONNECTING", "RESOLVE", "TCP_CONNECT"}; String[] reply = {"AUTH","GET_CONFIG","ASSIGN_IP","ADD_ROUTES"}; String[] connected = {"CONNECTED"}; String[] notconnected = {"DISCONNECTED", "EXITING"}; for(String x:noreplyet) if(state.equals(x)) return ConnectionStatus.LEVEL_CONNECTING_NO_SERVER_REPLY_YET; for(String x:reply) if(state.equals(x)) return ConnectionStatus.LEVEL_CONNECTING_SERVER_REPLIED; for(String x:connected) if(state.equals(x)) return ConnectionStatus.LEVEL_CONNECTED; for(String x:notconnected) if(state.equals(x)) return ConnectionStatus.LEVEL_NOTCONNECTED; return ConnectionStatus.UNKNOWN_LEVEL; } public synchronized static void removeStateListener(StateListener sl) { stateListener.remove(sl); } synchronized public static LogItem[] getlogbuffer() { // The stoned way of java to return an array from a vector // brought to you by eclipse auto complete return logbuffer.toArray(new LogItem[logbuffer.size()]); } public static void updateStateString (String state, String msg) { int rid = getLocalizedState(state); ConnectionStatus level = getLevel(state); updateStateString(state, msg, rid, level); } public synchronized static void updateStateString(String state, String msg, int resid, ConnectionStatus level) { // Workound for OpenVPN doing AUTH and wait and being connected // Simply ignore these state if (mLastLevel == ConnectionStatus.LEVEL_CONNECTED && (state.equals("WAIT") || state.equals("AUTH"))) { newLogItem(new LogItem((LogLevel.DEBUG), String.format("Ignoring OpenVPN Status in CONNECTED state (%s->%s): %s",state,level.toString(),msg))); return; } mLaststate= state; mLaststatemsg = msg; mLastStateresid = resid; mLastLevel = level; for (StateListener sl : stateListener) { sl.updateState(state,msg,resid,level); } //newLogItem(new LogItem((LogLevel.DEBUG), String.format("New OpenVPN Status (%s->%s): %s",state,level.toString(),msg))); } public static void logInfo(String message) { newLogItem(new LogItem(LogLevel.INFO, message)); } public static void logInfo(int resourceId, Object... args) { newLogItem(new LogItem(LogLevel.INFO, resourceId, args)); } public static void logDebug(int resourceId, Object... args) { newLogItem(new LogItem(LogLevel.DEBUG, resourceId, args)); } private synchronized static void newLogItem(LogItem logItem) { logbuffer.addLast(logItem); if(logbuffer.size()>MAXLOGENTRIES) logbuffer.removeFirst(); for (LogListener ll : logListener) { ll.newLog(logItem); } } public static void logError(String msg) { newLogItem(new LogItem(LogLevel.ERROR, msg)); } public static void logWarning(int resourceId, Object... args) { newLogItem(new LogItem(LogLevel.WARNING, resourceId, args)); } public static void logWarning(String msg) { newLogItem(new LogItem(LogLevel.WARNING, msg)); } public static void logError(int resourceId) { newLogItem(new LogItem(LogLevel.ERROR, resourceId)); } public static void logError(int resourceId, Object... args) { newLogItem(new LogItem(LogLevel.ERROR, resourceId, args)); } public static void logMessageOpenVPN(LogLevel level, int ovpnlevel, String message) { newLogItem(new LogItem(level, ovpnlevel, message)); } public static synchronized void updateByteCount(long in, long out) { long lastIn = mlastByteCount[0]; long lastOut = mlastByteCount[1]; long diffIn = mlastByteCount[2] = in - lastIn; long diffOut = mlastByteCount[3] = out - lastOut; mlastByteCount = new long[] {in,out,diffIn,diffOut}; for(ByteCountListener bcl:byteCountListener){ bcl.updateByteCount(in, out, diffIn,diffOut); } } }
Java
package com.ecomdev.openvpn.core; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import com.ecomdev.openvpn.VpnProfile; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.AssetManager; import android.preference.PreferenceManager; public class ProfileManager { private static final String PREFS_NAME = "VPNList"; private static final String ONBOOTPROFILE = "onBootProfile"; private static ProfileManager instance; private static VpnProfile mLastConnectedVpn=null; private HashMap<String,VpnProfile> profiles=new HashMap<String, VpnProfile>(); private static VpnProfile tmpprofile=null; private static VpnProfile get(String key) { if (tmpprofile!=null && tmpprofile.getUUIDString().equals(key)) return tmpprofile; if(instance==null) return null; return instance.profiles.get(key); } private ProfileManager() { } private static void checkInstance(Context context) { if(instance == null) { instance = new ProfileManager(); instance.loadVPNList(context); } } synchronized public static ProfileManager getInstance(Context context) { checkInstance(context); return instance; } public static void setConntectedVpnProfileDisconnected(Context c) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); Editor prefsedit = prefs.edit(); prefsedit.putString(ONBOOTPROFILE, null); prefsedit.apply(); } public static void setConnectedVpnProfile(Context c, VpnProfile connectedrofile) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); Editor prefsedit = prefs.edit(); prefsedit.putString(ONBOOTPROFILE, connectedrofile.getUUIDString()); prefsedit.apply(); mLastConnectedVpn=connectedrofile; } public static VpnProfile getOnBootProfile(Context c) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); boolean useStartOnBoot = prefs.getBoolean("restartvpnonboot", false); String mBootProfileUUID = prefs.getString(ONBOOTPROFILE,null); if(useStartOnBoot && mBootProfileUUID!=null) return get(c, mBootProfileUUID); else return null; } public Collection<VpnProfile> getProfiles() { return profiles.values(); } public VpnProfile getProfileByName(String name) { for (VpnProfile vpnp : profiles.values()) { if(vpnp.getName().equals(name)) { return vpnp; } } return null; } public void saveProfileList(Context context) { SharedPreferences sharedprefs = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE); Editor editor = sharedprefs.edit(); editor.putStringSet("vpnlist", profiles.keySet()); // For reasing I do not understand at all // Android saves my prefs file only one time // if I remove the debug code below :( int counter = sharedprefs.getInt("counter", 0); editor.putInt("counter", counter+1); editor.apply(); } public void addProfile(VpnProfile profile) { profiles.put(profile.getUUID().toString(),profile); } public static void setTemporaryProfile(VpnProfile tmp) { ProfileManager.tmpprofile = tmp; } public void saveProfile(Context context,VpnProfile profile) { // First let basic settings save its state ObjectOutputStream vpnfile; try { vpnfile = new ObjectOutputStream(context.openFileOutput((profile.getUUID().toString() + ".vp"),Activity.MODE_PRIVATE)); vpnfile.writeObject(profile); vpnfile.flush(); vpnfile.close(); } catch (FileNotFoundException e) { VpnStatus.logException("saving VPN profile", e); throw new RuntimeException(e); } catch (IOException e) { VpnStatus.logException("saving VPN profile", e); throw new RuntimeException(e); } } private void loadVPNList(Context context) { /*SharedPreferences listpref = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE); Set<String> vlist = listpref.getStringSet("vpnlist", null); Exception exp =null; if(vlist==null){ vlist = new HashSet<String>(); } for (String vpnentry : vlist) { try { ObjectInputStream vpnfile = new ObjectInputStream(context.openFileInput(vpnentry + ".vp")); VpnProfile vp = ((VpnProfile) vpnfile.readObject()); // Sanity check if(vp==null || vp.mName==null || vp.getUUID()==null) continue; vp.upgradeProfile(); profiles.put(vp.getUUID().toString(), vp); } catch (StreamCorruptedException e) { exp=e; } catch (FileNotFoundException e) { exp=e; } catch (IOException e) { exp=e; } catch (ClassNotFoundException e) { exp=e; } if(exp!=null) { VpnStatus.logException("Loading VPN List",exp); } }*/ } public int getNumberOfProfiles() { return profiles.size(); } public void removeProfile(Context context,VpnProfile profile) { String vpnentry = profile.getUUID().toString(); profiles.remove(vpnentry); saveProfileList(context); context.deleteFile(vpnentry + ".vp"); if(mLastConnectedVpn==profile) mLastConnectedVpn=null; } public static VpnProfile get(Context context, String profileUUID) { checkInstance(context); return get(profileUUID); } public static VpnProfile getLastConnectedVpn() { return mLastConnectedVpn; } }
Java
package com.ecomdev.openvpn.core; import android.os.Build; import android.text.TextUtils; import java.math.BigInteger; import java.net.Inet6Address; import java.util.*; public class NetworkSpace { static class ipAddress implements Comparable<ipAddress> { private BigInteger netAddress; public int networkMask; private boolean included; private boolean isV4; @Override public int compareTo(ipAddress another) { int comp = getFirstAddress().compareTo(another.getFirstAddress()); if (comp != 0) return comp; // bigger mask means smaller address block if (networkMask > another.networkMask) return -1; else if (another.networkMask == networkMask) return 0; else return 1; } public ipAddress(CIDRIP ip, boolean include) { included = include; netAddress = BigInteger.valueOf(ip.getInt()); networkMask = ip.len; isV4 = true; } public ipAddress(Inet6Address address, int mask, boolean include) { networkMask = mask; included = include; int s = 128; netAddress = BigInteger.ZERO; for (byte b : address.getAddress()) { s -= 16; netAddress = netAddress.add(BigInteger.valueOf(b).shiftLeft(s)); } } public BigInteger getLastAddress() { return getMaskedAddress(true); } public BigInteger getFirstAddress() { return getMaskedAddress(false); } private BigInteger getMaskedAddress(boolean one) { BigInteger numAddress = netAddress; int numBits; if (isV4) { numBits = 32 - networkMask; } else { numBits = 128 - networkMask; } for (int i = 0; i < numBits; i++) { if (one) numAddress = numAddress.setBit(i); else numAddress = numAddress.clearBit(i); } return numAddress; } @Override public String toString() { //String in = included ? "+" : "-"; if (isV4) return String.format(Locale.US,"%s/%d", getIPv4Address(), networkMask); else return String.format(Locale.US, "%s/%d", getIPv6Address(), networkMask); } ipAddress(BigInteger baseAddress, int mask, boolean included, boolean isV4) { this.netAddress = baseAddress; this.networkMask = mask; this.included = included; this.isV4 = isV4; } public ipAddress[] split() { ipAddress firsthalf = new ipAddress(getFirstAddress(), networkMask + 1, included, isV4); ipAddress secondhalf = new ipAddress(firsthalf.getLastAddress().add(BigInteger.ONE), networkMask + 1, included, isV4); assert secondhalf.getLastAddress().equals(getLastAddress()); return new ipAddress[]{firsthalf, secondhalf}; } String getIPv4Address() { assert (isV4); assert (netAddress.longValue() <= 0xffffffffl); assert (netAddress.longValue() >= 0); long ip = netAddress.longValue(); return String.format(Locale.US, "%d.%d.%d.%d", (ip >> 24) % 256, (ip >> 16) % 256, (ip >> 8) % 256, ip % 256); } String getIPv6Address() { assert (!isV4); BigInteger r = netAddress; if (r.longValue() == 0) return "::"; Vector<String> parts = new Vector<String>(); while (r.compareTo(BigInteger.ZERO) == 1) { parts.add(0, String.format(Locale.US, "%x", r.mod(BigInteger.valueOf(256)).longValue())); r = r.shiftRight(16); } return TextUtils.join(":", parts); } public boolean containsNet(ipAddress network) { return getFirstAddress().compareTo(network.getFirstAddress()) != 1 && getLastAddress().compareTo(network.getLastAddress()) != -1; } } TreeSet<ipAddress> mIpAddresses = new TreeSet<ipAddress>(); public Collection<ipAddress> getNetworks(boolean included) { Vector<ipAddress> ips = new Vector<ipAddress>(); for (ipAddress ip : mIpAddresses) { if (ip.included == included) ips.add(ip); } return ips; } public void clear() { mIpAddresses.clear(); } void addIP(CIDRIP cidrIp, boolean include) { mIpAddresses.add(new ipAddress(cidrIp, include)); } void addIPv6(Inet6Address address, int mask, boolean included) { mIpAddresses.add(new ipAddress(address, mask, included)); } TreeSet<ipAddress> generateIPList() { TreeSet<ipAddress> ipsSorted = new TreeSet<ipAddress>(mIpAddresses); Iterator<ipAddress> it = ipsSorted.iterator(); ipAddress currentNet = null; if (it.hasNext()) currentNet = it.next(); while (it.hasNext()) { // Check if it and the next of it are compatbile ipAddress nextNet = it.next(); assert currentNet != null; if (currentNet.getLastAddress().compareTo(nextNet.getFirstAddress()) == -1) { // Everything good, no overlapping nothing to do currentNet = nextNet; } else { // This network is smaller or equal to the next but has the same base address if (currentNet.getFirstAddress().equals(nextNet.getFirstAddress()) && currentNet.networkMask >= nextNet.networkMask) { if (currentNet.included == nextNet.included) { ipsSorted.remove(currentNet); } else { // our currentnet is included in next and nextnet needs to be split ipsSorted.remove(nextNet); ipAddress[] newNets = nextNet.split(); if (newNets[0].getLastAddress().equals(currentNet.getLastAddress())) { assert (newNets[0].networkMask == currentNet.networkMask); // Don't add the lower half that would conflict with currentNet } else { ipsSorted.add(newNets[0]); } ipsSorted.add(newNets[1]); } } else { assert (currentNet.networkMask < nextNet.networkMask); assert (nextNet.getFirstAddress().compareTo(currentNet.getFirstAddress()) == 1); // This network is bigger than the next and last ip of current >= next assert (currentNet.getLastAddress().compareTo(nextNet.getLastAddress()) != -1); if (currentNet.included == nextNet.included) { ipsSorted.remove(nextNet); } else { ipsSorted.remove(currentNet); ipAddress[] newNets = currentNet.split(); ipsSorted.add(newNets[0]); if (newNets[1].networkMask == nextNet.networkMask) { assert (newNets[1].getFirstAddress().equals(nextNet.getFirstAddress())); assert (newNets[1].getLastAddress().equals(currentNet.getLastAddress())); } else { ipsSorted.add(newNets[1]); } } } // Reset iterator it = ipsSorted.iterator(); currentNet = it.next(); } } return ipsSorted; } Collection<ipAddress> getPositiveIPList() { TreeSet<ipAddress> ipsSorted = generateIPList(); Vector<ipAddress> ips = new Vector<ipAddress>(); for (ipAddress ia : ipsSorted) { if (ia.included) ips.add(ia); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // Include postive routes from the original set under < 4.4 since these might overrule the local // network but only if no smaller negative route exists for(ipAddress origIp: mIpAddresses){ if (!origIp.included) continue; // The netspace exists if(ipsSorted.contains(origIp)) continue; boolean skipIp=false; // If there is any smaller net that is excluded we may not add the positive route back for (ipAddress calculatedIp: ipsSorted) { if(!calculatedIp.included && origIp.containsNet(calculatedIp)) { skipIp=true; break; } } if (skipIp) continue; // It is safe to include the IP ips.add(origIp); } } return ips; } }
Java
package com.ecomdev.openvpn.core; import android.app.Application; /** * Created by arne on 28.12.13. */ public class ICSOpenVPNApplication extends Application { @Override public void onCreate() { super.onCreate(); PRNGFixes.apply(); } }
Java
package com.ecomdev.openvpn.core; import com.ecomdev.openvpn.VpnProfile; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Vector; //! Openvpn Config FIle Parser, probably not 100% accurate but close enough // And remember, this is valid :) // --<foo> // bar // </foo> public class ConfigParser { public static final String CONVERTED_PROFILE = "converted Profile"; private HashMap<String, Vector<Vector<String>>> options = new HashMap<String, Vector<Vector<String>>>(); private HashMap<String, Vector<String>> meta = new HashMap<String, Vector<String>>(); private boolean extraRemotesAsCustom=false; public void parseConfig(Reader reader) throws IOException, ConfigParseError { BufferedReader br =new BufferedReader(reader); while (true){ String line = br.readLine(); if(line==null) break; // Check for OpenVPN Access Server Meta information if (line.startsWith("# OVPN_ACCESS_SERVER_")) { Vector<String> metaarg = parsemeta(line); meta.put(metaarg.get(0),metaarg); continue; } Vector<String> args = parseline(line); if(args.size() ==0) continue; if(args.get(0).startsWith("--")) args.set(0, args.get(0).substring(2)); checkinlinefile(args,br); String optionname = args.get(0); if(!options.containsKey(optionname)) { options.put(optionname, new Vector<Vector<String>>()); } options.get(optionname).add(args); } } private Vector<String> parsemeta(String line) { String meta = line.split("#\\sOVPN_ACCESS_SERVER_", 2)[1]; String[] parts = meta.split("=",2); Vector<String> rval = new Vector<String>(); Collections.addAll(rval, parts); return rval; } private void checkinlinefile(Vector<String> args, BufferedReader br) throws IOException, ConfigParseError { String arg0 = args.get(0).trim(); // CHeck for <foo> if(arg0.startsWith("<") && arg0.endsWith(">")) { String argname = arg0.substring(1, arg0.length()-1); String inlinefile = VpnProfile.INLINE_TAG; String endtag = String.format("</%s>",argname); do { String line = br.readLine(); if(line==null){ throw new ConfigParseError(String.format("No endtag </%s> for starttag <%s> found",argname,argname)); } if(line.trim().equals(endtag)) break; else { inlinefile+=line; inlinefile+= "\n"; } } while(true); args.clear(); args.add(argname); args.add(inlinefile); } } enum linestate { initial, readin_single_quote , reading_quoted, reading_unquoted, done} private boolean space(char c) { // I really hope nobody is using zero bytes inside his/her config file // to sperate parameter but here we go: return Character.isWhitespace(c) || c == '\0'; } public class ConfigParseError extends Exception { private static final long serialVersionUID = -60L; public ConfigParseError(String msg) { super(msg); } } // adapted openvpn's parse function to java private Vector<String> parseline(String line) throws ConfigParseError { Vector<String> parameters = new Vector<String>(); if (line.length()==0) return parameters; linestate state = linestate.initial; boolean backslash = false; char out=0; int pos=0; String currentarg=""; do { // Emulate the c parsing ... char in; if(pos < line.length()) in = line.charAt(pos); else in = '\0'; if (!backslash && in == '\\' && state != linestate.readin_single_quote) { backslash = true; } else { if (state == linestate.initial) { if (!space (in)) { if (in == ';' || in == '#') /* comment */ break; if (!backslash && in == '\"') state = linestate.reading_quoted; else if (!backslash && in == '\'') state = linestate.readin_single_quote; else { out = in; state = linestate.reading_unquoted; } } } else if (state == linestate.reading_unquoted) { if (!backslash && space (in)) state = linestate.done; else out = in; } else if (state == linestate.reading_quoted) { if (!backslash && in == '\"') state = linestate.done; else out = in; } else if (state == linestate.readin_single_quote) { if (in == '\'') state = linestate.done; else out = in; } if (state == linestate.done) { /* ASSERT (parm_len > 0); */ state = linestate.initial; parameters.add(currentarg); currentarg = ""; out =0; } if (backslash && out!=0) { if (!(out == '\\' || out == '\"' || space (out))) { throw new ConfigParseError("Options warning: Bad backslash ('\\') usage"); } } backslash = false; } /* store parameter character */ if (out!=0) { currentarg+=out; } } while (pos++ < line.length()); return parameters; } final String[] unsupportedOptions = { "config", "connection", "proto-force", "remote-random", "tls-server" }; // Ignore all scripts // in most cases these won't work and user who wish to execute scripts will // figure out themselves final String[] ignoreOptions = { "tls-client", "askpass", "auth-nocache", "up", "down", "route-up", "ipchange", "route-up", "route-pre-down", "auth-user-pass-verify", "dhcp-release", "dhcp-renew", "dh", "group", "ip-win32", "management-hold", "management", "management-client", "management-query-remote", "management-query-passwords", "management-query-proxy", "management-external-key", "management-forget-disconnect", "management-signal", "management-log-cache", "management-up-down", "management-client-user", "management-client-group", "pause-exit", "plugin", "machine-readable-output", "persist-key", "register-dns", "route-delay", "route-gateway", "route-metric", "route-method", "status", "script-security", "show-net-up", "suppress-timestamps", "tmp-dir", "tun-ipv6", "topology", "user", "win-sys", }; final String[][] ignoreOptionsWithArg = { {"setenv", "IV_GUI_VER"}, {"setenv", "IV_OPENVPN_GUI_VERSION"} }; final String[] connectionOptions = { "local", "remote", "float", "port", // "connect-retry", "connect-timeout", "connect-retry-max", "link-mtu", "tun-mtu", "tun-mtu-extra", "fragment", "mtu-disc", "local-port", "remote-port", "bind", "nobind", "proto", "http-proxy", "http-proxy-retry", "http-proxy-timeout", "http-proxy-option", "socks-proxy", "socks-proxy-retry", "explicit-exit-notify", "mssfix" }; // This method is far too long public VpnProfile convertProfile() throws ConfigParseError{ boolean noauthtypeset=true; VpnProfile np = new VpnProfile(CONVERTED_PROFILE); // Pull, client, tls-client np.clearDefaults(); if(options.containsKey("client") || options.containsKey("pull")) { np.mUsePull=true; options.remove("pull"); options.remove("client"); } Vector<String> secret = getOption("secret", 1, 2); if(secret!=null) { np.mAuthenticationType=VpnProfile.TYPE_STATICKEYS; noauthtypeset=false; np.mUseTLSAuth=true; np.mTLSAuthFilename=secret.get(1); if(secret.size()==3) np.mTLSAuthDirection=secret.get(2); } Vector<Vector<String>> routes = getAllOption("route", 1, 4); if(routes!=null) { String routeopt = ""; String routeExcluded = ""; for(Vector<String> route:routes){ String netmask = "255.255.255.255"; String gateway = "vpn_gateway"; if(route.size() >= 3) netmask = route.get(2); if (route.size() >= 4) gateway = route.get(3); String net = route.get(1); try { CIDRIP cidr = new CIDRIP(net, netmask); if (gateway.equals("net_gateway")) routeExcluded += cidr.toString() + " "; else routeopt+=cidr.toString() + " "; } catch (ArrayIndexOutOfBoundsException aioob) { throw new ConfigParseError("Could not parse netmask of route " + netmask); } catch (NumberFormatException ne) { throw new ConfigParseError("Could not parse netmask of route " + netmask); } } np.mCustomRoutes=routeopt; np.mExcludedRoutes=routeExcluded; } Vector<Vector<String>> routesV6 = getAllOption("route-ipv6", 1, 4); if (routesV6!=null) { String customIPv6Routes = ""; for (Vector<String> route:routesV6){ customIPv6Routes += route.get(1) + " "; } np.mCustomRoutesv6 = customIPv6Routes; } // Also recognize tls-auth [inline] direction ... Vector<Vector<String>> tlsauthoptions = getAllOption("tls-auth", 1, 2); if(tlsauthoptions!=null) { for(Vector<String> tlsauth:tlsauthoptions) { if(tlsauth!=null) { if(!tlsauth.get(1).equals("[inline]")) { np.mTLSAuthFilename=tlsauth.get(1); np.mUseTLSAuth=true; } if(tlsauth.size()==3) np.mTLSAuthDirection=tlsauth.get(2); } } } Vector<String> direction = getOption("key-direction", 1, 1); if(direction!=null) np.mTLSAuthDirection=direction.get(1); if(getAllOption("redirect-gateway", 0, 5) != null) np.mUseDefaultRoute=true; Vector<String> dev =getOption("dev",1,1); Vector<String> devtype =getOption("dev-type",1,1); if ((devtype != null && devtype.get(1).equals("tun")) || (dev != null && dev.get(1).startsWith("tun")) || (devtype == null && dev == null)) { //everything okay } else { throw new ConfigParseError("Sorry. Only tun mode is supported. See the FAQ for more detail"); } Vector<String> mode =getOption("mode",1,1); if (mode != null){ if(!mode.get(1).equals("p2p")) throw new ConfigParseError("Invalid mode for --mode specified, need p2p"); } Vector<String> port = getOption("port", 1,1); if(port!=null){ np.mServerPort = port.get(1); } Vector<String> rport = getOption("rport", 1,1); if(port!=null){ np.mServerPort = port.get(1); } Vector<String> proto = getOption("proto", 1,1); if(proto!=null){ np.mUseUdp=isUdpProto(proto.get(1)); } // Parse remote config Vector<Vector<String>> remotes = getAllOption("remote",1,3); if(remotes!=null && remotes.size()>=1 ) { Vector<String> remote = remotes.get(0); switch (remote.size()) { case 4: np.mUseUdp=isUdpProto(remote.get(3)); case 3: np.mServerPort = remote.get(2); case 2: np.mServerName = remote.get(1); } } Vector<Vector<String>> dhcpoptions = getAllOption("dhcp-option", 2, 2); if(dhcpoptions!=null) { for(Vector<String> dhcpoption:dhcpoptions) { String type=dhcpoption.get(1); String arg = dhcpoption.get(2); if(type.equals("DOMAIN")) { np.mSearchDomain=dhcpoption.get(2); } else if(type.equals("DNS")) { np.mOverrideDNS=true; if(np.mDNS1.equals(VpnProfile.DEFAULT_DNS1)) np.mDNS1=arg; else np.mDNS2=arg; } } } Vector<String> ifconfig = getOption("ifconfig", 2, 2); if(ifconfig!=null) { try { CIDRIP cidr = new CIDRIP(ifconfig.get(1), ifconfig.get(2)); np.mIPv4Address=cidr.toString(); } catch (NumberFormatException nfe) { throw new ConfigParseError("Could not pase ifconfig IP address: " + nfe.getLocalizedMessage()); } } if(getOption("remote-random-hostname", 0, 0)!=null) np.mUseRandomHostname=true; if(getOption("float", 0, 0)!=null) np.mUseFloat=true; if(getOption("comp-lzo", 0, 1)!=null) np.mUseLzo=true; Vector<String> cipher = getOption("cipher", 1, 1); if(cipher!=null) np.mCipher= cipher.get(1); Vector<String> auth = getOption("auth", 1, 1); if(auth!=null) np.mAuth = auth.get(1); Vector<String> ca = getOption("ca",1,1); if(ca!=null){ np.mCaFilename = ca.get(1); } Vector<String> cert = getOption("cert",1,1); if(cert!=null){ np.mClientCertFilename = cert.get(1); np.mAuthenticationType = VpnProfile.TYPE_CERTIFICATES; noauthtypeset=false; } Vector<String> key= getOption("key",1,1); if(key!=null) np.mClientKeyFilename=key.get(1); Vector<String> pkcs12 = getOption("pkcs12",1,1); if(pkcs12!=null) { np.mPKCS12Filename = pkcs12.get(1); np.mAuthenticationType = VpnProfile.TYPE_KEYSTORE; noauthtypeset=false; } Vector<String> compatnames = getOption("compat-names",1,2); Vector<String> nonameremapping = getOption("no-name-remapping",1,1); Vector<String> tlsremote = getOption("tls-remote",1,1); if(tlsremote!=null){ np.mRemoteCN = tlsremote.get(1); np.mCheckRemoteCN=true; np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE; if((compatnames!=null && compatnames.size() > 2) || (nonameremapping!=null)) np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING; } Vector<String> verifyx509name = getOption("verify-x509-name",1,2); if(verifyx509name!=null){ np.mRemoteCN = verifyx509name.get(1); np.mCheckRemoteCN=true; if(verifyx509name.size()>2) { if (verifyx509name.get(2).equals("name")) np.mX509AuthType=VpnProfile.X509_VERIFY_TLSREMOTE_RDN; else if (verifyx509name.get(2).equals("name-prefix")) np.mX509AuthType=VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX; else throw new ConfigParseError("Unknown parameter to x509-verify-name: " + verifyx509name.get(2) ); } else { np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_DN; } } Vector<String> verb = getOption("verb",1,1); if(verb!=null){ np.mVerb=verb.get(1); } if(getOption("nobind", 0, 0) != null) np.mNobind=true; if(getOption("persist-tun", 0,0) != null) np.mPersistTun=true; Vector<String> connectretry = getOption("connect-retry", 1, 1); if(connectretry!=null) np.mConnectRetry =connectretry.get(1); Vector<String> connectretrymax = getOption("connect-retry-max", 1, 1); if(connectretrymax!=null) np.mConnectRetryMax =connectretrymax.get(1); Vector<Vector<String>> remotetls = getAllOption("remote-cert-tls", 1, 1); if(remotetls!=null) if(remotetls.get(0).get(1).equals("server")) np.mExpectTLSCert=true; else options.put("remotetls",remotetls); Vector<String> authuser = getOption("auth-user-pass",0,1); if(authuser !=null){ if(noauthtypeset) { np.mAuthenticationType=VpnProfile.TYPE_USERPASS; } else if(np.mAuthenticationType==VpnProfile.TYPE_CERTIFICATES) { np.mAuthenticationType=VpnProfile.TYPE_USERPASS_CERTIFICATES; } else if(np.mAuthenticationType==VpnProfile.TYPE_KEYSTORE) { np.mAuthenticationType=VpnProfile.TYPE_USERPASS_KEYSTORE; } if(authuser.size()>1) { // Set option value to password get to get cance to embed later. np.mUsername=null; np.mPassword=authuser.get(1); useEmbbedUserAuth(np,authuser.get(1)); } } // Parse OpenVPN Access Server extra Vector<String> friendlyname = meta.get("FRIENDLY_NAME"); if(friendlyname !=null && friendlyname.size() > 1) np.mName=friendlyname.get(1); Vector<String> ocusername = meta.get("USERNAME"); if(ocusername !=null && ocusername.size() > 1) np.mUsername=ocusername.get(1); // Check the other options if(remotes !=null && remotes.size()>1 && extraRemotesAsCustom) { // first is already added remotes.remove(0); np.mCustomConfigOptions += getOptionStrings(remotes); np.mUseCustomConfig=true; } checkIgnoreAndInvalidOptions(np); fixup(np); return np; } public void useExtraRemotesAsCustom(boolean b) { this.extraRemotesAsCustom = b; } private boolean isUdpProto(String proto) throws ConfigParseError { boolean isudp; if(proto.equals("udp") || proto.equals("udp6")) isudp=true; else if (proto.equals("tcp-client") || proto.equals("tcp") || proto.equals("tcp6") || proto.endsWith("tcp6-client")) isudp =false; else throw new ConfigParseError("Unsupported option to --proto " + proto); return isudp; } static public void useEmbbedUserAuth(VpnProfile np,String inlinedata) { String data = inlinedata.replace(VpnProfile.INLINE_TAG, ""); String[] parts = data.split("\n"); if(parts.length >= 2) { np.mUsername=parts[0]; np.mPassword=parts[1]; } } private void checkIgnoreAndInvalidOptions(VpnProfile np) throws ConfigParseError { for(String option:unsupportedOptions) if(options.containsKey(option)) throw new ConfigParseError(String.format("Unsupported Option %s encountered in config file. Aborting",option)); for(String option:ignoreOptions) // removing an item which is not in the map is no error options.remove(option); if(options.size()> 0) { np.mCustomConfigOptions += "# These Options were found in the config file do not map to config settings:\n"; for(Vector<Vector<String>> option:options.values()) { np.mCustomConfigOptions += getOptionStrings(option); } np.mUseCustomConfig=true; } } boolean ignoreThisOption(Vector<String> option) { for (String[] ignoreOption : ignoreOptionsWithArg) { if (option.size() < ignoreOption.length) continue; boolean ignore = true; for (int i = 0; i < ignoreOption.length; i++) { if (!ignoreOption[i].equals(option.get(i))) ignore = false; } if (ignore) return true; } return false; } private String getOptionStrings(Vector<Vector<String>> option) { String custom = ""; for (Vector<String> optionsline : option) { if (!ignoreThisOption(optionsline)) { for (String arg : optionsline) custom += VpnProfile.openVpnEscape(arg) + " "; custom += "\n"; } } return custom; } private void fixup(VpnProfile np) { if(np.mRemoteCN.equals(np.mServerName)) { np.mRemoteCN=""; } } private Vector<String> getOption(String option, int minarg, int maxarg) throws ConfigParseError { Vector<Vector<String>> alloptions = getAllOption(option, minarg, maxarg); if(alloptions==null) return null; else return alloptions.lastElement(); } private Vector<Vector<String>> getAllOption(String option, int minarg, int maxarg) throws ConfigParseError { Vector<Vector<String>> args = options.get(option); if(args==null) return null; for(Vector<String> optionline:args) if(optionline.size()< (minarg+1) || optionline.size() > maxarg+1) { String err = String.format(Locale.getDefault(),"Option %s has %d parameters, expected between %d and %d", option,optionline.size()-1,minarg,maxarg ); throw new ConfigParseError(err); } options.remove(option); return args; } }
Java
package com.ecomdev.openvpn.fragments; import java.io.File; import java.util.ArrayList; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.VpnStatus; public class SendDumpFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_senddump, container, false); v.findViewById(R.id.senddump).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { emailMiniDumps(); } }); return v; } public void emailMiniDumps() { //need to "send multiple" to get more than one attachment final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); emailIntent.setType("*/*"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"Arne Schwabe <arne@rfc2549.org>"}); String version; String name="ics-openvpn"; try { PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version = packageinfo.versionName; name = packageinfo.applicationInfo.name; } catch (NameNotFoundException e) { version = "error fetching version"; } emailIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("%s %s Minidump",name,version)); emailIntent.putExtra(Intent.EXTRA_TEXT, "Please describe the issue you have experienced"); ArrayList<Uri> uris = new ArrayList<Uri>(); File ldump = getLastestDump(getActivity()); if(ldump==null) { VpnStatus.logError("No Minidump found!"); } uris.add(Uri.parse("content://com.ecomdev.openvpn.FileProvider/" + ldump.getName())); uris.add(Uri.parse("content://com.ecomdev.openvpn.FileProvider/" + ldump.getName() + ".log")); emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); startActivity(emailIntent); } static public File getLastestDump(Context c) { long newestDumpTime=0; File newestDumpFile=null; for(File f:c.getCacheDir().listFiles()) { if(!f.getName().endsWith(".dmp")) continue; if (newestDumpTime < f.lastModified()) { newestDumpTime = f.lastModified(); newestDumpFile=f; } } // Ignore old dumps //if(System.currentTimeMillis() - 48 * 60 * 1000 > newestDumpTime ) //return null; return newestDumpFile; } }
Java
package com.ecomdev.openvpn.fragments; import android.os.Bundle; import android.preference.PreferenceFragment; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ProfileManager; public abstract class OpenVpnPreferencesFragment extends PreferenceFragment { protected VpnProfile mProfile; protected abstract void loadSettings(); protected abstract void saveSettings(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID"); mProfile = ProfileManager.get(getActivity(),profileUUID); getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName())); } @Override public void onPause() { super.onPause(); saveSettings(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(savedInstanceState!=null) { String profileUUID=savedInstanceState.getString(VpnProfile.EXTRA_PROFILEUUID); mProfile = ProfileManager.get(getActivity(),profileUUID); loadSettings(); } } @Override public void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); saveSettings(); outState.putString(VpnProfile.EXTRA_PROFILEUUID, mProfile.getUUIDString()); } }
Java
package com.ecomdev.openvpn.fragments; import android.app.Fragment; import android.app.PendingIntent; import android.content.*; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.text.Html; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.TextView; import com.android.vending.billing.IInAppBillingService; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.VpnStatus; import org.json.JSONException; import org.json.JSONObject; import java.util.*; public class AboutFragment extends Fragment implements View.OnClickListener { public static final String INAPPITEM_TYPE_INAPP = "inapp"; public static final String RESPONSE_CODE = "RESPONSE_CODE"; private static final int DONATION_CODE = 12; private static final int BILLING_RESPONSE_RESULT_OK = 0; private static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; private static final String[] donationSkus = { "donation1eur", "donation2eur", "donation5eur", "donation10eur", "donation1337eur","donation23eur","donation25eur",}; IInAppBillingService mService; Hashtable<View, String> viewToProduct = new Hashtable<View, String>(); ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); initGooglePlayDonation(); } }; private void initGooglePlayDonation() { new Thread("queryGMSInApp") { @Override public void run() { initGMSDonateOptions(); } }.start(); } private TextView gmsTextView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivity().bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE); } @Override public void onDestroy() { super.onDestroy(); if (mServiceConn != null) { getActivity().unbindService(mServiceConn); } } private void initGMSDonateOptions() { try { int billingSupported = mService.isBillingSupported(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP); if (billingSupported != BILLING_RESPONSE_RESULT_OK) { Log.i("OpenVPN", "Play store billing not supported"); return; } ArrayList skuList = new ArrayList(); Collections.addAll(skuList, donationSkus); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); Bundle ownedItems = mService.getPurchases(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP, null); if (ownedItems.getInt(RESPONSE_CODE) != BILLING_RESPONSE_RESULT_OK) return; final ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST"); Bundle skuDetails = mService.getSkuDetails(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP, querySkus); if (skuDetails.getInt(RESPONSE_CODE) != BILLING_RESPONSE_RESULT_OK) return; final ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { createPlayBuyOptions(ownedSkus, responseList); } }); } } catch (RemoteException e) { VpnStatus.logException(e); } } private static class SkuResponse { String title; String price; SkuResponse(String p, String t) { title=t; price=p; } } private void createPlayBuyOptions(ArrayList<String> ownedSkus, ArrayList<String> responseList) { try { Vector<Pair<String,String>> gdonation = new Vector<Pair<String, String>>(); gdonation.add(new Pair<String, String>(getString(R.string.donatePlayStore),null)); HashMap<String, SkuResponse> responseMap = new HashMap<String, SkuResponse>(); for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); responseMap.put( object.getString("productId"), new SkuResponse( object.getString("price"), object.getString("title"))); } for (String sku: donationSkus) if (responseMap.containsKey(sku)) gdonation.add(getSkuTitle(sku, responseMap.get(sku).title, responseMap.get(sku).price, ownedSkus)); String gmsTextString=""; for(int i=0;i<gdonation.size();i++) { if(i==1) gmsTextString+= " "; else if(i>1) gmsTextString+= ", "; gmsTextString+=gdonation.elementAt(i).first; } SpannableString gmsText = new SpannableString(gmsTextString); int lStart = 0; int lEnd=0; for(Pair<String, String> item:gdonation){ lEnd = lStart + item.first.length(); if (item.second!=null) { final String mSku = item.second; ClickableSpan cspan = new ClickableSpan() { @Override public void onClick(View widget) { triggerBuy(mSku); } }; gmsText.setSpan(cspan,lStart,lEnd,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } lStart = lEnd+2; // Account for ", " between items } if(gmsTextView !=null) { gmsTextView.setText(gmsText); gmsTextView.setMovementMethod(LinkMovementMethod.getInstance()); gmsTextView.setVisibility(View.VISIBLE); } } catch (JSONException e) { VpnStatus.logException("Parsing Play Store IAP",e); } } private Pair<String,String> getSkuTitle(final String sku, String title, String price, ArrayList<String> ownedSkus) { String text; if (ownedSkus.contains(sku)) return new Pair<String,String>(getString(R.string.thanks_for_donation, price),null); if (price.contains("€")|| price.contains("\u20ac")) { text= title; } else { text = String.format(Locale.getDefault(), "%s (%s)", title, price); } //return text; return new Pair<String,String>(price, sku); } private void triggerBuy(String sku) { try { Bundle buyBundle = mService.getBuyIntent(3, getActivity().getPackageName(), sku, INAPPITEM_TYPE_INAPP, "Thanks for the donation! :)"); if (buyBundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { PendingIntent buyIntent = (PendingIntent) buyBundle.getParcelable(RESPONSE_BUY_INTENT); getActivity().startIntentSenderForResult(buyIntent.getIntentSender(), DONATION_CODE, new Intent(), 0, 0, 0); } } catch (RemoteException e) { VpnStatus.logException(e); } catch (IntentSender.SendIntentException e) { VpnStatus.logException(e); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.about, container, false); //TextView ver = (TextView) v.findViewById(R.id.version); String version; String name = "Openvpn"; try { PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version = packageinfo.versionName; name = getString(R.string.app); } catch (NameNotFoundException e) { version = "error fetching version"; } //ver.setText(getString(R.string.version_info, name, version)); TextView paypal = (TextView) v.findViewById(R.id.donatestring); String donatetext = getActivity().getString(R.string.donatewithpaypal); Spanned htmltext = Html.fromHtml(donatetext); paypal.setText(htmltext); paypal.setMovementMethod(LinkMovementMethod.getInstance()); gmsTextView = (TextView) v.findViewById(R.id.donategms); /* recreating view without onCreate/onDestroy cycle */ if (mService!=null) initGooglePlayDonation(); TextView translation = (TextView) v.findViewById(R.id.translation); // Don't print a text for myself if (getString(R.string.translationby).contains("Arne Schwabe")) translation.setText(""); else translation.setText(R.string.translationby); WebView wv = (WebView)v.findViewById(R.id.webView); wv.loadUrl("file:///android_asset/full_licenses.html"); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mService!=null) initGooglePlayDonation(); } @Override public void onClick(View v) { } }
Java
package com.ecomdev.openvpn.fragments; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.TreeMap; import android.app.AlertDialog; import android.app.ListFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.ecomdev.openvpn.activities.FileSelect; import com.ecomdev.openvpn.R; public class FileSelectionFragment extends ListFragment { private static final String ITEM_KEY = "key"; private static final String ITEM_IMAGE = "image"; private static final String ROOT = "/"; private List<String> path = null; private TextView myPath; private ArrayList<HashMap<String, Object>> mList; private Button selectButton; private String parentPath; private String currentPath = ROOT; private String[] formatFilter = null; private File selectedFile; private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>(); private String mStartPath; private CheckBox mInlineImport; private Button mClearButton; private boolean mHideImport=false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.file_dialog_main, container,false); myPath = (TextView) v.findViewById(R.id.path); mInlineImport = (CheckBox) v.findViewById(R.id.doinline); if(mHideImport) { mInlineImport.setVisibility(View.GONE); mInlineImport.setChecked(false); } selectButton = (Button) v.findViewById(R.id.fdButtonSelect); selectButton.setEnabled(false); selectButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (selectedFile != null) { if(mInlineImport.isChecked()) ((FileSelect) getActivity()).importFile(selectedFile.getPath()); else ((FileSelect) getActivity()).setFile(selectedFile.getPath()); } } }); mClearButton = (Button) v.findViewById(R.id.fdClear); mClearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ((FileSelect) getActivity()).clearData(); } }); if(!((FileSelect) getActivity()).showClear()) { mClearButton.setVisibility(View.GONE); mClearButton.setEnabled(false); } return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mStartPath = ((FileSelect) getActivity()).getSelectPath(); getDir(mStartPath); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void getDir(String dirPath) { boolean useAutoSelection = dirPath.length() < currentPath.length(); Integer position = lastPositions.get(parentPath); getDirImpl(dirPath); if (position != null && useAutoSelection) { getListView().setSelection(position); } } /** * Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido. * * @param dirPath * Diretorio pai. */ private void getDirImpl(final String dirPath) { currentPath = dirPath; final List<String> item = new ArrayList<String>(); path = new ArrayList<String>(); mList = new ArrayList<HashMap<String, Object>>(); File f = new File(currentPath); File[] files = f.listFiles(); if (files == null) { currentPath = ROOT; f = new File(currentPath); files = f.listFiles(); } myPath.setText(getText(R.string.location) + ": " + currentPath); if (!currentPath.equals(ROOT)) { item.add(ROOT); addItem(ROOT, R.drawable.ic_root_folder_am); path.add(ROOT); item.add("../"); addItem("../", R.drawable.ic_root_folder_am); path.add(f.getParent()); parentPath = f.getParent(); } TreeMap<String, String> dirsMap = new TreeMap<String, String>(); TreeMap<String, String> dirsPathMap = new TreeMap<String, String>(); TreeMap<String, String> filesMap = new TreeMap<String, String>(); TreeMap<String, String> filesPathMap = new TreeMap<String, String>(); for (File file : files) { if (file.isDirectory()) { String dirName = file.getName(); dirsMap.put(dirName, dirName); dirsPathMap.put(dirName, file.getPath()); } else { final String fileName = file.getName(); final String fileNameLwr = fileName.toLowerCase(Locale.getDefault()); // se ha um filtro de formatos, utiliza-o if (formatFilter != null) { boolean contains = false; for (String aFormatFilter : formatFilter) { final String formatLwr = aFormatFilter.toLowerCase(Locale.getDefault()); if (fileNameLwr.endsWith(formatLwr)) { contains = true; break; } } if (contains) { filesMap.put(fileName, fileName); filesPathMap.put(fileName, file.getPath()); } // senao, adiciona todos os arquivos } else { filesMap.put(fileName, fileName); filesPathMap.put(fileName, file.getPath()); } } } item.addAll(dirsMap.tailMap("").values()); item.addAll(filesMap.tailMap("").values()); path.addAll(dirsPathMap.tailMap("").values()); path.addAll(filesPathMap.tailMap("").values()); SimpleAdapter fileList = new SimpleAdapter(getActivity(), mList, R.layout.file_dialog_row, new String[] { ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.fdrowtext, R.id.fdrowimage }); for (String dir : dirsMap.tailMap("").values()) { addItem(dir, R.drawable.ic_root_folder_am); } for (String file : filesMap.tailMap("").values()) { addItem(file, R.drawable.ic_doc_generic_am); } fileList.notifyDataSetChanged(); setListAdapter(fileList); } private void addItem(String fileName, int imageId) { HashMap<String, Object> item = new HashMap<String, Object>(); item.put(ITEM_KEY, fileName); item.put(ITEM_IMAGE, imageId); mList.add(item); } @Override public void onListItemClick(ListView l, View v, int position, long id) { File file = new File(path.get(position)); if (file.isDirectory()) { selectButton.setEnabled(false); if (file.canRead()) { lastPositions.put(currentPath, position); getDir(path.get(position)); } else { new AlertDialog.Builder(getActivity()).setIcon(R.drawable.icon) .setTitle("[" + file.getName() + "] " + getText(R.string.cant_read_folder)) .setPositiveButton("OK", null).show(); } } else { selectedFile = file; v.setSelected(true); selectButton.setEnabled(true); } } public void setNoInLine() { mHideImport=true; } }
Java
package com.ecomdev.openvpn.fragments; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.SwitchPreference; import android.util.Pair; import com.ecomdev.openvpn.activities.FileSelect; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.views.RemoteCNPreference; import com.ecomdev.openvpn.VpnProfile; import java.io.IOException; public class Settings_Authentication extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener, OnPreferenceClickListener { private static final int SELECT_TLS_FILE = 23223232; private static final int SELECT_TLS_FILE_KITKAT = SELECT_TLS_FILE +1; private CheckBoxPreference mExpectTLSCert; private CheckBoxPreference mCheckRemoteCN; private RemoteCNPreference mRemoteCN; private ListPreference mTLSAuthDirection; private Preference mTLSAuthFile; private SwitchPreference mUseTLSAuth; private EditTextPreference mCipher; private String mTlsAuthFileData; private EditTextPreference mAuth; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.vpn_authentification); mExpectTLSCert = (CheckBoxPreference) findPreference("remoteServerTLS"); mCheckRemoteCN = (CheckBoxPreference) findPreference("checkRemoteCN"); mRemoteCN = (RemoteCNPreference) findPreference("remotecn"); mRemoteCN.setOnPreferenceChangeListener(this); mUseTLSAuth = (SwitchPreference) findPreference("useTLSAuth" ); mTLSAuthFile = findPreference("tlsAuthFile"); mTLSAuthDirection = (ListPreference) findPreference("tls_direction"); mTLSAuthFile.setOnPreferenceClickListener(this); mCipher =(EditTextPreference) findPreference("cipher"); mCipher.setOnPreferenceChangeListener(this); mAuth =(EditTextPreference) findPreference("auth"); mAuth.setOnPreferenceChangeListener(this); loadSettings(); } @Override protected void loadSettings() { mExpectTLSCert.setChecked(mProfile.mExpectTLSCert); mCheckRemoteCN.setChecked(mProfile.mCheckRemoteCN); mRemoteCN.setDN(mProfile.mRemoteCN); mRemoteCN.setAuthType(mProfile.mX509AuthType); onPreferenceChange(mRemoteCN, new Pair<Integer, String>(mProfile.mX509AuthType, mProfile.mRemoteCN)); mUseTLSAuth.setChecked(mProfile.mUseTLSAuth); mTlsAuthFileData= mProfile.mTLSAuthFilename; setTlsAuthSummary(mTlsAuthFileData); mTLSAuthDirection.setValue(mProfile.mTLSAuthDirection); mCipher.setText(mProfile.mCipher); onPreferenceChange(mCipher, mProfile.mCipher); mAuth.setText(mProfile.mAuth); onPreferenceChange(mAuth, mProfile.mAuth); if (mProfile.mAuthenticationType == VpnProfile.TYPE_STATICKEYS) { mExpectTLSCert.setEnabled(false); mCheckRemoteCN.setEnabled(false); mUseTLSAuth.setChecked(true); } else { mExpectTLSCert.setEnabled(true); mCheckRemoteCN.setEnabled(true); } } @Override protected void saveSettings() { mProfile.mExpectTLSCert=mExpectTLSCert.isChecked(); mProfile.mCheckRemoteCN=mCheckRemoteCN.isChecked(); mProfile.mRemoteCN=mRemoteCN.getCNText(); mProfile.mX509AuthType=mRemoteCN.getAuthtype(); mProfile.mUseTLSAuth = mUseTLSAuth.isChecked(); mProfile.mTLSAuthFilename = mTlsAuthFileData; if(mTLSAuthDirection.getValue()==null) mProfile.mTLSAuthDirection=null; else mProfile.mTLSAuthDirection = mTLSAuthDirection.getValue(); if(mCipher.getText()==null) mProfile.mCipher=null; else mProfile.mCipher = mCipher.getText(); if(mAuth.getText()==null) mProfile.mAuth = null; else mProfile.mAuth = mAuth.getText(); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if(preference==mRemoteCN) { @SuppressWarnings("unchecked") int authtype = ((Pair<Integer, String>) newValue).first; @SuppressWarnings("unchecked") String dn = ((Pair<Integer, String>) newValue).second; if ("".equals(dn)) preference.setSummary(getX509String(VpnProfile.X509_VERIFY_TLSREMOTE_RDN, mProfile.mServerName)); else preference.setSummary(getX509String(authtype,dn)); } else if (preference == mCipher || preference == mAuth) { preference.setSummary((CharSequence) newValue); } return true; } private CharSequence getX509String(int authtype, String dn) { String ret =""; switch (authtype) { case VpnProfile.X509_VERIFY_TLSREMOTE: case VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING: ret+="tls-remote "; break; case VpnProfile.X509_VERIFY_TLSREMOTE_DN: ret="dn: "; break; case VpnProfile.X509_VERIFY_TLSREMOTE_RDN: ret="rdn: "; break; case VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX: ret="rdn prefix: "; break; } return ret + dn; } void startFileDialog() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Intent startFC = Utils.getFilePickerIntent (Utils.FileType.TLS_AUTH_FILE); startActivityForResult(startFC, SELECT_TLS_FILE_KITKAT); } else { Intent startFC = new Intent(getActivity(), FileSelect.class); startFC.putExtra(FileSelect.START_DATA, mTlsAuthFileData); startFC.putExtra(FileSelect.WINDOW_TITLE, R.string.tls_auth_file); startActivityForResult(startFC, SELECT_TLS_FILE); } } @Override public boolean onPreferenceClick(Preference preference) { startFileDialog(); return true; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==SELECT_TLS_FILE && resultCode == Activity.RESULT_OK){ String result = data.getStringExtra(FileSelect.RESULT_DATA); mTlsAuthFileData=result; setTlsAuthSummary(result); } else if (requestCode == SELECT_TLS_FILE_KITKAT && resultCode == Activity.RESULT_OK) { try { mTlsAuthFileData= VpnProfile.INLINE_TAG + Utils.getStringFromFilePickerResult(Utils.FileType.TLS_AUTH_FILE,data,getActivity()); setTlsAuthSummary(mTlsAuthFileData); } catch (IOException e) { VpnStatus.logException(e); } } } private void setTlsAuthSummary(String result) { if(result==null) result = getString(R.string.no_certificate); if(result.startsWith(VpnProfile.INLINE_TAG)) mTLSAuthFile.setSummary(R.string.inline_file_data); else mTLSAuthFile.setSummary(result); } }
Java
package com.ecomdev.openvpn.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.ecomdev.openvpn.activities.FileSelect; import com.ecomdev.openvpn.R; public class InlineFileTab extends Fragment { private static final int MENU_SAVE = 0; private EditText mInlineData; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mInlineData.setText(((FileSelect)getActivity()).getInlineData()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.file_dialog_inline, container, false); mInlineData =(EditText) v.findViewById(R.id.inlineFileData); return v; } public void setData(String data) { if(mInlineData!=null) mInlineData.setText(data); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.add(0, MENU_SAVE, 0, "Use inline data") .setIcon(android.R.drawable.ic_menu_save) .setAlphabeticShortcut('u') .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==MENU_SAVE){ ((FileSelect)getActivity()).saveInlineData(mInlineData.getText().toString()); return true; } return super.onOptionsItemSelected(item); } }
Java
package com.ecomdev.openvpn.fragments; import android.app.Fragment; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ecomdev.openvpn.R; public class FaqFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v= inflater.inflate(R.layout.faq, container, false); insertHtmlEntry(v,R.id.broken_images_faq,R.string.broken_images_faq); insertHtmlEntry(v,R.id.faq_howto,R.string.faq_howto); insertHtmlEntry(v, R.id.baterry_consumption, R.string.baterry_consumption); insertHtmlEntry(v, R.id.faq_tethering, R.string.faq_tethering); insertHtmlEntry(v, R.id.faq_vpndialog43, R.string.faq_vpndialog43); insertHtmlEntry(v, R.id.faq_system_dialog_xposed, R.string.faq_system_dialog_xposed); return v; } private void insertHtmlEntry (View v, int viewId, int stringId) { TextView faqitem = (TextView) v.findViewById(viewId); faqitem.setText(Html.fromHtml(getActivity().getString(stringId))); faqitem.setMovementMethod(LinkMovementMethod.getInstance()); } }
Java
package com.ecomdev.openvpn.fragments; import java.io.File; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.api.ExternalAppDatabase; public class GeneralSettings extends PreferenceFragment implements OnPreferenceClickListener, OnClickListener { private ExternalAppDatabase mExtapp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.general_settings); PreferenceCategory devHacks = (PreferenceCategory) findPreference("device_hacks"); Preference loadtun = findPreference("loadTunModule"); if(!isTunModuleAvailable()) { loadtun.setEnabled(false); devHacks.removePreference(loadtun); } CheckBoxPreference cm9hack = (CheckBoxPreference) findPreference("useCM9Fix"); if (!cm9hack.isChecked() && (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1)) { devHacks.removePreference(cm9hack); } mExtapp = new ExternalAppDatabase(getActivity()); Preference clearapi = findPreference("clearapi"); clearapi.setOnPreferenceClickListener(this); if(devHacks.getPreferenceCount()==0) getPreferenceScreen().removePreference(devHacks); setClearApiSummary(); } private void setClearApiSummary() { Preference clearapi = findPreference("clearapi"); if(mExtapp.getExtAppList().isEmpty()) { clearapi.setEnabled(false); clearapi.setSummary(R.string.no_external_app_allowed); } else { clearapi.setEnabled(true); clearapi.setSummary(getString(R.string.allowed_apps,getExtAppList(", "))); } } private String getExtAppList(String delim) { ApplicationInfo app; PackageManager pm = getActivity().getPackageManager(); String applist=null; for (String packagename : mExtapp.getExtAppList()) { try { app = pm.getApplicationInfo(packagename, 0); if (applist==null) applist = ""; else applist += delim; applist+=app.loadLabel(pm); } catch (NameNotFoundException e) { // App not found. Remove it from the list mExtapp.removeApp(packagename); } } return applist; } private boolean isTunModuleAvailable() { // Check if the tun module exists on the file system return new File("/system/lib/modules/tun.ko").length() > 10; } @Override public boolean onPreferenceClick(Preference preference) { if(preference.getKey().equals("clearapi")){ Builder builder = new AlertDialog.Builder(getActivity()); builder.setPositiveButton(R.string.clear, this); builder.setNegativeButton(android.R.string.cancel, null); builder.setMessage(getString(R.string.clearappsdialog,getExtAppList("\n"))); builder.show(); } return true; } @Override public void onClick(DialogInterface dialog, int which) { if( which == Dialog.BUTTON_POSITIVE){ mExtapp.clearAllApiApps(); setClearApiSummary(); } } }
Java
package com.ecomdev.openvpn.fragments; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import com.ecomdev.openvpn.R; public class Settings_Routing extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { private EditTextPreference mCustomRoutes; private CheckBoxPreference mUseDefaultRoute; private EditTextPreference mCustomRoutesv6; private CheckBoxPreference mUseDefaultRoutev6; private CheckBoxPreference mRouteNoPull; private CheckBoxPreference mLocalVPNAccess; private EditTextPreference mExcludedRoutes; private EditTextPreference mExcludedRoutesv6; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.vpn_routing); mCustomRoutes = (EditTextPreference) findPreference("customRoutes"); mUseDefaultRoute = (CheckBoxPreference) findPreference("useDefaultRoute"); mCustomRoutesv6 = (EditTextPreference) findPreference("customRoutesv6"); mUseDefaultRoutev6 = (CheckBoxPreference) findPreference("useDefaultRoutev6"); mExcludedRoutes = (EditTextPreference) findPreference("excludedRoutes"); mExcludedRoutesv6 = (EditTextPreference) findPreference("excludedRoutesv6"); mRouteNoPull = (CheckBoxPreference) findPreference("routenopull"); mLocalVPNAccess = (CheckBoxPreference) findPreference("unblockLocal"); mCustomRoutes.setOnPreferenceChangeListener(this); mCustomRoutesv6.setOnPreferenceChangeListener(this); loadSettings(); } @Override protected void loadSettings() { mUseDefaultRoute.setChecked(mProfile.mUseDefaultRoute); mUseDefaultRoutev6.setChecked(mProfile.mUseDefaultRoutev6); mCustomRoutes.setText(mProfile.mCustomRoutes); mCustomRoutesv6.setText(mProfile.mCustomRoutesv6); mExcludedRoutes.setText(mProfile.mExcludedRoutes); mExcludedRoutes.setText(mProfile.mExcludedRoutesv6); mRouteNoPull.setChecked(mProfile.mRoutenopull); mLocalVPNAccess.setChecked(mProfile.mAllowLocalLAN); // Sets Summary onPreferenceChange(mCustomRoutes, mCustomRoutes.getText()); onPreferenceChange(mCustomRoutesv6, mCustomRoutesv6.getText()); mRouteNoPull.setEnabled(mProfile.mUsePull); } @Override protected void saveSettings() { mProfile.mUseDefaultRoute = mUseDefaultRoute.isChecked(); mProfile.mUseDefaultRoutev6 = mUseDefaultRoutev6.isChecked(); mProfile.mCustomRoutes = mCustomRoutes.getText(); mProfile.mCustomRoutesv6 = mCustomRoutesv6.getText(); mProfile.mRoutenopull = mRouteNoPull.isChecked(); mProfile.mAllowLocalLAN =mLocalVPNAccess.isChecked(); mProfile.mExcludedRoutes = mExcludedRoutes.getText(); mProfile.mExcludedRoutesv6 = mExcludedRoutesv6.getText(); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if( preference == mCustomRoutes || preference == mCustomRoutesv6 || preference == mExcludedRoutes || preference == mExcludedRoutesv6) preference.setSummary((String)newValue); saveSettings(); return true; } }
Java
package com.ecomdev.openvpn.fragments; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.*; import android.content.*; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.IBinder; import android.os.Message; import android.text.SpannableString; import android.text.format.DateFormat; import android.text.style.ImageSpan; import android.view.*; import android.widget.*; import android.widget.AdapterView.OnItemLongClickListener; import com.ecomdev.openvpn.*; import com.ecomdev.openvpn.activities.DisconnectVPN; import com.ecomdev.openvpn.activities.MainActivity; import com.ecomdev.openvpn.core.OpenVPNManagement; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import com.ecomdev.openvpn.core.VpnStatus.LogItem; import com.ecomdev.openvpn.core.VpnStatus.LogListener; import com.ecomdev.openvpn.core.VpnStatus.StateListener; import com.ecomdev.openvpn.core.OpenVpnService; import com.ecomdev.openvpn.core.OpenVpnService.LocalBinder; import com.ecomdev.openvpn.core.ProfileManager; import org.jetbrains.annotations.Nullable; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import static android.content.Context.MODE_PRIVATE; import static com.ecomdev.openvpn.core.OpenVpnService.humanReadableByteCount; public class LogFragment extends ListFragment implements StateListener, SeekBar.OnSeekBarChangeListener, RadioGroup.OnCheckedChangeListener, VpnStatus.ByteCountListener { private static final String LOGTIMEFORMAT = "logtimeformat"; private static final int START_VPN_CONFIG = 0; private static final String VERBOSITYLEVEL = "verbositylevel"; private static final String TIMER_NAME = "Loading"; protected OpenVpnService mService; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { mService =null; } }; private SeekBar mLogLevelSlider; private LinearLayout mOptionsLayout; private RadioGroup mTimeRadioGroup; private TextView mUpStatus; private TextView mDownStatus; private TextView mConnectStatus; private Button mDisconnectButton; private boolean mShowOptionsLayout; private Timer mTimer; private boolean mIsTimerRun = false; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { ladapter.setLogLevel(progress+1); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.radioISO: ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_ISO); break; case R.id.radioNone: ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_NONE); break; case R.id.radioShort: ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_SHORT); break; } } @Override public void updateByteCount(long in, long out, long diffIn, long diffOut) { //%2$s/s %1$s - ↑%4$s/s %3$s final String down = String.format("%2$s/s %1$s", humanReadableByteCount(in, false), humanReadableByteCount(diffIn / OpenVPNManagement.mBytecountInterval, true)); final String up = String.format("%2$s/s %1$s", humanReadableByteCount(out, false), humanReadableByteCount(diffOut / OpenVPNManagement.mBytecountInterval, true)); if (mUpStatus != null && mDownStatus != null) { if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mUpStatus.setText(up); mDownStatus.setText(down); } }); } } } class LogWindowListAdapter implements ListAdapter, LogListener, Callback { private static final int MESSAGE_NEWLOG = 0; private static final int MESSAGE_CLEARLOG = 1; private static final int MESSAGE_NEWTS = 2; private static final int MESSAGE_NEWLOGLEVEL = 3; public static final int TIME_FORMAT_NONE = 0; public static final int TIME_FORMAT_SHORT = 1; public static final int TIME_FORMAT_ISO = 2; private static final int MAX_STORED_LOG_ENTRIES = 1000; private Vector<LogItem> allEntries=new Vector<LogItem>(); private Vector<LogItem> currentLevelEntries=new Vector<LogItem>(); private Handler mHandler; private Vector<DataSetObserver> observers=new Vector<DataSetObserver>(); private int mTimeFormat=0; private int mLogLevel=3; public LogWindowListAdapter() { initLogBuffer(); if (mHandler == null) { mHandler = new Handler(this); } VpnStatus.addLogListener(this); } private void initLogBuffer() { allEntries.clear(); Collections.addAll(allEntries, VpnStatus.getlogbuffer()); initCurrentMessages(); } String getLogStr() { String str = ""; for(LogItem entry:allEntries) { str+=getTime(entry, TIME_FORMAT_ISO) + entry.getString(getActivity()) + '\n'; } return str; } private void shareLog() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, getLogStr()); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.ics_openvpn_log_file)); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Send Logfile")); } @Override public void registerDataSetObserver(DataSetObserver observer) { observers.add(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { observers.remove(observer); } @Override public int getCount() { return currentLevelEntries.size(); } @Override public Object getItem(int position) { return currentLevelEntries.get(position); } @Override public long getItemId(int position) { return ((Object)currentLevelEntries.get(position)).hashCode(); } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView v; if(convertView==null) v = new TextView(getActivity()); else v = (TextView) convertView; LogItem le = currentLevelEntries.get(position); String msg = le.getString(getActivity()); String time = getTime(le, mTimeFormat); msg = time + msg; int spanStart = time.length(); SpannableString t = new SpannableString(msg); //t.setSpan(getSpanImage(le,(int)v.getTextSize()),spanStart,spanStart+1, Spanned.SPAN_INCLUSIVE_INCLUSIVE); v.setText(t); return v; } private String getTime(LogItem le, int time) { if (time != TIME_FORMAT_NONE) { Date d = new Date(le.getLogtime()); java.text.DateFormat timeformat; if (time== TIME_FORMAT_ISO) timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); else timeformat = DateFormat.getTimeFormat(getActivity()); return timeformat.format(d) + " "; } else { return ""; } } private ImageSpan getSpanImage(LogItem li, int imageSize) { int imageRes = android.R.drawable.ic_menu_call; switch (li.getLogLevel()) { case ERROR: imageRes = android.R.drawable.ic_notification_clear_all; break; case INFO: imageRes = android.R.drawable.ic_menu_compass; break; case VERBOSE: imageRes = android.R.drawable.ic_menu_info_details; break; case WARNING: imageRes = android.R.drawable.ic_menu_camera; break; } Drawable d = getResources().getDrawable(imageRes); //d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); d.setBounds(0, 0, imageSize, imageSize); ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM); return span; } @Override public int getItemViewType(int position) { return 0; } @Override public int getViewTypeCount() { return 1; } @Override public boolean isEmpty() { return currentLevelEntries.isEmpty(); } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } @Override public void newLog(LogItem logMessage) { Message msg = Message.obtain(); assert (msg!=null); msg.what=MESSAGE_NEWLOG; Bundle bundle=new Bundle(); bundle.putParcelable("logmessage", logMessage); msg.setData(bundle); mHandler.sendMessage(msg); } @Override public boolean handleMessage(Message msg) { // We have been called if(msg.what==MESSAGE_NEWLOG) { LogItem logMessage = msg.getData().getParcelable("logmessage"); if(addLogMessage(logMessage)) for (DataSetObserver observer : observers) { observer.onChanged(); } } else if (msg.what == MESSAGE_CLEARLOG) { for (DataSetObserver observer : observers) { observer.onInvalidated(); } initLogBuffer(); } else if (msg.what == MESSAGE_NEWTS) { for (DataSetObserver observer : observers) { observer.onInvalidated(); } } else if (msg.what == MESSAGE_NEWLOGLEVEL) { initCurrentMessages(); for (DataSetObserver observer: observers) { observer.onChanged(); } } return true; } private void initCurrentMessages() { currentLevelEntries.clear(); for(LogItem li: allEntries) { if (li.getVerbosityLevel() <= mLogLevel || mLogLevel == VpnProfile.MAXLOGLEVEL) currentLevelEntries.add(li); } } /** * * @param logmessage * @return True if the current entries have changed */ private boolean addLogMessage(LogItem logmessage) { allEntries.add(logmessage); if (allEntries.size() > MAX_STORED_LOG_ENTRIES) { Vector<LogItem> oldAllEntries = allEntries; allEntries = new Vector<LogItem>(allEntries.size()); for (int i=50;i<oldAllEntries.size();i++) { allEntries.add(oldAllEntries.elementAt(i)); } initCurrentMessages(); return true; } else { if (logmessage.getVerbosityLevel() <= mLogLevel) { currentLevelEntries.add(logmessage); return true; } else { return false; } } } void clearLog() { // Actually is probably called from GUI Thread as result of the user // pressing a button. But better safe than sorry VpnStatus.clearLog(); VpnStatus.logInfo(R.string.logCleared); mHandler.sendEmptyMessage(MESSAGE_CLEARLOG); } public void setTimeFormat(int newTimeFormat) { mTimeFormat= newTimeFormat; mHandler.sendEmptyMessage(MESSAGE_NEWTS); } public void setLogLevel(int logLevel) { mLogLevel = logLevel; mHandler.sendEmptyMessage(MESSAGE_NEWLOGLEVEL); } } private LogWindowListAdapter ladapter; private TextView mSpeedView; private TextView mLoadView; @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==R.id.clearlog) { ladapter.clearLog(); return true; } else if(item.getItemId()==R.id.cancel){ disconnect(); return true; } else if(item.getItemId()==R.id.send) { ladapter.shareLog(); } /*else if(item.getItemId()==R.id.edit_vpn) { VpnProfile lastConnectedprofile = ProfileManager.getLastConnectedVpn(); if(lastConnectedprofile!=null) { Intent vprefintent = new Intent(getActivity(),VPNPreferences.class) .putExtra(VpnProfile.EXTRA_PROFILEUUID,lastConnectedprofile.getUUIDString()); startActivityForResult(vprefintent,START_VPN_CONFIG); } else { Toast.makeText(getActivity(), R.string.log_no_last_vpn, Toast.LENGTH_LONG).show(); } } */else if(item.getItemId() == R.id.toggle_time) { showHideOptionsPanel(); } else if(item.getItemId() == android.R.id.home) { // This is called when the Home (Up) button is pressed // in the Action Bar. Intent parentActivityIntent = new Intent(getActivity(), MainActivity.class); parentActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(parentActivityIntent); getActivity().finish(); return true; } return super.onOptionsItemSelected(item); } private void disconnect() { Intent intent = new Intent(getActivity(),DisconnectVPN.class); startActivity(intent); } private void showHideOptionsPanel() { boolean optionsVisible = (mOptionsLayout.getVisibility() != View.GONE); ObjectAnimator anim; if (optionsVisible) { anim = ObjectAnimator.ofFloat(mOptionsLayout,"alpha",1.0f, 0f); anim.addListener(collapseListener); } else { mOptionsLayout.setVisibility(View.VISIBLE); anim = ObjectAnimator.ofFloat(mOptionsLayout,"alpha", 0f, 1.0f); //anim = new TranslateAnimation(0.0f, 0.0f, mOptionsLayout.getHeight(), 0.0f); } //anim.setInterpolator(new AccelerateInterpolator(1.0f)); //anim.setDuration(300); //mOptionsLayout.startAnimation(anim); anim.start(); } AnimatorListenerAdapter collapseListener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animator) { mOptionsLayout.setVisibility(View.GONE); } }; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.logmenu, menu); if (getResources().getBoolean(R.bool.logSildersAlwaysVisible)) menu.removeItem(R.id.toggle_time); } @Override public void onResume() { super.onResume(); VpnStatus.addStateListener(this); VpnStatus.addByteCountListener(this); Intent intent = new Intent(getActivity(), OpenVpnService.class); intent.setAction(OpenVpnService.START_SERVICE); getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == START_VPN_CONFIG && resultCode== Activity.RESULT_OK) { String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); final VpnProfile profile = ProfileManager.get(getActivity(),configuredVPN); ProfileManager.getInstance(getActivity()).saveProfile(getActivity(), profile); // Name could be modified, reset List adapter AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle(R.string.configuration_changed); dialog.setMessage(R.string.restart_vpn_after_change); dialog.setPositiveButton(R.string.restart, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(getActivity(), LaunchVPN.class); intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUIDString()); intent.setAction(Intent.ACTION_MAIN); startActivity(intent); } }); dialog.setNegativeButton(R.string.ignore, null); dialog.create().show(); } super.onActivityResult(requestCode, resultCode, data); } @Override public void onStop() { super.onStop(); VpnStatus.removeStateListener(this); VpnStatus.removeByteCountListener(this); if(mService!=null) getActivity().unbindService(mConnection); getActivity().getPreferences(0).edit().putInt(LOGTIMEFORMAT, ladapter.mTimeFormat) .putInt(VERBOSITYLEVEL, ladapter.mLogLevel).apply(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ListView lv = getListView(); lv.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Log Entry",((TextView) view).getText()); clipboard.setPrimaryClip(clip); Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show(); return true; } }); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.log_fragment, container, false); setHasOptionsMenu(true); ladapter = new LogWindowListAdapter(); ladapter.mTimeFormat = getActivity().getPreferences(0).getInt(LOGTIMEFORMAT, 0); int logLevel = getActivity().getPreferences(0).getInt(VERBOSITYLEVEL, 0); ladapter.setLogLevel(logLevel); setListAdapter(ladapter); mTimeRadioGroup = (RadioGroup) v.findViewById(R.id.timeFormatRadioGroup); mTimeRadioGroup.setOnCheckedChangeListener(this); if(ladapter.mTimeFormat== LogWindowListAdapter.TIME_FORMAT_ISO) { mTimeRadioGroup.check(R.id.radioISO); } else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_NONE) { mTimeRadioGroup.check(R.id.radioNone); } else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_SHORT) { mTimeRadioGroup.check(R.id.radioShort); } mSpeedView = (TextView) v.findViewById(R.id.speed); mLoadView = (TextView) v.findViewById(R.id.load); mOptionsLayout = (LinearLayout) v.findViewById(R.id.logOptionsLayout); mLogLevelSlider = (SeekBar) v.findViewById(R.id.LogLevelSlider); mLogLevelSlider.setMax(VpnProfile.MAXLOGLEVEL-1); mLogLevelSlider.setProgress(logLevel-1); mLogLevelSlider.setOnSeekBarChangeListener(this); if(getResources().getBoolean(R.bool.logSildersAlwaysVisible)) mOptionsLayout.setVisibility(View.VISIBLE); mUpStatus = (TextView) v.findViewById(R.id.speedUp); mDownStatus = (TextView) v.findViewById(R.id.speedDown); mConnectStatus = (TextView) v.findViewById(R.id.speedStatus); mDisconnectButton = (Button) v.findViewById(R.id.logFragmentDisconnect); mDisconnectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { disconnect(); } }); if (mShowOptionsLayout) mOptionsLayout.setVisibility(View.VISIBLE); return v; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if(getResources().getBoolean(R.bool.logSildersAlwaysVisible)) { mShowOptionsLayout=true; if (mOptionsLayout!= null) mOptionsLayout.setVisibility(View.VISIBLE); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void updateState(final String status, final String logMessage, final int resId, final ConnectionStatus level) { if (isAdded()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setEnableDisconnectedButtonByState(resId); String prefix = getString(resId) + ":"; if (status.equals("BYTECOUNT") || status.equals("NOPROCESS")) prefix = ""; if (resId == R.string.unknown_state) prefix += status; if (mSpeedView != null) { updateSpeedView(resId); } if (mConnectStatus != null) { mConnectStatus.setText(getString(resId)); } } }); } } private void setEnableDisconnectedButtonByState(int resId) { switch (resId) { case R.string.state_disconnected: case R.string.state_noprocess: case R.string.state_exiting: mDisconnectButton.setEnabled(false); break; default: mDisconnectButton.setEnabled(true); } } private void updateSpeedView(int resId) { switch (resId) { case R.string.state_noprocess: cancelTimer(); mLoadView.setText(""); mSpeedView.setText(getString(R.string.disconnected)); break; case R.string.state_disconnected: case R.string.state_connected: cancelTimer(); mLoadView.setText(""); mSpeedView.setText(getString(resId)); break; case R.string.state_user_vpn_password: case R.string.state_nonetwork: case R.string.speed_waiting: if (mTimer == null) { startLoading(); } break; } } private void startLoading() { mSpeedView.setText(getString(R.string.state_connecting)); mTimer = new Timer(TIMER_NAME); mIsTimerRun = true; mTimer.schedule(new TimerTask() { @Override public void run() { int count = 4; while (mIsTimerRun) { final StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < count && mIsTimerRun; i++) { mLoadView.post(new Runnable() { @Override public void run() { mLoadView.setText(stringBuffer); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stringBuffer.append("."); } } } }, 0); } private void cancelTimer() { mIsTimerRun = false; if (mTimer != null) { mTimer.cancel(); mTimer = null; } } private void startDemoTime(int resId) { switch (resId) { case R.string.state_connected: SharedPreferences preferences = getActivity().getSharedPreferences(Constants.sMAIN_SHARED_PREFERENCE, MODE_PRIVATE); SharedPreferences.Editor edit = preferences.edit(); edit.putLong(Constants.sPREF_START_DEMO_TIME, System.currentTimeMillis()); edit.putInt(Constants.sPREF_LEFT_HOURS, getResources().getInteger(R.integer.demoHours)); boolean isDemo = preferences.getBoolean(Constants.sPREF_IS_DEMO, true); boolean isTimeOut = preferences.getBoolean(Constants.sPREF_IS_TIMEOUT, false); if (isDemo && !isTimeOut) { Intent intent = new Intent(getActivity(), UpdateDemoTimeReceiver.class); PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), Constants.sUPDATE_DEMO_TIME_RECEIVER_NUM, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE); // alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR, broadcast); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 1000*60, 1000*60, broadcast); } break; } } @Override public void onDestroy() { VpnStatus.removeLogListener(ladapter); super.onDestroy(); } }
Java
package com.ecomdev.openvpn.fragments; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import com.ecomdev.openvpn.R; public class Settings_Obscure extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { private CheckBoxPreference mUseRandomHostName; private CheckBoxPreference mUseFloat; private CheckBoxPreference mUseCustomConfig; private EditTextPreference mCustomConfig; private ListPreference mLogverbosity; private CheckBoxPreference mPersistent; private ListPreference mConnectretrymax; private EditTextPreference mConnectretry; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.vpn_obscure); mUseRandomHostName = (CheckBoxPreference) findPreference("useRandomHostname"); mUseFloat = (CheckBoxPreference) findPreference("useFloat"); mUseCustomConfig = (CheckBoxPreference) findPreference("enableCustomOptions"); mCustomConfig = (EditTextPreference) findPreference("customOptions"); mPersistent = (CheckBoxPreference) findPreference("usePersistTun"); mConnectretrymax = (ListPreference) findPreference("connectretrymax"); mConnectretry = (EditTextPreference) findPreference("connectretry"); mConnectretrymax.setOnPreferenceChangeListener(this); mConnectretrymax.setSummary("%s"); mConnectretry.setOnPreferenceChangeListener(this); loadSettings(); } protected void loadSettings() { mUseRandomHostName.setChecked(mProfile.mUseRandomHostname); mUseFloat.setChecked(mProfile.mUseFloat); mUseCustomConfig.setChecked(mProfile.mUseCustomConfig); mCustomConfig.setText(mProfile.mCustomConfigOptions); mPersistent.setChecked(mProfile.mPersistTun); mConnectretrymax.setValue(mProfile.mConnectRetryMax); onPreferenceChange(mConnectretrymax, mProfile.mConnectRetryMax); mConnectretry.setText(mProfile.mConnectRetry); onPreferenceChange(mConnectretry, mProfile.mConnectRetry); } protected void saveSettings() { mProfile.mUseRandomHostname = mUseRandomHostName.isChecked(); mProfile.mUseFloat = mUseFloat.isChecked(); mProfile.mUseCustomConfig = mUseCustomConfig.isChecked(); mProfile.mCustomConfigOptions = mCustomConfig.getText(); mProfile.mConnectRetryMax = mConnectretrymax.getValue(); mProfile.mPersistTun = mPersistent.isChecked(); mProfile.mConnectRetry = mConnectretry.getText(); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference == mConnectretrymax) { if(newValue==null) { newValue="5"; } mConnectretrymax.setDefaultValue(newValue); for(int i=0;i<mConnectretrymax.getEntryValues().length;i++){ if(mConnectretrymax.getEntryValues().equals(newValue)) mConnectretrymax.setSummary(mConnectretrymax.getEntries()[i]); } } else if (preference == mConnectretry) { if(newValue==null || newValue=="") newValue="5"; mConnectretry.setSummary(String.format("%s s" , newValue)); } return true; } }
Java
package com.ecomdev.openvpn.fragments; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ProfileManager; public class ShowConfigFragment extends Fragment { private String configtext; public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID"); final VpnProfile vp = ProfileManager.get(getActivity(),profileUUID); View v=inflater.inflate(R.layout.viewconfig, container,false); final TextView cv = (TextView) v.findViewById(R.id.configview); int check=vp.checkProfile(getActivity()); if(check!=R.string.no_error_found) { cv.setText(check); configtext = getString(check); } else { // Run in own Thread since Keystore does not like to be queried from the main thread cv.setText("Generating config..."); startGenConfig(vp, cv); } return v; } private void startGenConfig(final VpnProfile vp, final TextView cv) { new Thread() { public void run() { final String cfg=vp.getConfigFile(getActivity(),false); configtext= cfg; getActivity().runOnUiThread(new Runnable() { @Override public void run() { cv.setText(cfg); } }); } }.start(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.configmenu, menu); } private void shareConfig() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, configtext); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_config_title)); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Export Configfile")); } @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); if (itemId == R.id.sendConfig) { shareConfig(); return true; } else { return super.onOptionsItemSelected(item); } } }
Java
package com.ecomdev.openvpn.fragments; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceManager; import android.preference.SwitchPreference; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; public class Settings_IP extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener { private EditTextPreference mIPv4; private EditTextPreference mIPv6; private SwitchPreference mUsePull; private CheckBoxPreference mOverrideDNS; private EditTextPreference mSearchdomain; private EditTextPreference mDNS1; private EditTextPreference mDNS2; private CheckBoxPreference mNobind; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Make sure default values are applied. In a real app, you would // want this in a shared function that is used to retrieve the // SharedPreferences wherever they are needed. PreferenceManager.setDefaultValues(getActivity(), R.xml.vpn_ipsettings, false); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.vpn_ipsettings); mIPv4 = (EditTextPreference) findPreference("ipv4_address"); mIPv6 = (EditTextPreference) findPreference("ipv6_address"); mUsePull = (SwitchPreference) findPreference("usePull"); mOverrideDNS = (CheckBoxPreference) findPreference("overrideDNS"); mSearchdomain =(EditTextPreference) findPreference("searchdomain"); mDNS1 = (EditTextPreference) findPreference("dns1"); mDNS2 = (EditTextPreference) findPreference("dns2"); mNobind = (CheckBoxPreference) findPreference("nobind"); mIPv4.setOnPreferenceChangeListener(this); mIPv6.setOnPreferenceChangeListener(this); mDNS1.setOnPreferenceChangeListener(this); mDNS2.setOnPreferenceChangeListener(this); mUsePull.setOnPreferenceChangeListener(this); mOverrideDNS.setOnPreferenceChangeListener(this); mSearchdomain.setOnPreferenceChangeListener(this); loadSettings(); } @Override protected void loadSettings() { mUsePull.setChecked(mProfile.mUsePull); mIPv4.setText(mProfile.mIPv4Address); mIPv6.setText(mProfile.mIPv6Address); mDNS1.setText(mProfile.mDNS1); mDNS2.setText(mProfile.mDNS2); mOverrideDNS.setChecked(mProfile.mOverrideDNS); mSearchdomain.setText(mProfile.mSearchDomain); mNobind.setChecked(mProfile.mNobind); if (mProfile.mAuthenticationType == VpnProfile.TYPE_STATICKEYS) mUsePull.setChecked(false); // Sets Summary onPreferenceChange(mIPv4, mIPv4.getText()); onPreferenceChange(mIPv6, mIPv6.getText()); onPreferenceChange(mDNS1, mDNS1.getText()); onPreferenceChange(mDNS2, mDNS2.getText()); onPreferenceChange(mSearchdomain, mSearchdomain.getText()); setDNSState(); } @Override protected void saveSettings() { mProfile.mUsePull = mUsePull.isChecked(); mProfile.mIPv4Address = mIPv4.getText(); mProfile.mIPv6Address = mIPv6.getText(); mProfile.mDNS1 = mDNS1.getText(); mProfile.mDNS2 = mDNS2.getText(); mProfile.mOverrideDNS = mOverrideDNS.isChecked(); mProfile.mSearchDomain = mSearchdomain.getText(); mProfile.mNobind = mNobind.isChecked(); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if(preference==mIPv4 || preference == mIPv6 || preference==mDNS1 || preference == mDNS2 || preference == mSearchdomain ) preference.setSummary((String)newValue); if(preference== mUsePull || preference == mOverrideDNS) if(preference==mOverrideDNS) { // Set so the function gets the right value mOverrideDNS.setChecked((Boolean) newValue); } setDNSState(); saveSettings(); return true; } private void setDNSState() { boolean enabled; mOverrideDNS.setEnabled(mUsePull.isChecked()); if(!mUsePull.isChecked()) enabled =true; else enabled = mOverrideDNS.isChecked(); mDNS1.setEnabled(enabled); mDNS2.setEnabled(enabled); mSearchdomain.setEnabled(enabled); } }
Java
package com.ecomdev.openvpn.fragments; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.util.Base64; import android.webkit.MimeTypeMap; import junit.framework.Assert; import java.io.*; import java.util.TreeSet; import java.util.Vector; public class Utils { @TargetApi(Build.VERSION_CODES.KITKAT) public static Intent getFilePickerIntent(FileType fileType) { Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT); i.addCategory(Intent.CATEGORY_OPENABLE); TreeSet<String> supportedMimeTypes = new TreeSet<String>(); Vector<String> extensions = new Vector<String>(); switch (fileType) { case PKCS12: i.setType("application/x-pkcs12"); supportedMimeTypes.add("application/x-pkcs12"); extensions.add("p12"); extensions.add("pfx"); break; case CLIENT_CERTIFICATE: case CA_CERTIFICATE: i.setType("application/x-pem-file"); supportedMimeTypes.add("application/x-x509-ca-cert"); supportedMimeTypes.add("application/x-x509-user-cert"); supportedMimeTypes.add("application/x-pem-file"); supportedMimeTypes.add("text/plain"); extensions.add("pem"); extensions.add("crt"); break; case KEYFILE: i.setType("application/x-pem-file"); supportedMimeTypes.add("application/x-pem-file"); supportedMimeTypes.add("application/pkcs8"); extensions.add("key"); break; case OVPN_CONFIG: i.setType("application/x-openvpn-profile"); supportedMimeTypes.add("application/x-openvpn-profile"); supportedMimeTypes.add("application/openvpn-profile"); supportedMimeTypes.add("application/ovpn"); extensions.add("ovpn"); extensions.add("conf"); break; case TLS_AUTH_FILE: i.setType("text/plain"); // Backup .... supportedMimeTypes.add("application/pkcs8"); extensions.add("txt"); extensions.add("key"); break; case USERPW_FILE: Assert.fail(); break; } MimeTypeMap mtm = MimeTypeMap.getSingleton(); for (String ext : extensions) { String mimeType = mtm.getMimeTypeFromExtension(ext); if (mimeType != null) supportedMimeTypes.add(mimeType); else supportedMimeTypes.add("application/octet-stream"); } i.putExtra(Intent.EXTRA_MIME_TYPES, supportedMimeTypes.toArray(new String[supportedMimeTypes.size()])); return i; } public enum FileType { PKCS12(0), CLIENT_CERTIFICATE(1), CA_CERTIFICATE(2), OVPN_CONFIG(3), KEYFILE(4), TLS_AUTH_FILE(5), USERPW_FILE(6); private int value; FileType(int i) { value=i; } public static FileType getFileTypeByValue(int value) { switch(value) { case 0: return PKCS12; case 1: return CLIENT_CERTIFICATE; case 2: return CA_CERTIFICATE; case 3: return OVPN_CONFIG; case 4: return KEYFILE; case 5: return TLS_AUTH_FILE; case 6: return USERPW_FILE; default: return null; } } public int getValue() { return value; } } static private byte[] readBytesFromStream(InputStream input) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = input.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); input.close(); return buffer.toByteArray(); } public static String getStringFromFilePickerResult(FileType ft, Intent result, Context c) throws IOException { Uri uri = result.getData(); if (uri ==null) return null; byte[] fileData = readBytesFromStream(c.getContentResolver().openInputStream(uri)); String newData = null; switch (ft) { case PKCS12: newData = Base64.encodeToString(fileData, Base64.DEFAULT); break; default: newData = new String(fileData, "UTF-8"); break; } return newData; } public static boolean isDifferenceNotExceed(long firstArg, long secondArg, long delta) { return false; } }
Java
package com.ecomdev.openvpn.fragments; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.security.KeyChainException; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import com.ecomdev.openvpn.views.FileSelectLayout; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.R.id; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.core.X509Utils; import java.security.cert.X509Certificate; public class Settings_Basic extends Fragment implements View.OnClickListener, OnItemSelectedListener, Callback, FileSelectLayout.FileSelectCallback { private static final int CHOOSE_FILE_OFFSET = 1000; private static final int UPDATE_ALIAS = 20; private TextView mServerAddress; private TextView mServerPort; private FileSelectLayout mClientCert; private FileSelectLayout mCaCert; private FileSelectLayout mClientKey; private TextView mAliasName; private TextView mAliasCertificate; private CheckBox mUseLzo; private ToggleButton mTcpUdp; private Spinner mType; private FileSelectLayout mpkcs12; private TextView mPKCS12Password; private Handler mHandler; private EditText mUserName; private EditText mPassword; private View mView; private VpnProfile mProfile; private EditText mProfileName; private EditText mKeyPassword; private SparseArray<FileSelectLayout> fileselects = new SparseArray<FileSelectLayout>(); private void addFileSelectLayout (FileSelectLayout fsl, Utils.FileType type) { int i = fileselects.size() + CHOOSE_FILE_OFFSET; fileselects.put(i, fsl); fsl.setCaller(this, i, type); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String profileUuid = getArguments().getString(getActivity().getPackageName() + ".profileUUID"); mProfile=ProfileManager.get(getActivity(),profileUuid); getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName())); } private void setKeystoreCertficate() { new Thread() { public void run() { String certstr=""; try { X509Certificate cert = KeyChain.getCertificateChain(getActivity(), mProfile.mAlias)[0]; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { { if (isInHardwareKeystore()) certstr+=getString(R.string.hwkeychain); } } certstr+=X509Utils.getCertificateFriendlyName(cert); } catch (Exception e) { certstr="Could not get certificate from Keystore: " +e.getLocalizedMessage(); } final String certStringCopy=certstr; getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAliasCertificate.setText(certStringCopy); } }); } }.start(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private boolean isInHardwareKeystore() throws KeyChainException, InterruptedException { String algorithm = KeyChain.getPrivateKey(getActivity(), mProfile.mAlias).getAlgorithm(); return KeyChain.isBoundKeyAlgorithm(algorithm); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.basic_settings,container,false); mProfileName = (EditText) mView.findViewById(R.id.profilename); mServerAddress = (TextView) mView.findViewById(R.id.address); mServerPort = (TextView) mView.findViewById(R.id.port); mClientCert = (FileSelectLayout) mView.findViewById(R.id.certselect); mClientKey = (FileSelectLayout) mView.findViewById(R.id.keyselect); mCaCert = (FileSelectLayout) mView.findViewById(R.id.caselect); mpkcs12 = (FileSelectLayout) mView.findViewById(R.id.pkcs12select); mUseLzo = (CheckBox) mView.findViewById(R.id.lzo); mTcpUdp = (ToggleButton) mView.findViewById(id.tcpudp); mType = (Spinner) mView.findViewById(R.id.type); mPKCS12Password = (TextView) mView.findViewById(R.id.pkcs12password); mAliasName = (TextView) mView.findViewById(R.id.aliasname); mAliasCertificate = (TextView) mView.findViewById(id.alias_certificate); mUserName = (EditText) mView.findViewById(R.id.auth_username); mPassword = (EditText) mView.findViewById(R.id.auth_password); mKeyPassword = (EditText) mView.findViewById(R.id.key_password); addFileSelectLayout(mCaCert, Utils.FileType.CA_CERTIFICATE); addFileSelectLayout(mClientCert, Utils.FileType.CLIENT_CERTIFICATE); addFileSelectLayout(mClientKey, Utils.FileType.KEYFILE); addFileSelectLayout(mpkcs12, Utils.FileType.PKCS12); mCaCert.setShowClear(); mType.setOnItemSelectedListener(this); mView.findViewById(R.id.select_keystore_button).setOnClickListener(this); if (mHandler == null) { mHandler = new Handler(this); } return mView; } @Override public void onStart() { super.onStart(); String profileUuid =getArguments().getString(getActivity().getPackageName() + ".profileUUID"); mProfile=ProfileManager.get(getActivity(),profileUuid); loadPreferences(); } @Override public void onActivityResult(int request, int result, Intent data) { if (result == Activity.RESULT_OK && request >= CHOOSE_FILE_OFFSET) { FileSelectLayout fsl = fileselects.get(request); fsl.parseResponse(data, getActivity()); savePreferences(); // Private key files may result in showing/hiding the private key password dialog if(fsl==mClientKey) { changeType(mType.getSelectedItemPosition()); } } } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent == mType) { changeType(position); } } @Override public void onPause() { super.onPause(); savePreferences(); } private void changeType(int type){ // hide everything mView.findViewById(R.id.pkcs12).setVisibility(View.GONE); mView.findViewById(R.id.certs).setVisibility(View.GONE); mView.findViewById(R.id.statickeys).setVisibility(View.GONE); mView.findViewById(R.id.keystore).setVisibility(View.GONE); mView.findViewById(R.id.cacert).setVisibility(View.GONE); mView.findViewById(R.id.userpassword).setVisibility(View.GONE); mView.findViewById(R.id.key_password_layout).setVisibility(View.GONE); // Fall through are by design switch(type) { case VpnProfile.TYPE_USERPASS_CERTIFICATES: mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); case VpnProfile.TYPE_CERTIFICATES: mView.findViewById(R.id.certs).setVisibility(View.VISIBLE); mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); if(mProfile.requireTLSKeyPassword()) mView.findViewById(R.id.key_password_layout).setVisibility(View.VISIBLE); break; case VpnProfile.TYPE_USERPASS_PKCS12: mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); case VpnProfile.TYPE_PKCS12: mView.findViewById(R.id.pkcs12).setVisibility(View.VISIBLE); break; case VpnProfile.TYPE_STATICKEYS: mView.findViewById(R.id.statickeys).setVisibility(View.VISIBLE); break; case VpnProfile.TYPE_USERPASS_KEYSTORE: mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); case VpnProfile.TYPE_KEYSTORE: mView.findViewById(R.id.keystore).setVisibility(View.VISIBLE); mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); break; case VpnProfile.TYPE_USERPASS: mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE); mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE); break; } } private void loadPreferences() { mProfileName.setText(mProfile.mName); mClientCert.setData(mProfile.mClientCertFilename, getActivity()); mClientKey.setData(mProfile.mClientKeyFilename, getActivity()); mCaCert.setData(mProfile.mCaFilename, getActivity()); mUseLzo.setChecked(mProfile.mUseLzo); mServerPort.setText(mProfile.mServerPort); mServerAddress.setText(mProfile.mServerName); mTcpUdp.setChecked(mProfile.mUseUdp); mType.setSelection(mProfile.mAuthenticationType); mpkcs12.setData(mProfile.mPKCS12Filename, getActivity()); mPKCS12Password.setText(mProfile.mPKCS12Password); mUserName.setText(mProfile.mUsername); mPassword.setText(mProfile.mPassword); mKeyPassword.setText(mProfile.mKeyPassword); setAlias(); } void savePreferences() { mProfile.mName = mProfileName.getText().toString(); mProfile.mCaFilename = mCaCert.getData(); mProfile.mClientCertFilename = mClientCert.getData(); mProfile.mClientKeyFilename = mClientKey.getData(); mProfile.mUseLzo = mUseLzo.isChecked(); mProfile.mServerPort =mServerPort.getText().toString(); mProfile.mServerName = mServerAddress.getText().toString(); mProfile.mUseUdp = mTcpUdp.isChecked(); mProfile.mAuthenticationType = mType.getSelectedItemPosition(); mProfile.mPKCS12Filename = mpkcs12.getData(); mProfile.mPKCS12Password = mPKCS12Password.getText().toString(); mProfile.mPassword = mPassword.getText().toString(); mProfile.mUsername = mUserName.getText().toString(); mProfile.mKeyPassword = mKeyPassword.getText().toString(); } private void setAlias() { if(mProfile.mAlias == null) { mAliasName.setText(R.string.client_no_certificate); mAliasCertificate.setText(""); } else { mAliasCertificate.setText("Loading certificate from Keystore..."); mAliasName.setText(mProfile.mAlias); setKeystoreCertficate(); } } public void showCertDialog () { try { KeyChain.choosePrivateKeyAlias(getActivity(), new KeyChainAliasCallback() { public void alias(String alias) { // Credential alias selected. Remember the alias selection for future use. mProfile.mAlias=alias; mHandler.sendEmptyMessage(UPDATE_ALIAS); } }, new String[] {"RSA"}, // List of acceptable key types. null for any null, // issuer, null for any mProfile.mServerName, // host name of server requesting the cert, null if unavailable -1, // port of server requesting the cert, -1 if unavailable mProfile.mAlias); // alias to preselect, null if unavailable } catch (ActivityNotFoundException anf) { Builder ab = new AlertDialog.Builder(getActivity()); ab.setTitle(R.string.broken_image_cert_title); ab.setMessage(R.string.broken_image_cert); ab.setPositiveButton(android.R.string.ok, null); ab.show(); } } @Override public void onClick(View v) { if (v == mView.findViewById(R.id.select_keystore_button)) { showCertDialog(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); savePreferences(); if(mProfile!=null) { outState.putString(getActivity().getPackageName() + "profileUUID", mProfile.getUUID().toString()); } } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public boolean handleMessage(Message msg) { setAlias(); return true; } }
Java
package com.ecomdev.openvpn.fragments; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.ListFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.Html.ImageGetter; import android.view.*; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.ecomdev.openvpn.*; import com.ecomdev.openvpn.activities.ConfigConverter; import com.ecomdev.openvpn.activities.FileSelect; import com.ecomdev.openvpn.activities.VPNPreferences; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.core.VpnStatus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Process; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class VPNProfileList extends ListFragment { public final static int RESULT_VPN_DELETED = Activity.RESULT_FIRST_USER; private static final String TIMER_NAME = "Ping"; private static final int MENU_ADD_PROFILE = Menu.FIRST; private static final int START_VPN_CONFIG = 92; private static final int SELECT_PROFILE = 43; private static final int IMPORT_PROFILE = 231; private static final int FILE_PICKER_RESULT = 392; private static final int MENU_IMPORT_PROFILE = Menu.FIRST +1; private Map<String, Drawable> mFlags = new HashMap<String, Drawable>(4); private Button mPingServers; private Timer mTimer; private boolean mIsTimerRun = false; private ExecutorService mService = Executors.newCachedThreadPool(); private AtomicInteger mItemsCount = new AtomicInteger(); class VPNArrayAdapter extends ArrayAdapter<VpnProfile> { public VPNArrayAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); View titleview = v.findViewById(R.id.vpn_list_item_left); titleview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { VpnProfile profile =(VpnProfile) getListAdapter().getItem(position); startVPN(profile); } }); ImageView imageView = (ImageView) v.findViewById(R.id.flag); Drawable drawable = mFlags.get(getItem(position).toString()); imageView.setImageDrawable(drawable); if (getItem(position).mPing != -1) { TextView pingImage = (TextView) v.findViewById(R.id.pingImage); float weight = (getCount() - position) / (float)getCount(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f - weight); params.bottomMargin = getResources().getDimensionPixelSize(R.dimen.ping_image); params.topMargin = getResources().getDimensionPixelSize(R.dimen.ping_image); pingImage.setLayoutParams(params); View pingImageRightSide = v.findViewById(R.id.pingImageRightSide); params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, weight); pingImageRightSide.setLayoutParams(params); if (position == 0) { pingImage.setText(getString(R.string.fastest_server)); } } /*View settingsview = v.findViewById(R.id.quickedit_settings); settingsview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { VpnProfile editProfile = (VpnProfile) getListAdapter().getItem(position); editVPN(editProfile); } });*/ return v; } } private ArrayAdapter<VpnProfile> mArrayadapter; protected VpnProfile mEditProfile=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); if (getPM().getNumberOfProfiles() != 4) // 4 profiles (Canada, USA, USA-2, Europe) { startConfigImport(Uri.parse("Canada")); startConfigImport(Uri.parse("Europe")); startConfigImport(Uri.parse("USA")); startConfigImport(Uri.parse("USA-2")); } mFlags.put("Canada", getResources().getDrawable(R.drawable.canada_flag)); mFlags.put("Europe", getResources().getDrawable(R.drawable.europe_flag)); mFlags.put("USA", getResources().getDrawable(R.drawable.usa_flag)); mFlags.put("USA-2", getResources().getDrawable(R.drawable.usa_flag)); } class MiniImageGetter implements ImageGetter { @Override public Drawable getDrawable(String source) { Drawable d=null; if ("ic_menu_add".equals(source)) d = getActivity().getResources().getDrawable(android.R.drawable.ic_menu_add); else if("ic_menu_archive".equals(source)) d = getActivity().getResources().getDrawable(R.drawable.ic_menu_archive); if(d!=null) { d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; }else{ return null; } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.vpn_profile_list, container,false); TextView newvpntext = (TextView) v.findViewById(R.id.add_new_vpn_hint); TextView importvpntext = (TextView) v.findViewById(R.id.import_vpn_hint); newvpntext.setText(Html.fromHtml(getString(R.string.add_new_vpn_hint),new MiniImageGetter(),null)); importvpntext.setText(Html.fromHtml(getString(R.string.vpn_import_hint),new MiniImageGetter(),null)); mPingServers = (Button) v.findViewById(R.id.pingServers); mPingServers.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mPingServers.setEnabled(false); loadingTextButton(); checkConnectionSpeedToServer(); } }); VpnStatus.addStateListener(new VpnStatus.StateListener() { @Override public void updateState(String state, String logmessage, final int localizedResId, VpnStatus.ConnectionStatus level) { mPingServers.post(new Runnable() { @Override public void run() { switch (localizedResId) { case R.string.state_noprocess: case R.string.state_disconnected: case R.string.state_user_vpn_password: case R.string.state_nonetwork: mPingServers.setEnabled(true); break; case R.string.state_connected: mPingServers.setEnabled(false); break; } } }); } }); return v; } private void checkConnectionSpeedToServer() { mItemsCount.set(0); for (int i = 0; i < mArrayadapter.getCount(); i++) { final VpnProfile item = mArrayadapter.getItem(i); mService.submit(new Runnable() { @Override public void run() { int minPing = getMinPingTime(item.mServerName, 4); item.mPing = minPing; mItemsCount.incrementAndGet(); if (mItemsCount.get() == mArrayadapter.getCount()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { cancelTimer(); setListAdapterSortByPing(); } }); } } }); } } private int getMinPingTime(String host, int count) { int result = -1; try { for (int i = 0; i < count; i++) { String ping = ping(host); if (ping != null) { float pingTime = Float.valueOf(ping); if (result == -1) { result = (int) pingTime; } else { result = (int) Math.min(result, pingTime); } } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return result; } private String ping(String host) throws IOException, InterruptedException { StringBuffer echo = new StringBuffer(); Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("ping -c 1 " + host); proc.waitFor(); int exit = proc.exitValue(); if (exit == 0) { InputStreamReader reader = new InputStreamReader(proc.getInputStream()); BufferedReader buffer = new BufferedReader(reader); String line = ""; while ((line = buffer.readLine()) != null) { echo.append(line + "\n"); } return getPingStats(echo.toString()); } else if (exit == 1) { return null; } else { return null; } } public static String getPingStats(String s) { if (s.contains("0% packet loss")) { int start = s.indexOf("/mdev = "); int end = s.indexOf(" ms\n", start); s = s.substring(start + 8, end); String stats[] = s.split("/"); return stats[2]; } else if (s.contains("100% packet loss")) { return null; } else if (s.contains("% packet loss")) { return null; } else if (s.contains("unknown host")) { return null; } else { return null; } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListAdapter(); } static class VpnProfileNameComparator implements Comparator<VpnProfile> { @Override public int compare(VpnProfile lhs, VpnProfile rhs) { if (lhs == rhs) // Catches also both null return 0; if (lhs == null) return -1; if (rhs == null) return 1; if (lhs.mName == null) return -1; if (rhs.mName == null) return 1; return lhs.mName.compareTo(rhs.mName); } } private class VPNProfilePingComparator implements Comparator<VpnProfile> { @Override public int compare(VpnProfile vpnProfile, VpnProfile vpnProfile2) { if (vpnProfile == null) { return 1; } if (vpnProfile2 == null) { return -1; } if (vpnProfile.mPing != -1 && vpnProfile2.mPing != -1) { if (vpnProfile.mPing == vpnProfile2.mPing) { return compareName(vpnProfile, vpnProfile2); } else { return Integer.valueOf(vpnProfile.mPing).compareTo(Integer.valueOf(vpnProfile2.mPing)); } } if (vpnProfile.mPing == -1 && vpnProfile2.mPing == -1) { return compareName(vpnProfile, vpnProfile2); } if (vpnProfile.mPing == -1) { return 1; } if (vpnProfile2.mPing == -1) { return -1; } return 0; } private int compareName(VpnProfile vpnProfile, VpnProfile vpnProfile2) { if (vpnProfile.mName == null) return -1; if (vpnProfile2.mName == null) return 1; return vpnProfile.mName.compareToIgnoreCase(vpnProfile2.mName); } } private void setListAdapterSortByPing() { if (mArrayadapter != null) { Collection<VpnProfile> allvpn = getPM().getProfiles(); TreeSet<VpnProfile> sortedset = new TreeSet<VpnProfile>(new VPNProfilePingComparator()); sortedset.addAll(allvpn); mArrayadapter.clear(); mArrayadapter.addAll(sortedset); setListAdapter(mArrayadapter); mPingServers.setEnabled(true); mPingServers.setText(getText(R.string.ping_servers)); } } private void loadingTextButton() { mTimer = new Timer(TIMER_NAME); mIsTimerRun = true; mTimer.schedule(new TimerTask() { @Override public void run() { int count = 4; while (mIsTimerRun) { final StringBuffer stringBuffer = new StringBuffer("Looking for the fastest server for you"); for (int i = 0; i < count && mIsTimerRun; i++) { mPingServers.post(new Runnable() { @Override public void run() { mPingServers.setText(stringBuffer); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stringBuffer.append("."); } } } }, 0); } private void cancelTimer() { mIsTimerRun = false; if (mTimer != null) { mTimer.cancel(); mTimer = null; } } private void setListAdapter() { mArrayadapter = new VPNArrayAdapter(getActivity(),R.layout.vpn_list_item,R.id.vpn_item_title); Collection<VpnProfile> allvpn = getPM().getProfiles(); TreeSet<VpnProfile> sortedset = new TreeSet<VpnProfile>(new VPNProfilePingComparator()); sortedset.addAll(allvpn); mArrayadapter.addAll(sortedset); setListAdapter(mArrayadapter); } /* @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.add(0, MENU_ADD_PROFILE, 0 , R.string.menu_add_profile) .setIcon(android.R.drawable.ic_menu_add) .setAlphabeticShortcut('a') .setTitleCondensed(getActivity().getString(R.string.add)) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); menu.add(0, MENU_IMPORT_PROFILE, 0, R.string.menu_import) .setIcon(R.drawable.ic_menu_archive) .setAlphabeticShortcut('i') .setTitleCondensed(getActivity().getString(R.string.menu_import_short)) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT ); }*/ @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); if (itemId == MENU_ADD_PROFILE) { onAddProfileClicked(); return true; } else if (itemId == MENU_IMPORT_PROFILE) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) startFilePicker(); else startImportConfig(); return true; } else { return super.onOptionsItemSelected(item); } } @TargetApi(Build.VERSION_CODES.KITKAT) private void startFilePicker() { Intent i = Utils.getFilePickerIntent(Utils.FileType.OVPN_CONFIG); startActivityForResult(i, FILE_PICKER_RESULT); } private void startImportConfig() { Intent intent = new Intent(getActivity(),FileSelect.class); intent.putExtra(FileSelect.NO_INLINE_SELECTION, true); intent.putExtra(FileSelect.WINDOW_TITLE, R.string.import_configuration_file); startActivityForResult(intent, SELECT_PROFILE); } private void onAddProfileClicked() { Context context = getActivity(); if (context != null) { final EditText entry = new EditText(context); entry.setSingleLine(); AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(R.string.menu_add_profile); dialog.setMessage(R.string.add_profile_name_prompt); dialog.setView(entry); dialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = entry.getText().toString(); if (getPM().getProfileByName(name)==null) { VpnProfile profile = new VpnProfile(name); addProfile(profile); editVPN(profile); } else { Toast.makeText(getActivity(), R.string.duplicate_profile_name, Toast.LENGTH_LONG).show(); } } }); dialog.setNegativeButton(android.R.string.cancel, null); dialog.create().show(); } } private void addProfile(VpnProfile profile) { getPM().addProfile(profile); getPM().saveProfileList(getActivity()); getPM().saveProfile(getActivity(),profile); mArrayadapter.add(profile); } private ProfileManager getPM() { return ProfileManager.getInstance(getActivity()); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_VPN_DELETED){ if(mArrayadapter != null && mEditProfile !=null) mArrayadapter.remove(mEditProfile); } if(resultCode != Activity.RESULT_OK) return; if (requestCode == START_VPN_CONFIG) { String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); VpnProfile profile = ProfileManager.get(getActivity(),configuredVPN); getPM().saveProfile(getActivity(), profile); // Name could be modified, reset List adapter setListAdapter(); } else if(requestCode== SELECT_PROFILE) { String fileData = data.getStringExtra(FileSelect.RESULT_DATA); Uri uri = new Uri.Builder().path(fileData).scheme("file").build(); startConfigImport(uri); } else if(requestCode == IMPORT_PROFILE) { String profileUUID = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID); mArrayadapter.add(ProfileManager.get(getActivity(), profileUUID)); } else if(requestCode == FILE_PICKER_RESULT) { if (data != null) { Uri uri = data.getData(); startConfigImport(uri); } } } private void startConfigImport(Uri uri) { Intent startImport = new Intent(getActivity(),ConfigConverter.class); startImport.setAction(ConfigConverter.IMPORT_PROFILE); startImport.setData(uri); startActivityForResult(startImport, IMPORT_PROFILE); } private void editVPN(VpnProfile profile) { mEditProfile =profile; Intent vprefintent = new Intent(getActivity(),VPNPreferences.class) .putExtra(getActivity().getPackageName() + ".profileUUID", profile.getUUID().toString()); startActivityForResult(vprefintent,START_VPN_CONFIG); } private void startVPN(VpnProfile profile) { getPM().saveProfile(getActivity(), profile); Intent intent = new Intent(getActivity(),LaunchVPN.class); intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUID().toString()); intent.setAction(Intent.ACTION_MAIN); startActivity(intent); } }
Java
package com.ecomdev.openvpn; /** * Created by ymka on 09.08.14. */ public class Constants { public static final int sUPDATE_DEMO_TIME_RECEIVER_NUM = 24442; public static final String sMAIN_SHARED_PREFERENCE = "mainSharedPreference"; public static final String sPREF_IS_DEMO = "isDemo"; public static final String sPREF_IS_TIMEOUT = "isTimeOut"; public static final String sPREF_START_DEMO_TIME = "time"; public static final String sPREF_LEFT_HOURS = "leftHours"; }
Java
package com.ecomdev.openvpn; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by ymka on 03.08.14. */ public class UpdateDemoTimeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("qwe", "update " + System.currentTimeMillis()); Intent intent1 = new Intent(context, DemoService.class); DemoService.LocalBinder iBinder = ((DemoService.LocalBinder)peekService(context, intent1)); DemoService service = iBinder.getService(); service.updateTime(); } }
Java
package com.ecomdev.openvpn; import java.io.IOException; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.net.VpnService; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.InputType; import android.text.TextUtils; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.*; import com.ecomdev.openvpn.activities.LogWindow; import com.ecomdev.openvpn.core.VpnStatus; import com.ecomdev.openvpn.core.VpnStatus.ConnectionStatus; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.core.VPNLaunchHelper; /** * This Activity actually handles two stages of a launcher shortcut's life cycle. * * 1. Your application offers to provide shortcuts to the launcher. When * the user installs a shortcut, an activity within your application * generates the actual shortcut and returns it to the launcher, where it * is shown to the user as an icon. * * 2. Any time the user clicks on an installed shortcut, an intent is sent. * Typically this would then be handled as necessary by an activity within * your application. * * We handle stage 1 (creating a shortcut) by simply sending back the information (in the form * of an {@link android.content.Intent} that the launcher will use to create the shortcut. * * You can also implement this in an interactive way, by having your activity actually present * UI for the user to select the specific nature of the shortcut, such as a contact, picture, URL, * media item, or action. * * We handle stage 2 (responding to a shortcut) in this sample by simply displaying the contents * of the incoming {@link android.content.Intent}. * * In a real application, you would probably use the shortcut intent to display specific content * or start a particular operation. */ public class LaunchVPN extends Activity { public static final String EXTRA_KEY = "com.ecomdev.openvpn.shortcutProfileUUID"; public static final String EXTRA_NAME = "com.ecomdev.openvpn.shortcutProfileName"; public static final String EXTRA_HIDELOG = "com.ecomdev.openvpn.showNoLogWindow"; private static final int START_VPN_PROFILE= 70; private ProfileManager mPM; private VpnProfile mSelectedProfile; private boolean mhideLog=false; private boolean mCmfixed=false; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mPM =ProfileManager.getInstance(this); } @Override protected void onStart() { super.onStart(); // Resolve the intent final Intent intent = getIntent(); final String action = intent.getAction(); // If the intent is a request to create a shortcut, we'll do that and exit if(Intent.ACTION_MAIN.equals(action)) { // we got called to be the starting point, most likely a shortcut String shortcutUUID = intent.getStringExtra( EXTRA_KEY); String shortcutName = intent.getStringExtra( EXTRA_NAME); mhideLog = intent.getBooleanExtra(EXTRA_HIDELOG, false); VpnProfile profileToConnect = ProfileManager.get(this,shortcutUUID); if(shortcutName != null && profileToConnect ==null) profileToConnect = ProfileManager.getInstance(this).getProfileByName(shortcutName); if(profileToConnect ==null) { VpnStatus.logError(R.string.shortcut_profile_notfound); // show Log window to display error showLogWindow(); finish(); return; } mSelectedProfile = profileToConnect; launchVPN(); } } private void askForPW(final int type) { final EditText entry = new EditText(this); final View userpwlayout = getLayoutInflater().inflate(R.layout.userpass, null); entry.setSingleLine(); entry.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); entry.setTransformationMethod(new PasswordTransformationMethod()); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("Need " + getString(type)); dialog.setMessage("Enter the password for profile " + mSelectedProfile.mName); if (type == R.string.password) { ((EditText)userpwlayout.findViewById(R.id.username)).setText(mSelectedProfile.mUsername); ((EditText)userpwlayout.findViewById(R.id.password)).setText(mSelectedProfile.mPassword); //((CheckBox)userpwlayout.findViewById(R.id.save_password)).setChecked(!TextUtils.isEmpty(mSelectedProfile.mPassword)); ((CheckBox)userpwlayout.findViewById(R.id.show_password)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) ((EditText)userpwlayout.findViewById(R.id.password)).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); else ((EditText)userpwlayout.findViewById(R.id.password)).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } }); dialog.setView(userpwlayout); } else { dialog.setView(entry); } AlertDialog.Builder builder = dialog.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (type == R.string.password) { mSelectedProfile.mUsername = ((EditText) userpwlayout.findViewById(R.id.username)).getText().toString(); String pw = ((EditText) userpwlayout.findViewById(R.id.password)).getText().toString(); /*if (((CheckBox) userpwlayout.findViewById(R.id.save_password)).isChecked()) { mSelectedProfile.mPassword=pw; } else*/ { mSelectedProfile.mPassword=null; mSelectedProfile.mTransientPW = pw; } } else { mSelectedProfile.mTransientPCKS12PW = entry.getText().toString(); } onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null); } }); dialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { VpnStatus.updateStateString("USER_VPN_PASSWORD_CANCELLED", "", R.string.state_user_vpn_password_cancelled, ConnectionStatus.LEVEL_NOTCONNECTED); finish(); } }); dialog.create().show(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==START_VPN_PROFILE) { if(resultCode == Activity.RESULT_OK) { int needpw = mSelectedProfile.needUserPWInput(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean isTestLogin = prefs.getBoolean("isTestLogin", true); if(!isTestLogin && needpw !=0) { VpnStatus.updateStateString("USER_VPN_PASSWORD", "", R.string.state_user_vpn_password, ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT); askForPW(needpw); } else { if (isTestLogin) { mSelectedProfile.mUsername = "test"; mSelectedProfile.mTransientPW = "test"; } boolean showlogwindow = prefs.getBoolean("showlogwindow", true); if(!mhideLog && showlogwindow) showLogWindow(); new startOpenVpnThread().start(); } } else if (resultCode == Activity.RESULT_CANCELED) { // User does not want us to start, so we just vanish VpnStatus.updateStateString("USER_VPN_PERMISSION_CANCELLED", "", R.string.state_user_vpn_permission_cancelled, ConnectionStatus.LEVEL_NOTCONNECTED); finish(); } } } void showLogWindow() { Intent startLW = new Intent(getBaseContext(),LogWindow.class); startLW.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(startLW); } void showConfigErrorDialog(int vpnok) { AlertDialog.Builder d = new AlertDialog.Builder(this); d.setTitle(R.string.config_error_found); d.setMessage(vpnok); d.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); d.show(); } void launchVPN () { int vpnok = mSelectedProfile.checkProfile(this); if(vpnok!= R.string.no_error_found) { showConfigErrorDialog(vpnok); return; } Intent intent = VpnService.prepare(this); // Check if we want to fix /dev/tun SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean usecm9fix = prefs.getBoolean("useCM9Fix", false); boolean loadTunModule = prefs.getBoolean("loadTunModule", false); if(loadTunModule) execeuteSUcmd("insmod /system/lib/modules/tun.ko"); if(usecm9fix && !mCmfixed ) { execeuteSUcmd("chown system /dev/tun"); } if (intent != null) { VpnStatus.updateStateString("USER_VPN_PERMISSION", "", R.string.state_user_vpn_permission, ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT); // Start the query try { startActivityForResult(intent, START_VPN_PROFILE); } catch (ActivityNotFoundException ane) { // Shame on you Sony! At least one user reported that // an official Sony Xperia Arc S image triggers this exception VpnStatus.logError(R.string.no_vpn_support_image); showLogWindow(); } } else { onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null); } } private void execeuteSUcmd(String command) { ProcessBuilder pb = new ProcessBuilder("su","-c",command); try { Process p = pb.start(); int ret = p.waitFor(); if(ret ==0) mCmfixed=true; } catch (InterruptedException e) { VpnStatus.logException("SU command", e); } catch (IOException e) { VpnStatus.logException("SU command", e); } } private class startOpenVpnThread extends Thread { @Override public void run() { VPNLaunchHelper.startOpenVpn(mSelectedProfile, getBaseContext()); finish(); } } }
Java
package jtacck.labmedicine; import com.google.android.maps.Overlay; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; /** * @deprecated * An overlay used to draw the route. * * @see com.google.android.maps.Overlay * * @author Andrewlo * */ public class MyOverLay extends Overlay { /** * Location of first of series of points */ private GeoPoint gp1; /** * Location of the second points */ private GeoPoint gp2; /** * Radius of the route. */ private int mRadius = 6; /** * Default mode of the circle. */ private int mode = 0; /** * Color of the path. */ private int defaultColor; @SuppressWarnings("unused") private String text = ""; @SuppressWarnings("unused") private Bitmap img = null; /** * Creates a new overlay with a beginning and ending geopoint with a mode. * * @param gp1 * - the first point * @param gp2 * - the second point * @param mode * - the mode of the route */ public MyOverLay(GeoPoint gp1, GeoPoint gp2, int mode) { this(gp1, gp2, mode, 999); } /** * Constructs a new overlay with a given end, beginning, mode, and default * color. * * @param gp1 * - first point of the current path to be drawn * @param gp2 * - second point of the path to be drawn * @param mode * - which part of the route * @param defaultColor * - the color of the route */ public MyOverLay(GeoPoint gp1, GeoPoint gp2, int mode, int defaultColor) { this.gp1 = gp1; this.gp2 = gp2; this.mode = mode; this.defaultColor = defaultColor; } /** * Sets the text for the route. * * @param text * - the text to used */ public void setText(String text) { this.text = text; } /** * Sets a bitmap to be used on the route * * @param bitmap * - the bitmap to be used */ public void setBitmap(Bitmap bitmap) { this.img = bitmap; } /** * Retrieves the current mode. * * @return The int representing the mode. */ public int getMode() { return mode; } /* (non-Javadoc) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long) * * Overriden draw method which calcualtes the points to be drawn. */ @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { Projection projection = mapView.getProjection(); if (shadow == false) { Paint paint = new Paint(); paint.setAntiAlias(true); Point point = new Point(); projection.toPixels(gp1, point); // mode=1 start if (mode == 1) { if (defaultColor == 999) paint.setColor(Color.BLUE); else paint.setColor(defaultColor); RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); // start point canvas.drawOval(oval, paint); } // mode=2 path else if (mode == 2) { if (defaultColor == 999) paint.setColor(Color.RED); else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(120); //The actual path canvas.drawLine(point.x, point.y, point2.x, point2.y, paint); } /* mode=3 end */ else if (mode == 3) { /* the last path */ if (defaultColor == 999) paint.setColor(Color.GREEN); else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(120); canvas.drawLine(point.x, point.y, point2.x, point2.y, paint); RectF oval = new RectF(point2.x - mRadius, point2.y - mRadius, point2.x + mRadius, point2.y + mRadius); /* end point */ paint.setAlpha(255); canvas.drawOval(oval, paint); } } return super.draw(canvas, mapView, shadow, when); } }
Java
package jtacck.labmedicine; import android.app.ProgressDialog; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import android.widget.Toast; /** * Customized tab activity for displaying routing information and a map. * * @see android.app.TabActivity * * @author Andrew * */ public class RouteMapTabActivity extends TabActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** Removes the title of the window **/ this.requestWindowFeature(Window.FEATURE_NO_TITLE); /** Set view to tabbed layout **/ setContentView(R.layout.tabbed_layout); Intent intent; TabHost.TabSpec spec; /** Retrieve reference to resources and tab host **/ Resources res = getResources(); TabHost tabHost = getTabHost(); /** Create an Intent to launch an Activity for the tab **/ intent = new Intent().setClass(this, RouteListActivity.class); /** Initialize a TabSpec for each tab and add it to the TabHost **/ spec = tabHost .newTabSpec("route") .setIndicator("Route", res.getDrawable(R.drawable.icon_tab_route)) .setContent(intent); tabHost.addTab(spec); /** Reuse other intent for another activity **/ intent = new Intent().setClass(this, GoogleMapActivity.class); /** Same as above **/ spec = tabHost.newTabSpec("map") .setIndicator("Map", res.getDrawable(R.drawable.maps_icon)) .setContent(intent); tabHost.addTab(spec); /*getTabWidget().getChildAt(1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ProgressDialog.show(RouteMapTabActivity.this, "", "Retrieving data...", true, true); getTabHost().setCurrentTab(1); } });*/ /** Set default tab **/ tabHost.setCurrentTab(0); } }
Java
package jtacck.labmedicine; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.*; import jvm.jtacck.db.records.CheckListPair; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.serials.Barcode; import jvm.jtacck.serials.GPS; import jvm.jtacck.serials.LoginInfo; import jvm.jtacck.serials.Route; import jvm.jtacck.serials.ShippingList; import android.util.Log; /** * @author Jesse Jeng * * A framework used by the Android platform to connect to the Android * server through sockets. Also handles asynchronous updates of routes * and GPS coordinates * */ public class ServerLinker { private InetAddress hostAddress; private Socket listenSocket; private Socket requestSocket; private int listenPort; private int requestPort; private LoginInfo login; private boolean authenticated; private Route nextRoute; private CheckListPair clp; private ObjectOutputStream lsoos; private ObjectInputStream lsois; private ObjectOutputStream rsoos; private ObjectInputStream rsois; private BlockingQueue<GPS> gpsQueue; private volatile boolean gpsThreading; private GPSThread gpsThread; private ListenThread listenThread; private boolean loggedIn; private boolean hasNextRoute; /** * @param hostAddress * Network address of the Android server * @param listenPort * Port number for listening * @param requestPort * Port number for requesting * @param login * LoginInfo that will be sent to the server */ public ServerLinker(String hostAddress, int listenPort, int requestPort, LoginInfo login) { try { this.hostAddress = InetAddress.getByName(hostAddress); } catch (UnknownHostException e) { Log.w("AndroidServer", "Unknown host"); } this.listenPort = listenPort; this.requestPort = requestPort; this.listenSocket = null; this.requestSocket = null; if (login.username == null) { login = new LoginInfo("", ""); } this.login = login; this.authenticated = false; this.nextRoute = null; this.clp = null; this.gpsQueue = new LinkedBlockingQueue<GPS>(); this.gpsThread = null; this.listenThread = null; this.loggedIn = false; this.hasNextRoute = false; } /** * Connects to the Android server by opening sockets * * @return True if a successful connection was made to the Android server */ public boolean connect() { try { if (listenSocket == null || !listenSocket.isConnected()) { listenSocket = new Socket(hostAddress, listenPort); } if (requestSocket == null || !requestSocket.isConnected()) { requestSocket = new Socket(hostAddress, requestPort); } } catch (Exception e) { authenticated = false; Log.w("AndroidServer", "Can't connect to sockets"); return false; } return true; } /** * Disconnects from the server and closes all IO streams */ public void disconnect() { try { if (!listenSocket.isOutputShutdown()) { listenSocket.shutdownOutput(); } if (!listenSocket.isInputShutdown()) { listenSocket.shutdownInput(); } if (!listenSocket.isClosed()) { listenSocket.close(); } } catch (Exception e) { Log.w("AndroidServer", "Error closing listen socket"); } try { if (!requestSocket.isOutputShutdown()) { requestSocket.shutdownOutput(); } if (!requestSocket.isInputShutdown()) { requestSocket.shutdownInput(); } if (!requestSocket.isClosed()) { requestSocket.close(); } } catch (Exception e) { Log.w("AndroidServer", "Error closing request socket"); } gpsThreading = false; if (gpsThread != null) { gpsThread.interrupt(); } if (listenThread != null) { listenThread.interrupt(); } authenticated = false; } public void startListening() { if (listenThread == null) { listenThread = new ListenThread(); listenThread.start(); } } public boolean hasCheckListPair() { return clp != null; } public CheckListPair getCheckListPair() { if (hasCheckListPair()) { return clp; } else { try { synchronized (listenThread) { listenThread.wait(); } } catch (Exception e) { e.printStackTrace(); } return clp; } } public boolean hasNextRoute() { return hasNextRoute; } public Route getNextRoute() { if (nextRoute != null) { hasNextRoute = false; return nextRoute; } else { try { synchronized (listenThread) { listenThread.wait(); } } catch (Exception e) { e.printStackTrace(); } hasNextRoute = false; return nextRoute; } } private synchronized Object request(Object message) { if (!authenticated) { return null; } if (message == null) { return null; } RequestThread rt = new RequestThread(message); rt.start(); try { rt.join(); } catch (InterruptedException e) { // Do something } return rt.getInput(); } /** * @param barcode * Barcode of the package that was collected * @return True if the status of the package was updated successfully */ public boolean packageCollected(String barcode) { // TODO: Implement this method Object result = request(new Barcode(barcode)); return result != null && !(result instanceof Exception); } /** * Updates the server/database of the phone/courier's current GPS location * * @param latitude * GPS latitude coordinate * @param longitude * GPS longitude coordinate */ public void updateGPS(double latitude, double longitude) { // GPS coordinate = new GPS(latitude, longitude); // Object result = request(coordinate); // return result != null && !(result instanceof Exception); gpsQueue.offer(new GPS(latitude, longitude)); } /** * @param Current * pickup location * @return A list of shipments/packages to be scanned/picked up */ public ShippingList getShippingList(ClientSite site) { Log.w("DEBUG", "HERE"); Object result = request(site); if (result != null && !(result instanceof Exception)) { return (ShippingList) result; } return null; } /** * @return True if the user is authenticated */ public boolean authenticated() { return authenticated; } /** * @return True if the user already logged in */ public boolean loggedIn() { return loggedIn; } /** * Authenticates the phone against the Android server by sending login * information that contains username and password */ public void authenticate() { try { if (!authenticated && connect()) { Object input = null; lsoos = new ObjectOutputStream(listenSocket.getOutputStream()); lsoos.flush(); lsois = new ObjectInputStream(listenSocket.getInputStream()); lsoos.writeObject(login); input = lsois.readObject(); authenticated = !(input instanceof Exception); if (!authenticated) { loggedIn = ((Exception) input).getMessage().compareTo( "Already logged in") == 0; } // Authenticate the socket on requestPort rsoos = new ObjectOutputStream(requestSocket.getOutputStream()); rsoos.flush(); rsois = new ObjectInputStream(requestSocket.getInputStream()); rsoos.writeObject(login); input = rsois.readObject(); authenticated = !(input instanceof Exception) && authenticated; if (!authenticated) { disconnect(); } else { if (gpsThread != null) { gpsThread.interrupt(); } if (listenThread != null) { listenThread.interrupt(); } gpsThread = new GPSThread(); gpsThread.start(); } } } catch (SocketException e) { Log.w("ObjectStream", "Socket Closed"); } catch (IOException e) { Log.w("ObjectStream", "IO Exceptions"); } catch (ClassNotFoundException e) { Log.w("ObjectStream", "Object not serializable"); } } private class GPSThread extends Thread { public GPSThread() { super("GPSThread"); } public void run() { gpsThreading = true; try { while (gpsThreading) { request(gpsQueue.take()); } } catch (InterruptedException e) { } } } private class ListenThread extends Thread { public ListenThread() { super("ListenThread"); } public void run() { try { while (authenticated && connect()) { Object input = null; lsoos.flush(); input = lsois.readObject(); if (input instanceof Route) { hasNextRoute = true; Log.e("CRASHING", "Size " + ((Route) input).route.size()); nextRoute = ((Route) input); } if (input instanceof CheckListPair) { clp = (CheckListPair) input; } synchronized (this) { notify(); } } } catch (SocketException e) { Log.w("ObjectStream", "Socket Closed"); disconnect(); } catch (IOException e) { if (!listenSocket.isInputShutdown()) { Log.i("ObjectStream", "Shutdown"); } else { Log.w("ObjectStream", "IO Exceptions"); } } catch (ClassNotFoundException e) { Log.w("ObjectStream", "Object not serializable"); } } } private class RequestThread extends Thread { private Object input; private Object message; public RequestThread(Object message) { super("RequestThread"); this.input = null; this.message = message; } public void run() { try { if (authenticated && connect()) { rsoos.writeObject(message); rsoos.flush(); input = rsois.readObject(); } } catch (SocketException e) { Log.w("ObjectStream", "Socket Closed"); input = null; } catch (IOException e) { Log.w("ObjectStream", "IO Exceptions"); input = null; } catch (ClassNotFoundException e) { Log.w("ObjectStream", "Object not serializable"); input = null; } } public Object getInput() { return input; } } }
Java
package jtacck.labmedicine; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; /** * Handles the screen that shows one package's data. * * @author Kevin * */ public class PackageActivity extends Activity { private String[] data; private Bundle extras; private OnClickListener listener; private String barcode; private CheckBox check; private boolean sent; /** * Called when PackageActivity is started. Uses a bundle labeled "jtacck" * supplied by the creating Activity to display the proper information. This bundle * is an extra of the Intent for the PackageActivity (NOT savedInstanceState). * Bundle jtacck must include: * A StringArray with key "contents" that represents the contents of the package. * An int with key "selectedID" that is the requestCode when this * activity is started for result. * A String with key "title" that is the text to be displayed at the top of the screen. * A String with key "barcode" that is the text representation of the package's * unique ID. * A String with key "requirements" that represents the requirements of the package. * * @param savedInstanceState * @Override */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); extras = getIntent().getBundleExtra("jtacck"); setContentView(R.layout.package_screen); TextView title = (TextView) findViewById(R.id.package_screen_title); TextView barcodeText = (TextView) findViewById(R.id.package_barcode); TextView requirements = (TextView) findViewById(R.id.package_requirements); ListView contents = (ListView) findViewById(R.id.package_contents); check = (CheckBox) findViewById(R.id.package_checkbox); data = extras.getStringArray("contents"); contents.setAdapter(new ArrayAdapter<String>(this, R.layout.listview_text_format, data)); barcode = extras.getString("barcode"); title.setText(extras.getString("title")); barcodeText.setText("Barcode: " + barcode); requirements.setText(extras.getString("requirements")); if(extras.getBoolean("collected")){ check.setChecked(true); sent = true; setResult(1); }else { check.setChecked(false); sent = false; setResult(-extras.getInt("selectedID")); } listener = new OnClickListener() { public void onClick(View view) { if(!sent) { MainActivity.linker.packageCollected(barcode); sent = true; MainActivity.sList = MainActivity.linker .getShippingList(MainActivity.currentSite); MainActivity.cache.collect(barcode); } check.setChecked(true); setResult(1); } }; check.setOnClickListener(listener); } }
Java
package jtacck.labmedicine; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; import jvm.jtacck.db.records.ShippingInformation; public class RouteData { private Map<Hospital, List<ClientSite>> hospMap; private Map<ClientSite, List<ShippingInformation>> siteMap; public RouteData() { hospMap = new LinkedHashMap<Hospital, List<ClientSite>>(); siteMap = new LinkedHashMap<ClientSite, List<ShippingInformation>>(); } public void addHospital(Hospital hosp, LinkedHashMap<ClientSite, List<ShippingInformation>> sites) { List<ClientSite> site = new ArrayList<ClientSite>(); for(ClientSite s : sites.keySet()) site.add(s); hospMap.put(hosp, site); siteMap.putAll(sites); } public void addClientSite(ClientSite site, List<ShippingInformation> pack) { siteMap.put(site, pack); } public List<ClientSite> getSites(Hospital hosp) { return hospMap.get(hosp); } public List<ShippingInformation> getPackages(ClientSite site) { return siteMap.get(site); } }
Java
package jtacck.labmedicine; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import jvm.jtacck.db.records.CheckListPair; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; import jvm.jtacck.db.records.ShippingInformation; public class Cache { public enum ChecklistState { START, END, SITE, SHIPPING, ROUTE, NULL; } private CheckListPair checkLists; // private ChecklistState state; private RouteData data; private Hospital currentHosp; private ClientSite currentSite; private Map<ClientSite, Set<ShippingInformation>> collected; public Cache() { data = new RouteData(); checkLists = new CheckListPair(new ArrayList<String>(), new ArrayList<String>()); // state = ChecklistState.START; currentSite = null; currentHosp = null; collected = new HashMap<ClientSite, Set<ShippingInformation>>(); } protected synchronized String[] startRoute() { // state = ChecklistState.START; return checkLists.startingList.toArray(new String[0]); } protected synchronized String[] arriveHosp(Hospital hosp) { // state = ChecklistState.ROUTE; currentHosp = hosp; List<ClientSite> info = data.getSites(currentHosp); String[] answer = new String[info.size()]; for(int i = 0; i < info.size(); i++) answer[i] = info.get(i).name; return answer; } private boolean siteDone(ClientSite site) { for(ShippingInformation info : data.getPackages(site)) if(info.status.status_id < 2 && !collected.containsValue(info)) return false; return true; } protected synchronized List<Boolean> isChecked(ChecklistState state) { List<Boolean> answer = new ArrayList<Boolean>(); switch(state) { case START: return null; case END: return null; case SITE: return null; case SHIPPING: for(int i = 0; i < data.getPackages(currentSite).size(); i++) answer.add(data.getPackages(currentSite).get(i).status.status_id >= 2 || collected.containsKey(currentSite) && collected.get(currentSite).contains(data.getPackages(currentSite).get(i))); break; case ROUTE: for(int i = 0; i < data.getSites(currentHosp).size(); i++) answer.add(siteDone(data.getSites(currentHosp).get(i))); break; } return answer; } protected synchronized void collect(String barcode) { int packageID = 0; while(packageID <= data.getPackages(currentSite).size()) if(barcode.equals(data.getPackages(currentSite).get(packageID).specimen.barcode)) break; else packageID++; if(collected.containsKey(currentSite)) { Set<ShippingInformation> info = collected.get(currentSite); info.add(data.getPackages(currentSite).get(packageID)); collected.put(currentSite, info); }else { Set<ShippingInformation> info = new HashSet<ShippingInformation>(); info.add(data.getPackages(currentSite).get(packageID)); collected.put(currentSite, info); } } protected synchronized String[] endRoute() { // state = ChecklistState.END; return checkLists.endingList.toArray(new String[0]); } protected ChecklistState strToEnum(String string) { if(string.equals("START")) return ChecklistState.START; else if(string.equals("END")) return ChecklistState.END; else if(string.equals("ROUTE")) return ChecklistState.ROUTE; else if(string.equals("SITE")) return ChecklistState.SITE; else if(string.equals("SHIPPING")) return ChecklistState.SHIPPING; else return null; } protected synchronized String[] arriveSite(ClientSite site) { currentSite = site; // state = ChecklistState.SITE; return currentSite.instructions.toArray(new String[0]); } protected synchronized String[] getPackages() { // state = ChecklistState.SHIPPING; List<String> answer = new ArrayList<String>(); for(ShippingInformation info : data.getPackages(currentSite)) answer.add(info.specimen.description); return answer.toArray(new String[0]); } protected synchronized void setStartEndChecklists(CheckListPair lists) { checkLists = lists; } protected RouteData getRouteData() { return data; } protected ShippingInformation getPackageById(int id) { return data.getPackages(currentSite).get(id); } }
Java
package jtacck.labmedicine; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import jtacck.labmedicine.Cache.ChecklistState; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.ShippingInformation; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import android.widget.Toast; /** * Listens for an item to be selected on a ListView in CheckListActivity. * * @author Kevin * */ public class ChecklistListener implements OnClickListener { private Activity current; private Class<?> next; private ChecklistState state; private Serializable data; /** * @param current * The Activity that uses this object. * @param next * The next Activity to start when onClick is called. * @param data * Data to be sent to the server when onClick is called. */ protected ChecklistListener(Activity current, Class<?> next, ChecklistState state, Serializable data) { this.current = current; this.next = next; this.state = state; this.data = data; } /** * Makes sure all items are checked then if they are starts the next * activity. If some item is not checked then a message is displayed * informing the user of that fact. * * @param view * This is the object that was clicked. * * @Override */ public void onClick(View view) { ListView listView = (ListView) current .findViewById(R.id.instruction_view); boolean allChecked = true; for (int i = 0; i < listView.getCount(); i++) { allChecked = allChecked && listView.isItemChecked(i); } if (allChecked) { if (next != null) { Intent intent = new Intent(current.getApplicationContext(), next); if (next.equals(RouteMapTabActivity.class) && state.equals(Cache.ChecklistState.SHIPPING)) { if (!RouteListActivity.end.isEmpty()) { RouteListActivity.current.add(RouteListActivity.end .get(0)); RouteListActivity.end.remove(0); } RouteListActivity.beginning.add(RouteListActivity.current .get(0)); RouteListActivity.current.remove(0); } // Test to see if this is a ClientSite checklist. If it is then // it // links to a package list checklist and extra steps must be // taken // to initialize the next Activity. if (next.equals(ChecklistActivity.class)) { String[] toDo = new String[] { "Error" }; // if (data instanceof ClientSite) { // MainActivity.sList = MainActivity.linker // .getShippingList((ClientSite) data); // if (MainActivity.sList != null) { // List<ShippingInformation> list = // MainActivity.sList.shippingList; // List<String> strings = new LinkedList<String>(); // // for (int i = 0; i < list.size(); i++) { // if (list.get(i).status.status_id == 1) { // strings.add(list.get(i).specimen.description); // } // } // toDo = strings.toArray(new String[0]); // } // } Bundle extras = new Bundle(); switch (state) { case SITE: extras.putString("state", "SHIPPING"); extras.putBoolean("freeform", false); break; case SHIPPING: extras.putString("string", "END"); default: extras.putString("state", "START"); } // extras.putStringArray("toDo", toDo); extras.putSerializable("nextActivity", RouteMapTabActivity.class); // extras.putBoolean("conditional", true); extras.putSerializable("forResult", PackageActivity.class); intent.putExtra("jtacck", extras); } current.startActivity(intent); current.finish(); } else SharedMethods.logoutAlert(current).show(); } else { Toast.makeText(current.getApplicationContext(), "YOU DIDN'T COMPLETE THE CHECKLIST", Toast.LENGTH_LONG) .show(); return; } } }
Java
package jtacck.labmedicine; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; import jvm.jtacck.db.records.ShippingInformation; import jvm.jtacck.serials.Route; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ListView; import android.widget.SimpleExpandableListAdapter; import android.widget.Toast; import android.util.Log; public class RouteListActivity extends Activity { private static String[] routeText = null; public static Intent i = null; private ExpandableListAdapter mAdapter; private ExpandableListView list; public static boolean modified = true; public static List<String> beginning = new ArrayList<String>(); public static List<String> current = new ArrayList<String>(); public static List<String> end = new ArrayList<String>(); public static String currentHospital = ""; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.route_screen); list = (ExpandableListView) findViewById(R.id.route_screen_list); // list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); OnClickListener listener = new OnClickListener() { public void onClick(View view) { Bundle extras = new Bundle(); extras.putString("state", "END"); Intent intent = new Intent(RouteListActivity.this, ChecklistActivity.class); intent.putExtra("jtacck", extras); RouteListActivity.this.startActivity(intent); } }; ((Button) findViewById(R.id.checkoutbutton)) .setOnClickListener(listener); try { Thread.sleep(200); } catch (Exception e) { Log.i("DEBUG", "THREAD SLEEP ERROR"); } if (MainActivity.route != null && routeText == null) { Route r = MainActivity.route; List<String> temp = new LinkedList<String>(); for (Hospital h : r.route.keySet()) { List<ClientSite> sites = r.route.get(h); LinkedHashMap<ClientSite, List<ShippingInformation>> siteMap = new LinkedHashMap<ClientSite, List<ShippingInformation>>(); for (ClientSite s : sites) { siteMap.put(s, MainActivity.linker.getShippingList(s).shippingList); temp.add(h.name + " - " + s.name); } MainActivity.cache.getRouteData().addHospital(h, siteMap); } routeText = temp.toArray(new String[0]); if (routeText.length > 0) { current.add(routeText[0]); for (String s : routeText) { end.add(s); } end.remove(0); } } createExpandable(); list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (groupPosition == 1) { int i = childPosition; ExpandableListAdapter temp = parent .getExpandableListAdapter(); for (int j = 0; j < groupPosition; j++) { i += temp.getChildrenCount(j); } Route r = MainActivity.route; Bundle extras = new Bundle(); if (r != null) { int j = 0; for (Hospital h : r.route.keySet()) { List<ClientSite> sites = r.route.get(h); for (ClientSite s : sites) { RouteData data = MainActivity.cache .getRouteData(); data.addHospital( h, new LinkedHashMap<ClientSite, List<ShippingInformation>>()); if (i == j) { MainActivity.currentSite = s; MainActivity.sList = null; } j++; } } } extras.putSerializable("nextActivity", ChecklistActivity.class); extras.putSerializable("serverRequest", MainActivity.currentSite); extras.putString("state", "SITE"); Intent intent = new Intent(RouteListActivity.this, ChecklistActivity.class); intent.putExtra("jtacck", extras); RouteListActivity.this.startActivity(intent); } return true; } }); /* * list.setAdapter(new ArrayAdapter(this, R.layout.listview_text_format, * routeText)); list.setOnItemClickListener(new RouteListener(this)); */ } @Override protected void onResume() { super.onResume(); /* * ((ListView) findViewById(R.id.route_screen_list)) .setAdapter(new * MenuAdapter<String>(this, R.layout.listview_text_format, routeText)); */ if (MainActivity.linker.hasNextRoute()) { MainActivity.route = MainActivity.linker.getNextRoute(); if (MainActivity.route != null) { Route r = MainActivity.route; List<String> temp = new LinkedList<String>(); for (Hospital h : r.route.keySet()) { List<ClientSite> sites = r.route.get(h); LinkedHashMap<ClientSite, List<ShippingInformation>> siteMap = new LinkedHashMap<ClientSite, List<ShippingInformation>>(); for (ClientSite s : sites) { siteMap.put( s, MainActivity.linker.getShippingList(s).shippingList); temp.add(h.name + " - " + s.name); } MainActivity.cache.getRouteData().addHospital(h, siteMap); } routeText = temp.toArray(new String[0]); Log.e("CRASHING", temp.size() + " " + routeText.length); if (!temp.contains(current.get(0))) { current.clear(); end.clear(); current.add(temp.get(0)); for (String s : temp) { end.add(s); } end.remove(0); } else { end.clear(); for (int i = temp.indexOf(current.get(0)) + 1; i < temp .size(); i++) { end.add(temp.get(i)); } } createExpandable(); Toast.makeText(this, "Route has been updated", Toast.LENGTH_SHORT).show(); } } list.expandGroup(1); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: return SharedMethods.logoutAlert(this); } return null; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.text: showDialog(1); break; case R.id.icontext: break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { showDialog(1); return true; } return false; } private void createExpandable() { List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); Map<String, String> curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put("NAME", "Previous Client Sites"); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); Map<String, String> curChildMap = new HashMap<String, String>(); for (String s : beginning) { curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put("CS", s); } childData.add(children); curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put("NAME", "Current Client Sites"); children = new ArrayList<Map<String, String>>(); for (String s : current) { curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put("CS", s); } childData.add(children); curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put("NAME", "End Client Sites"); children = new ArrayList<Map<String, String>>(); for (String s : end) { curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put("CS", s); } childData.add(children); // Set up our adapter mAdapter = new SimpleExpandableListAdapter(this, groupData, R.layout.listview_text_format, new String[] { "NAME" }, new int[] { R.id.listview_text_format }, childData, R.layout.listview_text_format, new String[] { "CS" }, new int[] { R.id.listview_text_format }); list.setAdapter(mAdapter); if (MainActivity.route != null && !current.isEmpty()) { Route r = MainActivity.route; for (Hospital h : r.route.keySet()) { for (ClientSite c : r.route.get(h)) { if ((h.name + " - " + c.name).equals(current.get(0))) { currentHospital = h.address; } } } } } }
Java
package jtacck.labmedicine; import java.util.LinkedHashMap; import java.util.List; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; import jvm.jtacck.db.records.ShippingInformation; import jvm.jtacck.db.records.User; import jvm.jtacck.serials.Route; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; public class RouteListener implements OnItemClickListener { private Activity main; private User user; protected RouteListener(Activity main) { this.main = main; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub //user = new User("uname", "passcode", "John", "Smith", ) ListView list = (ListView) parent.findViewById(R.id.route_screen_list); int i = list.getCheckedItemPosition(); Route r = MainActivity.route; Bundle extras = new Bundle(); if (r != null) { int j = 0; for (Hospital h : r.route.keySet()) { List<ClientSite> sites = r.route.get(h); for (ClientSite s : sites) { RouteData data = MainActivity.cache.getRouteData(); data.addHospital(h, new LinkedHashMap<ClientSite, List<ShippingInformation>>()); if (i == j) { MainActivity.currentSite = s; MainActivity.sList = null; } j++; } } } // extras.putStringArray("toDo", MainActivity.currentSite.instructions.toArray(new String[0])); extras.putSerializable("nextActivity", ChecklistActivity.class); extras.putSerializable("serverRequest", MainActivity.currentSite); extras.putString("state", "SITE"); Intent intent = new Intent(main,ChecklistActivity.class); intent.putExtra("jtacck", extras); main.startActivity(intent); } }
Java
package jtacck.labmedicine; import android.os.Bundle; import android.preference.PreferenceActivity; /** * @author Jesse Jeng * * Activity that lets the user configure various settings for the * application * */ public class PreferencesFromXml extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); } }
Java
package jtacck.labmedicine; import java.util.List; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; /** * Extended class of Map Activity that also implements a location listener * within itself. Used to display the map and help draw various overlays * * @see com.google.android.maps.MapActivity * @see android.location.LocationListener * * @author Andrew * */ public class GoogleMapActivity extends MapActivity implements LocationListener { /** * Tag used for debugging. */ private static final String TAG = "GoogleMapActivity"; /** * The LocationManager used to retrieve the location properties. */ LocationManager locationManager; /** * Geocoder used to translate between points and addresses. */ Geocoder geocoder; /** * Used to display information on the map */ TextView locationText; /** * The MapView used to display the map. */ MapView mapView; /** * Stores the controller used to obtain controls of the map. */ MapController mapController; /** * List of overlays to be drawn */ List<Overlay> mapOverlays; /** * Icon to be drawn on the points */ Drawable drawable; /** * The actual class that draws the overlays */ GoogleMapOverlay itemizedoverlay; /** * Overlay class used to display information about our location. */ MyLocationOverlay myLocOverlay; /* * (non-Javadoc) * * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle) * * Sets up everything we need for this activity. For more information read * the comments along the code for this method. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.g_map); Button route = (Button) findViewById(R.id.firstButtonId); Button findMyself = (Button) findViewById(R.id.secondButtonId); route.setOnClickListener(new OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) * * When the user clicks on the button we want them to be sent to the * Google maps and have the route calculated if possible. */ @Override public void onClick(View v) { if (myLocOverlay.getMyLocation() != null && RouteListActivity.currentHospital != null) { // Create a new intent and pass the URL so that it can be // used to calculate the route Intent intent = new Intent(Intent.ACTION_VIEW, Uri .parse("http://maps.google.com/maps?saddr=" + myLocOverlay.getLastFix().getLatitude() + "," + myLocOverlay.getLastFix().getLongitude() + "&daddr=" + RouteListActivity.currentHospital)); // Set the intent to open the package and class for map intent.setComponent(new ComponentName( "com.google.android.apps.maps", "com.google.android.maps.MapsActivity")); startActivity(intent); } else { // We don't have a location yet so let user know it Toast.makeText( GoogleMapActivity.this, "Please wait, your location has not been identified", Toast.LENGTH_SHORT).show(); } } }); findMyself.setOnClickListener(new OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) * * Simply move the map to center on our current location. */ @Override public void onClick(View v) { if (myLocOverlay.getMyLocation() != null) { mapController.animateTo(myLocOverlay.getMyLocation()); } else { // We don't have a location yet so let user know it Toast.makeText( GoogleMapActivity.this, "Please wait, your location has not been identified", Toast.LENGTH_SHORT).show(); } } }); locationText = (TextView) this.findViewById(R.id.lblLocationInfo); // Retrieves the map and set options mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.preLoad(); // Retrieve the map controller and set the zoom level mapController = mapView.getController(); mapController.setZoom(16); geocoder = new Geocoder(this); // Get location services locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Overlays to be used, picture to be drawn, and draws the overlay mapOverlays = mapView.getOverlays(); drawable = this.getResources().getDrawable(R.drawable.icon); itemizedoverlay = new GoogleMapOverlay(drawable, this); myLocOverlay = new MyLocationOverlay(this, mapView); } /* * (non-Javadoc) * * @see com.google.android.maps.MapActivity#onResume() * * Begin the listener and calculate any new points obtained since the last * pause of this activity. */ @Override protected void onResume() { super.onResume(); // Request location updates from both network and GPS locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 10, this); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, this); // Set up overlay features now myLocOverlay.enableCompass(); if (myLocOverlay.enableMyLocation()) { mapOverlays.add(myLocOverlay); } // When we get location we want to use it myLocOverlay.runOnFirstFix(new Runnable() { public void run() { if (myLocOverlay.isMyLocationEnabled()) { mapController.animateTo(myLocOverlay.getMyLocation()); } } }); } /* * (non-Javadoc) * * @see com.google.android.maps.MapActivity#onPause() * * Closes the listener upon leaving the activity and does some cleanup work. */ @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); // turn off the overlay features myLocOverlay.disableMyLocation(); myLocOverlay.disableCompass(); // clear all overlays mapOverlays.clear(); } /* * (non-Javadoc) * * @see com.google.android.maps.MapActivity#isRouteDisplayed() * * Inherited method that must be implemented. Currently we have no use for * it so we return false since we are not displaying a route. */ @Override protected boolean isRouteDisplayed() { return false; } /* * (non-Javadoc) * * @see * android.location.LocationListener#onLocationChanged(android.location. * Location) * * This is called whenever we get a new location from our location manager. * For now we just want it to animate to the point we're at and tell the * user we found their location or something along those lines. */ @Override public void onLocationChanged(Location location) { this.locationText.setText("Location found!"); // Necessary because geopoints are a factor of 1e6 of normal coords int latitude = (int) (location.getLatitude() * 1e6); int longitude = (int) (location.getLongitude() * 1e6); GeoPoint point = new GeoPoint(latitude, longitude); mapController.animateTo(point); } /* * (non-Javadoc) * * @see * android.location.LocationListener#onProviderDisabled(java.lang.String) * * This method must be implemented as it as abstract. Currently we have no * use for it, so it is blank, but it must be implemented. */ @Override public void onProviderDisabled(String provider) { } /* * (non-Javadoc) * * @see * android.location.LocationListener#onProviderEnabled(java.lang.String) * * This method must be implemented as it as abstract. Currently we have no * use for it, so it is blank, but it must be implemented. */ @Override public void onProviderEnabled(String provider) { } /* * (non-Javadoc) * * @see android.location.LocationListener#onStatusChanged(java.lang.String, * int, android.os.Bundle) * * This method must be implemented as it as abstract. Currently we have no * use for it, so it is blank, but it must be implemented. */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { } /* * (non-Javadoc) * * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) * * Used to inflate the options menu with a certain XML. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /* * (non-Javadoc) * * @see android.app.Activity#onCreateDialog(int) * * Creates the dialog for the logout. */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: return SharedMethods.logoutAlert(this); } return null; } /* * (non-Javadoc) * * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) * * Based on the option chosen in the menu will perform one of the options * listed below. Android forces you to have at least two menu items, but we * hide the other one. Possibly have more which is why we use a case. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.text: showDialog(1); break; case R.id.icontext: break; } return true; } /* * (non-Javadoc) * * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent) * * Displays the dialog for the logout if they back key is pressed. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { showDialog(1); return true; } return false; } }
Java
package jtacck.labmedicine; import java.util.List; import jtacck.labmedicine.Cache.ChecklistState; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; import jvm.jtacck.db.records.Item; import jvm.jtacck.db.records.ShippingInformation; import jvm.jtacck.db.records.Specimen; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; /** * Displays a list that can be checked and a button to go to the next screen * only if all items are checked. * * @author Kevin * */ public class ChecklistActivity extends Activity { private OnItemClickListener listener; private ListView listView; private ArrayAdapter<String> adapter; private int currentPosition; private ChecklistState state; /** * Called when ChecklistActivity is started. Requires a Bundle named * "jtacck" as an extra to the Activity's intent. Bundle jtacck must * include: A StringArray with key "toDo" that represents the checklist * contents. A Class<?> stored as a Serializable with key "nextActivity" * that is the Activity that will start when the checklist is completed. A * Serializable with key "serverRequest" that is the message if any) sent to * the server when an item is clicked. A boolean with key "conditional" that * states if the checklist is related to another Activity. (defaults to * false if not included) * * @Override */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Bundle extras = this.getIntent().getBundleExtra("jtacck"); setContentView(R.layout.checklist_list_layout); listView = (ListView) findViewById(R.id.instruction_view); String[] toDo; Button scanButton = (Button) findViewById(R.id.scan_button); scanButton.setVisibility(View.GONE); OnClickListener barcodeListener = new OnClickListener() { public void onClick(View v) { Intent intent = new Intent( "com.google.zxing.client.android.SCAN"); startActivityForResult(intent, 0); } }; state = MainActivity.cache.strToEnum(extras.getString("state")); // if(extras.getString("state") != null) { switch (state) { case START: toDo = MainActivity.cache.startRoute(); break; case END: toDo = MainActivity.cache.endRoute(); break; case SITE: toDo = MainActivity.cache.arriveSite((ClientSite) extras .getSerializable("serverRequest")); break; case ROUTE: toDo = MainActivity.cache.arriveHosp((Hospital) extras .getSerializable("serverRequest")); break; case SHIPPING: toDo = MainActivity.cache.getPackages(); refresh(); listener = new OnItemClickListener() { public void onItemClick(AdapterView<?> adview, View view, int position, long id) { Bundle params = new Bundle(); ShippingInformation shippingInfo = MainActivity.cache .getPackageById(position); Specimen specimen = shippingInfo.specimen; String[] contents = new String[specimen.contents.size()]; Item[] content = specimen.contents.toArray(new Item[0]); for (int i = 0; i < contents.length; i++) contents[i] = content[i].name; params.putStringArray("contents", contents); params.putInt("selectedID", position); params.putString("barcode", specimen.barcode); params.putString("requirements", specimen.requirements); params.putString("title", specimen.description); params.putBoolean("collected", MainActivity.cache .isChecked(state).get(position)); Intent intent = new Intent(ChecklistActivity.this, (Class<?>) extras.getSerializable("forResult")); intent.putExtra("jtacck", params); listView.setItemChecked(position, false); startActivityForResult(intent, position + 1); } }; listView.setOnItemClickListener(listener); scanButton.setOnClickListener(barcodeListener); scanButton.setVisibility(View.VISIBLE); break; default: toDo = new String[0]; } // }else // toDo = extras.getStringArray("toDo"); adapter = new ArrayAdapter<String>(this, R.layout.checklist, toDo); listView.setAdapter(adapter); View button = findViewById(R.id.to_shipping_button); button.setOnClickListener(new ChecklistListener(this, (Class<?>) extras .getSerializable("nextActivity"), MainActivity.cache .strToEnum(extras.getString("state")), extras .getSerializable("serverRequest"))); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); refresh(); // if (extras.getBoolean("conditional", false)) { // refresh(); // listener = new OnItemClickListener() { // public void onItemClick(AdapterView<?> adview, View view, // int position, long id) { // // Bundle params = new Bundle(); // ShippingInformation shippingInfo = MainActivity.sList.shippingList // .get(position); // Specimen specimen = shippingInfo.specimen; // // String[] contents = new String[specimen.contents.size()]; // Item[] content = specimen.contents.toArray(new Item[0]); // for (int i = 0; i < contents.length; i++) // contents[i] = content[i].name; // // params.putStringArray("contents", contents); // params.putInt("selectedID", position); // params.putString("barcode", specimen.barcode); // params.putString("requirements", specimen.requirements); // params.putString("title", specimen.description); // params.putBoolean("collected", // shippingInfo.status.status_id >= 2); // // Intent intent = new Intent(ChecklistActivity.this, // (Class<?>) extras.getSerializable("forResult")); // intent.putExtra("jtacck", params); // // listView.setItemChecked(position, false); // // startActivityForResult(intent, position + 1); // } // }; /* } else */if (extras.getBoolean("freeform", true)) { currentPosition = 0; OnItemClickListener listen = new OnItemClickListener() { public void onItemClick(AdapterView<?> adview, View view, int position, long id) { if (position > currentPosition) listView.setItemChecked(position, !listView.isItemChecked(position)); else if (position == currentPosition) { if (listView.isItemChecked(position)) currentPosition++; else currentPosition--; } else if (position + 1 == currentPosition) { currentPosition--; listView.setItemChecked(position, false); } else listView.setItemChecked(position, true); } }; listView.setOnItemClickListener(listen); } } /** * Result from conditional checklist items are sent here. */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); for (int i = 0; i < adapter.getCount(); i++) { if (contents .equals(MainActivity.cache.getPackageById(i).specimen.barcode)) listener.onItemClick(null, null, i, i); } } else if (resultCode == RESULT_CANCELED) { // Handle cancel } } if (resultCode <= 0) { listView.setItemChecked(-resultCode, false); } else listView.setItemChecked(requestCode - 1, true); refresh(); } private void refresh() { List<Boolean> checked = MainActivity.cache.isChecked(state); if (checked != null) for (int i = 0; i < checked.size(); i++) listView.setItemChecked(i, checked.get(i)); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /* * (non-Javadoc) * * @see android.app.Activity#onCreateDialog(int) * * Creates the actual dialog. */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case 1: return SharedMethods.logoutAlert(this); } return null; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.text: showDialog(1); break; case R.id.icontext: break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { final Bundle extras = this.getIntent().getBundleExtra("jtacck"); ListView listView = (ListView) this.findViewById(R.id.instruction_view); boolean allChecked = true; for (int i = 0; i < listView.getCount(); i++) { allChecked = allChecked && listView.isItemChecked(i); } if (keyCode == KeyEvent.KEYCODE_BACK && MainActivity.cache.strToEnum(extras.getString("state")) .equals(Cache.ChecklistState.SHIPPING) && !allChecked) { Toast.makeText(this, "Please complete the check list", Toast.LENGTH_SHORT).show(); return true; } super.onKeyDown(keyCode, event); return true; } }
Java
package jtacck.labmedicine; import java.util.ArrayList; import android.app.AlertDialog; import android.content.Context; import android.graphics.drawable.Drawable; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; public class GoogleMapOverlay extends ItemizedOverlay<OverlayItem> { private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); private Context mContext; public GoogleMapOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); } public GoogleMapOverlay(Drawable defaultMarker, Context context) { super(boundCenterBottom(defaultMarker)); mContext = context; } @Override protected OverlayItem createItem(int i) { return mOverlays.get(i); } @Override public int size() { return mOverlays.size(); } public void addOverlay(OverlayItem overlay) { mOverlays.add(overlay); populate(); } @Override protected boolean onTap(int index) { OverlayItem item = mOverlays.get(index); AlertDialog.Builder dialog = new AlertDialog.Builder(mContext); dialog.setTitle(item.getTitle()); dialog.setMessage(item.getSnippet()); dialog.show(); return true; } }
Java
package jtacck.labmedicine; import java.util.Calendar; import java.util.Iterator; import jvm.jtacck.db.records.CheckListPair; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.ShippingInformation; import jvm.jtacck.serials.Route; import jvm.jtacck.serials.ShippingList; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; /** * @author Kevin Anderson + Jesse Jeng + Andrew Lau * * Main Activity for the Android application, starts with the login * screen where the user can login with correct username and password. * The user can also access the preference screen through this activity */ public class MainActivity extends Activity { /** * Reference to the ServerLinker object, used for all necessary connections * to the Android server */ protected static ServerLinker linker = null; /** * Username and password preferences */ private static SharedPreferences pref; private static String PREF_USERNAME; private static String PREF_PASSWORD; private static String REMEMBER = "REMEMBER_INFO"; /** * Checkbox for the "Remember me" functionality */ private static CheckBox remember; /** * Text input box for username */ private static EditText usernameField; /** * Text input box for password */ private static EditText passwordField; /** * Route object that contains all the Hospital objects and ClientSite * objects, used for displaying the route screen */ protected static Route route = null; /** * Reference to the currently selected ClientSite */ protected static ClientSite currentSite = null; /** * Reference to the currently selected ShippingList */ protected static ShippingList sList = null; protected static ShippingInformation sInfo = null; protected static Iterator<ClientSite> currentHospList; protected static CheckListPair routeCheckList; protected static final Cache cache = new Cache(); protected static Thread t; /** * Location Manager that gives us access to features to retrieve locations */ protected static LocationManager mLocManager; /** * Location listener used to listen for updates of location */ protected LocationListener listener; /** * Whether GPS has been updated at least once upon login */ protected static boolean hasUpdated; /** Called when the activity is first created. */ /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) * * Handler for when the activity is first created. Creates all the input * boxes for the login screen and a checkbox that enables/diables the * 'Remember me' function */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the preferences used by the application and load defaults pref = PreferenceManager.getDefaultSharedPreferences(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); usernameField = (EditText) findViewById(R.id.username_input); passwordField = (EditText) findViewById(R.id.password_in); remember = (CheckBox) findViewById(R.id.checkBox1); hasUpdated = false; final LoginButton loginButton = new LoginButton(this, usernameField, passwordField); // See if check box was checked at any time if (pref.getBoolean(REMEMBER, false)) { remember.setChecked(true); } // Set the event handler to reset preferences if remember login is not // checked remember.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { PREF_USERNAME = ""; PREF_PASSWORD = ""; pref.edit().putString("PREF_USERNAME", PREF_USERNAME) .putString("PREF_PASSWORD", PREF_PASSWORD).commit(); } } }); // Sets the event handler for when the user presses enter key in the // password input box passwordField.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { findViewById(R.id.login_button).performClick(); return true; } return false; } }); // Sets the event handler for when the user hits the 'submit' button findViewById(R.id.login_button).setOnClickListener(loginButton); mLocManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); listener = new LocationListener() { private static final int TWO_MINUTES = 1000 * 60 * 2; /** * Best GPS location we encounter so far */ private Location bestSoFar; /** * Calendar object used to retrieve time */ private Calendar c = Calendar.getInstance(); /** * Time associated to the calendar object */ private long time = c.getTimeInMillis(); /** * Determines whether one Location reading is better than the * current Location fix * * @param location * The new Location that you want to evaluate * @param currentBestLocation * The current Location fix, to which you want to compare * the new one */ protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isBetweenNewerAndOlder = timeDelta < TWO_MINUTES / 2; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current // location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it // must be worse } else if (isSignificantlyOlder || isBetweenNewerAndOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation .getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider( location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness // and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } /* * (non-Javadoc) * * @see * android.location.LocationListener#onLocationChanged(android.location * .Location) * * When we get a new location we want to update GPS if it is a * better location than our last */ @Override public void onLocationChanged(Location location) { if (linker != null) { if (bestSoFar != null) { if (isBetterLocation(location, bestSoFar)) { long time_now = c.getTimeInMillis(); Log.w("GPS", "SENDING TOO FAST"); Log.w("time", "Time is " + time_now); Log.w("time", "Time was " + time); linker.updateGPS(location.getLatitude(), location.getLongitude()); bestSoFar = location; time = time_now; } } else { bestSoFar = location; } } } /* * (non-Javadoc) * * @see * android.location.LocationListener#onProviderDisabled(java.lang * .String) * * This method must be implemented as it as abstract. Currently we * have no use for it, so it is blank, but it must be implemented. */ @Override public void onProviderDisabled(String provider) { } /* * (non-Javadoc) * * @see * android.location.LocationListener#onProviderEnabled(java.lang * .String) * * This method must be implemented as it as abstract. Currently we * have no use for it, so it is blank, but it must be implemented. */ @Override public void onProviderEnabled(String provider) { } /* * (non-Javadoc) * * @see android.location.LocationListener#onStatusChanged(java.lang. * String, int, android.os.Bundle) * * This method must be implemented as it as abstract. Currently we * have no use for it, so it is blank, but it must be implemented. */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }; mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listener); mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 300, listener); } /* * (non-Javadoc) * * @see android.app.Activity#onPause() */ @Override protected void onPause() { MainActivity.super.onPause(); boolean isChecked = remember.isChecked(); // Save values to preferences if user wants to remember their login, // else we just store the state of our check box if (isChecked) { PREF_USERNAME = usernameField.getText().toString(); PREF_PASSWORD = passwordField.getText().toString(); pref.edit().putString("PREF_USERNAME", PREF_USERNAME) .putString("PREF_PASSWORD", PREF_PASSWORD) .putBoolean(REMEMBER, true).commit(); } else { pref.edit().putBoolean(REMEMBER, false).commit(); } } /* * (non-Javadoc) * * @see android.app.Activity#onResume() */ @Override protected void onResume() { MainActivity.super.onResume(); // Load values saved in preferences PREF_USERNAME = pref.getString("PREF_USERNAME", ""); PREF_PASSWORD = pref.getString("PREF_PASSWORD", ""); usernameField.setText(PREF_USERNAME); passwordField.setText(PREF_PASSWORD); if (pref.getBoolean(REMEMBER, false)) { remember.setChecked(true); } else { remember.setChecked(false); } mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listener); mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, listener); if (linker != null) { linker.disconnect(); } } /* * (non-Javadoc) * * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate or create the menu MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /* * (non-Javadoc) * * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) * * Event handler for the various actions user can perform after hitting the * menu button. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.main_text: // Load the preferences page startActivity(new Intent(this, PreferencesFromXml.class)); break; case R.id.main_icontext: break; } return true; } @Override protected void onDestroy() { super.onDestroy(); mLocManager.removeUpdates(listener); if (linker != null) { linker.disconnect(); } } }
Java
package jtacck.labmedicine; import jvm.jtacck.serials.LoginInfo; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; /** * @author Andrew Lau * * Event handler for the 'submit' button on the login screen */ public class LoginButton implements OnClickListener { /** * Handler to the main activity */ private static Activity main; /** * Text username and password entered in the text box */ private static EditText username, password; private static SharedPreferences pref; /** * Reference to AsyncTask */ private static Login temp = new Login(); /** * Thread used for timeout of logging in. */ private static Thread t; /** * @param main * Reference to the main activity * @param username * Username entered in the text box * @param password * Password entered in the text box */ protected LoginButton(Activity main, EditText username, EditText password) { LoginButton.main = main; LoginButton.username = username; LoginButton.password = password; pref = PreferenceManager.getDefaultSharedPreferences(main); } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) * * Event handler when the button is clicked, creates an AsyncTask that * connects to the Android server in the background. Runs a thread that will * cancel the AsyncTask in 10 seconds as a time out functionality */ public void onClick(View arg0) { // make sure the task isn't about to run or pending if (temp.getStatus() != AsyncTask.Status.PENDING || temp.getStatus() != AsyncTask.Status.RUNNING) { temp = new Login(); temp.execute(); // we need to set a timeout incase login takes too long // work in progress t = new Thread(new Runnable() { @Override public void run() { try { // Retrieve the value that we set in our preferences Thread.sleep(Integer.parseInt(pref.getString(main .getString(R.string.preferences_timeout_key), "")) * 1000); if (MainActivity.linker != null) { temp.cancel(true); } } catch (InterruptedException e) { Log.i("LoginButton", "Timeout thread has been interrupted"); } } }); t.start(); } } /** * @author Andrew Lau * * AsyncTask that handles login for the Android * */ static class Login extends AsyncTask<Void, Integer, Integer> { private ProgressDialog pd; /* * (non-Javadoc) * * @see android.os.AsyncTask#onPreExecute() * * Pops up a progress dialog on the main activity, blocking user from * entering any input until the AsyncTask is done executing */ @Override protected void onPreExecute() { pd = ProgressDialog.show(main, "", "Attempting to log in to server...", true, true, new OnCancelListener() { /* * (non-Javadoc) * * @see * android.content.DialogInterface.OnCancelListener# * onCancel(android.content.DialogInterface) * * Interrupt our timeout thread and disconnect if a user * cancels our dialog */ @Override public void onCancel(DialogInterface dialog) { t.interrupt(); LoginButton.temp.cancel(true); if (MainActivity.linker != null) { MainActivity.linker.disconnect(); } } }); } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) * * Background execution of the AsyncTask. Starts by creating a * ServerLinker object and then attempts to establish connection and * authentication with the Android server. */ @Override protected Integer doInBackground(Void... params) { // Create new login information LoginInfo info = new LoginInfo(username.getText().toString(), password.getText().toString()); // This is repeated throughout the code since you need to check if // the task has been canceled if (isCancelled()) { return 3; } // Read values from our preference MainActivity.linker = new ServerLinker( pref.getString( main.getString(R.string.preferences_host_key), ""), Integer.parseInt(pref.getString( main.getString(R.string.preferences_listenport_key), "")), Integer.parseInt(pref.getString(main .getString(R.string.preferences_requestport_key), "")), info); if (isCancelled()) { return 3; } // Authenticate with the server MainActivity.linker.authenticate(); if (isCancelled()) { return 3; } // Check to make sure linker is connected if (!MainActivity.linker.connect()) { if (isCancelled()) { return 3; } return 1; } // Check to make sure it stil lis authenticated if (!MainActivity.linker.authenticated()) { if (isCancelled()) { return 3; } if (MainActivity.linker.loggedIn()) { return 4; } else { return 2; } } if (isCancelled()) { return 3; } MainActivity.linker.startListening(); ServerLinker linker = MainActivity.linker; if (isCancelled()) { return 3; } // Retrieve the check list data MainActivity.routeCheckList = linker.getCheckListPair(); MainActivity.cache.setStartEndChecklists(MainActivity.routeCheckList); MainActivity.route = linker.getNextRoute(); return 0; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onCancelled() * * Handler for when the AsyncTask is canceled. Interrupts timeout thread * and tells users they canceled or timed out */ @Override protected void onCancelled() { t.interrupt(); pd.dismiss(); Toast.makeText(main.getApplicationContext(), "Login canceled or timed out.", Toast.LENGTH_LONG).show(); if (MainActivity.linker != null) { MainActivity.linker.disconnect(); } } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) * * Handler for when the AsyncTask finishes its background execution. * Displays different behavior on the UI base on what happened in the * execution handler. Starts the route screen activity when the user * establishes a connection/authentication with the Android server. */ protected void onPostExecute(Integer result) { t.interrupt(); pd.dismiss(); if (result == 1) { // Can't connect, tell user Toast.makeText(main.getApplicationContext(), "No connection to the server.", Toast.LENGTH_LONG) .show(); } else if (result == 2) { // Can't authenticate, tell user Toast.makeText(main.getApplicationContext(), "Login Failed. Incorrect username or password.", Toast.LENGTH_LONG).show(); } else if (result == 4) { // Can't login, tell user Toast.makeText(main.getApplicationContext(), "Login Failed. Already logged in.", Toast.LENGTH_LONG) .show(); } else { // If linker has a valid connection if ((MainActivity.linker.authenticated() && MainActivity.linker .connect())) { Intent intent = new Intent(main, ChecklistActivity.class); Bundle extras = new Bundle(); extras.putString("state", "START"); extras.putSerializable("nextActivity", RouteMapTabActivity.class); intent.putExtra("jtacck", extras); // Check if GPS information has been updated yet if (!MainActivity.hasUpdated) { Location location = MainActivity.mLocManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { location = MainActivity.mLocManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { MainActivity.linker.updateGPS( location.getLatitude(), location.getLongitude()); MainActivity.hasUpdated = true; } } } main.startActivity(intent); } } } } }
Java
package jtacck.labmedicine; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.location.Location; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; /** * @deprecated * * Overlay used to draw the noticeable blue circles over a location on the map * portion of the Android application. * * @see com.google.android.maps.Overlay * * @author Andrew * */ public class CircleOverlay extends Overlay { /** * Current location of the mobile device. */ Location currentLocation; /** * The image that is drawn representing the accuracy of the Network/GPS. */ private Paint accuracyPaint; /** * The center of the circle aka where we're at. */ private Point center; /** * The left "side" of the circle so that we can calculate the radius. */ private Point left; // Temporarily not used in correspondance with the drawable. // private Drawable drawable; // private int width; // private int height; /** * Constructs a new circle overlay at the location. * * @param location * - the Location of where a circle is to be drawn */ public CircleOverlay(Location location) { currentLocation = location; } /* (non-Javadoc) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean) * * Overridden draw method that dras he actual circle. */ @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); /** Set the antialiasing and size of stroke **/ accuracyPaint = new Paint(); accuracyPaint.setAntiAlias(true); accuracyPaint.setStrokeWidth(2.0f); // The drawable // drawable = mapView.getContext().getResources() // .getDrawable(R.drawable.maps_icon); // width = drawable.getIntrinsicWidth(); // height = drawable.getIntrinsicHeight(); /** Set up variables **/ center = new Point(); left = new Point(); double latitude; double longitude; float accuracy; Projection projection = mapView.getProjection(); /** Get attributes to the location **/ latitude = currentLocation.getLatitude(); longitude = currentLocation.getLongitude(); accuracy = currentLocation.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 * 2.5)) * 1E6)); projection.toPixels(leftGeo, left); projection.toPixels(new GeoPoint( (int) (currentLocation.getLatitude() * 1E6), (int) (currentLocation.getLongitude() * 1E6)), center); int radius = center.x - left.x; /** Set color and style of each circle and it's location **/ 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); // Add back after finding a suitable placemark for location. // Might decide to use MyLocationOverlay // drawable.setBounds(center.x - width / 2, center.y - height / 2, // center.x + width / 2, center.y + height / 2); // drawable.draw(canvas); } }
Java
package jtacck.labmedicine; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Paint.Style; 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; public class MyLocOverlay extends MyLocationOverlay { /** * The image that is drawn representing the accuracy of the Network/GPS. */ private Paint accuracyPaint; /** * The center of the circle aka where we're at. */ private Point center; /** * The left "side" of the circle so that we can calculate the radius. */ private Point left; public MyLocOverlay(Context context, MapView mapView) { super(context, mapView); } @Override protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) { super.drawMyLocation(canvas, mapView, lastFix, myLocation, when); // /** Set the antialiasing and size of stroke **/ // accuracyPaint = new Paint(); // accuracyPaint.setAntiAlias(true); // accuracyPaint.setStrokeWidth(1.0f); // // /** Set up variables **/ // center = new Point(); // left = new Point(); // double latitude; // double longitude; // float accuracy; // Projection projection = mapView.getProjection(); // // /** Get attributes to the location **/ // latitude = lastFix.getLatitude(); // longitude = lastFix.getLongitude(); // 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 * 2.5)) * // 1E6)); // projection.toPixels(leftGeo, left); // projection.toPixels(myLocation, center); // int radius = center.x - left.x; // // /** Set color and style of each circle and it's location **/ // 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); } }
Java
package jtacck.labmedicine; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.widget.Toast; /** * Used to consolidate methods that are used by several activities rather than * having repeated code in methods. * * @author Lau * */ public class SharedMethods extends Activity { /** * Performs the actual function of logging out. * * @param a * - activity that is calling the logout */ public static void logout(Activity a) { Intent myIntent = new Intent(a.getApplicationContext(), MainActivity.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); a.startActivity(myIntent); MainActivity.linker.disconnect(); Toast.makeText(a.getApplicationContext(), "You have been logged out.", Toast.LENGTH_LONG).show(); } /** * Generates a logout alert for an activity. * * @param a * - activity that is requesting the alert * * @return Returns a new AlertDialog asking to logout. */ public static AlertDialog logoutAlert(final Activity a) { return new AlertDialog.Builder(a) .setMessage("Proceed to log out?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { SharedMethods.logout(a); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); } }
Java
package jvm.jtacck.serials; import java.io.Serializable; /** * @author Jesse Jeng * * The LoginInfo class wraps two values of the type String in an object. * * An object of type LoginInfo contains two fields whose types are String. * */ public class LoginInfo implements Serializable { /** * serialVersionUID for the class */ private static final long serialVersionUID = 2981582439185436774L; /** * Login information for a courier - username */ public final String username; /** * Login information for a courier - password */ public final String password; /** * Constructs a newly allocated LoginInfo object that represents the * specified login information * * @param username * The username to be contained in an LoginInfo. * * @param password * The password to be contained in an LoginInfo. */ public LoginInfo(String username, String password) { this.username = username; this.password = password; } }
Java
package jvm.jtacck.serials; import java.io.Serializable; /** * @author Jesse Jeng * * The GPS class wraps two values of the primitive type double in an * object. * * An object of type GPS contains two fields whose types are double. * */ public class GPS implements Serializable { /** * serialVersionUID for the class */ private static final long serialVersionUID = -2128022093923591501L; /** * GPS coordinates - latitude */ public final double latitude; /** * GPS coordinates - longitude */ public final double longitude; /** * Constructs a newly allocated GPS object that represents the specified * GPS coordinates; * * @param latitude * The latitude to be contained in a GPS. * * @param longitude * The longitude to be contained in a GPS. * */ public GPS(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } }
Java
package jvm.jtacck.serials; import java.io.Serializable; import java.util.List; import jvm.jtacck.db.records.ShippingInformation; /** * @author Jesse Jeng * * The ShippingList class wraps a value of the type * List<ShippingInformation> in an object. * * An object of type ShippingList contains a single field * whose type is List<ShippingInformation>. * */ public class ShippingList implements Serializable { /** * serialVersionUID for the class */ private static final long serialVersionUID = -1334572194511333187L; /** * A list of ShippingInformation objects * * See ShippingInformation */ public final List<ShippingInformation> shippingList; /** * Constructs a newly allocated ShippingList object that * represents the specified list of ShippingInformation objects * * @param clientSiteList * The List<ShippingInformation> to be contained in an * ShippingList. */ public ShippingList(List<ShippingInformation> shippingList) { this.shippingList = shippingList; } }
Java
package jvm.jtacck.serials; import java.io.Serializable; /** * @author Jesse Jeng * * The Barcode class wraps a value of the primitive type String in an * object. * * An object of type Barcode contains a single field whose type is * String. * */ public class Barcode implements Serializable { /** * serialVersionUID for the class */ private static final long serialVersionUID = 5031339088827918706L; /** * Unique barcode associated with a Specimen object * * See Specimen */ public final String barcode; /** * Constructs a newly allocated Barcode object that represents the specified * barcode value. * * @param barcode * The barcode to be converted to an Barcode. */ public Barcode(String barcode) { this.barcode = barcode; } }
Java
package jvm.jtacck.serials; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Hospital; /** * @author Jesse Jeng * * The Route class wraps a value of the type List<ClientSite> * in an object. * * An object of type Route contains a single field whose type * is List<ClientSite>. * */ public class Route implements Serializable { /** * serialVersionUID for the class */ private static final long serialVersionUID = -3913558679275974161L; /** * A list of ClientSite objects * * See ClientSite */ public final LinkedHashMap<Hospital, List<ClientSite>> route; /** * Constructs a newly allocated Route object that represents the * specified list of ClientSite objects * * @param clientSiteList * The List<ClientSite> to be contained in an Route. */ public Route(List<ClientSite> siteRoute) { route = new LinkedHashMap<Hospital, List<ClientSite>>(); for (ClientSite site : siteRoute) { Hospital h = site.hospital; if (route.containsKey(h)) { List<ClientSite> siteList = route.get(h); siteList.add(site); } else { List<ClientSite> siteList = new LinkedList<ClientSite>(); siteList.add(site); route.put(h, siteList); } } } }
Java
package jvm.jtacck; import static jvm.jtacck.Util.logger; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import jvm.jtacck.db.AwesomeCoreHandler; import jvm.jtacck.db.records.CheckListPair; import jvm.jtacck.db.records.ClientSite; import jvm.jtacck.db.records.Courier; import jvm.jtacck.db.records.ShippingInformation; import jvm.jtacck.serials.Barcode; import jvm.jtacck.serials.GPS; import jvm.jtacck.serials.LoginInfo; import jvm.jtacck.serials.Route; import jvm.jtacck.serials.ShippingList; /** * @author Jesse Jeng * * Default ports: Port 4000 = Push route to Android phones; never * listens Port 9001 = Handle requests from Android phones; always * listens * */ public final class AndroidServer extends Thread { /** * Boolean for controlling all threads within the AndroidServer */ private volatile boolean threading; private int pushPort; private int listenPort; /** * A map structure that keeps track of all the threads associated with * asynchronous update of courier routes */ private HashMap<String, PushSocketThread> pushMap; /** * A map structure that keeps track of all the threads associated with * handling requests from couriers */ private HashMap<String, ListenSocketThread> listenMap; /** * A list that keeps track of all the socket listeners */ private LinkedList<SocketListener> listenerList; /** * A list that keeps track of all the socket threads regardless of their * type, used to force close all threads */ private LinkedList<SocketThread> threadList; /** * For local testing purposes * * @param args * Command line arguments * @throws InterruptedException */ public static void main(String args[]) throws InterruptedException { AndroidServer s = new AndroidServer(4000, 9001); s.start(); s.join(); } /** * Constructs a multithreaded AndroidServer object that handles socket * communications with the Android phone. * * @param pushPort * The port used for asynchronous updates of courier routes. * After authentication, the Android phone will always be * listening on this port where the AndroidServer will be sending * updated routes through this port. DEFAULT = 4000 * @param listenPort * The port used for handling all requests from the Android * phone. After authentication, the AndroidServer will always be * listening on this port where the Android phone will be sending * requests through this port. DEFAULT = 9001 */ public AndroidServer(int pushPort, int listenPort) { this.threading = true; this.pushMap = new HashMap<String, PushSocketThread>(); this.listenMap = new HashMap<String, ListenSocketThread>(); this.listenerList = new LinkedList<SocketListener>(); this.threadList = new LinkedList<SocketThread>(); this.pushPort = pushPort; this.listenPort = listenPort; AwesomeCoreHandler.setServer(this); } /* * (non-Javadoc) * * @see java.lang.Thread#run() * * Creates two listener threads to listen for socket connections on the two * ports */ public synchronized void run() { try { SocketListener pushSocketListener = new SocketListener(pushPort); SocketListener requestSocketListener = new SocketListener( listenPort); listenerList.add(pushSocketListener); listenerList.add(requestSocketListener); pushSocketListener.start(); requestSocketListener.start(); logger.info("Listening to port " + listenPort + " + Pushing on port " + pushPort); } catch (Exception e) { stopAndroidServer(); logger.info("Failure in starting the AndroidServer"); } } /** * Stops the AndroidServer and all created threads */ public void stopAndroidServer() { threading = false; for (SocketListener listener : listenerList) { listener.stopListener(); } logger.info("Server stopped"); } /** * Updates the route to the associated courier's phone * * @param username * Courier's username for login * @param route * The route to be updated to the phone */ public void pushRoute(String username, Route route) { PushSocketThread thread = pushMap.get(username); if (thread != null) { thread.queueRoute(route); } } /** * @author Jesse Jeng * * Thread class that listens for socket connections and spawns the * appropriate type of threads base on port connected * */ private class SocketListener extends Thread { private ServerSocket serverSocket; private int port; /** * Constructor for the SocketListener * * @param port * Port to listen on; listen port or request port */ public SocketListener(int port) throws IOException { super("SocketListener - Port: " + port); this.port = port; serverSocket = new ServerSocket(port); } /* * (non-Javadoc) * * @see java.lang.Thread#run() * * Listens for socket connections and spawns socket threads to handle * accepted connections */ public void run() { try { while (threading) { SocketThread thread = port == pushPort ? new PushSocketThread( serverSocket.accept()) : new ListenSocketThread( serverSocket.accept()); logger.fine("Accepted connection on port " + port); threadList.add(thread); thread.start(); } } catch (SocketException e) { logger.info("Server Socket closed on port: " + port); } catch (IOException e) { e.printStackTrace(); } } /** * Stops the listener and all socket threads spawned by the listener */ public void stopListener() { for (SocketThread thread : threadList) { thread.closeSocket(); } try { serverSocket.close(); } catch (IOException e) { System.err.println("stopListener - serverSocket.close()"); } } } /** * @author Jesse Jeng Socket thread class, extended by specific types of * socket threads that behaves differently depending on the port * they operate on * */ protected class SocketThread extends Thread { protected Socket socket; protected String username; protected ObjectOutputStream oos; protected ObjectInputStream ois; protected boolean socketClosed; protected boolean authenticated; protected volatile long time; /** * Constructor for socket thread * * @param socket * Socket accepted from the SocketListener */ public SocketThread(Socket socket) { super("SocketThread - Port(" + socket.getLocalPort() + ")"); this.socket = socket; this.username = "Unknown"; this.authenticated = false; this.time = System.currentTimeMillis(); try { this.socket.setSoTimeout(300000); oos = new ObjectOutputStream(socket.getOutputStream()); oos.flush(); ois = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { logger.info("Can't get input or output stream"); this.socket = null; } socketClosed = false; } /** * Helper method for reading objects from the input stream, logs all * incoming objects and the username associated with the stream. * * @return The object from the input stream */ protected Object readObject() { String err = this.getName() + " - Read object failed due to ("; try { Object input = ois.readObject(); logger.finer("Read (" + (input == null ? null : input.getClass()) + ") from user: " + username); return input; } catch (SocketTimeoutException e) { err += "SocketTimeoutException"; } catch (ClassNotFoundException e) { err += "ClassNotFoundException)"; } catch (EOFException e) { err += "EOFException)"; } catch (SocketException e) { err += "SocketException)"; } catch (IOException e) { err += "IOException)"; } connectionLost(err); return null; } /** * Helper method for sending objects through the output stream, logs all * outgoing objects and the username associated with them * * @param output * The object to be sent over the output stream */ protected void writeObject(Object output) { String err = this.getName() + " - Write object failed due to ("; try { oos.writeObject(output); oos.flush(); logger.finer("Pushed (" + (output == null ? null : output.getClass()) + ") to user: " + username); return; } catch (EOFException e) { err += "EOFException)"; } catch (SocketException e) { err += "SocketException)"; } catch (IOException e) { err += "IOException)"; } connectionLost(err); } /** * Logs given error string and closees the socket * * @param err * Error string to log */ protected void connectionLost(String err) { logger.info(err + " - Connection lost for user: " + username); closeSocket(); } /** * Authenticates the socket against the connected Android phone by first * reading in a LoginInfo object that contains username and password. It * then checks the information against the database. Sends back a String * if authenticated successfully or Exception if the LoginInfo is * incorrect. */ protected void authenticate() { // End authentication immediately if something went wrong with // socket initialization if (socket == null) { return; } String err = "Failed to authenticate due to ("; Object input = readObject(); if (input instanceof LoginInfo) { LoginInfo info = (LoginInfo) input; username = info.username; if (pushMap.containsKey(username) && listenMap.containsKey(username)) { writeObject(new Exception("Already logged in")); err += "Already logged in)"; } else { try { authenticated = AwesomeCoreHandler.getUserInfo( username, info.password) != null; } catch (IllegalStateException e) { err += "No database connection)"; } if (authenticated) { writeObject("Success"); } else { writeObject(new Exception("Failure")); err += "Username does not exist in database)"; } } } else { writeObject(new Exception("Not LoginInfo")); err += "Not LoginInfo)"; } if (!authenticated) { connectionLost(err); } } /** * Closes the socket and all IO streams */ public void closeSocket() { authenticated = false; try { if (!socket.isOutputShutdown()) { socket.shutdownOutput(); } if (!socket.isInputShutdown()) { socket.shutdownInput(); } if (!socket.isClosed()) { socket.close(); logger.finer(getClass() + " stopped on port: " + socket.getLocalPort() + " for user: " + username); } } catch (IOException e) { logger.info("Error when closing socket"); } threadList.remove(this); } } /** * @author Jesse Jeng * * Thread class for handling pushing objects to the Android phone. * This socket thread does not listen/read any inputs from the * Android after authentication. It simply pushes any updates from * the database through the output stream of the socket * */ private class PushSocketThread extends SocketThread { /** * A blocking queue that queues up new routes from the database */ private BlockingDeque<Route> routeQueue; public PushSocketThread(Socket socket) { super(socket); routeQueue = new LinkedBlockingDeque<Route>(); } /* * (non-Javadoc) * * @see java.lang.Thread#run() * * Execution method of the PushSocketThread */ public void run() { // Authenticates this socket thread authenticate(); if (authenticated) { // Stores itself in a map that's keeping track of all the logged // in couriers and the threads associated with them pushMap.put(username, this); pushCheckListPair(); pushInitialRoute(); while (authenticated && threading) { try { writeObject(routeQueue.take()); } catch (InterruptedException e) { connectionLost("PushSocketThread interrupted"); } } pushMap.remove(username); } closeSocket(); } /** * @param route * Route object to be queued */ public void queueRoute(Route route) { routeQueue.offer(route); } /** * Sends the beginning/ending shift check list to the Android */ public void pushCheckListPair() { if (authenticated) { String err = "Failed to push CheckListPair due to ("; try { CheckListPair clp = AwesomeCoreHandler.getCheckLists(); if (clp != null) { writeObject(clp); } else { writeObject(new Exception("No CheckListPair")); err += "No CheckListPair)"; connectionLost(err); } } catch (IllegalStateException e) { err += "No database connection)"; connectionLost(err); } } } /** * Sends the initial route to the Android */ public void pushInitialRoute() { if (authenticated) { String err = "Failed to push initial route due to ("; try { Route route = AwesomeCoreHandler .getRouteWithPackages(username); if (route != null) { writeObject(route); } else { writeObject(new Exception("No route")); err += "No route)"; connectionLost(err); } } catch (IllegalStateException e) { err += "No database connection)"; connectionLost(err); } } } } /** * @author Jesse Jeng * * Thread that handles requests sent from the Android, it is always * listening for requests. Sends back objects depending on what was * received from the Android * */ private class ListenSocketThread extends SocketThread { public ListenSocketThread(Socket socket) { super(socket); } /* * (non-Javadoc) * * @see java.lang.Thread#run() * * Execution method of ListenSocketThread */ public void run() { // Authenticates this socket/thread authenticate(); if (authenticated) { // Stores itself in a map that's keeping track of all the logged // in couriers and the threads associated with them listenMap.put(username, this); while (authenticated && threading) { Object input = readObject(); if (input instanceof Barcode) { updateBarcode((Barcode) input); } else if (input instanceof GPS) { updateGPS((GPS) input); } else if (input instanceof ClientSite) { sendShippingList((ClientSite) input); } else { if (authenticated) { writeObject(new Exception("Unknown")); } } } // Because the push thread is being blocked by the blocking // queue, this listen thread needs to be the one interrupting // the block. The two threads are linked by a common username SocketThread t = pushMap.get(username); if (t != null) { t.interrupt(); } listenMap.remove(username); } closeSocket(); } /** * Updates the database that the status of the given barcode(package) * has been picked up by the associated courier * * @param input * Barcode to be updated */ private void updateBarcode(Barcode input) { String barcode = input.barcode; if (AwesomeCoreHandler.pickedUp(barcode, username)) { writeObject("Success"); } else { writeObject(new Exception("Failure")); } } /** * Updates GPS location in the database for the associated courier * * @param input * GPS object that contains latitude and longitude */ private void updateGPS(GPS input) { double latitude = input.latitude; double longitude = input.longitude; AwesomeCoreHandler.updateGPS(username, latitude, longitude); writeObject("Success"); } /** * Gets a list of shipping information from the database associated with * the given client site and then sends to the Android * * @param input * ClientSite object that will be used to determine the * associated shipping list */ private void sendShippingList(ClientSite input) { List<ShippingInformation> shippingList = AwesomeCoreHandler .specimenFrom(input); if (shippingList != null) { writeObject(new ShippingList(shippingList)); } else { writeObject(new Exception("Failure")); } } } }
Java
package jvm.jtacck.logging; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * An OutputStream that writes contents to a Logger upon each call to flush() * * Credit: Nick Stephen * http://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and */ public class LoggingOutputStream extends ByteArrayOutputStream { private String lineSeparator; private Logger logger; private Level level; /** * Constructor * @param logger Logger to write to * @param level Level at which to write the log message */ public LoggingOutputStream(Logger logger, Level level) { super(); this.logger = logger; this.level = level; lineSeparator = System.getProperty("line.separator"); } /** * upon flush() write the existing contents of the OutputStream to the logger as * a log record. * @throws java.io.IOException in case of error */ public void flush() throws IOException { String record; synchronized(this) { super.flush(); record = this.toString(); super.reset(); } if (record.trim().length() == 0 || record.equals(lineSeparator)) { // avoid empty records return; } logger.logp(level, "", "", record); } }
Java
package jvm.jtacck.logging; import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.util.logging.Level; /** * Class defining 2 new Logging levels, one for STDOUT, one for STDERR, used * when multiplexing STDOUT and STDERR into the same rolling log file via the * Java Logging APIs. * * Credit: Nick Stephen * http://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and */ public class StdOutErrLevel extends Level { private static final long serialVersionUID = -5145526949544714699L; /** * Private constructor */ private StdOutErrLevel(String name, int value) { super(name, value); } /** * Level for STDOUT activity. */ public static Level STDOUT = new StdOutErrLevel("STDOUT", Level.INFO.intValue() + 53); /** * Level for STDERR activity */ public static Level STDERR = new StdOutErrLevel("STDERR", Level.INFO.intValue() + 54); /** * Method to avoid creating duplicate instances when deserializing the * object. * * @return the singleton instance of this <code>Level</code> value in this * classloader * @throws ObjectStreamException * If unable to deserialize */ protected Object readResolve() throws ObjectStreamException { if (this.intValue() == STDOUT.intValue()) return STDOUT; if (this.intValue() == STDERR.intValue()) return STDERR; throw new InvalidObjectException("Unknown instance :" + this); } }
Java
package jvm.jtacck; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.FileHandler; import java.util.logging.Filter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; import jvm.jtacck.logging.LoggingOutputStream; import jvm.jtacck.logging.StdOutErrLevel; import jvm.jtacck.test.db.ScriptRunner; /** * TODO Doc */ /** * @author Cody Schroeder * */ public final class Util { /** A utility logger meant for system-wide use. */ public static final Logger logger = Logger.getLogger("Global"); /** The value of System.out on this class' static instantiation. */ public static final PrintStream stdout = System.out; /** The value of System.err on this class' static instantiation. */ public static final PrintStream stderr = System.err; public static String sqlPath; public static ScriptRunner sr; static { // Set logging to use a file as well. try { FileHandler fileHandler = new FileHandler("jtacck-server%u.log", true); fileHandler.setFormatter(new SimpleFormatter()); logger.addHandler(fileHandler); } catch (Exception e) { logger.severe("FileHandler for Logger could not be attached."); } } /** * Replaces System.out and System.err with streams that redirect to both * {@link logger} and their respective streams with the {@link Level}s * {@link StdOutErrLevel#STDOUT} and {@link StdOutErrLevel#STDERR}, * respectively. */ public static void logStdOutErr() { // Remove global handlers that deal with streams (System.out/err). Logger globalLogger = Logger.getAnonymousLogger().getParent(); for (Handler h : globalLogger.getHandlers()) if (h instanceof StreamHandler) globalLogger.removeHandler(h); // Force stdout/stderr into the logger. OutputStream los = new LoggingOutputStream(logger, StdOutErrLevel.STDOUT); System.setOut(new PrintStream(los, true)); los = new LoggingOutputStream(logger, StdOutErrLevel.STDERR); System.setErr(new PrintStream(los, true)); // A simple Filter that only allows an exact Level. final class LevelFilter implements Filter { final Level level; public LevelFilter(Level level) { this.level = level; } public final boolean isLoggable(LogRecord record) { return record.getLevel() == level; } } // Add handlers to logger that will push STDOUT/STDERR levels to their appropriate streams. StreamHandler stdoutHandler = new StreamHandler(stdout, new SimpleFormatter()); stdoutHandler.setLevel(Level.ALL); stdoutHandler.setFilter(new LevelFilter(StdOutErrLevel.STDOUT)); logger.addHandler(stdoutHandler); StreamHandler stderrHandler = new StreamHandler(stderr, new SimpleFormatter()); stderrHandler.setLevel(Level.ALL); stderrHandler.setFilter(new LevelFilter(StdOutErrLevel.STDERR)); logger.addHandler(stderrHandler); } /** * Restores System.out and System.err to their values on this class' static * initialization. This can be used to undo {@link Util#logStdOutErr()}. */ public static void restoreStdOutErr() { System.setOut(stdout); System.setErr(stderr); } /** * @return <code>false</code> iff any Object passed is null */ public static boolean noNulls (Object... os) { for (int i = 0; i < os.length; i++) { if (os[i] == null) { return false; } } return true; } /** * Creates a script runner to run SQL scripts * * @param user * The user of the database * @param password * The password for the user * @param server * The server name of the database * @param port * The port the database is located at * @param name * The name of the database */ private static void makeScriptRunner() { String username = System.getProperty("test.dbuser"); String password = System.getProperty("test.dbpass"); String server = System.getProperty("test.dbserver"); String port = System.getProperty("test.dbport"); String dbname = System.getProperty("test.dbname"); String sqlPath = System.getProperty("test.dbsqlpath"); Util.sqlPath = sqlPath; String dbAddress = server+":"+port+"/"+dbname; sr = null; try { Class.forName("org.postgresql.Driver"); Connection dbConn = DriverManager.getConnection("jdbc:postgresql://" + dbAddress, username, password); sr = new ScriptRunner(dbConn, false, true); sr.setLogWriter(null); } catch (Exception e) { e.printStackTrace(); } } /** * Runs the given sql script in the database. It assumes the file is located * with the path given by the System Property "test.dbsqlpath". * * @param sr * The ScriptRunner to run the script with * @param filename * the name of the script to run. * * @throws SQLException * @throws IOException * @throws FileNotFoundException */ public static void runScript(String filename) throws FileNotFoundException, IOException, SQLException { if (sr == null) { makeScriptRunner(); } sr.runScript(new BufferedReader(new FileReader(sqlPath + File.separator + filename))); } /** * Runs the setup scripts for the web site test suite. * @throws FileNotFoundException * @throws IOException * @throws SQLException */ public static void setUp() throws FileNotFoundException, IOException, SQLException { setUp("small-test.sql"); } /** * Runs the generic setup script and a customized setup script given by * filename * @param filename * The name of the script to run. Must be in the 'sqlpath' * directory * @throws FileNotFoundException * @throws IOException * @throws SQLException */ public static void setUp(String filename) throws FileNotFoundException, IOException, SQLException { runScript("setup.sql"); runScript(filename); } /** * Runs the teardown.sql that removes all the tables from the database. This * allows for a fresh database to be created for the next test. * @throws SQLException * @throws IOException * @throws FileNotFoundException */ public static void tearDown() throws FileNotFoundException, IOException, SQLException { runScript("teardown.sql"); } }
Java
package jvm.jtacck.db; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.sql.SQLException; import jvm.jtacck.AndroidServer; import jvm.jtacck.db.records.*; import jvm.jtacck.serials.Route; import static jvm.jtacck.Util.*; /** * AwesomeCoreHandler(ACH) represents an interface over the PostgresHandler. The * purpose of ACH is to provide a useful interface to the servers so that data * can be sent as Strings and ints rather than the Record objects used by the * PostgresHandler. This interface also provides, in addition to the general * getters, more specific getters that have been specially tailored to the needs * of the server. * * @author Andrew Lau * * @see jvm.jtacck.db.PostgresHandler * */ public final class AwesomeCoreHandler { /** * A list of Android servers that can be used. */ private final static List<AndroidServer> server = new LinkedList<AndroidServer>(); /** * The handler used to connect to the database. */ private static PostgresHandler dbConnection = null; /** * A filler variable used for variables that are automatically generated. */ private final static int FILLER = 1; /** * Adds an Android Server to the current list of servers. * * @param serv * - reference to an Android Server. */ synchronized public static void setServer(AndroidServer serv) { if (serv != null && !server.contains(serv)) { server.add(serv); } } /** * Attempts to create a new connection to the database with the given * username, password, and database address. * * @param username * - username for the PostgresHandler * @param password * - password that corresponds to the username. * @param dbAddress * - address of the database. Must be of the format * [server]:[port]/[databasename]. * * @return Returns true if a connection to the database has been made. * Otherwise, returns false. */ public static boolean createConnection(String username, String password, String dbAddress) { try { dbConnection = new PostgresHandler(username, password, dbAddress); return true; } catch (SQLException e) { logger.info("Connection to database couldn't be made"); return false; } } /** * Attempts to close the connection with the database. * * @return Returns true if the connection to the database has been closed. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database */ public static boolean closeConnection() throws IllegalStateException { noConnection(); try { dbConnection.close(); return true; } catch (SQLException e) { logger.info("Connection to database already closed"); return false; } } // ---------------------------------------------------------------------------- // Methods that add to the database // ---------------------------------------------------------------------------- /** * Attempts to add a client site to the database. * * @param name * - name of the client site * @param hospital * - the id of hospital associated to the client site. * @param instructions * - instructions of what to do at the client site. Intended for * couriers * @param phone * - phone number of the client site * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean addClientSite(String name, int hospital_id, List<String> instructions, String phone) throws IllegalStateException, IllegalArgumentException { noConnection(); Hospital hospital = getHospital(hospital_id); if (noNulls(hospital, instructions, phone, name) && lengthChecker(name)) { try { dbConnection.addRecord(new ClientSite(FILLER, name, hospital, instructions, phone)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "One or more arguments were null or name was too short"); } } /** * Attempts to add a courier to the database. * * @param username * - the username of the user who is being assigned as a courier * @param password * - the password assigned to the username * @param first * - the first name of the person * @param last * - the last name of the person * @param site_id * - the id of the client site the person is assigned to * @param type_id * - the id of the type the person is * @param client_id_route * - the id of client sites of the route the courier is assigned * to * @param lat * - The latitude of the current user based on the Android GPS * @param longit * - The longitude of the current user based on the Android GPS * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean addCourier(String username, String password, String first, String last, int site_id, int type_id, List<Integer> client_id_route) throws IllegalStateException, IllegalArgumentException { noConnection(); if (client_id_route != null) { List<ClientSite> temp = new LinkedList<ClientSite>(); for (Integer i : client_id_route) { if (getClientSite(i) == null) { throw new IllegalArgumentException("Invalid destination " + i); } temp.add(getClientSite(i)); } try { dbConnection.addRecord(new Courier(new User(username, password, first, last, getClientSite(site_id), getUserType(type_id)), temp, 0, 0, temp.size() == 0 ? null : temp.get(0))); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Route or username is null."); } } /** * Attempts to add a hospital to the database. * * @param name * - name of the hospital * @param address * - address of the hospital in the form: [Address 1], [Address * 2], [City], [State], [ZipCode] * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean addHospital(String name, String address) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(name, address) && lengthChecker(name, address)) { try { dbConnection.addRecord(new Hospital(FILLER, name, address)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or address is invalid"); } } /** * Adds an item to the given specimen. Use this to add a item to the * existing item collection of a specimen. * * @param barcode * - barcode of the specimen * @param name * - name of the item * @param color * - color of the item (or its cap) * * @return Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if there is an invalid argument */ public static boolean addItemToSpecimen(String barcode, String name, String color) throws IllegalStateException, IllegalArgumentException { noConnection(); if (getShippingInfo(barcode) == null) { throw new IllegalArgumentException("Invalid barcode"); } if (noNulls(name, color) && lengthChecker(name, color) && barcode.length() > 0) { try { Specimen old = dbConnection.getSpecimenByID(barcode); Collection<Item> temp = new LinkedList<Item>(); temp.addAll(old.contents); temp.add(new Item(FILLER, name, color)); Specimen replace = new Specimen(old.barcode, old.description, old.requirements, temp); dbConnection.changeRecord(replace); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "Name or color is invalid or barcode is less than 0."); } } /** * Attempts to add a Status into the database. * * @param name * - the name of the status * @param desc * - the description of the status * * @return Returns true if addition was successful. Otherwise, returns * false. * * @throws IllegalStateException * if there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean addStatus(String name, String desc) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(name, desc) && lengthChecker(name, desc)) { try { dbConnection.addRecord(new Status(FILLER, name, desc)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or description is invalid"); } } /** * Attempts to add shipping information to the database. * * @param barcode * - a barcode used to identify the specimen * @param reqs * - any requirements associated to the specimen * @param instructions * - any instructions needed for the specimen * @param items * - a collection of items within the specimen package * @param username * - the username of the person adding the specimen info * @param dest * - an id representing a client site destination * @param status * - an id representing a status type * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if there is an invalid argument */ public static boolean addShippingInformation(String barcode, String desc, String reqs, Map<String, List<String>> items, String username, int dest) throws IllegalStateException, IllegalArgumentException { noConnection(); if (getShippingInfo(barcode) != null || items == null) { throw new IllegalArgumentException("Duplicate barcode exists" + " or null items"); } Collection<Item> actualItems = new LinkedList<Item>(); if (!items.isEmpty()) { for (String s : items.keySet()) { for (String t : items.get(s)) { actualItems.add(new Item(FILLER, s, t)); } } } if (noNulls(reqs, desc, username, getUser(username), getClientSite(dest)) && !barcode.isEmpty() && !actualItems.isEmpty()) { try { Specimen s_temp = new Specimen(barcode, desc, reqs, actualItems); dbConnection.addRecord(new ShippingInformation(s_temp, getUser(username), getClientSite(dest), getStatus(1), null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "Null strings detected, ivalid username/destination or " + "barcode is less than 1."); } } /** * Attempts to add a user to the database. If the user is of type courier, * then the user will be automatically created a courier record. * * @param username * - The username of the person being added * @param password * - The password associated to the username * @param first * - The first name of the person * @param last * - The last name of the person * @param site_id * - A client site that the person is assigned to * @param type_id * - A user type regarding the person's privileges * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the arguments are not valid such as being null */ public static boolean addUser(String username, String password, String first, String last, int site_id, int type_id) throws IllegalStateException, IllegalArgumentException { noConnection(); ClientSite cs = getClientSite(site_id); UserType type = getUserType(type_id); if (noNulls(username, password, first, last, cs, type) && lengthChecker(username, password, first, last)) { if (getUser(username) != null) { return false; } try { dbConnection.addRecord(new User(username, password, first, last, cs, type)); if (type.type_id == 5) { return addCourier(username, password, first, last, site_id, type_id, new LinkedList<Integer>()); } return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("One or more of the parameters" + " are invalid. Input must not be empty."); } } /** * Attempts to add a User Type into the database. * * @param name * - the name of the user type * @param desc * - the description of the user type * * @return Returns true if addition was successful. Otherwise, returns * false. * * @throws IllegalStateException * if there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean addUserType(String name, String desc) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(name, desc) && lengthChecker(name, desc)) { try { dbConnection.addRecord(new UserType(FILLER, name, desc)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or description is invalid"); } } // ------------------------------------------------------------------------- // // Methods that modify items in the database // // ------------------------------------------------------------------------- // //////////////////////////////////////////// // // Check list // // //////////////////////////////////////////// /** * Attempts to modify a check list in the database. * * @param start * - the starting check list * @param end * - the ending check list * * @return Returns true if modification was successful. Otherwise, returns * false. * @throws IllegalStateException * if the there is no connection to the database */ public static boolean changeCheckList(List<String> start, List<String> end) throws IllegalStateException { noConnection(); CheckListPair temp = getCheckLists(); try { if (start == null) { start = temp.startingList; } if (end == null) { end = temp.endingList; } dbConnection.changeRecord(new CheckListPair(start, end)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } /** * Attempts to modify the starting check list. If passed null, will do * nothing. * * @param start * - the new starting check list * * @return Returns true if modification is successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database */ public static boolean changeStartingList(List<String> start) throws IllegalStateException { return start == null || changeCheckList(start, null); } /** * Attempts to modify the ending check list. If passed null, will do * nothing. * * @param start * - the new ending check list * * @return Returns true if modification is successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database */ public static boolean changeEndingList(List<String> end) throws IllegalStateException { return end == null || changeCheckList(null, end); } // //////////////////////////////////////////// // // ClientSite // // //////////////////////////////////////////// /** * Attempts to modify a client site to the database. * * @param cs_id * - the id of the client site * @param name * - name of the client site * @param hospital_id * - the id of hospital associated to the client site. SHOULD NOT * BE MODIFIABLE BY END USER. * @param instructions * - instructions of what to do at the client site. Intended for * couriers * @param phone * - phone number of the client site * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeClientSite(int cs_id, String name, int hospital_id, List<String> instructions, String phone) throws IllegalStateException, IllegalArgumentException { noConnection(); Hospital hospital = getHospital(hospital_id); ClientSite cs = getClientSite(cs_id); if (noNulls(hospital, cs, instructions, phone, name) && !name.isEmpty()) { try { dbConnection.changeRecord(new ClientSite(cs_id, name, hospital, instructions, phone)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "One or more arguments were null or name was too short"); } } /** * Attempts to modify the name of a client site. * * @param cs_id * - the id of the client site * @param name * - the new name of the client site * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeClientSiteName(int cs_id, String name) throws IllegalStateException, IllegalArgumentException { ClientSite temp = getClientSite(cs_id); if (temp != null) { return changeClientSite(cs_id, name, temp.hospital.hospital_id, temp.instructions, temp.phone_number); } else { return false; } } /** * Attempts to modify check list associated to a client site. * * @param cs_id * - the id of the client site * @param instructions * - instructions of what to do at the client site. Intended for * couriers * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeClientSiteList(int cs_id, List<String> instructions) throws IllegalStateException, IllegalArgumentException { if (noNulls(instructions, getClientSite(cs_id))) { ClientSite temp = getClientSite(cs_id); return changeClientSite(cs_id, temp.name, temp.hospital.hospital_id, instructions, temp.phone_number); } else { throw new IllegalArgumentException( "One or more arguments were null or name was too short"); } } /** * Attempts to modify the phone number of a client site. * * @param cs_id * - the id of the client site * @param phone * - the new phone number of the client site * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeClientSitePhone(int cs_id, String phone) throws IllegalStateException, IllegalArgumentException { ClientSite temp = getClientSite(cs_id); if (temp != null) { return changeClientSite(cs_id, temp.name, temp.hospital.hospital_id, temp.instructions, phone); } else { return false; } } // //////////////////////////////////////////// // // Courier // // //////////////////////////////////////////// /** * Attempts to modify a courier to the database. * * @param username * - the username of the user who is being assigned as a courier. * THIS SHOULD NOT BE MODIFIABLE BY END USER. * @param password * - the password assigned to the username * @param first * - the first name of the person * @param last * - the last name of the person * @param site_id * - the id of the client site the person is assigned to * @param type_id * - the id of the type the person is * @param client_id_route * - the id of client sites of the route the courier is assigned * to * @param lat * - The latitude of the current user based on the Android GPS * @param longit * - The longitude of the current user based on the Android GPS * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeCourier(String username, String password, String first, String last, int site_id, int type_id, List<Integer> client_id_route) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(username, password, first, last, client_id_route, getUser(username), getCourierInfo(username)) && lengthChecker(username, password, first, last)) { List<ClientSite> temp = new LinkedList<ClientSite>(); for (Integer i : client_id_route) { if (getClientSite(i) == null) { throw new IllegalArgumentException("Invalid destination " + i); } temp.add(getClientSite(i)); } Courier old = getCourierInfo(username); ClientSite cs = null; if ((old.nextDest == null || !temp.contains(old.nextDest)) && !temp.isEmpty()) { cs = temp.get(0); } else if (temp.contains(old.nextDest)) { cs = old.nextDest; } try { dbConnection.changeRecord(new Courier(new User(username, password, first, last, getClientSite(site_id), getUserType(type_id)), temp, old.latitude, old.longitude, cs)); server.get(0).pushRoute(username, getRouteWithPackages(username)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("One or more strings are null " + "or of empty length"); } } /** * Attempts to modify a route assigned to a courier in the database. * * @param username * - the username of the user who is being assigned as a courier. * THIS SHOULD NOT BE MODIFIABLE BY END USER. * @param client_id_route * - the id of client sites of the route the courier is assigned * to * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeCourierRoute(String username, List<Integer> client_id_route) throws IllegalStateException, IllegalArgumentException { if (noNulls(username, client_id_route, getCourierInfo(username))) { Courier old = getCourierInfo(username); return changeCourier(username, old.user.password, old.user.fname, old.user.lname, old.user.site.client_id, old.user.type.type_id, client_id_route); } else { throw new IllegalArgumentException("One or more strings are null " + "or of empty length"); } } // //////////////////////////////////////////// // // Hospital // // //////////////////////////////////////////// /** * Attempts to modify a hospital to the database. * * @param hospital_id * - id of the hospital being modified. THIS SHOULD NOT BE * MODIFIABLE BY END USER. * @param name * - name of the hospital * @param address * - address of the hospital in the form: [Address 1], [Address * 2], [City], [State], [ZipCode] * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean changeHospital(int hospital_id, String name, String address) throws IllegalStateException, IllegalArgumentException { noConnection(); Hospital hospital = getHospital(hospital_id); if (noNulls(hospital, name, address) && lengthChecker(name, address)) { try { dbConnection.changeRecord(new Hospital(hospital_id, name, address)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or address is invalid"); } } /** * Attempts to modify the name of a hospital. * * @param h_id * - the id of the hospital * @param name * - the new name of the hospital * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeHospitalName(int h_id, String name) throws IllegalStateException, IllegalArgumentException { Hospital temp = getHospital(h_id); if (temp != null) { return changeHospital(h_id, name, temp.address); } else { return false; } } /** * Attempts to modify the address of a hospital. * * @param h_id * - the id of the hospital * @param address * - the new address of the hospital in the form: [Address 1], * [Address 2], [City], [State], [ZipCode] * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeHospitalAddress(int h_id, String address) throws IllegalStateException, IllegalArgumentException { Hospital temp = getHospital(h_id); if (temp != null) { return changeHospital(h_id, temp.name, address); } else { return false; } } // //////////////////////////////////////////// // // Status // // //////////////////////////////////////////// /** * Attempts to modify a status in the database. * * @param id * - the id of the status * @param name * - the name of the status * @param desc * - the description of the status * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeStatus(int id, String name, String desc) throws IllegalStateException, IllegalArgumentException { noConnection(); Status temp = getStatus(id); if (noNulls(temp, name, desc) && lengthChecker(name, desc)) { try { dbConnection.changeRecord(new Status(id, name, desc)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or description is invalid"); } } /** * Attempts to modify the name of a status in the database. * * @param id * - the id of the status * @param name * - the name of the status * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeStatusName(int id, String name) throws IllegalStateException, IllegalArgumentException { Status temp = getStatus(id); if (temp != null) { return changeStatus(id, name, temp.description); } else { return false; } } /** * Attempts to modify the description of a status in the database. * * @param id * - the id of the status * @param desc * - the description of the status * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeStatusDesc(int id, String desc) throws IllegalStateException, IllegalArgumentException { Status temp = getStatus(id); if (temp != null) { return changeStatus(id, temp.name, desc); } else { return false; } } // //////////////////////////////////////////// // // Shipping Information // // //////////////////////////////////////////// /** * Attempts to modify shipping information to the database. This method can * not be used to change a specimen package. To add items to a shipping * information, please use the addItemsToSpec method. To update the specimen * use the changeSpecimenInfo method. * * @param barcode * - a barcode used to identify the specimen. SHOULD NOT BE * MODIFIABLE BY END USER. * @param username * - the username of the person adding the specimen info * @param dest * - an id representing a client site destination * @param status * - an id representing a status type * @param cour * - the username of the courier to be assigned * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if there is an invalid argument */ public static boolean changeShippingInformation(String barcode, String username, int dest, int status, String cour) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(username, getUser(username), getClientSite(dest)) && !barcode.isEmpty()) { try { Courier c_temp = getCourierInfo(cour); ShippingInformation temp = getShippingInfo(barcode); Status newStatus = getStatus(status); if (!noNulls(newStatus)) { throw new IllegalArgumentException( "Invalid barcode or courier"); } dbConnection.changeRecord(new ShippingInformation( temp.specimen, getUser(username), getClientSite(dest), newStatus, c_temp)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "Null strings detected, ivalid username/destination or " + "barcode is less than 1."); } } /** * Attempts to modify the shipper associated to the shipping information. * * @param barcode * - the barcode associated to the shipping information * * @param username * - the username of the new shipper * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeShippingInformationShipper(String barcode, String username) throws IllegalStateException, IllegalArgumentException { ShippingInformation temp = getShippingInfo(barcode); if (temp != null) { return changeShippingInformation(barcode, username, temp.destination.client_id, temp.status.status_id, temp.courier.user.username); } else { return false; } } /** * Attempts to modify the destination associated to the shipping * information. * * @param barcode * - the barcode associated to the shipping information * * @param destination * - the new destination of the package * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeShippingInformationDestination(String barcode, int dest) throws IllegalStateException, IllegalArgumentException { ShippingInformation temp = getShippingInfo(barcode); if (temp != null) { return changeShippingInformation(barcode, temp.shipper.username, dest, temp.status.status_id, temp.courier.user.username); } else { return false; } } /** * Attempts to modify the courier associated to the shipping information. * * @param barcode * - the barcode associated to the shipping information * * @param courier * - the new courier assigned to the package * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeShippingInformationCourier(String barcode, String cour) throws IllegalStateException, IllegalArgumentException { ShippingInformation temp = getShippingInfo(barcode); if (temp != null) { return changeShippingInformation(barcode, temp.shipper.username, temp.destination.client_id, temp.status.status_id, cour); } else { return false; } } // //////////////////////////////////////////// // // Specimen Info // // //////////////////////////////////////////// /** * Attempts to modify a specimen in the database. Use this to update * existing specimen data. * * @param barcode * - the barcode of the Specimen being modified. SHOULD NOT BE * MODIFIABLE BY THE END USER. * @param desc * - the description of the Specimen * @param requirements * - the requirements of shipping for the Specimen * @param contents * - the contents of the Specimen * * @returns Returns true if the addition to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if there is an invalid argument */ public static boolean changeSpecimenInfo(String barcode, String desc, String requirements, Map<Integer, List<String>> items) throws IllegalStateException, IllegalArgumentException { noConnection(); // TODO : change Map<Integer, List<String>> Collection<Item> temp = new LinkedList<Item>(); for (Integer i : items.keySet()) { temp.add(new Item(i, items.get(i).get(0), items.get(i).get(1))); } if (noNulls(desc, requirements) && !barcode.isEmpty() && !temp.isEmpty()) { try { dbConnection.changeRecord(new Specimen(barcode, desc, requirements, temp)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Description or requirements" + "is empty"); } } // //////////////////////////////////////////// // // User // // //////////////////////////////////////////// /** * Attempts to modify a user to the database. * * @param username * - The username of the person being added. SHOULD NOT BE * MODIFIABLE BY END USER. * @param password * - The password associated to the username * @param first * - The first name of the person * @param last * - The last name of the person * @param site_id * - A client site that the person is assigned to * @param type_id * - A user type regarding the person's privileges * * @returns Returns true if the modification to the database was successful. * Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the arguments are not valid such as being null */ public static boolean changeUser(String username, String password, String first, String last, int site_id, int type_id) throws IllegalStateException, IllegalArgumentException { noConnection(); ClientSite cs = getClientSite(site_id); UserType type = getUserType(type_id); if (noNulls(username, password, first, last, cs, type) && lengthChecker(username, password, first, last)) { if (getUser(username) == null) { return false; } try { dbConnection.changeRecord(new User(username, password, first, last, cs, type)); if (type.type_id == 5) { return addCourier(username, password, first, last, site_id, type_id, new LinkedList<Integer>()); } else if (type.type_id != 5 && getCourierInfo(username) != null) { return removeCourier(username); } return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("One or more of the parameters" + " are invalid. Input must not be empty."); } } /** * Attempts to modify the password of a user. * * @param username * - the id of the client site * @param password * - the new password * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserPassword(String username, String password) throws IllegalStateException, IllegalArgumentException { User temp = getUser(username); if (temp != null) { return changeUser(username, password, temp.fname, temp.lname, temp.site.client_id, temp.type.type_id); } else { return false; } } /** * Attempts to modify the first and last name of a user. * * @param username * - the id of the client site * @param fname * - first name of the user * @param lname * - last name of the user * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserFirstLastName(String username, String fname, String lname) throws IllegalStateException, IllegalArgumentException { User temp = getUser(username); if (temp != null) { return changeUser(username, temp.password, fname, lname, temp.site.client_id, temp.type.type_id); } else { return false; } } /** * Attempts to modify the client site of a user. * * @param username * - the id of the client site * @param cs * - the new client site associated to the user * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserClientSite(String username, int cs) throws IllegalStateException, IllegalArgumentException { User temp = getUser(username); if (temp != null) { return changeUser(username, temp.password, temp.fname, temp.lname, cs, temp.type.type_id); } else { return false; } } /** * Attempts to modify the type of a user. * * @param username * - the id of the client site * @param type * - the new type of the user * * @return Returns true if modification was successful. Otherwise, false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserStatus(String username, int type) throws IllegalStateException, IllegalArgumentException { User temp = getUser(username); if (temp != null) { return changeUser(username, temp.password, temp.fname, temp.lname, temp.site.client_id, type); } else { return false; } } // //////////////////////////////////////////// // // UserType // // //////////////////////////////////////////// /** * Attempts to modify a user type in the database. * * @param id * - the id of the user type * @param name * - the name of the user type * @param desc * - the description of the user type * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserType(int id, String name, String desc) throws IllegalStateException, IllegalArgumentException { noConnection(); Status temp = getStatus(id); if (noNulls(temp, name, desc) && lengthChecker(name, desc)) { try { dbConnection.changeRecord(new UserType(id, name, desc)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Name or description is invalid"); } } /** * Attempts to modify the name of a user type in the database. * * @param id * - the id of the user type * @param name * - the name of the user type * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserTypeName(int id, String name) throws IllegalStateException, IllegalArgumentException { UserType temp = getUserType(id); if (temp != null) { return changeUserType(id, name, temp.description); } else { return false; } } /** * Attempts to modify the description of a user type in the database. * * @param id * - the id of the user type * @param desc * - the description of the user type * * @return Returns true if modification was successful. Otherwise, returns * false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean changeUserTypeDesc(int id, String desc) throws IllegalStateException, IllegalArgumentException { UserType temp = getUserType(id); if (temp != null) { return changeUserType(id, temp.name, desc); } else { return false; } } // ---------------------------------------------------------------------------- // Methods that remove items in the database // ---------------------------------------------------------------------------- /** * Attempts to remove a client site from the database. * * @param id * - id of the client site * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean removeClientSite(int id) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(getClientSite(id))) { try { dbConnection.removeRecord(new ClientSite(id, null, null, null, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("ID is invalid"); } } /** * Attempts to remove a courier from the database. * * @param username * - the username of the user who is being removed as a courier. * THIS SHOULD NOT BE MODIFIABLE BY END USER. * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if one of the parameters are invalid */ public static boolean removeCourier(String username) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(username, getCourierInfo(username))) { try { dbConnection.removeRecord(new Courier(new User(username, null, null, null, null, null), null, 0, 0, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "Username is invalid or user is not a courier"); } } /** * Attempts to remove a hospital from the database. * * @param hospital_id * - id of the hospital being modified. THIS SHOULD NOT BE * MODIFIABLE BY END USER. * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean removeHospital(int hospital_id) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(getHospital(hospital_id))) { try { dbConnection .removeRecord(new Hospital(hospital_id, null, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("ID is invalid"); } } /** * Attempts to remove shipping information from the database. * * @param barcode * - a barcode used to identify the specimen. SHOULD NOT BE * MODIFIABLE BY END USER. * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if there is an invalid argument */ public static boolean removeShippingInformation(String barcode) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(barcode, getShippingInfo(barcode))) { try { dbConnection.changeRecord(getShippingInfo(barcode)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException( "Null strings detected, ivalid username/destination or " + "barcode is less than 1."); } } /** * Attempts to remove a status from the database. * * @param id * - id of the status to be removed * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean removeStatus(int id) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(getStatus(id))) { try { dbConnection.removeRecord(new Status(id, null, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("ID is invalid"); } } /** * Attempts to remove a user from the database. * * @param username * - The username of the person being added. SHOULD NOT BE * MODIFIABLE BY END USER. * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the arguments are not valid such as being null */ public static boolean removeUser(String username) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(username, getUser(username))) { try { dbConnection.removeRecord(new User(username, null, null, null, null, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("Username is invalid"); } } /** * Attempts to remove a user type from the database. * * @param id * - id of the user type to be removed * * @return Returns true if removal was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database * @throws IllegalArgumentException * if the parameters are invalid */ public static boolean removeUserType(int id) throws IllegalStateException, IllegalArgumentException { noConnection(); if (noNulls(getUserType(id))) { try { dbConnection.removeRecord(new UserType(id, null, null)); return true; } catch (SQLException e) { logger.info(e.toString()); return false; } } else { throw new IllegalArgumentException("ID is invalid"); } } // ------------------------------------------------------------------------- // // Methods that retrieve information from the database // // ------------------------------------------------------------------------- /** * Attempts to retrieve information related to the username and password. * * @param username * The username of the person whose information is being looked * up * @param password * The password associated to the username * @return Returns the User object associated to the given username and * password. If no username and/or password combination is in the * database, returns null. */ public static User getUserInfo(String username, String password) { noConnection(); if (noNulls(username, password) && lengthChecker(username, password)) { return dbConnection.login(username, password); } else { return null; } } /** * Attempts to retrieve the user type of the given username. * * @param username * - the username to be looked up * * @return Returns the <code>UserType</code> object corresponding to the * given username, if applicable. Otherwise, returns <code>null * </code> */ public static UserType getUserType(String username) { noConnection(); try { if (username != null && !username.isEmpty()) { return dbConnection.getUserType(username); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); } return null; } /** * Attempts to retrieve the courier corresponding to the username. * * @param username * - the username to be looked up * * @return Returns the <code>Courier</code> object corresponding to the * given username, if applicable. Otherwise, returns <code>null * </code> */ public static Courier getCourierInfo(String username) { noConnection(); try { if (username != null && !username.isEmpty()) { return dbConnection.getCourierByID(username); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve the courier corresponding to the username. * * @param username * - the username to be looked up * * @return Returns the <code>Courier</code> object corresponding to the * given username, if applicable. Otherwise, returns <code>null * </code> */ public static List<ClientSite> getRoute(String username) { noConnection(); Courier temp = getCourierInfo(username); if (temp != null) { return temp.route; } else { return null; } } /** * Attempts to retrieve the shipping information containing the given bar * code. * * @param barcode * - the bar code to be looked up * * @return Returns the <code>ShippingInformation</code> object corresponding * to the given username, if applicable. Otherwise, returns * <code>null</code> */ public static ShippingInformation getShippingInfo(String barcode) { noConnection(); try { if (barcode != null && !barcode.isEmpty()) { return dbConnection.getShippingInfoFor(barcode); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve the specimen containing the given bar code. * * @param barcode * - the bar code to be looked up * * @return Returns the <code>Specimen</code> object corresponding to the * given username, if applicable. Otherwise, returns <code>null * </code> */ public static Specimen getSpecimen(String barcode) { noConnection(); try { if (barcode != null && !barcode.isEmpty()) { return dbConnection.getSpecimenByID(barcode); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve shipping information from a client site. * * @param c * - the ClientSite to be looked up * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the shipping information for the given client * site. Otherwise, returns <code>null</code> */ public static List<ShippingInformation> specimenFrom(ClientSite c) { noConnection(); try { if (c != null) { return dbConnection.specimensFrom(c); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve shipping information from a client site. * * @param c * - the ClientSite to be looked up * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the shipping information for the given client * site. Otherwise, returns <code>null</code> */ public static List<ShippingInformation> specimensTo(ClientSite c) { noConnection(); try { if (c != null) { return dbConnection.specimensTo(c); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all shipping information in the database. * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the shipping information in the database. * Otherwise, returns <code>null</code> */ public static List<ShippingInformation> getAllShippingInformation() { noConnection(); try { return dbConnection.getAllShippingInformation(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all client sites in the database. * * @return Returns a <code>List&lt;ClientSite&gt;</code> object containing * all the client sites in the database. Otherwise, returns * <code>null</code> */ public static List<ClientSite> getAllClientSites() { noConnection(); try { return dbConnection.getAllClientSites(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all couriers in the database. * * @return Returns a <code>List&lt;Courier&gt;</code> object containing all * the couriers in the database. Otherwise, returns <code>null * </code> */ public static List<Courier> getAllCouriers() { noConnection(); try { return dbConnection.getAllCouriers(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all hospitals in the database. * * @return Returns a <code>List&lt;Hospital&gt;</code> object containing all * the hospitals in the database. Otherwise, returns <code>null * </code> */ public static List<Hospital> getAllHospitals() { noConnection(); try { return dbConnection.getAllHospitals(); } catch (SQLException e) { logger.warning("Should not error here when getting hospitals"); logger.info(e.toString()); return null; } } /** * Attempts to retrieve all user types in the database. * * @return Returns a <code>List&lt;Item&gt;</code> object containing all the * items in the database. Otherwise, returns <code>null</code> */ public static List<Item> getAllItems() { noConnection(); try { return dbConnection.getAllItems(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all specimens in the database. * * @return Returns a <code>List&lt;Specimen&gt;</code> object containing all * the specimens in the database. Otherwise, returns <code>null * </code> */ public static List<Specimen> getAllSpecimens() { noConnection(); try { return dbConnection.getAllSpecimens(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all user types in the database. * * @return Returns a <code>List&lt;UserType&gt;</code> object containing all * the user types in the database. Otherwise, returns <code> * null</code> */ public static List<UserType> getAllUserTypes() { noConnection(); try { return dbConnection.getAllUserTypes(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all users in the database. * * @return Returns a <code>List&lt;User&gt;</code> object containing all the * users in the database. Otherwise, returns <code>null</code> */ public static List<User> getAllUsers() { noConnection(); try { return dbConnection.getAllUsers(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all couriers currently in transit. * * @return Returns a <code>List&lt;Courier&gt;</code> object containing all * the couriers in transit. Otherwise, returns <code>null * </code> */ public static List<Courier> getInTransitCouriers() { List<Courier> temp = getAllCouriers(); List<Courier> inTransit = new LinkedList<Courier>(); for (Courier x : temp) { if (x.longitude != 0.0 && x.latitude != 0.0) { inTransit.add(x); } } return inTransit; } /** * Attempts to retrieve all packages from user. * * @param user * - username of shipping * * @return Return list of ShippingInformation */ public static List<ShippingInformation> getAllShippingByUser(String user) { List<ShippingInformation> ret = new LinkedList<ShippingInformation>(); if (user != null && !user.isEmpty()) { for (ShippingInformation x : getAllShippingInformation()) { if (x.shipper.username.toLowerCase().equals(user.toLowerCase())) { ret.add(x); } } } return ret; } /** * Attempts to retrieve a check list from the database. * * @return Returns a CheckListPair if found. Otherwise, returns null. */ public static CheckListPair getCheckLists() throws IllegalStateException { noConnection(); try { return dbConnection.getCheckLists(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve a user from the database. * * @param username * - username of the person to retrieve * * @return Returns the User associated to the username. Otherwise, returns * null. * */ public static User getUser(String username) { try { if (username != null && !username.isEmpty()) { return dbConnection.getUserByID(username); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve a hospital from the database. * * @param id * - the id of the hospital * * @return Returns the Hospital associated to the ID. Otherwise, returns * null. */ public static Hospital getHospital(int id) { try { if (id > 0) { return dbConnection.getHospitalByID(id); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve a client site from the database. * * @param id * - the id of the client site * * @return Returns the ClientSite associated to the ID. Otherwise, returns * null. */ public static ClientSite getClientSite(int id) { try { if (id > 0) { return dbConnection.getClientSiteByID(id); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve a user type from the database. * * @param id * - the id of the user type * * @return Returns the UserType associated to the ID. Otherwise, returns * null. */ public static UserType getUserType(int id) { try { if (id > 0) { return dbConnection.getUserTypeByID(id); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve a status from the database. * * @param id * - the id of the status * * @return Returns the Status associated to the ID. Otherwise, returns null. */ public static Status getStatus(int id) { try { if (id > 0) { return dbConnection.getStatusByID(id); } else { return null; } } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * @deprecated * * Retrieves shipping information that is relevant to the user * based on the parameters used. * * @param is * - a variable amount of ints where each int represents the id * of a Status * * @return Returns a map where the key is the id of the Status and the value * is a list of related ShippingInformation to that id. */ @SuppressWarnings("unchecked") public static Map<Integer, List<ShippingInformation>> getReleveantInfo( int... is) { Map<Integer, List<ShippingInformation>> status = new HashMap<Integer, List<ShippingInformation>>(); List<ShippingInformation>[] storage = (List<ShippingInformation>[]) new LinkedList[is.length]; int[] sortedInput = is.clone(); Arrays.sort(sortedInput); for (int i = 0; i < storage.length; i++) { storage[i] = new LinkedList<ShippingInformation>(); } for (ShippingInformation x : getAllShippingInformation()) { for (int i = 0; i < is.length; i++) { if (sortedInput[i] == x.status.status_id) { storage[i].add(x); break; } } } for (int i = 0; i < storage.length; i++) { status.put(sortedInput[i], storage[i]); } return status; } /** * Attempts to retrieve all packages that are marked as "In Transit" or * "Waiting" to be picked up. * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the packages that are in transit or yet to be * picked up. Otherwise, returns <code>null</code> */ public static List<ShippingInformation> getCurrentPackages() { noConnection(); try { return dbConnection.getNotArrived(); } catch (SQLException e) { logger.info(e.toString()); return null; } } /** * Attempts to retrieve all specimens assigned to the given username. * * @param username * - username to be looked up for specimens * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the packages that are associated to the given * username. Otherwise, returns <code>null</code> */ public static List<ShippingInformation> getAllSpecimensByUsername( String username) { return getAllSpecHelper(username, true); } /** * Attempts to retrieve all specimens assigned to the given name. * * @param name * - name to be looked up for specimens * * @return Returns a <code>List&lt;ShippingInformation&gt;</code> object * containing all the packages that are associated to the given * name. Otherwise, returns <code>null</code> */ public static List<ShippingInformation> getAllSpecimensByName(String name) { return getAllSpecHelper(name, false); } /** * Changes the status of a shipment to "Arrived" * * @param barcode * - the barcode of the shipment * * @return Returns true if change was successful. Otherwise, returns false. */ public static boolean arrived(String barcode) { ShippingInformation temp = getShippingInfo(barcode); if (noNulls(barcode, temp)) { changeShippingInformation(barcode, temp.shipper.username, temp.destination.client_id, 3, temp.courier == null ? "" : temp.courier.user.username); return true; } else { return false; } } /** * Attempts to retrieve the starting check list from the database. * * @return Returns the starting check list if successful. Otherwise, null. * * @throws IllegalStateException * if the there is no connection to the database */ public static List<String> getStartingList() throws IllegalStateException { CheckListPair temp = getCheckLists(); if (temp == null) { return null; } else { return getCheckLists().startingList; } } /** * Attempts to retrieve the ending check list from the database. * * @return Returns the ending check list if successful. Otherwise, null. * * @throws IllegalStateException * if the there is no connection to the database */ public static List<String> getEndingList() { CheckListPair temp = getCheckLists(); if (temp == null) { return null; } else { return getCheckLists().endingList; } } // ------------------------------------------------------------------------- // // Android server specific // // ------------------------------------------------------------------------- /** * Retrieves a list of client site that have packages. * * @param username * - username of the courier to be looked up * * @return Returns a list of client sites that have packages. */ public static Route getRouteWithPackages(String username) { List<ClientSite> newCS = new LinkedList<ClientSite>(); if (username != null) { List<ClientSite> temp = getRoute(username); if (temp != null) { for (ClientSite x : temp) { List<ShippingInformation> s = specimenFrom(x); if (s != null && !s.isEmpty()) { newCS.add(x); } } } } return new Route(newCS); } /** * Attempts to update the GPS of a courier. * * @param username * - username of the courier * @param latitude * - latitude of the courier * @param longitude * -longitude of the courier * * @throws IllegalStateException * if the there is no connection to the database */ public static void updateGPS(String username, double latitude, double longitude) throws IllegalStateException { noConnection(); if (noNulls(username, getCourierInfo(username))) { Courier temp = getCourierInfo(username); try { dbConnection.changeRecord(new Courier(temp.user, temp.route, latitude, longitude, temp.nextDest)); } catch (SQLException e) { logger.info(e.toString()); } } else { logger.info("GPS Update failed: username or courier is null"); } } /** * Changes the status of a shipment to "Picked Up." * * @param barcode * - the barcode of the shipment * * @return Returns true if change was successful. Otherwise, returns false. * * @throws IllegalStateException * if the there is no connection to the database */ public static boolean pickedUp(String barcode, String username) throws IllegalStateException { if (noNulls(barcode, getShippingInfo(barcode))) { ShippingInformation temp = getShippingInfo(barcode); changeShippingInformation(barcode, temp.shipper.username, temp.destination.client_id, 2, username); return true; } else { return false; } } // ------------------------------------------------------------------------- // // Helper methods // // ------------------------------------------------------------------------- /** * Helper that throws an exception if there is no connection to the * database. */ private static void noConnection() throws IllegalStateException { if (dbConnection == null) { throw new IllegalStateException("Connection to the database" + "has not bee made"); } } /** * @deprecated Deprecated method that checks to see if courier is at * nextDest. */ @SuppressWarnings("unused") private static boolean checkLoc(Courier courier, ClientSite specLoc) { return courier.route.indexOf(courier.nextDest) <= courier.route .indexOf(specLoc); } /** * Get specimen of certain couriers based on either their username or first * name. */ private static List<ShippingInformation> getAllSpecHelper(String s, boolean username) { List<ShippingInformation> temp = new LinkedList<ShippingInformation>(); if (s != null && !s.isEmpty()) { for (ShippingInformation x : getAllShippingInformation()) { if ((username && x.courier.user.username.equals(s)) || (!username && x.courier.user.fname.equals(s))) { temp.add(x); } } } return temp; } /** * Helper that checks to make sure length of strings aren't 0. */ private static boolean lengthChecker(String... strings) { for (int i = 0; i < strings.length; i++) { if (strings[i].isEmpty()) { return false; } } return true; } }
Java
/** * */ package jvm.jtacck.db; import java.sql.SQLException; import java.util.Date; import java.util.List; import jvm.jtacck.db.records.*; /** * @author Chris Gamble * * A DatabaseHandler is an Interface to be used in the Jtacck Lab * Transport System. It's functionality is to create a barrier between * database access and the rest of the system. The interface allows the * database system to change without changing the rest of the system * along with it. * * Current functionality is open(), close(), and addRecord(r), * isClosed(), login(u), */ public interface DatabaseHandler { /** * Opens a connection to the database if one has is not already open. * * @throws SQLException * if a database access error occurs */ public void open() throws SQLException; /** * Closes the connection to the database if it has not already been closed * * @throws SQLException * if a database access error occurs */ public void close() throws SQLException; /** * Checks to see if the connection is open or closed and returns true if it * is closed. * * @return True if the database connection is closed. * @throws SQLException * if a database access error occurs */ public boolean isClosed() throws SQLException; /** * Takes a username and password, and if there is a corresponding username * with that password, returns the User for that username. * * @param username * The username to login into the system with. * @param password * The password to login into the system with. * @return If there is a user u with matching username and password, then * returns the User of that u. Else returns null. Null means the * attempt to login failed. * @throws SQLException * if a database access error occurs */ public User login(String username, String password); /** * Adds the given Record to the database. * * @param r * The Record to add to the database, can be any of these * subclasses of Record: ClientSite, Courier, Hospital, * ShippingInformation, Status, User, UserType. Integer based * ID's are allowed to be null as they will be provided a unique * ID from the database. * @throws SQLException * if a database access error occurs */ public void addRecord(ClientSite cs) throws SQLException; public void addRecord(Courier c) throws SQLException; public void addRecord(Hospital h) throws SQLException; public void addRecord(ShippingInformation si) throws SQLException; public void addRecord(Specimen sp) throws SQLException; public void addRecord(Status st) throws SQLException; public void addRecord(User u) throws SQLException; public void addRecord(UserType ut) throws SQLException; /** * Changes the Record given in the database to the new values. Any unique * identifiers must remain constant. * * When updating a Specimen, the Items of Specimen.contents, will add any * new item_ids and remove any item_ids that are not found in the new * contents. * * @param r * The Record to add to the database, can be any of these * subclasses of Record: ClientSite, Courier, Hospital, * ShippingInformation, Specimen, Status, User, UserType. The ID * must not change. * @throws SQLException * if a database access error occurs */ public void changeRecord(CheckListPair clp) throws SQLException; public void changeRecord(ClientSite cs) throws SQLException; public void changeRecord(Courier c) throws SQLException; public void changeRecord(Hospital h) throws SQLException; public void changeRecord(ShippingInformation si) throws SQLException; public void changeRecord(Specimen sp) throws SQLException; public void changeRecord(Status st) throws SQLException; public void changeRecord(User u) throws SQLException; public void changeRecord(UserType ut) throws SQLException; /** * Removes the Record given from the database. * * An SQLException will be thrown if a Record that is currently in use by a * ShippingInformation and will result in the Record not being removed from * the database * * @param r * The Record to remove to the database, can be any of these * subclasses of Record: ClientSite, Courier, Hospital, * ShippingInformation, Specimen, Status, User, UserType. The ID * must not change. * @throws SQLException * if a database access error occurs */ public void removeRecord(ClientSite cs) throws SQLException; public void removeRecord(Courier c) throws SQLException; public void removeRecord(Hospital h) throws SQLException; public void removeRecord(ShippingInformation si) throws SQLException; public void removeRecord(Status st) throws SQLException; public void removeRecord(User u) throws SQLException; public void removeRecord(UserType ut) throws SQLException; /** * Returns a single ClientSite for the id given * * @param client_id * the id for the specific ClientSite request * @return either a ClientSite or null if the site is not found. * @throws SQLException * if a database access error occurs */ public ClientSite getClientSiteByID(int client_id) throws SQLException; /** * Takes a username and returns the Courier of that username if the User is * a Courier. * * @param username * The unique username of a User who's UserType is a Courier * @return The Courier Record associated with the given username. * @throws SQLException * if a database access error occurs */ public Courier getCourierByID(String username) throws SQLException; /** * Returns a single User for the id given * * @param hospital_id * the id for the specific User request * @return either a Hospital or null if the hospital is not found. */ public Hospital getHospitalByID(int hospital_id) throws SQLException; /** * Takes an int and returns the Item corresponding to that id. * * @param item_id * The id of the Item requested * @return either the Item or null if the item is not found. * @throws SQLException * if a database access error occurs */ public Item getItemByID(int item_id) throws SQLException; /** * Takes a barcode and returns the ShippingInformation corresponding to that * barcode * * @param barcode * The barcode of the Specimen whose ShippingInformation is * requested * @return either the ShippingInformation or null if the ShippingInformation * is not found. * @throws SQLException * if a database access error occurs */ public ShippingInformation getShippingByID(String barcode) throws SQLException; /** * Takes a barcode and returns the ShippingInformation corresponding to that * barcode * * @param barcode * The barcode of the Specimen requested * @return either the Specimen or null if the specimen is not found. * @throws SQLException * if a database access error occurs */ public Specimen getSpecimenByID(String barcode) throws SQLException; /** * Takes an int and returns the Status corresponding to that id. * * @param status_id * The id of the Status requested * @return either the Status or null if the Status is not found. * @throws SQLException * if a database access error occurs */ public Status getStatusByID(int status_id) throws SQLException; /** * Returns a single User for the id given * * @param username * the username for the specific User request * @return either a User or null if the User is not found. */ public User getUserByID(String username) throws SQLException; /** * Takes an int and returns the UserType corresponding to that id. * * @param type_id * The id of the UserType requested * @return either the UserType or null if the UserType is not found. * @throws SQLException * if a database access error occurs */ public UserType getUserTypeByID(int type_id) throws SQLException; /** * Takes the client site and returns a list of all users who are associated * with the given site * * @param cs * The ClientSite that the requested Users are associated with. * @return A List of Users that are associated with cs. * @throws SQLException * if a database access error occurs */ public List<User> getUsersOf(ClientSite cs) throws SQLException; /** * Takes a username, and returns the UserType of that username. * * @param username * A username of a User in the database * @return The UserType of the username given * @throws SQLException * if a database access error occurs */ public UserType getUserType(String username) throws SQLException; /** * Takes a barcode, and returns the ShippingInformation for the Specimen * that barcode is an identifier for. * * @param barcode * The unique barcode of a Specimen in the database * @return The ShippingInformation with the unique identifier of the * Specimen with barcode as their barcode. * @throws SQLException * if a database access error occurs */ public ShippingInformation getShippingInfoFor(String barcode) throws SQLException; /** * Returns the checklist pair that is stored in the database. This * corresponds to the starting and ending checklists for couriers to use. */ public CheckListPair getCheckLists() throws SQLException; /** * Takes a ClientSite and returns a list of ShippingInformation for all * Specimens that have been shipped from the given ClientSite. * * @param clientID * The ClientSite that the requested Specimens were shipped from. * @return A List of each ShippingInformation where the Specimens were * shipped from cs. * @throws SQLException * if a database access error occurs */ // TODO: overload this method for Users and Hospitals public List<ShippingInformation> specimensFrom(ClientSite cs) throws SQLException; /** * Takes a ClientSite and returns a list of ShippingInformation for all * Specimens that have destinations of the given ClientSite. * * @param clientID * The ClientSite that the requested Specimens were shipped to. * @return A List of each ShippingInformation where the Specimens were * shipped to cs. * @throws SQLException * if a database access error occurs */ public List<ShippingInformation> specimensTo(ClientSite cs) throws SQLException; /** * Returns a list of all ClientSites available. * * @return A List containing every ClientSite in the system. * @throws SQLException * if a database access error occurs */ public List<ClientSite> getAllClientSites() throws SQLException; /** * Returns a list of all Couriers available. * * @return A List containing every Couriers in the system. * @throws SQLException * if a database access error occurs */ public List<Courier> getAllCouriers() throws SQLException; /** * Returns a list of all Hospitals available. * * @return A List containing every Hospital in the system. * @throws SQLException * if a database access error occurs */ public List<Hospital> getAllHospitals() throws SQLException; /** * Returns a list of all Items available. This method is pretty much useless * because you should not be messing with items alone, so DON'T USE IT! * * @return A List containing every Item in the system. * @throws SQLException * if a database access error occurs */ public List<Item> getAllItems() throws SQLException; /** * Returns a list of all ShippingInformation available. This is equivalent * to getting it for all Specimens as the barcodes are the same. * * @return A List containing every ShippingInformation in the system. * @throws SQLException * if a database access error occurs */ public List<ShippingInformation> getAllShippingInformation() throws SQLException; /** * Returns a list of all ShippingInformation that doesn't have the status * "Arrived". This will be a more brief list and will be the most recent of * the specimens * * @return A List containing every non delivered specimen in the system. * @throws SQLException * if a database access error occurs */ public List<ShippingInformation> getNotArrived() throws SQLException; /** * Returns a list of all Specimens available. * * @return A List containing every Specimen in the system. * @throws SQLException * if a database access error occurs */ public List<Specimen> getAllSpecimens() throws SQLException; /** * Returns a list of all Statuses available. * * @return A List containing every Status in the system. * @throws SQLException * if a database access error occurs */ public List<Status> getAllStatuses() throws SQLException; /** * Returns a list of all Users available. * * @return A List containing every User in the system. * @throws SQLException * if a database access error occurs */ public List<User> getAllUsers() throws SQLException; /** * Returns a list of all UserTypes available. * * @return A List containing every UserType in the system. * @throws SQLException * if a database access error occurs */ public List<UserType> getAllUserTypes() throws SQLException; /** * Returns a Date object of the last time the ShippingInformation with the * given barcode was update. * @param barcode * The id of the ShippingInformation to get the timestamp of * @return A Date object with the day and time of the last update to the * ShippingInformation. * @throws SQLException * If a database access error occurs */ public Date getLastUpdate(String barcode) throws SQLException; /** * Returns a Date object of the first time the ShippingInformation with the * given barcode was update. * @param barcode * The id of the ShippingInformation to get the timestamp of * @return A Date object with the day and time of the first update to the * ShippingInformation. * @throws SQLException * If a database access error occurs */ public Date getFirstUpdate(String barcode) throws SQLException; }
Java
package jvm.jtacck.db.records; /** * * @author Chris Gamble * * Represents a type of user of the system. each user belongs to one of * these types, and depending on the type of user, they are restricted * to what they can access. * */ public class UserType extends Record { private static final long serialVersionUID = -8832343003300183498L; public final int type_id; public final String name; public final String description; /** * Constructs a new UserType * * @param id * the unique id of the UserType * NON-NULLABLE * @param name * the name of the UserType * @param description * an english description of what this type of user can do */ public UserType(int id, String name, String description) { this.type_id = id; this.name = name; this.description = description; } @Override public boolean equals(Object o) { if (o instanceof UserType) { UserType other = (UserType) o; boolean x = (type_id == other.type_id) && checkString(name, other.name) && checkString(description, other.description); return x; } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return type_id + name.hashCode() + description.hashCode(); } public String toString() { return type_id + ": " + name + ", " + description + "."; } }
Java
package jvm.jtacck.db.records; /** * @author Chris Gamble * * Represents a User record in the database. A user has a username, a * password, a first and last name, as well as the client_site he/she is * associated with and the type of user they are. */ public class User extends Record { private static final long serialVersionUID = 6496590428267700346L; public final String username; public final String password; public final String fname; public final String lname; public final ClientSite site; public final UserType type; /** * Constructs a new User * * @param username * The primary key of a User(s) * NON-NULLABLE * @param password * The encrypted password of the user * NON-NULLABLE * @param fname * The first name of the user * @param lname * The last name of the user * @param siteID * The client_id of the Client_Site this user is associated with * NON-NULLABLE * @param typeID * The type_id of the User_Type that this user is * NON-NULLABLE */ public User(String username, String password, String fname, String lname, ClientSite site, UserType type) { super(); this.username = username; this.password = password; this.fname = fname; this.lname = lname; this.site = site; this.type = type; } @Override public boolean equals(Object o){ if (o instanceof User) { User other = (User) o; boolean x = username.equals(other.username) && password.equals(other.password) && checkString(fname, other.fname) && checkString(lname, other.lname) && site.equals(other.site) && type.equals(other.type); return x; } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return username.hashCode() + fname.hashCode() + lname.hashCode() + site.hashCode() + type.hashCode(); } public String toString() { return username + ": " + fname + ", " + lname + ", " + site.name + ", " + type.name + "."; } }
Java
package jvm.jtacck.db.records; import java.util.Collections; import java.util.List; /** * * @author Chris Gamble * * Represents a Courier. A Courier is a specific type of user, who has * additional fields to have. They are associated by a username, they * have a list that contains their route, and they also have the last * known latitude and longitude of the Courier. * */ public class Courier extends Record { private static final long serialVersionUID = -1417538378931608908L; public final User user; public final List<ClientSite> route; public final double latitude; public final double longitude; public final ClientSite nextDest; /** * Constructs a new Courier * * @param username * the unique User to this Courier * NON-NULLABLE * @param route * A List of ClientSites that this Courier will travel to. * @param lat * Double of the latitude global position * @param lon * Double of the longitude global position */ public Courier(User username, List<ClientSite> route, double lat, double lon, ClientSite next) { this.user = username; this.route = Collections.unmodifiableList(route); this.latitude = lat; this.longitude = lon; this.nextDest = next; } @Override public boolean equals(Object o){ if (o instanceof Courier) { Courier other = (Courier) o; return checkDoubles(latitude, other.latitude) && checkDoubles(longitude, other.longitude) && checkLists(route, other.route) && user.equals(other.user) && nextDest.equals(other.nextDest); } return false; } private strictfp boolean checkDoubles(double l1, double l2) { return Math.abs(l1 - l2) < .000000001; } private boolean checkLists(List<ClientSite> s1, List<ClientSite> s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return user.hashCode() + (new Double(latitude)).hashCode() + (new Double(longitude).hashCode()); } public String toString() { return user.username + ": " + route + ", " + nextDest.name + "."; } }
Java
package jvm.jtacck.db.records; /** * * @author Chris Gamble * * Represents a Status a Specimen can have. A Status consists of a * unique id, a name, and a description of the status. * * There are currently 3 valid statuses. * Status(1, 'Waiting', 'The shipment is waiting to be picked up.'), * Status(2, 'In Transit', 'The shipment has been picked up and is on its way to the LAB.'), Status(3, 'Arrived', 'The shipment has arrived at is final destination.'); */ public class Status extends Record { private static final long serialVersionUID = -4260083509589747379L; public final int status_id; public final String name; public final String description; /** * Constructs a Status * * @param id * the unique id of the status. * NON-NULLABLE * @param name * the name of the status. * @param description * an english description of the status. */ public Status(int id, String name, String description) { this.status_id = id; this.name = name; this.description = description; } @Override public boolean equals(Object o){ if (o instanceof Status) { Status other = (Status) o; return (status_id == other.status_id) && checkString(name, other.name) && checkString(description, other.description); } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return status_id + name.hashCode() + description.hashCode(); } public String toString() { return status_id + ": " + name + ", " + description + "."; } }
Java
package jvm.jtacck.db.records; /** * * @author Chris Gamble * * Represents a relational table of a database. Shipping information * relates a Specimen to other records. the username who started the * tracking process (shipped), the client_site that it is destined for, * the status of the specimen, and the username of the courier who has * picked up the specimen if applicable. */ public class ShippingInformation extends Record { private static final long serialVersionUID = -1632753780672299640L; public final Specimen specimen; public final User shipper; public final ClientSite destination; public final Courier courier; public final Status status; /** * Constructs a ShippingInformation relation * * @param spec * the Specimen the relation refers to, used as unique idd * NON-NULLABLE * @param shipper * the User who shipped the Specimen * NON-NULLABLE * @param dest * the ClientSite that is the final destination of the Specimen * NON-NULLABLE * @param cour * the Courier who is transporting the Specimen * @param stat * the Status of the Specimen * NON-NULLABLE */ public ShippingInformation(Specimen spec, User shipper, ClientSite dest, Status stat, Courier cour) { this.specimen = spec; this.shipper = shipper; this.destination = dest; this.courier = cour; this.status = stat; } @Override public boolean equals(Object o){ if (o instanceof ShippingInformation) { ShippingInformation other = (ShippingInformation) o; boolean x = specimen.equals(other.specimen) && shipper.equals(other.shipper) && destination.equals(other.destination) && checkCourier(courier, other.courier) && status.equals(other.status); return x; } return false; } public boolean checkCourier(Courier s1, Courier s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return specimen.hashCode() + shipper.hashCode() + destination.hashCode() + status.hashCode(); } public String toString() { return specimen.barcode + ": " + shipper.username + ", " + destination.name + ", " + status.name + ", " + courier + "."; } }
Java
package jvm.jtacck.db.records; /** * * @author Chris Gamble * * Represents an Item. An Item is the lowest form of a Specimen. * Physically it contains a vial containing a sample of some sort, has a * name of the sample, and the color of a cap. This representation has a * unique identifier item_id, as well as the name and cap color. */ public class Item extends Record { private static final long serialVersionUID = 6864353390164895991L; public final int item_id; public final String name; public final String capColor; /** * Constructs an Item * * @param id * a unique identifier of the Item * NON-NULLABLE * @param name * the name of the Item * @param capColor * The color of the cap the Item has */ public Item(int id, String name, String capColor) { this.item_id = id; this.name = name; this.capColor = capColor; } @Override public boolean equals(Object o){ if (o instanceof Item) { Item other = (Item) o; return (item_id == other.item_id) && checkString(name, other.name) && checkString(capColor, other.capColor); } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return item_id + name.hashCode() + capColor.hashCode(); } public String toString() { return item_id + ": " + name + ", " + capColor + "."; } }
Java
package jvm.jtacck.db.records; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; /** * * @author Chris Gamble * * Represents a Specimen of the tracking system. A specimen is comprised * of a Collection of Items, as well as a unique barcode, a description * of the specimen as well as requirements of shipping for the specimen. * The collection of Items represents the contains table of the * database, where one Specimen may contain multiple Items, but two * Specimens cannot contain the same Item. */ public class Specimen extends Record { private static final long serialVersionUID = -5530188823133494025L; public final String barcode; public final String description; public final String requirements; public final Collection<Item> contents; /** * Constructs a Specimen * * @param barcode * unique integer for an instance * NON-NULLABLE * @param description * an English description of the Specimen. * @param requirements * an English explanation of shipping requirements for the * Specimen. * @param contents * A collection of the Items contained by the Specimen. Must not * be empty. * NON-NULLABLE */ public Specimen(String barcode, String description, String requirements, Collection<Item> contents) { this.barcode = barcode; this.description = description; this.requirements = requirements; this.contents = Collections.unmodifiableList(new LinkedList<Item>(contents)); } @Override public boolean equals(Object o){ if (o instanceof Specimen) { Specimen other = (Specimen) o; return (barcode.equals(other.barcode)) && checkString(description, other.description) && checkString(requirements, other.requirements) && contents.equals(other.contents); } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return barcode.hashCode() + description.hashCode() + requirements.hashCode(); } public String toString() { return barcode + ": " + description + ", " + requirements + ", " + contents + "."; } }
Java
package jvm.jtacck.db.records; /** * @author Chris Gamble * * Represents a Hospital record in the database. A hospital has an ID * number, a name, and an address. */ public class Hospital extends Record { private static final long serialVersionUID = -1878531611795940701L; public final String name; public final String address; public final int hospital_id; /** * Constructs a new Hospital * * @param hid * The hospital_id of this hospital * NON-NULLABLE * @param name * The name of this hospital * @param address * The address of this hospital Must be of the form: * "<<Address1>>, <<Address2>>, <<City>>, <<State>>, <<ZipCode>>" */ public Hospital(int hid, String name, String address) { super(); this.hospital_id = hid; this.name = name; this.address = address; } @Override public boolean equals(Object o){ if (o instanceof Hospital) { Hospital other = (Hospital) o; boolean x = (hospital_id == other.hospital_id) && checkString(name, other.name) && checkString(address, other.address); return x; } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } @Override public int hashCode() { return hospital_id + name.hashCode() + address.hashCode(); } public String toString() { return hospital_id + ": " + name + ", " + address + "."; } }
Java
package jvm.jtacck.db.records; import java.io.Serializable; import java.util.List; /** * TODO * @author Chris Gamble * */ public class CheckListPair extends Record implements Serializable { private static final long serialVersionUID = 1653895091733105977L; public final List<String> startingList; public final List<String> endingList; public CheckListPair(List<String> starting, List<String> ending){ startingList = starting; endingList = ending; } public boolean equals(Object o) { if (o instanceof CheckListPair) { CheckListPair other = (CheckListPair) o; return startingList.equals(other.startingList) && endingList.equals(other.endingList); } return false; } public int hashCode() { return startingList.hashCode() + endingList.hashCode(); } public String toString() { return "Starting CheckList: " + startingList + " \nEnding CheckList: " + endingList; } }
Java
package jvm.jtacck.db.records; import java.util.Collections; import java.util.List; /** * * @author Chris Gamble * * Represents a Client_Site in our database. A Client Site is a sub * section of a hospital from where specimens can be picked up for * shipping. Client sites have the fields client_id, name, the * hospital_id of the hospital it belongs to and instructions. The * instructions are for the courier to know what where to pick up the * specimens from the site. * */ public class ClientSite extends Record { private static final long serialVersionUID = 4834310666833409829L; public final int client_id; public final String name; public final Hospital hospital; public final List<String> instructions; public final String phone_number; /** * Constructs a new ClientSite Record * * @param id * the id number of the clientsite * NON-NULLABLE * @param name * the name of the clientsite * @param hosp * the id of the hospital to which this site belongs * NON-NULLABLE * @param instructs * A Sequential List of Instructions for couriers who pick up at * this ClientSite * @param phone * 10 digit phone number of the ClientSite */ public ClientSite(int id, String name, Hospital hosp, List<String> instructs, String phone) { this.client_id = id; this.name = name; this.hospital = hosp; this.instructions = Collections.unmodifiableList(instructs); this.phone_number = phone; } @Override public boolean equals(Object o){ if (o instanceof ClientSite) { ClientSite other = (ClientSite) o; boolean x = client_id == other.client_id && checkString(name, other.name) && checkString(phone_number, other.phone_number) && checkList(instructions, other.instructions) && hospital.equals(other.hospital); return x; } return false; } public boolean checkString(String s1, String s2) { if (s1 == null) { return s2 == null; }else { return s1.equals(s2); } } public boolean checkList(List<String> l1, List<String> l2) { if (l1 == null) { return l2 == null; }else { return l1.equals(l2); } } @Override public int hashCode() { return client_id + name.hashCode() + hospital.hashCode() + phone_number.hashCode(); } public String toString() { return client_id + ": " + name + ", " + hospital.name + ", " + phone_number + "."; } }
Java
package jvm.jtacck.db.records; import java.io.Serializable; /** * @author Chris Gamble * * Generic type to indicate that the file is a record of the database. * This is a placeholder for any type of record that may be used in the * Jtacck Lab Medicine System. * */ public class Record implements Serializable{ private static final long serialVersionUID = -1260955860461473143L; public Record() { }; }
Java
package jvm.jtacck.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import jvm.jtacck.db.records.*; /** * PostgresHandler represents a connection to a database containing the * following schema: * * hospital (hospital_id, name, address) client_site (client_id, name, * hospital_id, instructions, phone_number) user_type (type_id, name, * description) users (username, password, fname, lname, site_id, type_id) * courier (username, route, lat_loc, long_loc, nextDest) specimen (barcode, * description, requirements) item (item_id, name, cap_color) status (status_id, * name, description) contains (barcode, item_id) shipping_info (barcode, * shipper, destination_id, status_id integer, courier_id varchar(20)) * * PostgresHandler is an implementation of DatabaseHandler that is specific to * using a PostgreSQL Database, as the database management system used for the * jtacck tracking system. * * @author Chris Gamble * */ public class PostgresHandler implements DatabaseHandler { private Connection dbConn; private String dbAddress; private String user; private String password; // SQL Queries private static final String ADD_CLIENT_SITE = "INSERT INTO client_site VALUES ( DEFAULT, ?, ?, ?, ?);"; private static final String ADD_COURIER = "INSERT INTO courier VALUES ( ?, ?, ?, ?, ?);"; private static final String ADD_HOSPITAL = "INSERT INTO hospital VALUES ( DEFAULT, ?, ?);"; private static final String ADD_ITEM = "INSERT INTO item VALUES ( DEFAULT, ?, ?);"; private static final String ADD_TO_CONTAINS = "INSERT INTO contains VALUES ( ?, ?);"; private static final String ADD_SHIPPING_INFO = "INSERT INTO shipping_info VALUES ( ?, ?, ?, ?, ?, 'now', 'now')"; private static final String ADD_SPECIMEN = "INSERT INTO specimen VALUES ( ?, ?, ?)"; private static final String ADD_STATUS = "INSERT INTO status VALUES ( DEFAULT, ?, ?);"; private static final String ADD_USER = "INSERT INTO users VALUES ( ?, ?, ?, ?, ?, ?);"; private static final String ADD_USER_TYPE = "INSERT INTO user_type VALUES ( DEFAULT, ?, ?);"; private static final String UPDATE_CHECKLIST_PAIR = "UPDATE checklist " + "SET starting = ?, ending = ? " + "WHERE checklist_id = 1;"; private static final String UPDATE_CLIENT_SITE = "UPDATE client_site " + "SET name = ?, hospital_id = ?, instructions = ?, phone_number = ? " + "WHERE client_id = ?;"; private static final String UPDATE_COURIER = "UPDATE courier " + "SET route = ?, lat_loc = ?, long_loc = ?, next_destination = ? " + "WHERE username = ?;"; private static final String UPDATE_HOSPITAL = "UPDATE hospital " + "SET name = ?, address = ? " + "WHERE hospital_id = ?;"; private static final String UPDATE_ITEM = "UPDATE item " + "SET name = ?, cap_color = ? " + "WHERE item_id = ?;"; private static final String UPDATE_SHIPPING_INFO = "UPDATE shipping_info " + "SET shipper = ?, destination_id = ?, status_id = ?, courier_id = ?, time_updated = 'now' " + "WHERE barcode = ?;"; private static final String UPDATE_SPECIMEN = "UPDATE specimen " + "SET description = ?, requirements = ? " + "WHERE barcode = ?;"; private static final String UPDATE_STATUS = "UPDATE status " + "SET name = ?, description = ? " + "WHERE status_id = ?;"; private static final String UPDATE_USER = "UPDATE users " + "SET password = ?, fname = ?, lname = ?, site_id = ?, type_id = ? " + "WHERE username = ?;"; private static final String UPDATE_USER_TYPE = "UPDATE user_type " + "SET name = ?, description = ? " + "WHERE type_id = ?;"; private static final String GET_CHECKLISTS = "SELECT * FROM checklist WHERE checklist_id = 1;"; private static final String GET_CLIENT_SITE = "SELECT * FROM client_site WHERE client_id = ?;"; private static final String GET_COURIER = "SELECT * FROM courier WHERE username = ?;"; private static final String GET_HOSPITAL = "SELECT * FROM hospital WHERE hospital_id = ?;"; private static final String GET_ITEM = "SELECT * FROM item WHERE item_id = ?;"; private static final String GET_SHIPPING_INFO = "SELECT * FROM shipping_info WHERE barcode = ?;"; private static final String GET_SPECIMEN = "SELECT * FROM specimen s WHERE s.barcode = ?;"; private static final String GET_CONTENTS = "SELECT * FROM contains c WHERE c.barcode = ?;"; private static final String GET_STATUS = "SELECT * FROM status WHERE status_id = ?;"; private static final String GET_USER = "SELECT * FROM users WHERE username = ?;"; private static final String GET_USER_TYPE = "SELECT * FROM user_type WHERE type_id = ?;"; private static final String GET_ALL_CLIENT_SITES = "SELECT * FROM client_site;"; private static final String GET_ALL_COURIERS = "SELECT * FROM courier;"; private static final String GET_ALL_HOSPITALS = "SELECT * FROM hospital;"; private static final String GET_ALL_ITEMS = "SELECT * FROM item;"; private static final String GET_ALL_SHIPPING_INFOS = "SELECT * FROM shipping_info si;"; private static final String GET_ALL_SPECIMENS = "SELECT * FROM specimen;"; private static final String GET_ALL_STATUSES = "SELECT * FROM status;"; private static final String GET_ALL_USERS = "SELECT * FROM users;"; private static final String GET_ALL_USER_TYPES = "SELECT * FROM user_type;"; private static final String REMOVE_CLIENT_SITE = "DELETE FROM client_site " + "WHERE client_id = ?;"; private static final String REMOVE_COURIER = "DELETE FROM courier " + "WHERE username = ?;"; private static final String REMOVE_HOSPITAL = "DELETE FROM hospital " + "WHERE hospital_id = ?;"; private static final String REMOVE_ITEM = "DELETE FROM item " + "WHERE item_id = ?;"; private static final String REMOVE_SHIPPING_INFO = "DELETE FROM shipping_info " + "WHERE barcode = ?;"; private static final String REMOVE_SPECIMEN = "DELETE FROM specimen " + "WHERE barcode = ? "; private static final String REMOVE_STATUS = "DELETE FROM status " + "WHERE status_id = ?;"; private static final String REMOVE_USER = "DELETE FROM users " + "WHERE username = ?;"; private static final String REMOVE_USER_TYPE = "DELETE FROM user_type " + "WHERE type_id = ?;"; // Specialty private static final String BEGIN_TRANSACTION = "BEGIN TRANSACTION;"; private static final String COMMIT_TRANSACTION = "ABORT TRANSACTION;"; private static final String ABORT_TRANSACTION = "COMMIT TRANSACTION;"; private static final String GET_SPECIMENS_FROM = "SELECT barcode " + "FROM shipping_info s, users u " + "WHERE s.shipper = u.username AND u.site_id = ?;"; private static final String GET_SPECIMENS_TO = "SELECT barcode " + "FROM shipping_info " + "WHERE destination_id = ?;"; private static final String GET_USERS_OF_SITE = "SELECT username FROM users WHERE site_id = ?;"; private static final String GET_NOT_ARRIVED = "SELECT * FROM shipping_info si WHERE NOT status_id = 3;"; // PreparedStatements private PreparedStatement addClientPS; private PreparedStatement addCourierPS; private PreparedStatement addHospitalPS; private PreparedStatement addItemPS; private PreparedStatement addToContainsPS; private PreparedStatement addShippingInfoPS; private PreparedStatement addSpecimenPS; private PreparedStatement addStatusPS; private PreparedStatement addUserPS; private PreparedStatement addUserTypePS; private PreparedStatement updateCheckListPairPS; private PreparedStatement updateClientSitePS; private PreparedStatement updateCourierPS; private PreparedStatement updateHospitalPS; private PreparedStatement updateItemPS; private PreparedStatement updateShippingInfoPS; private PreparedStatement updateSpecimenPS; private PreparedStatement updateStatusPS; private PreparedStatement updateUserPS; private PreparedStatement updateUserTypePS; private PreparedStatement getCheckListsPS; private PreparedStatement getClientSitePS; private PreparedStatement getCourierPS; private PreparedStatement getHospitalPS; private PreparedStatement getItemPS; private PreparedStatement getShippingInfoPS; private PreparedStatement getSpecimenPS; private PreparedStatement getContentsPS; private PreparedStatement getStatusPS; private PreparedStatement getUserPS; private PreparedStatement getUserTypePS; private PreparedStatement getAllClientSitesPS; private PreparedStatement getAllCouriersPS; private PreparedStatement getAllHospitalsPS; private PreparedStatement getAllItemsPS; private PreparedStatement getAllShippingInfosPS; private PreparedStatement getAllSpecimensPS; private PreparedStatement getAllStatusesPS; private PreparedStatement getAllUsersPS; private PreparedStatement getAllUserTypesPS; private PreparedStatement removeClientSitePS; private PreparedStatement removeCourierPS; private PreparedStatement removeHospitalPS; private PreparedStatement removeItemPS; private PreparedStatement removeShippingInfoPS; private PreparedStatement removeSpecimenPS; private PreparedStatement removeStatusPS; private PreparedStatement removeUserPS; private PreparedStatement removeUserTypePS; // Specialty private PreparedStatement beginTransactionPS; private PreparedStatement commitTransactionPS; private PreparedStatement abortTransactionPS; private PreparedStatement getSpecimensFromPS; private PreparedStatement getSpecimensToPS; private PreparedStatement getUsersOfSitePS; private PreparedStatement getNotArrivedPS; /** * Constructs a new PostgresHandler. The username and password here are * separate from the Jtacck System. * * @param username * : the username for the postgres database, this user name must * have read/write/modify access to the database. * @param password * : the password for the username for the database. * @param dbAddress * : the server, port, and database name to access. Must be of * the form "<<server>>:<<port>>/<<databasename>>" where << >> * indicates a described variable * @throws SQLException * If a database error occurs. */ public PostgresHandler(String username, String password, String dbAddress) throws SQLException { this.user = username; this.password = password; this.dbAddress = dbAddress; open(); initializePreparedStatements(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#open() */ @Override synchronized public void open() throws SQLException { if (dbConn == null) { try { Class.forName("org.postgresql.Driver"); dbConn = DriverManager.getConnection("jdbc:postgresql://" + dbAddress, user, password); } catch (Exception e) { throw new SQLException("Postgres Database Driver Not Found"); } } if (dbConn.isClosed()) { dbConn = DriverManager.getConnection("jdbc:postgresql://" + dbAddress, user, password); } } /* * (non-Javadoc) * * @see database.DatabaseHandler#close() */ @Override synchronized public void close() throws SQLException { if (!isClosed()) { dbConn.close(); } } /* * (non-Javadoc) * * @see database.DatabaseHandler#isClosed() */ @Override synchronized public boolean isClosed() throws SQLException { return dbConn.isClosed(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#login(String, String) */ @Override synchronized public User login(String username, String password) { try { User u = getUserByID(username); if (u.password.equals(password)) { return u; } } catch (Exception e) { } return null; } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(ClientSite cs) throws SQLException { addClientPS.clearParameters(); addClientPS.setString(1, cs.name); addClientPS.setInt(2, cs.hospital.hospital_id); addClientPS.setArray(3, dbConn.createArrayOf("text", cs.instructions .toArray())); addClientPS.setString(4, cs.phone_number); addClientPS.executeUpdate(); } /** * Creates all the prepared statements on initialization to speed up * individual connection times. * @throws SQLException * if a database error occurs */ synchronized private void initializePreparedStatements() throws SQLException { addClientPS = dbConn.prepareStatement(ADD_CLIENT_SITE); addCourierPS = dbConn.prepareStatement(ADD_COURIER); addHospitalPS = dbConn.prepareStatement(ADD_HOSPITAL); addItemPS = dbConn.prepareStatement(ADD_ITEM, Statement.RETURN_GENERATED_KEYS); addToContainsPS = dbConn.prepareStatement(ADD_TO_CONTAINS); addShippingInfoPS = dbConn.prepareStatement(ADD_SHIPPING_INFO); addSpecimenPS = dbConn.prepareStatement(ADD_SPECIMEN); addStatusPS = dbConn.prepareStatement(ADD_STATUS); addUserPS = dbConn.prepareStatement(ADD_USER); addUserTypePS = dbConn.prepareStatement(ADD_USER_TYPE); updateCheckListPairPS = dbConn.prepareStatement(UPDATE_CHECKLIST_PAIR); updateClientSitePS = dbConn.prepareStatement(UPDATE_CLIENT_SITE); updateCourierPS = dbConn.prepareStatement(UPDATE_COURIER); updateHospitalPS = dbConn.prepareStatement(UPDATE_HOSPITAL); updateItemPS = dbConn.prepareStatement(UPDATE_ITEM); updateShippingInfoPS = dbConn.prepareStatement(UPDATE_SHIPPING_INFO); updateSpecimenPS = dbConn.prepareStatement(UPDATE_SPECIMEN); updateStatusPS = dbConn.prepareStatement(UPDATE_STATUS); updateUserPS = dbConn.prepareStatement(UPDATE_USER); updateUserTypePS = dbConn.prepareStatement(UPDATE_USER_TYPE); getCheckListsPS = dbConn.prepareStatement(GET_CHECKLISTS); getClientSitePS = dbConn.prepareStatement(GET_CLIENT_SITE); getCourierPS = dbConn.prepareStatement(GET_COURIER); getHospitalPS = dbConn.prepareStatement(GET_HOSPITAL); getItemPS = dbConn.prepareStatement(GET_ITEM); getShippingInfoPS = dbConn.prepareStatement(GET_SHIPPING_INFO); getSpecimenPS = dbConn.prepareStatement(GET_SPECIMEN); getContentsPS = dbConn.prepareStatement(GET_CONTENTS); getStatusPS = dbConn.prepareStatement(GET_STATUS); getUserPS = dbConn.prepareStatement(GET_USER); getUserTypePS = dbConn.prepareStatement(GET_USER_TYPE); getAllClientSitesPS = dbConn.prepareStatement(GET_ALL_CLIENT_SITES); getAllCouriersPS = dbConn.prepareStatement(GET_ALL_COURIERS); getAllHospitalsPS = dbConn.prepareStatement(GET_ALL_HOSPITALS); getAllItemsPS = dbConn.prepareStatement(GET_ALL_ITEMS); getAllShippingInfosPS = dbConn.prepareStatement(GET_ALL_SHIPPING_INFOS); getAllSpecimensPS = dbConn.prepareStatement(GET_ALL_SPECIMENS); getAllStatusesPS = dbConn.prepareStatement(GET_ALL_STATUSES); getAllUsersPS = dbConn.prepareStatement(GET_ALL_USERS); getAllUserTypesPS = dbConn.prepareStatement(GET_ALL_USER_TYPES); removeClientSitePS = dbConn.prepareStatement(REMOVE_CLIENT_SITE); removeCourierPS = dbConn.prepareStatement(REMOVE_COURIER); removeHospitalPS = dbConn.prepareStatement(REMOVE_HOSPITAL); removeItemPS = dbConn.prepareStatement(REMOVE_ITEM); removeShippingInfoPS = dbConn.prepareStatement(REMOVE_SHIPPING_INFO); removeSpecimenPS = dbConn.prepareStatement(REMOVE_SPECIMEN); removeStatusPS = dbConn.prepareStatement(REMOVE_STATUS); removeUserPS = dbConn.prepareStatement(REMOVE_USER); removeUserTypePS = dbConn.prepareStatement(REMOVE_USER_TYPE); // Specialized beginTransactionPS = dbConn.prepareStatement(BEGIN_TRANSACTION); commitTransactionPS = dbConn.prepareStatement(COMMIT_TRANSACTION); abortTransactionPS = dbConn.prepareStatement(ABORT_TRANSACTION); getUsersOfSitePS = dbConn.prepareStatement(GET_USERS_OF_SITE); getSpecimensFromPS = dbConn.prepareStatement(GET_SPECIMENS_FROM); getSpecimensToPS = dbConn.prepareStatement(GET_SPECIMENS_TO); getNotArrivedPS = dbConn.prepareStatement(GET_NOT_ARRIVED); } /////////////////////// // Database Commands // /////////////////////// /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(Courier c) throws SQLException { addCourierPS.clearParameters(); addCourierPS.setString(1, c.user.username); List<Integer> x = new ArrayList<Integer>(); for (ClientSite cs : c.route) { x.add(cs.client_id); } addCourierPS.setArray(2, dbConn.createArrayOf("int", x.toArray())); addCourierPS.setDouble(3, c.latitude); addCourierPS.setDouble(4, c.longitude); if (c.nextDest != null) { addCourierPS.setInt(5, c.nextDest.client_id); } else addCourierPS.setObject(5, null); addCourierPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(Hospital h) throws SQLException { addHospitalPS.clearParameters(); addHospitalPS.setString(1, h.name); addHospitalPS.setString(2, h.address); addHospitalPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(ShippingInformation si) throws SQLException { Specimen sp = si.specimen; addRecord(sp); addShippingInfoPS.clearParameters(); addShippingInfoPS.setString(1, sp.barcode); addShippingInfoPS.setString(2, si.shipper.username); addShippingInfoPS.setInt(3, si.destination.client_id); addShippingInfoPS.setInt(4, si.status.status_id); // HARD CODE THIS??? String cour = (si.courier == null) ? null : si.courier.user.username; addShippingInfoPS.setString(5, cour); try { addShippingInfoPS.executeUpdate(); } catch (SQLException e) { // If there is a SQL Error, remove the specimen added removeRecord(si.specimen); throw e; } //dbConn.commit(); //dbConn.setAutoCommit(true); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(Specimen sp) throws SQLException { // TODO MAKE BEGIN TRANSACTION addSpecimenPS.clearParameters(); addSpecimenPS.setString(1, sp.barcode); addSpecimenPS.setString(2, sp.description); addSpecimenPS.setString(3, sp.requirements); addSpecimenPS.executeUpdate(); Collection<Item> temp = sp.contents; try { for (Item i : temp) { addItemToBarcode(i, sp.barcode); } } catch (SQLException e) { // If there is a SQL Error, remove the specimen added removeRecord(sp); throw e; } } /** * Helper function to speak to the database * * @param h * The Hospital to be added to the database */ synchronized private void addItemToBarcode(Item i, String barcode) throws SQLException { addItemPS.clearParameters(); addItemPS.setString(1, i.name); addItemPS.setString(2, i.capColor); addItemPS.executeUpdate(); ResultSet rs = addItemPS.getGeneratedKeys(); rs.next(); addToContainsPS.clearParameters(); addToContainsPS.setString(1, barcode); addToContainsPS.setInt(2, rs.getInt(1)); addToContainsPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(Status st) throws SQLException { addStatusPS.clearParameters(); addStatusPS.setString(1, st.name); addStatusPS.setString(2, st.description); addStatusPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(User u) throws SQLException { addUserPS.clearParameters(); addUserPS.setString(1, u.username); addUserPS.setString(2, u.password); addUserPS.setString(3, u.fname); addUserPS.setString(4, u.lname); addUserPS.setInt(5, u.site.client_id); addUserPS.setInt(6, u.type.type_id); addUserPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#addRecord(records.Record) */ @Override synchronized public void addRecord(UserType ut) throws SQLException { addUserTypePS.clearParameters(); addUserTypePS.setString(1, ut.name); addUserTypePS.setString(2, ut.description); addUserTypePS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(CheckListPair clp) throws SQLException { updateCheckListPairPS.clearParameters(); updateCheckListPairPS.setArray(1, dbConn.createArrayOf("text", clp.startingList.toArray())); updateCheckListPairPS.setArray(2, dbConn.createArrayOf("text", clp.endingList.toArray())); updateCheckListPairPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(ClientSite cs) throws SQLException { updateClientSitePS.clearParameters(); updateClientSitePS.setString(1, cs.name); updateClientSitePS.setInt(2, cs.hospital.hospital_id); updateClientSitePS.setArray(3, dbConn.createArrayOf("text", cs.instructions.toArray())); updateClientSitePS.setString(4, cs.phone_number); updateClientSitePS.setInt(5, cs.client_id); updateClientSitePS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(Courier c) throws SQLException { // Creates a list of ID's and not objects List<Integer> clientIDs = new ArrayList<Integer>(); for (ClientSite cs : c.route) { clientIDs.add(cs.client_id); } updateCourierPS.clearParameters(); updateCourierPS.setArray(1, dbConn.createArrayOf("int", clientIDs .toArray())); updateCourierPS.setDouble(2, c.latitude); updateCourierPS.setDouble(3, c.longitude); if (c.nextDest != null) { updateCourierPS.setInt(4, c.nextDest.client_id); } else updateCourierPS.setObject(5, null); updateCourierPS.setString(5, c.user.username); updateCourierPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(Hospital h) throws SQLException { updateHospitalPS.clearParameters(); updateHospitalPS.setString(1, h.name); updateHospitalPS.setString(2, h.address); updateHospitalPS.setInt(3, h.hospital_id); updateHospitalPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(ShippingInformation si) throws SQLException { // TODO THIS IS WRONG? ILLEGAL BARCODE? updateShippingInfoPS.clearParameters(); updateShippingInfoPS.setString(1, si.shipper.username); updateShippingInfoPS.setInt(2, si.destination.client_id); updateShippingInfoPS.setInt(3, si.status.status_id); if (si.courier == null) { updateShippingInfoPS.setNull(4, java.sql.Types.VARCHAR); } else { updateShippingInfoPS.setString(4, si.courier.user.username); } updateShippingInfoPS.setString(5, si.specimen.barcode); updateShippingInfoPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(Specimen sp) throws SQLException { // TODO MAKE INTO TRANSACTION updateSpecimenPS.clearParameters(); updateSpecimenPS.setString(1, sp.description); updateSpecimenPS.setString(2, sp.requirements); updateSpecimenPS.setString(3, sp.barcode); Specimen old = getSpecimenByID(sp.barcode); Collection<Item> keepThese = intersection(old.contents, sp.contents); Collection<Item> changeThese = difference(old.contents, sp.contents); for (Item i : changeThese) { if (old.contents.contains(i)) { removeRecord(i); } else { addItemToBarcode(i, sp.barcode); } } try { for (Item i : keepThese) { updateItem(i); } // Barcode will stay the same, so dont update the rest until everything // else has been updated updateSpecimenPS.executeUpdate(); } catch (SQLException e) { // Error updating old one, reverting back changeRecord(old); throw e; } } /** * Returns the intersection of the two Collections where equality is based * solely on Item.item_id == other, not Item.equals(other). * * @param oldColl * A Collection to intersect with. * @param newColl * A Collection to intersect with. * @return A new Collection of the intersection of the two given Collections */ synchronized private Collection<Item> intersection(Collection<Item> oldColl, Collection<Item> newColl) { Set<Item> ret = new HashSet<Item>(); for (Item i : oldColl) { for (Item j : newColl) { if (i.item_id == j.item_id) { ret.add(j); } } } return ret; } /** * Returns the difference of the two collections where equality is based * solely on Item.item_id == other, not Item.equals(other) * * @param oldColl * A Collection of Items to find the difference * @param newColl * A Collection of Items to find the difference * @return A new Collection of Items containing the difference of the two * given Collections */ synchronized private Collection<Item> difference(Collection<Item> oldColl, Collection<Item> newColl) { Set<Item> ret = new HashSet<Item>(); Set<Item> temp = new HashSet<Item>(newColl); for (Item i : oldColl) { boolean mark = false; for (Item j : newColl) { if (i.item_id == j.item_id) { mark = true; temp.remove(j); break; } } if (!mark) ret.add(i); } ret.addAll(temp); return ret; } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(Status st) throws SQLException { updateStatusPS.clearParameters(); updateStatusPS.setString(1, st.name); updateStatusPS.setString(2, st.description); updateStatusPS.setInt(3, st.status_id); updateStatusPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(User u) throws SQLException { updateUserPS.clearParameters(); updateUserPS.setString(1, u.password); updateUserPS.setString(2, u.fname); updateUserPS.setString(3, u.lname); updateUserPS.setInt(4, u.site.client_id); updateUserPS.setInt(5, u.type.type_id); updateUserPS.setString(6, u.username); updateUserPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#changeRecord(records.Record) */ @Override synchronized public void changeRecord(UserType ut) throws SQLException { updateUserTypePS.clearParameters(); updateUserTypePS.setString(1, ut.name); updateUserTypePS.setString(2, ut.description); updateUserTypePS.setInt(3, ut.type_id); updateUserTypePS.executeUpdate(); } @Override synchronized public List<ClientSite> getAllClientSites() throws SQLException { List<ClientSite> list = new ArrayList<ClientSite>(); ResultSet rs = getAllClientSitesPS.executeQuery(); while (rs.next()) { list.add(new ClientSite(rs.getInt("client_id"), rs .getString("name"), getHospitalByID(rs.getInt("hospital_id")), Arrays.asList((String[]) rs.getArray("instructions") .getArray()), rs.getString("phone_number"))); } return list; } @Override synchronized public List<Courier> getAllCouriers() throws SQLException { List<Courier> list = new ArrayList<Courier>(); ResultSet rs = getAllCouriersPS.executeQuery(); while (rs.next()) { List<ClientSite> temp = new ArrayList<ClientSite>(); Integer[] array = (Integer[]) rs.getArray("route").getArray(); for (int cid : array) { temp.add(getClientSiteByID(cid)); } list.add(new Courier(getUserByID(rs.getString("username")), temp, rs .getDouble("lat_loc"), rs.getDouble("long_loc"), getClientSiteByID(rs.getInt("next_destination")))); } return list; } @Override synchronized public List<Hospital> getAllHospitals() throws SQLException { List<Hospital> list = new ArrayList<Hospital>(); ResultSet rs = getAllHospitalsPS.executeQuery(); while (rs.next()) { list.add(new Hospital(rs.getInt("hospital_id"), rs .getString("name"), rs.getString("address"))); } return list; } @Override synchronized public List<Item> getAllItems() throws SQLException { List<Item> list = new ArrayList<Item>(); ResultSet rs = getAllItemsPS.executeQuery(); while (rs.next()) { list.add(new Item(rs.getInt("item_id"), rs.getString("name"), rs .getString("cap_color"))); } return list; } @Override synchronized public List<ShippingInformation> getAllShippingInformation() throws SQLException { List<ShippingInformation> list = new ArrayList<ShippingInformation>(); ResultSet rs = getAllShippingInfosPS.executeQuery(); while (rs.next()) { list.add(new ShippingInformation(getSpecimenByID(rs .getString("barcode")), getUserByID(rs.getString("shipper")), getClientSiteByID(rs.getInt("destination_id")), getStatusByID(rs .getInt("status_id")), getCourierByID(rs .getString("courier_id")))); } return list; } @Override synchronized public List<Specimen> getAllSpecimens() throws SQLException { List<Specimen> list = new ArrayList<Specimen>(); ResultSet rs = getAllSpecimensPS.executeQuery(); while (rs.next()) { String barcode = rs.getString("barcode"); String description = rs.getString("description"); String requirements = rs.getString("requirements"); List<Item> contents = getContents(barcode); list.add(new Specimen(barcode, description, requirements, Collections.unmodifiableList(contents))); } return list; } @Override synchronized public List<Status> getAllStatuses() throws SQLException { List<Status> list = new ArrayList<Status>(); ResultSet rs = getAllStatusesPS.executeQuery(); while (rs.next()) { list.add(new Status(rs.getInt("status_id"), rs.getString("name"), rs.getString("description"))); } return list; } @Override synchronized public List<User> getAllUsers() throws SQLException { List<User> list = new ArrayList<User>(); ResultSet rs = getAllUsersPS.executeQuery(); while (rs.next()) { list.add(new User(rs.getString("username"), rs .getString("password"), rs.getString("fname"), rs .getString("lname"), getClientSiteByID(rs.getInt("site_id")), getUserTypeByID(rs.getInt("type_id")))); } return list; } @Override synchronized public List<UserType> getAllUserTypes() throws SQLException { List<UserType> list = new ArrayList<UserType>(); ResultSet rs = getAllUserTypesPS.executeQuery(); while (rs.next()) { list.add(new UserType(rs.getInt("type_id"), rs.getString("name"), rs.getString("description"))); } return list; } @Override synchronized public CheckListPair getCheckLists() throws SQLException { ResultSet record; record = getCheckListsPS.executeQuery(); CheckListPair clp = null; if (record.next()) { clp = new CheckListPair(Arrays.asList((String[]) record.getArray( "starting").getArray()), Arrays.asList((String[]) record .getArray("ending").getArray())); } if (record.next()) throw new SQLException("Too many records with same ID!"); return clp; } @Override synchronized public ClientSite getClientSiteByID(int id) throws SQLException { getClientSitePS.clearParameters(); getClientSitePS.setInt(1, id); ResultSet record = getClientSitePS.executeQuery(); ClientSite cs = null; if (record.next()) { cs = new ClientSite(record.getInt("client_id"), record .getString("name"), getHospitalByID(record .getInt("hospital_id")), Arrays.asList((String[]) record .getArray("instructions").getArray()), record .getString("phone_number")); } if (record.next()) throw new SQLException("Too many records with same ID!"); return cs; } /** * Returns a list of items that are contained by the given barcode * * @param id * The barcode of the specimen to get the contents of * @return A List of Items that are related to the barcode * @throws SQLException * If there is a database error */ synchronized private List<Item> getContents(String id) throws SQLException { getContentsPS.clearParameters(); getContentsPS.setString(1, id); ResultSet contRec = getContentsPS.executeQuery(); List<Item> contents = new ArrayList<Item>(); while (contRec.next()) { if (!contRec.getString("barcode").equals(id)) throw new SQLException("Multiple Specimens retrieved"); contents.add(getItemByID(contRec.getInt("item_id"))); } return contents; } @Override synchronized public Courier getCourierByID(String id) throws SQLException { getCourierPS.clearParameters(); getCourierPS.setString(1, id); ResultSet record = getCourierPS.executeQuery(); Courier cour = null; if (record.next()) { List<ClientSite> temp = new ArrayList<ClientSite>(); Integer[] array = (Integer[]) record.getArray("route").getArray(); for (int cid : array) { temp.add(getClientSiteByID(cid)); } cour = new Courier(getUserByID(record.getString("username")), temp, record.getDouble("lat_loc"), record.getDouble("long_loc"), getClientSiteByID(record.getInt("next_destination"))); } if (record.next()) throw new SQLException("Too many records with same ID!"); return cour; } @Override synchronized public Hospital getHospitalByID(int id) throws SQLException { getHospitalPS.clearParameters(); getHospitalPS.setInt(1, id); ResultSet record = getHospitalPS.executeQuery(); Hospital h = null; if (record.next()) { h = new Hospital(record.getInt("hospital_id"), record .getString("name"), record.getString("address")); } if (record.next()) throw new SQLException("Too many records with same ID!"); return h; } @Override synchronized public Item getItemByID(int item_id) throws SQLException { getItemPS.clearParameters(); getItemPS.setInt(1, item_id); ResultSet record = getItemPS.executeQuery(); Item item = null; if (record.next()) { item = new Item(record.getInt("item_id"), record.getString("name"), record.getString("cap_color")); } if (record.next()) throw new SQLException("Too many records with same ID!"); return item; } @Override synchronized public List<ShippingInformation> getNotArrived() throws SQLException { List<ShippingInformation> list = new ArrayList<ShippingInformation>(); ResultSet rs = getNotArrivedPS.executeQuery(); while (rs.next()) { list.add(new ShippingInformation(getSpecimenByID(rs .getString("barcode")), getUserByID(rs.getString("shipper")), getClientSiteByID(rs.getInt("destination_id")), getStatusByID(rs .getInt("status_id")), getCourierByID(rs .getString("courier_id")))); } return list; } @Override synchronized public ShippingInformation getShippingByID(String barcode) throws SQLException { getShippingInfoPS.clearParameters(); getShippingInfoPS.setString(1, barcode); ResultSet record = getShippingInfoPS.executeQuery(); ShippingInformation si = null; if (record.next()) { si = new ShippingInformation(getSpecimenByID(record .getString("barcode")), getUserByID(record .getString("shipper")), getClientSiteByID(record .getInt("destination_id")), getStatusByID(record .getInt("status_id")), getCourierByID(record .getString("courier_id"))); } if (record.next()) throw new SQLException("Too many records with same ID!"); return si; } @Override synchronized public ShippingInformation getShippingInfoFor(String barcode) throws SQLException { return getShippingByID(barcode); } @Override synchronized public Specimen getSpecimenByID(String id) throws SQLException { getSpecimenPS.clearParameters(); getSpecimenPS.setString(1, id); ResultSet specRec = getSpecimenPS.executeQuery(); Specimen spec = null; if (specRec.next()) { String barcode = specRec.getString("barcode"); String description = specRec.getString("description"); String requirements = specRec.getString("requirements"); spec = new Specimen(barcode, description, requirements, Collections .unmodifiableList(getContents(barcode))); } if (specRec.next()) throw new SQLException("Too many records with same ID!"); return spec; } /** * Returns a list of ShippingInformation whose specimens either shipped from * the given ClientSite based on the given boolean. * * @param cs * The ClientSite referenced for the ShippingInformation * @return A List of ShippingInformation, in no particular order. * @throws SQLException * If a database error occurs. */ synchronized private List<ShippingInformation> getSpecimensFrom(ClientSite cs) throws SQLException { getSpecimensFromPS.clearParameters(); getSpecimensFromPS.setInt(1, cs.client_id); ResultSet rs = getSpecimensFromPS.executeQuery(); List<ShippingInformation> list = new ArrayList<ShippingInformation>(); while (rs.next()) { list.add(getShippingByID(rs.getString(1))); } return list; } /** * Returns a list of ShippingInformation whose specimens shipped to the * given ClientSite. * * @param cs * The ClientSite referenced for the ShippingInformation * @return A List of ShippingInformation, in no particular order. * @throws SQLException * If a database error occurs. */ synchronized private List<ShippingInformation> getSpecimensTo(ClientSite cs) throws SQLException { getSpecimensToPS.clearParameters(); getSpecimensToPS.setInt(1, cs.client_id); ResultSet rs = getSpecimensToPS.executeQuery(); List<ShippingInformation> list = new ArrayList<ShippingInformation>(); while (rs.next()) { list.add(getShippingByID(rs.getString(1))); } return list; } @Override synchronized public Status getStatusByID(int id) throws SQLException { getStatusPS.clearParameters(); getStatusPS.setInt(1, id); ResultSet record = getStatusPS.executeQuery(); Status stat = null; if (record.next()) { stat = new Status(record.getInt("status_id"), record .getString("name"), record.getString("description")); } if (record.next()) throw new SQLException("Too many records with same ID!"); return stat; } @Override synchronized public User getUserByID(String id) throws SQLException { getUserPS.clearParameters(); getUserPS.setString(1, id); ResultSet record = getUserPS.executeQuery(); User u = null; if (record.next()) { u = new User(record.getString("username"), record .getString("password"), record.getString("fname"), record .getString("lname"), getClientSiteByID(record.getInt("site_id")), getUserTypeByID(record .getInt("type_id"))); } if (record.next()) throw new SQLException("Too many records with same ID!"); return u; } /* * (non-Javadoc) * * @see database.DatabaseHandler#getUsersOf(int) */ @Override synchronized public List<User> getUsersOf(ClientSite cs) throws SQLException { getUsersOfSitePS.clearParameters(); getUsersOfSitePS.setInt(1, cs.client_id); ResultSet rs = getUsersOfSitePS.executeQuery(); List<User> list = new ArrayList<User>(); while (rs.next()) { list.add(getUserByID(rs.getString(1))); } return list; } @Override synchronized public UserType getUserType(String username) throws SQLException { User u = getUserByID(username); if (u == null) return null; return u.type; } @Override synchronized public UserType getUserTypeByID(int id) throws SQLException { getUserTypePS.clearParameters(); getUserTypePS.setInt(1, id); ResultSet record = getUserTypePS.executeQuery(); UserType ut = null; if (record.next()) { ut = new UserType(record.getInt("type_id"), record .getString("name"), record.getString("description")); } if (record.next()) throw new SQLException("Too many records with same ID!"); return ut; } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(ClientSite cs) throws SQLException { removeClientSitePS.clearParameters(); removeClientSitePS.setInt(1, cs.client_id); removeClientSitePS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(Courier c) throws SQLException { removeCourierPS.clearParameters(); removeCourierPS.setString(1, c.user.username); removeCourierPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(Hospital h) throws SQLException { removeHospitalPS.clearParameters(); removeHospitalPS.setInt(1, h.hospital_id); removeHospitalPS.executeUpdate(); } /** * Removes the given Item from the database and any associations to it. * * @param i * the Item to be removed from the database * @throws SQLException * if an error occurs in the database */ synchronized private void removeRecord(Item i) throws SQLException { removeItemPS.clearParameters(); removeItemPS.setInt(1, i.item_id); removeItemPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(ShippingInformation si) throws SQLException { String barcode = si.specimen.barcode; removeRecord(si.specimen); removeShippingInfoPS.clearParameters(); removeShippingInfoPS.setString(1, barcode); removeShippingInfoPS.executeUpdate(); } /** * Removes the given Specimen from the database and any associations to it. * * @param barcode * the barcode of the Specimen to be removed from the database * @throws SQLException * if an error occurs in the database */ synchronized private void removeRecord(Specimen sp) throws SQLException { String barcode = sp.barcode; Specimen spec = getSpecimenByID(barcode); removeSpecimenPS.clearParameters(); removeSpecimenPS.setString(1, barcode); for (Item i : spec.contents) { removeRecord(i); } removeSpecimenPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(Status st) throws SQLException { removeStatusPS.clearParameters(); removeStatusPS.setInt(1, st.status_id); removeStatusPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(User u) throws SQLException { removeUserPS.clearParameters(); removeUserPS.setString(1, u.username); removeUserPS.executeUpdate(); } /* * (non-Javadoc) * * @see database.DatabaseHandler#removeRecord(records.Record) */ @Override synchronized public void removeRecord(UserType ut) throws SQLException { removeUserTypePS.clearParameters(); removeUserTypePS.setInt(1, ut.type_id); removeUserTypePS.executeUpdate(); } //////////////////////////////// // Specialized Getter Methods // //////////////////////////////// @Override synchronized public List<ShippingInformation> specimensFrom(ClientSite cs) throws SQLException { return getSpecimensFrom(cs); } @Override synchronized public List<ShippingInformation> specimensTo(ClientSite cs) throws SQLException { return getSpecimensTo(cs); } /** * Helper function to communicate with database. * * @param is * The Item to update in the database */ synchronized private void updateItem(Item i) throws SQLException { updateItemPS.clearParameters(); updateItemPS.setString(1, i.name); updateItemPS.setString(2, i.capColor); updateItemPS.setInt(3, i.item_id); updateItemPS.executeUpdate(); } @Override synchronized public Date getLastUpdate(String barcode) throws SQLException { getShippingInfoPS.clearParameters(); getShippingInfoPS.setString(1, barcode); ResultSet results = getShippingInfoPS.executeQuery(); results.next(); Date date = results.getTimestamp("time_updated"); return date; } @Override synchronized public Date getFirstUpdate(String barcode) throws SQLException { getShippingInfoPS.clearParameters(); getShippingInfoPS.setString(1, barcode); ResultSet results = getShippingInfoPS.executeQuery(); results.next(); Date date = results.getTimestamp("time_added"); return date; } }
Java
package jvm.jtacck.test.db; /* * Copy and Paste of this code from http://pastebin.com/f10584951 * * License below states free use as long as license is kept with it. */ /* * Added additional null checks when closing the ResultSet and Statements. * * Thanks to pihug12 and Grzegorz Oledzki at stackoverflow.com * http://stackoverflow.com/questions/5332149/jdbc-scriptrunner-java-lang-nullpointerexception?tab=active#tab-top */ /* * Modified: Use logWriter in print(Object), JavaDoc comments, correct Typo. */ /* * Modified by Pantelis Sopasakis <chvng@mail.ntua.gr> to take care of DELIMITER statements. This way you * can execute scripts that contain some TRIGGER creation code. New version using REGEXPs! Latest * modification: Cater for a NullPointerException while parsing. Date: Feb 16, 2011, 11:48 EET */ /* * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class from the iBATIS Apache * project. Only removed dependency on Resource class and a constructor */ /* * Copyright 2004 Clinton Begin 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. */ import java.io.IOException; import java.io.LineNumberReader; import java.io.PrintWriter; import java.io.Reader; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Tool to run database scripts. This version of the script can be found at * https://gist.github.com/gists/831762/ */ public class ScriptRunner { private static final String DEFAULT_DELIMITER = ";"; private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+"; private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER"; private final Connection connection; private final boolean stopOnError; private final boolean autoCommit; private PrintWriter logWriter = new PrintWriter(System.out); private PrintWriter errorLogWriter = new PrintWriter(System.err); private String delimiter = DEFAULT_DELIMITER; private boolean fullLineDelimiter = false; /** * Default constructor. * * @param connection * @param autoCommit * @param stopOnError */ public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) { this.connection = connection; this.autoCommit = autoCommit; this.stopOnError = stopOnError; } /** * @param delimiter * @param fullLineDelimiter */ public void setDelimiter(String delimiter, boolean fullLineDelimiter) { this.delimiter = delimiter; this.fullLineDelimiter = fullLineDelimiter; } /** * Setter for logWriter property. * * @param logWriter * - the new value of the logWriter property */ public void setLogWriter(PrintWriter logWriter) { this.logWriter = logWriter; } /** * Setter for errorLogWriter property. * * @param errorLogWriter * - the new value of the errorLogWriter property */ public void setErrorLogWriter(PrintWriter errorLogWriter) { this.errorLogWriter = errorLogWriter; } /** * Runs an SQL script (read in using the Reader parameter). * * @param reader * - the source of the script * @throws SQLException * if any SQL errors occur * @throws IOException * if there is an error reading from the Reader */ public void runScript(Reader reader) throws IOException, SQLException { try { boolean originalAutoCommit = connection.getAutoCommit(); try { if (originalAutoCommit != autoCommit) { connection.setAutoCommit(autoCommit); } runScript(connection, reader); } finally { connection.setAutoCommit(originalAutoCommit); } } catch (IOException e) { throw e; } catch (SQLException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error running script. Cause: " + e, e); } } /** * Runs an SQL script (read in using the Reader parameter) using the connection passed in. * * @param conn * - the connection to use for the script * @param reader * - the source of the script * @throws SQLException * if any SQL errors occur * @throws IOException * if there is an error reading from the Reader */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { StringBuffer command = null; try { LineNumberReader lineReader = new LineNumberReader(reader); String line = null; while ((line = lineReader.readLine()) != null) { if (command == null) { command = new StringBuffer(); } String trimmedLine = line.trim(); if (trimmedLine.startsWith("--")) { println(trimmedLine); } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) { // Do nothing } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) { // Do nothing } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); Matcher matcher = pattern.matcher(trimmedLine); if (matcher.matches()) { setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter); line = lineReader.readLine(); if (line == null) { break; } trimmedLine = line.trim(); } command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); command.append(" "); Statement statement = conn.createStatement(); println(command); boolean hasResults = false; if (stopOnError) { hasResults = statement.execute(command.toString()); } else { try { statement.execute(command.toString()); } catch (SQLException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); } } if (autoCommit && !conn.getAutoCommit()) { conn.commit(); } ResultSet rs = statement.getResultSet(); if (hasResults && rs != null) { ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); for (int i = 0; i < cols; i++) { String name = md.getColumnLabel(i); print(name + "\t"); } println(""); while (rs.next()) { for (int i = 1; i <= cols; i++) { String value = rs.getString(i); print(value + "\t"); } println(""); } } command = null; try { if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (statement != null) { statement.close(); } } catch (Exception e) { e.printStackTrace(); // Ignore to workaround a bug in Jakarta DBCP } } else { Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); Matcher matcher = pattern.matcher(trimmedLine); if (matcher.matches()) { setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter); line = lineReader.readLine(); if (line == null) { break; } trimmedLine = line.trim(); } command.append(line); command.append(" "); } } if (!autoCommit) { conn.commit(); } } catch (SQLException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); throw e; } catch (IOException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); throw e; } finally { conn.rollback(); flush(); } } private String getDelimiter() { return delimiter; } private void print(Object o) { if (logWriter != null) { logWriter.print(o); } } private void println(Object o) { if (logWriter != null) { logWriter.println(o); } } private void printlnError(Object o) { if (errorLogWriter != null) { errorLogWriter.println(o); } } private void flush() { if (logWriter != null) { logWriter.flush(); } if (errorLogWriter != null) { errorLogWriter.flush(); } } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; /** * Data model for poll response. It is sent to server after response of student. */ public class PollResponse { private final String documentId; private final String sheetId; private final boolean anonymous; private final int questionNumber; private final String answers; private final boolean success; public PollResponse(String documentId, String sheetId, boolean anonymous, int questionNumber, String answers, boolean success) { super(); this.documentId = documentId; this.sheetId = sheetId; this.anonymous = anonymous; this.questionNumber = questionNumber; this.answers = answers; this.success = success; } public String getDocumentId() { return documentId; } public String getSheetId() { return sheetId; } public boolean isAnonymous() { return anonymous; } public int getQuestionNumber() { return questionNumber; } public String getAnswers() { return answers; } public boolean isSuccess() { return success; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; /** * Data model for response from Url Shortener service (used by GSON) */ public class ShortenedUrl { private final String id; public String getId() { return id; } public ShortenedUrl(String id) { this.id = id; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.io.Serializable; /** * Data model for quizzes from Google Docs List API. It's used both for * collections and spreadsheets (quizzes) */ public class DocsEntry implements Serializable, Comparable<DocsEntry> { /** * Type of doc entry */ public static final int COLLECTION = 0; public static final int QUIZ = 1; private int type; private String title; private String id; public DocsEntry(int type, String title, String id) { this.type = type; this.title = title; this.id = id; } public int getType() { return type; } public String getTitle() { return title; } public String getId() { return id; } @Override public int compareTo(DocsEntry another) { // Collections first, then sort alphabetically if (this.getType() == another.getType()) { return this.getTitle().compareTo(another.getTitle()); } else if (this.getType() == QUIZ && another.getType() == COLLECTION) { return 1; } else { return -1; } } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.io.Serializable; import java.util.List; /** * Data model for individual quiz. Contains questions and metadata. */ public class Quiz implements Serializable { private final String title; private final String description; private final String image; private final String leaderboardSheet; private final String statisticsSheet; private final String documentId; private int score; private List<Question> questions; public Quiz(String title, String description, String image, List<Question> questions, String leaderboardWorksheet, String documentId, String statisticsSheet) { this.title = title; this.description = description; this.questions = questions; this.image = image; this.leaderboardSheet = leaderboardWorksheet; this.documentId = documentId; this.statisticsSheet = statisticsSheet; } public String getTitle() { return title; } public String getDescription() { return description; } public String getImage() { return image; } public List<Question> getQuestions() { // Can be modified, because I perform filtering and randomizing of questions // later return questions; } public void setQuestions(List<Question> questions) { this.questions = questions; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getLeaderboardSheet() { return leaderboardSheet; } public String getDocumentId() { return documentId; } public String getStatisticsSheet() { return statisticsSheet; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.util.List; /** * Data model for statistics related to question */ public class Statistics { private String questionText; private int successes; private int failures; private List<Integer> answerCounts; public int getSuccesses() { return successes; } public void setSuccesses(int successes) { this.successes = successes; } public int getFailures() { return failures; } public void setFailures(int failures) { this.failures = failures; } public List<Integer> getAnswerCounts() { return answerCounts; } public Statistics(int successes, int failures, List<Integer> answerCounts, String questionText) { this.successes = successes; this.failures = failures; this.answerCounts = answerCounts; this.questionText = questionText; } public String getQuestionText() { return questionText; } public void setQuestionText(String questionText) { this.questionText = questionText; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.io.Serializable; import java.util.List; /** * Data model for question in the quiz */ public class Question implements Serializable { private final String questionText; private final List<Answer> answers; private final int number; private boolean success; private boolean anonymous; // Just for polling /** * Multiple choice is select 1 of X, Multiple select is Y of X */ public enum QuestionType { SINGLE_CHOICE, MULTIPLE_CHOICE } public String getQuestionText() { return questionText; } public List<Answer> getAnswers() { // Can be modified, because I perform randomizing answers later return answers; } /** * Determines question type based on number of correct answers */ public QuestionType getType() { int correctAnswers = 0; for (Answer answer : answers) { if (answer.isCorrect()) { correctAnswers++; } } if (correctAnswers == 1) { return QuestionType.SINGLE_CHOICE; } else { return QuestionType.MULTIPLE_CHOICE; } } public Question(String questionText, List<Answer> answers, int number) { this.questionText = questionText; this.answers = answers; this.number = number; this.anonymous = false; } public int getNumber() { return number; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public boolean isAnonymous() { return anonymous; } public void setAnonymous(boolean anonymous) { this.anonymous = anonymous; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import org.quizpoll.util.Utils; import java.io.Serializable; import java.util.Collections; import java.util.List; /** * Data model for polling session. Contains questions and metadata. */ public class Poll implements Serializable { // Special values for currentQuestion public static final int WAITING_FOR_INSTRUCTOR = -1; public static final int CLOSED = -2; public static final int UNKNOWN = -3; private final String title; private final String internalDataSheet; private final String responsesSheet; private final String documentId; private final List<Question> questions; private int currentQuestion; public Poll(String title, List<Question> questions, String internalDataWorksheet, String responsesWorksheet, String spreadsheetId) { this.internalDataSheet = internalDataWorksheet; this.responsesSheet = responsesWorksheet; this.title = title; this.questions = questions; this.documentId = spreadsheetId; this.currentQuestion = UNKNOWN; } public String getTitle() { return Utils.formatPollingName(title); } public List<Question> getQuestions() { return Collections.unmodifiableList(questions); } public String getDocumentId() { return documentId; } public String getInternalDataSheet() { return internalDataSheet; } public String getResponsesSheet() { return responsesSheet; } public int getCurrentQuestion() { return currentQuestion; } public void setCurrentQuestion(int currentQuestion) { this.currentQuestion = currentQuestion; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.io.Serializable; /** * Data model for answer for the question */ public class Answer implements Serializable, Comparable<Answer> { private final String answerText; private final boolean correct; private final int number; private boolean answered; public Answer(String answerText, boolean correct, int number) { this.answerText = answerText; this.correct = correct; this.number = number; } public String getAnswerText() { return answerText; } public boolean isCorrect() { return correct; } public int getNumber() { return number; } public boolean isAnswered() { return answered; } public void setAnswered(boolean answered) { this.answered = answered; } @Override public int compareTo(Answer another) { return this.number - another.number; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data.model; import java.io.Serializable; /** * Data model for leaderboard entry from spreadsheet. */ public class LeaderboardEntry implements Serializable, Comparable<LeaderboardEntry> { private int score; private final String ldap; public LeaderboardEntry(int score, String ldap) { this.score = score; this.ldap = ldap; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getLdap() { return ldap; } @Override public int compareTo(LeaderboardEntry another) { return another.score - this.score; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Helper class for accessing key-value settings. */ public class Preferences { /** * Types of preferences */ public static enum PrefType { AUTH_TOKEN_AE, AUTH_TOKEN_DOCS, USER_EMAIL, COOKIE_APPENGINE } public static void add(PrefType name, int value, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putInt(name.toString(), value); editor.commit(); } public static void add(PrefType name, float value, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(name.toString(), value); editor.commit(); } public static void add(PrefType name, String value, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putString(name.toString(), value); editor.commit(); } public static void add(PrefType name, boolean value, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(name.toString(), value); editor.commit(); } public static int getInt(PrefType name, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); return settings.getInt(name.toString(), 0); } public static double getDouble(PrefType name, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); return settings.getFloat(name.toString(), 0f); } public static String getString(PrefType name, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); return settings.getString(name.toString(), null); } public static boolean getBoolean(PrefType name, Context context) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); return settings.getBoolean(name.toString(), false); } public static boolean hasString(PrefType name, Context context) { return (getString(name, context) != null); } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.provider.BaseColumns; /** * Content Provider that exposes data in the database */ public class QuizPollProvider extends ContentProvider { private static final String DATABASE_NAME = "quizpoll.db"; private static final int DATABASE_VERSION = 1; private static final String POLLS_TABLE_NAME = "polls"; private static final String POLL_ITEM = "poll"; public static final String AUTHORITY = "org.quizpoll"; /** * Helper class that defines the columns that describe a polls list. */ public static final class PollList implements BaseColumns { /** * Content URI for a poll list */ public static final Uri CONTENT_URI = Uri.parse("content://" + QuizPollProvider.AUTHORITY + "/" + POLLS_TABLE_NAME); /** * Content URI for a single item */ public static final Uri ITEM_URI = Uri.parse("content://" + QuizPollProvider.AUTHORITY + "/" + POLL_ITEM); /** * MIME type for a poll list */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/org.quizpoll.poll_list"; /** * MIME type for a poll item */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/org.quizpoll.poll"; /** * Name of the poll */ public static final String TITLE = "title"; /** * Spreadsheet ID */ public static final String DOCUMENT_ID = "document_id"; /** * Timestamp of last access, used for sorting */ public static final String ACCESSSED = "accessed"; } // Codes for types of content that can be addressed // All polls private static final int LOOKUP_POLLS = 0; // Poll by document id private static final int LOOKUP_POLL_BY_DOCUMENT_ID = 1; // UriMatcher to recognize the URIs passed to this provider private static final UriMatcher sUriMatcher; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // Catch content://.../polls sUriMatcher.addURI(AUTHORITY, POLLS_TABLE_NAME, LOOKUP_POLLS); // Catch content://.../poll/* sUriMatcher.addURI(AUTHORITY, POLL_ITEM + "/*", LOOKUP_POLL_BY_DOCUMENT_ID); } /** * Factory class that will (re)create the database if necessary. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context content) { // Open the DB super(content, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create the poll lists table final String sql = "CREATE TABLE " + POLLS_TABLE_NAME + " (" + PollList._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PollList.DOCUMENT_ID + " TEXT, " + PollList.TITLE + " TEXT, " + PollList.ACCESSSED + " BIGINT);"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop tables db.execSQL("DROP TABLE IF EXISTS " + POLLS_TABLE_NAME); // Recreate database onCreate(db); } } // Instance of the DatabaseHelper providing access to the DB private DatabaseHelper mDbHelper; @Override public boolean onCreate() { mDbHelper = new DatabaseHelper(getContext()); return true; } @Override public String getType(Uri uri) { // Match URI and return correct MIME type switch (sUriMatcher.match(uri)) { case LOOKUP_POLLS: return PollList.CONTENT_TYPE; case LOOKUP_POLL_BY_DOCUMENT_ID: return PollList.CONTENT_ITEM_TYPE; } throw new IllegalArgumentException("Invalid URI:" + uri); } @Override public Uri insert(Uri uri, ContentValues initialValues) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); try { switch (sUriMatcher.match(uri)) { case LOOKUP_POLLS: initialValues.put(PollList.ACCESSSED, System.currentTimeMillis()); long taskId = db.insert(POLLS_TABLE_NAME, null, initialValues); return ContentUris.withAppendedId(PollList.CONTENT_URI, taskId); } throw new IllegalArgumentException("Invalid URI:" + uri); } finally { db.close(); } } @Override public int delete(Uri uri, String where, String[] whereArgs) { throw new UnsupportedOperationException("Delete not supported"); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); switch (sUriMatcher.match(uri)) { case LOOKUP_POLLS: return db.query(POLLS_TABLE_NAME, projection, selection, selectionArgs, null, null, PollList.ACCESSSED + " DESC"); } db.close(); // In matched case, cursor.close() is closing connection // automatically throw new IllegalArgumentException("Invalid URI:" + uri); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); try { if (values == null) { values = new ContentValues(); } switch (sUriMatcher.match(uri)) { case LOOKUP_POLL_BY_DOCUMENT_ID: values.put(PollList.ACCESSSED, System.currentTimeMillis()); return db.update(POLLS_TABLE_NAME, values, PollList.DOCUMENT_ID + " = '" + uri.getLastPathSegment() + "'", selectionArgs); } throw new IllegalArgumentException("Invalid URI:" + uri + sUriMatcher.match(uri)); } finally { db.close(); } } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.util; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import org.quizpoll.R; import org.quizpoll.ui.HomeActivity; /** * A class that handles some common activity-related functionality in the app, * such as setting up the action bar. Taken from Google IO 2011 app and * modified. */ public class ActivityHelper { private final Activity activity; private TextView titleText; public ActivityHelper(Activity activity) { this.activity = activity; } /** * Invoke "home" action, returning to HomeActivity. */ public void goHome() { if (activity instanceof HomeActivity) { return; } final Intent intent = new Intent(activity, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); } public void setupActionBar(String title) { setupActionBar(title, true); } /** * Sets up the action bar with the given title and accent color. If title is * null, then the app logo will be shown instead of a title. Otherwise, a home * button and title are visible. If color is null, then the default colorstrip * is visible. */ public void setupActionBar(String title, boolean showHomeButton) { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; View.OnClickListener homeClickListener = new View.OnClickListener() { @Override public void onClick(View view) { goHome(); } }; if (title != null) { // Add Home button if (showHomeButton) { addActionButtonCompat(R.drawable.ic_title_home, homeClickListener, true); } // Add title text titleText = new TextView(activity, null, R.attr.actionbarCompatTextStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(title); actionBarCompat.addView(titleText); } else { // Add app name titleText = new TextView(activity, null, R.attr.actionbarCompatTextStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(R.string.app_name); actionBarCompat.addView(titleText); // Add logo //ImageButton logo = new ImageButton(activity, null, R.attr.actionbarCompatLogoStyle); //logo.setOnClickListener(homeClickListener); //actionBarCompat.addView(logo); // Add spring (dummy view to align future children to the right) View spring = new View(activity); spring.setLayoutParams(springLayoutParams); actionBarCompat.addView(spring); } } /** * Change title later - needs to be initialized using setupActionBar */ public void changeTitle(String title) { if (titleText != null) { titleText.setText(title); } } /** * Returns the {@link ViewGroup} for the action bar on phones (compatibility * action bar). Can return null, and will return null on Honeycomb. */ public ViewGroup getActionBarCompat() { return (ViewGroup) activity.findViewById(R.id.actionbar_compat); } /** * Adds an action bar button to the compatibility action bar (on phones). */ public View addActionButtonCompat(int iconResId, View.OnClickListener clickListener, boolean separatorAfter) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(activity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams(new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(activity, null, R.attr.actionbarCompatButtonStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams((int) activity.getResources() .getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageResource(iconResId); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setOnClickListener(clickListener); // Add separator and button to the action bar in the desired order if (!separatorAfter) { actionBar.addView(separator); } actionBar.addView(actionButton); if (separatorAfter) { actionBar.addView(separator); } return actionButton; } }
Java
/* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.quizpoll.util; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import org.quizpoll.data.Preferences; import org.quizpoll.data.Preferences.PrefType; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Utility functions, mainly for formatting. */ public class Utils { private static String version = null; private static int versionCode = -1; /** * Formats date in more friendly way from server response. */ public static String formatDate(String aeDate) { // Remove the colon, because it's not ISO complaint int lastColon = aeDate.lastIndexOf(":"); aeDate = aeDate.substring(0, lastColon - 1) + aeDate.substring(lastColon + 1, aeDate.length()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:ss:mmZ"); try { Date date = sdf.parse(aeDate); return DateFormat.getDateTimeInstance().format(date); } catch (ParseException e) { return null; } } /** * All quiz spreadsheets now contain [Q] to differentiate them in the list */ public static String formatQuizName(String quizName) { return quizName.replace("[Q]", "").trim(); } /** * All polling spreadsheets now contain [P] to differentiate them in the list */ public static String formatPollingName(String pollingName) { return pollingName.replace("[P]", "").trim(); } public static String getVersion(Context context) { if (version == null) { updateVersion(context); } return version; } public static int getVersionCode(Context context) { if (versionCode == -1) { updateVersion(context); } return versionCode; } public static void updateVersion(Context context) { try { Utils.version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; Utils.versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { Utils.version = "Unknown"; Utils.versionCode = -1; } } /** * Extracts LDAP username from user email */ public static String getLdap(Context context) { return Preferences.getString(PrefType.USER_EMAIL, context).split("@")[0]; } /** * Returns google account registered on this phone or null if account not * present */ public static String getGoogleAccount(Context context) { AccountManager manager = AccountManager.get(context); Account[] accounts = manager.getAccountsByType("com.google"); String accountEmail = null; for (Account account : accounts) { return account.name; } return null; } }
Java