try {
                    if (content != null)
                        content.close();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)), e));
                }

/**
 * ****************************************************************************
 *
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *      Matt Chapman, example@nnthink.com - 89977 Make JDT .java agnostic
 * *****************************************************************************
 */
package org.eclipse.jdt.internal.ui.wizards;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.ibm.icu.text.Collator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.corext.util.Messages;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;

public class ClassPathDetector implements IResourceProxyVisitor {

    private HashMap<IPath, List<IPath>> fSourceFolders;

    private List<IResource> fClassFiles;

    private HashSet<IPath> fJARFiles;

    private IProject fProject;

    private IPath fResultOutputFolder;

    private IClasspathEntry[] fResultClasspath;

    private IProgressMonitor fMonitor;

    private static class CPSorter implements Comparator<IClasspathEntry> {

        private Collator fCollator = Collator.getInstance();

        public int compare(IClasspathEntry e1, IClasspathEntry e2) {
            return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
        }
    }

    public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
        fSourceFolders = new HashMap<IPath, List<IPath>>();
        fJARFiles = new HashSet<IPath>(10);
        fClassFiles = new ArrayList<IResource>(100);
        fProject = project;
        fResultClasspath = null;
        fResultOutputFolder = null;
        if (monitor == null) {
            monitor = new NullProgressMonitor();
        }
        detectClasspath(monitor);
    }

    private boolean isNested(IPath path, Iterator<IPath> iter) {
        while (iter.hasNext()) {
            IPath other = iter.next();
            if (other.isPrefixOf(path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Method detectClasspath.
     *
     * @param monitor The progress monitor (not null)
     * @throws CoreException in case of any failure
     */
    private void detectClasspath(IProgressMonitor monitor) throws CoreException {
        try {
            monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
            fMonitor = monitor;
            fProject.accept(this, IResource.NONE);
            monitor.worked(1);
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            detectSourceFolders(cpEntries);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            IPath outputLocation = detectOutputFolder();
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            detectLibraries(cpEntries, outputLocation);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            monitor.worked(1);
            if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
                return;
            }
            IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
            for (int i = 0; i < jreEntries.length; i++) {
                cpEntries.add(jreEntries[i]);
            }
            IClasspathEntry[] entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
            if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
                return;
            }
            fResultClasspath = entries;
            fResultOutputFolder = outputLocation;
        } finally {
            monitor.done();
        }
    }

    private IPath findInSourceFolders(IPath path) {
        Iterator<IPath> iter = fSourceFolders.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            List<IPath> cus = fSourceFolders.get(key);
            if (cus.contains(path)) {
                return (IPath) key;
            }
        }
        return null;
    }

    private IPath detectOutputFolder() throws CoreException {
        HashSet<IPath> classFolders = new HashSet<IPath>();
        for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext(); ) {
            IFile file = (IFile) iter.next();
            IClassFileReader reader = null;
            InputStream content = null;
            try {
                content = file.getContents();
                reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
            } finally {

            }
            if (reader == null) {
                // problematic class file
                continue;
            }
            char[] className = reader.getClassName();
            ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
            if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
                IPath packPath = file.getParent().getFullPath();
                int idx = CharOperation.lastIndexOf('/', className) + 1;
                IPath relPath = new Path(new String(className, 0, idx));
                IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));
                IPath resPath = null;
                if (idx == 0) {
                    resPath = packPath;
                } else {
                    IPath folderPath = getFolderPath(packPath, relPath);
                    if (folderPath != null) {
                        resPath = folderPath;
                    }
                }
                if (resPath != null) {
                    IPath path = findInSourceFolders(cuPath);
                    if (path != null) {
                        return resPath;
                    } else {
                        classFolders.add(resPath);
                    }
                }
            }
        }
        IPath projPath = fProject.getFullPath();
        if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
            return projPath;
        } else {
            IPath path = projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
            while (classFolders.contains(path)) {
                path = new Path(path.toString() + '1');
            }
            return path;
        }
    }

    private void detectLibraries(ArrayList<IClasspathEntry> cpEntries, IPath outputLocation) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = fJARFiles.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            if (isNested(path, sourceFolderSet.iterator())) {
                continue;
            }
            if (outputLocation != null && outputLocation.isPrefixOf(path)) {
                continue;
            }
            IClasspathEntry entry = JavaCore.newLibraryEntry(path, null, null);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        cpEntries.addAll(res);
    }

    private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
        ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
        Set<IPath> sourceFolderSet = fSourceFolders.keySet();
        for (Iterator<IPath> iter = sourceFolderSet.iterator(); iter.hasNext(); ) {
            IPath path = iter.next();
            ArrayList<IPath> excluded = new ArrayList<IPath>();
            for (Iterator<IPath> inner = sourceFolderSet.iterator(); inner.hasNext(); ) {
                IPath other = inner.next();
                if (!path.equals(other) && path.isPrefixOf(other)) {
                    IPath pathToExclude = other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
                    excluded.add(pathToExclude);
                }
            }
            IPath[] excludedPaths = excluded.toArray(new IPath[excluded.size()]);
            IClasspathEntry entry = JavaCore.newSourceEntry(path, excludedPaths);
            res.add(entry);
        }
        Collections.sort(res, new CPSorter());
        resEntries.addAll(res);
    }

    private void visitCompilationUnit(IFile file) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
        if (cu != null) {
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(0);
            CompilationUnit root = (CompilationUnit) parser.createAST(null);
            PackageDeclaration packDecl = root.getPackage();
            IPath packPath = file.getParent().getFullPath();
            String cuName = file.getName();
            if (packDecl == null) {
                addToMap(fSourceFolders, packPath, new Path(cuName));
            } else {
                IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    addToMap(fSourceFolders, folderPath, relPath.append(cuName));
                }
            }
        }
    }

    private void addToMap(HashMap<IPath, List<IPath>> map, IPath folderPath, IPath relPath) {
        List<IPath> list = map.get(folderPath);
        if (list == null) {
            list = new ArrayList<IPath>(50);
            map.put(folderPath, list);
        }
        list.add(relPath);
    }

    private IPath getFolderPath(IPath packPath, IPath relpath) {
        int remainingSegments = packPath.segmentCount() - relpath.segmentCount();
        if (remainingSegments >= 0) {
            IPath common = packPath.removeFirstSegments(remainingSegments);
            if (common.equals(relpath)) {
                return packPath.uptoSegment(remainingSegments);
            }
        }
        return null;
    }

    private boolean hasExtension(String name, String ext) {
        return name.endsWith(ext) && (ext.length() != name.length());
    }

    private boolean isValidCUName(String name) {
        return !JavaConventionsUtil.validateCompilationUnitName(name, JavaCore.create(fProject)).matches(IStatus.ERROR);
    }

    /* (non-Javadoc)
	 * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
	 */
    public boolean visit(IResourceProxy proxy) {
        if (fMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (proxy.getType() == IResource.FILE) {
            String name = proxy.getName();
            if (isValidCUName(name)) {
                visitCompilationUnit((IFile) proxy.requestResource());
            } else if (hasExtension(name, ".class")) {
                fClassFiles.add(proxy.requestResource());
            } else if (hasExtension(name, ".jar")) {
                fJARFiles.add(proxy.requestFullPath());
            }
            return false;
        }
        return true;
    }

    public IPath getOutputLocation() {
        return fResultOutputFolder;
    }

    public IClasspathEntry[] getClasspath() {
        if (fResultClasspath == null)
            return new IClasspathEntry[0];
        return fResultClasspath;
    }
}


@Override
    public boolean onCreateOptionsMenu(Menu menu)

/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 *
 */
package sk.vx.connectbot;

import java.util.List;
import sk.vx.connectbot.bean.HostBean;
import sk.vx.connectbot.bean.PortForwardBean;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends ListActivity {

    public final static String TAG = "ConnectBot.PortForwardListActivity";

    private static final int LISTENER_CYCLE_TIME = 500;

    protected HostDatabase hostdb;

    private List<PortForwardBean> portForwards;

    private ServiceConnection connection = null;

    protected TerminalBridge hostBridge = null;

    protected LayoutInflater inflater = null;

    private HostBean host;

    @Override
    public void onStart() {
        super.onStart();
        this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
        if (this.hostdb == null)
            this.hostdb = new HostDatabase(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        this.unbindService(connection);
        if (this.hostdb != null) {
            this.hostdb.close();
            this.hostdb = null;
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
        setContentView(R.layout.act_portforwardlist);
        // connect with hosts database and populate list
        this.hostdb = new HostDatabase(this);
        host = hostdb.findHostById(hostId);
        {
            final String nickname = host != null ? host.getNickname() : null;
            final Resources resources = getResources();
            if (nickname != null) {
                this.setTitle(String.format("%s: %s (%s)", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));
            } else {
                this.setTitle(String.format("%s: %s", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));
            }
        }
        connection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder service) {
                TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
                hostBridge = bound.getConnectedBridge(host);
                updateHandler.sendEmptyMessage(-1);
            }

            public void onServiceDisconnected(ComponentName name) {
                hostBridge = null;
            }
        };
        this.updateList();
        this.registerForContextMenu(this.getListView());
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                ListView lv = PortForwardListActivity.this.getListView();
                PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
                if (hostBridge != null) {
                    if (pfb.isEnabled())
                        hostBridge.disablePortForward(pfb);
                    else {
                        if (!hostBridge.enablePortForward(pfb))
                            Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
                    }
                    updateHandler.sendEmptyMessage(-1);
                }
            }
        });
        this.inflater = LayoutInflater.from(this);
    }

{
        super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(R.string.portforward_menu_add);
        add.setIcon(android.R.drawable.ic_menu_add);
        add.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // build dialog to prompt user about updating
                final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
                final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
                final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
                            final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
                            String type = HostDatabase.PORTFORWARD_LOCAL;
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    type = HostDatabase.PORTFORWARD_LOCAL;
                                    break;
                                case 1:
                                    type = HostDatabase.PORTFORWARD_REMOTE;
                                    break;
                                case 2:
                                    type = HostDatabase.PORTFORWARD_DYNAMIC5;
                                    break;
                            }
                            PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());
                            if (hostBridge != null) {
                                hostBridge.addPortForward(pfb);
                                hostBridge.enablePortForward(pfb);
                            }
                            if (host != null && !hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        // Create menu to handle deleting and editing port forward
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
        menu.setHeaderTitle(pfb.getNickname());
        MenuItem edit = menu.add(R.string.portforward_edit);
        edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
                final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
                if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
                    typeSpinner.setSelection(0);
                else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
                    typeSpinner.setSelection(1);
                else
                    typeSpinner.setSelection(2);
                final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
                nicknameEdit.setText(pfb.getNickname());
                final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
                sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
                final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
                if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
                    destEdit.setEnabled(false);
                } else {
                    destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
                }
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (hostBridge != null)
                                hostBridge.disablePortForward(pfb);
                            pfb.setNickname(nicknameEdit.getText().toString());
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
                                    break;
                                case 1:
                                    pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
                                    break;
                                case 2:
                                    pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
                                    break;
                            }
                            pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
                            pfb.setDest(destEdit.getText().toString());
                            // Use the new settings for the existing connection.
                            if (hostBridge != null)
                                updateHandler.postDelayed(new Runnable() {

                                    public void run() {
                                        hostBridge.enablePortForward(pfb);
                                        updateHandler.sendEmptyMessage(-1);
                                    }
                                }, LISTENER_CYCLE_TIME);
                            if (!hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).create().show();
                return true;
            }
        });
        MenuItem delete = menu.add(R.string.portforward_delete);
        delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // prompt user to make sure they really want this
                new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            // Delete the port forward from the host if needed.
                            if (hostBridge != null)
                                hostBridge.removePortForward(pfb);
                            hostdb.deletePortForward(pfb);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not delete port forward", e);
                        }
                        updateHandler.sendEmptyMessage(-1);
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
    }

    protected Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            PortForwardListActivity.this.updateList();
        }
    };

    protected void updateList() {
        if (hostBridge != null) {
            this.portForwards = hostBridge.getPortForwards();
        } else {
            if (this.hostdb == null)
                return;
            this.portForwards = this.hostdb.getPortForwardsForHost(host);
        }
        PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
        this.setListAdapter(adapter);
    }

    class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {

        class ViewHolder {

            public TextView nickname;

            public TextView caption;
        }

        private List<PortForwardBean> portForwards;

        public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
            super(context, R.layout.item_portforward, portForwards);
            this.portForwards = portForwards;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_portforward, null, false);
                holder = new ViewHolder();
                holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
                holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();
            PortForwardBean pfb = portForwards.get(position);
            holder.nickname.setText(pfb.getNickname());
            holder.caption.setText(pfb.getDescription());
            if (hostBridge != null && !pfb.isEnabled()) {
                holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            return convertView;
        }
    }
}


{
        super.onStop();
        this.unbindService(connection);
        if (this.hostdb != null) {
            this.hostdb.close();
            this.hostdb = null;
        }
    }

/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 *
 */
package sk.vx.connectbot;

import java.util.List;
import sk.vx.connectbot.bean.HostBean;
import sk.vx.connectbot.bean.PortForwardBean;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends ListActivity {

    public final static String TAG = "ConnectBot.PortForwardListActivity";

    private static final int LISTENER_CYCLE_TIME = 500;

    protected HostDatabase hostdb;

    private List<PortForwardBean> portForwards;

    private ServiceConnection connection = null;

    protected TerminalBridge hostBridge = null;

    protected LayoutInflater inflater = null;

    private HostBean host;

    @Override
    public void onStart() {
        super.onStart();
        this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
        if (this.hostdb == null)
            this.hostdb = new HostDatabase(this);
    }

    @Override
    public void onStop()

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
        setContentView(R.layout.act_portforwardlist);
        // connect with hosts database and populate list
        this.hostdb = new HostDatabase(this);
        host = hostdb.findHostById(hostId);
        {
            final String nickname = host != null ? host.getNickname() : null;
            final Resources resources = getResources();
            if (nickname != null) {
                this.setTitle(String.format("%s: %s (%s)", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));
            } else {
                this.setTitle(String.format("%s: %s", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));
            }
        }
        connection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder service) {
                TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
                hostBridge = bound.getConnectedBridge(host);
                updateHandler.sendEmptyMessage(-1);
            }

            public void onServiceDisconnected(ComponentName name) {
                hostBridge = null;
            }
        };
        this.updateList();
        this.registerForContextMenu(this.getListView());
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                ListView lv = PortForwardListActivity.this.getListView();
                PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
                if (hostBridge != null) {
                    if (pfb.isEnabled())
                        hostBridge.disablePortForward(pfb);
                    else {
                        if (!hostBridge.enablePortForward(pfb))
                            Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
                    }
                    updateHandler.sendEmptyMessage(-1);
                }
            }
        });
        this.inflater = LayoutInflater.from(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(R.string.portforward_menu_add);
        add.setIcon(android.R.drawable.ic_menu_add);
        add.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // build dialog to prompt user about updating
                final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
                final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
                final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
                            final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
                            String type = HostDatabase.PORTFORWARD_LOCAL;
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    type = HostDatabase.PORTFORWARD_LOCAL;
                                    break;
                                case 1:
                                    type = HostDatabase.PORTFORWARD_REMOTE;
                                    break;
                                case 2:
                                    type = HostDatabase.PORTFORWARD_DYNAMIC5;
                                    break;
                            }
                            PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());
                            if (hostBridge != null) {
                                hostBridge.addPortForward(pfb);
                                hostBridge.enablePortForward(pfb);
                            }
                            if (host != null && !hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        // Create menu to handle deleting and editing port forward
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
        menu.setHeaderTitle(pfb.getNickname());
        MenuItem edit = menu.add(R.string.portforward_edit);
        edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
                final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
                if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
                    typeSpinner.setSelection(0);
                else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
                    typeSpinner.setSelection(1);
                else
                    typeSpinner.setSelection(2);
                final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
                nicknameEdit.setText(pfb.getNickname());
                final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
                sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
                final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
                if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
                    destEdit.setEnabled(false);
                } else {
                    destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
                }
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (hostBridge != null)
                                hostBridge.disablePortForward(pfb);
                            pfb.setNickname(nicknameEdit.getText().toString());
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
                                    break;
                                case 1:
                                    pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
                                    break;
                                case 2:
                                    pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
                                    break;
                            }
                            pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
                            pfb.setDest(destEdit.getText().toString());
                            // Use the new settings for the existing connection.
                            if (hostBridge != null)
                                updateHandler.postDelayed(new Runnable() {

                                    public void run() {
                                        hostBridge.enablePortForward(pfb);
                                        updateHandler.sendEmptyMessage(-1);
                                    }
                                }, LISTENER_CYCLE_TIME);
                            if (!hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).create().show();
                return true;
            }
        });
        MenuItem delete = menu.add(R.string.portforward_delete);
        delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // prompt user to make sure they really want this
                new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            // Delete the port forward from the host if needed.
                            if (hostBridge != null)
                                hostBridge.removePortForward(pfb);
                            hostdb.deletePortForward(pfb);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not delete port forward", e);
                        }
                        updateHandler.sendEmptyMessage(-1);
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
    }

    protected Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            PortForwardListActivity.this.updateList();
        }
    };

    protected void updateList() {
        if (hostBridge != null) {
            this.portForwards = hostBridge.getPortForwards();
        } else {
            if (this.hostdb == null)
                return;
            this.portForwards = this.hostdb.getPortForwardsForHost(host);
        }
        PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
        this.setListAdapter(adapter);
    }

    class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {

        class ViewHolder {

            public TextView nickname;

            public TextView caption;
        }

        private List<PortForwardBean> portForwards;

        public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
            super(context, R.layout.item_portforward, portForwards);
            this.portForwards = portForwards;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_portforward, null, false);
                holder = new ViewHolder();
                holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
                holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();
            PortForwardBean pfb = portForwards.get(position);
            holder.nickname.setText(pfb.getNickname());
            holder.caption.setText(pfb.getDescription());
            if (hostBridge != null && !pfb.isEnabled()) {
                holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            return convertView;
        }
    }
}


/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 *
 */
package sk.vx.connectbot;

import java.util.List;
import sk.vx.connectbot.bean.HostBean;
import sk.vx.connectbot.bean.PortForwardBean;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends ListActivity {

    public final static String TAG = "ConnectBot.PortForwardListActivity";

    private static final int LISTENER_CYCLE_TIME = 500;

    protected HostDatabase hostdb;

    private List<PortForwardBean> portForwards;

    private ServiceConnection connection = null;

    protected TerminalBridge hostBridge = null;

    protected LayoutInflater inflater = null;

    private HostBean host;

    @Override
    public void onStart() {
        super.onStart();
        this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
        if (this.hostdb == null)
            this.hostdb = new HostDatabase(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        this.unbindService(connection);
        if (this.hostdb != null) {
            this.hostdb.close();
            this.hostdb = null;
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
        setContentView(R.layout.act_portforwardlist);
        // connect with hosts database and populate list
        this.hostdb = new HostDatabase(this);
        host = hostdb.findHostById(hostId);
        {
            final String nickname = host != null ? host.getNickname() : null;
            final Resources resources = getResources();
            if (nickname != null) {
                this.setTitle(String.format("%s: %s (%s)", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));
            } else {
                this.setTitle(String.format("%s: %s", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));
            }
        }
        connection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder service) {
                TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
                hostBridge = bound.getConnectedBridge(host);
                updateHandler.sendEmptyMessage(-1);
            }

            public void onServiceDisconnected(ComponentName name) {
                hostBridge = null;
            }
        };
        this.updateList();
        this.registerForContextMenu(this.getListView());
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                ListView lv = PortForwardListActivity.this.getListView();
                PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
                if (hostBridge != null) {
                    if (pfb.isEnabled())
                        hostBridge.disablePortForward(pfb);
                    else {
                        if (!hostBridge.enablePortForward(pfb))
                            Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
                    }
                    updateHandler.sendEmptyMessage(-1);
                }
            }
        });
        this.inflater = LayoutInflater.from(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(R.string.portforward_menu_add);
        add.setIcon(android.R.drawable.ic_menu_add);
        add.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // build dialog to prompt user about updating
                final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
                final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
                final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
                            final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
                            String type = HostDatabase.PORTFORWARD_LOCAL;
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    type = HostDatabase.PORTFORWARD_LOCAL;
                                    break;
                                case 1:
                                    type = HostDatabase.PORTFORWARD_REMOTE;
                                    break;
                                case 2:
                                    type = HostDatabase.PORTFORWARD_DYNAMIC5;
                                    break;
                            }
                            PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());
                            if (hostBridge != null) {
                                hostBridge.addPortForward(pfb);
                                hostBridge.enablePortForward(pfb);
                            }
                            if (host != null && !hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        // Create menu to handle deleting and editing port forward
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
        menu.setHeaderTitle(pfb.getNickname());
        MenuItem edit = menu.add(R.string.portforward_edit);
        edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
                final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
                if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
                    typeSpinner.setSelection(0);
                else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
                    typeSpinner.setSelection(1);
                else
                    typeSpinner.setSelection(2);
                final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
                nicknameEdit.setText(pfb.getNickname());
                final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
                sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
                final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
                if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
                    destEdit.setEnabled(false);
                } else {
                    destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
                }
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (hostBridge != null)
                                hostBridge.disablePortForward(pfb);
                            pfb.setNickname(nicknameEdit.getText().toString());
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
                                    break;
                                case 1:
                                    pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
                                    break;
                                case 2:
                                    pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
                                    break;
                            }
                            pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
                            pfb.setDest(destEdit.getText().toString());
                            // Use the new settings for the existing connection.
                            if (hostBridge != null)
                                updateHandler.postDelayed(new Runnable() {

                                    public void run() {
                                        hostBridge.enablePortForward(pfb);
                                        updateHandler.sendEmptyMessage(-1);
                                    }
                                }, LISTENER_CYCLE_TIME);
                            if (!hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).create().show();
                return true;
            }
        });
        MenuItem delete = menu.add(R

        delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // prompt user to make sure they really want this
                new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            // Delete the port forward from the host if needed.
                            if (hostBridge != null)
                                hostBridge.removePortForward(pfb);
                            hostdb.deletePortForward(pfb);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not delete port forward", e);
                        }
                        updateHandler.sendEmptyMessage(-1);
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
    }

    protected Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            PortForwardListActivity.this.updateList();
        }
    };

    protected void updateList() {
        if (hostBridge != null) {
            this.portForwards = hostBridge.getPortForwards();
        } else {
            if (this.hostdb == null)
                return;
            this.portForwards = this.hostdb.getPortForwardsForHost(host);
        }
        PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
        this.setListAdapter(adapter);
    }

    class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {

        class ViewHolder {

            public TextView nickname;

            public TextView caption;
        }

        private List<PortForwardBean> portForwards;

        public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
            super(context, R.layout.item_portforward, portForwards);
            this.portForwards = portForwards;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_portforward, null, false);
                holder = new ViewHolder();
                holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
                holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();
            PortForwardBean pfb = portForwards.get(position);
            holder.nickname.setText(pfb.getNickname());
            holder.caption.setText(pfb.getDescription());
            if (hostBridge != null && !pfb.isEnabled()) {
                holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            return convertView;
        }
    }
}


if (hostBridge != null) {
                    if (pfb.isEnabled())
                        hostBridge.disablePortForward(pfb);
                    else {
                        if (!hostBridge.enablePortForward(pfb))
                            Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
                    }
                    updateHandler.sendEmptyMessage(-1);
                }

/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 *
 */
package sk.vx.connectbot;

import java.util.List;
import sk.vx.connectbot.bean.HostBean;
import sk.vx.connectbot.bean.PortForwardBean;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends ListActivity {

    public final static String TAG = "ConnectBot.PortForwardListActivity";

    private static final int LISTENER_CYCLE_TIME = 500;

    protected HostDatabase hostdb;

    private List<PortForwardBean> portForwards;

    private ServiceConnection connection = null;

    protected TerminalBridge hostBridge = null;

    protected LayoutInflater inflater = null;

    private HostBean host;

    @Override
    public void onStart() {
        super.onStart();
        this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
        if (this.hostdb == null)
            this.hostdb = new HostDatabase(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        this.unbindService(connection);
        if (this.hostdb != null) {
            this.hostdb.close();
            this.hostdb = null;
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
        setContentView(R.layout.act_portforwardlist);
        // connect with hosts database and populate list
        this.hostdb = new HostDatabase(this);
        host = hostdb.findHostById(hostId);
        {
            final String nickname = host != null ? host.getNickname() : null;
            final Resources resources = getResources();
            if (nickname != null) {
                this.setTitle(String.format("%s: %s (%s)", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));
            } else {
                this.setTitle(String.format("%s: %s", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));
            }
        }
        connection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder service) {
                TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
                hostBridge = bound.getConnectedBridge(host);
                updateHandler.sendEmptyMessage(-1);
            }

            public void onServiceDisconnected(ComponentName name) {
                hostBridge = null;
            }
        };
        this.updateList();
        this.registerForContextMenu(this.getListView());
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                ListView lv = PortForwardListActivity.this.getListView();
                PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);

            }
        });
        this.inflater = LayoutInflater.from(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(R.string.portforward_menu_add);
        add.setIcon(android.R.drawable.ic_menu_add);
        add.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // build dialog to prompt user about updating
                final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
                final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
                final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
                            final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
                            String type = HostDatabase.PORTFORWARD_LOCAL;
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    type = HostDatabase.PORTFORWARD_LOCAL;
                                    break;
                                case 1:
                                    type = HostDatabase.PORTFORWARD_REMOTE;
                                    break;
                                case 2:
                                    type = HostDatabase.PORTFORWARD_DYNAMIC5;
                                    break;
                            }
                            PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());
                            if (hostBridge != null) {
                                hostBridge.addPortForward(pfb);
                                hostBridge.enablePortForward(pfb);
                            }
                            if (host != null && !hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        // Create menu to handle deleting and editing port forward
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
        menu.setHeaderTitle(pfb.getNickname());
        MenuItem edit = menu.add(R.string.portforward_edit);
        edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
                final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
                if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
                    typeSpinner.setSelection(0);
                else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
                    typeSpinner.setSelection(1);
                else
                    typeSpinner.setSelection(2);
                final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
                nicknameEdit.setText(pfb.getNickname());
                final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
                sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
                final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
                if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
                    destEdit.setEnabled(false);
                } else {
                    destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
                }
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (hostBridge != null)
                                hostBridge.disablePortForward(pfb);
                            pfb.setNickname(nicknameEdit.getText().toString());
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
                                    break;
                                case 1:
                                    pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
                                    break;
                                case 2:
                                    pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
                                    break;
                            }
                            pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
                            pfb.setDest(destEdit.getText().toString());
                            // Use the new settings for the existing connection.
                            if (hostBridge != null)
                                updateHandler.postDelayed(new Runnable() {

                                    public void run() {
                                        hostBridge.enablePortForward(pfb);
                                        updateHandler.sendEmptyMessage(-1);
                                    }
                                }, LISTENER_CYCLE_TIME);
                            if (!hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).create().show();
                return true;
            }
        });
        MenuItem delete = menu.add(R.string.portforward_delete);
        delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // prompt user to make sure they really want this
                new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            // Delete the port forward from the host if needed.
                            if (hostBridge != null)
                                hostBridge.removePortForward(pfb);
                            hostdb.deletePortForward(pfb);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not delete port forward", e);
                        }
                        updateHandler.sendEmptyMessage(-1);
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
    }

    protected Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            PortForwardListActivity.this.updateList();
        }
    };

    protected void updateList() {
        if (hostBridge != null) {
            this.portForwards = hostBridge.getPortForwards();
        } else {
            if (this.hostdb == null)
                return;
            this.portForwards = this.hostdb.getPortForwardsForHost(host);
        }
        PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
        this.setListAdapter(adapter);
    }

    class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {

        class ViewHolder {

            public TextView nickname;

            public TextView caption;
        }

        private List<PortForwardBean> portForwards;

        public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
            super(context, R.layout.item_portforward, portForwards);
            this.portForwards = portForwards;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_portforward, null, false);
                holder = new ViewHolder();
                holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
                holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();
            PortForwardBean pfb = portForwards.get(position);
            holder.nickname.setText(pfb.getNickname());
            holder.caption.setText(pfb.getDescription());
            if (hostBridge != null && !pfb.isEnabled()) {
                holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            return convertView;
        }
    }
}


try {
                            // Delete the port forward from the host if needed.
                            if (hostBridge != null)
                                hostBridge.removePortForward(pfb);
                            hostdb.deletePortForward(pfb);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not delete port forward", e);
                        }

/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 *
 */
package sk.vx.connectbot;

import java.util.List;
import sk.vx.connectbot.bean.HostBean;
import sk.vx.connectbot.bean.PortForwardBean;
import sk.vx.connectbot.service.TerminalBridge;
import sk.vx.connectbot.service.TerminalManager;
import sk.vx.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends ListActivity {

    public final static String TAG = "ConnectBot.PortForwardListActivity";

    private static final int LISTENER_CYCLE_TIME = 500;

    protected HostDatabase hostdb;

    private List<PortForwardBean> portForwards;

    private ServiceConnection connection = null;

    protected TerminalBridge hostBridge = null;

    protected LayoutInflater inflater = null;

    private HostBean host;

    @Override
    public void onStart() {
        super.onStart();
        this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
        if (this.hostdb == null)
            this.hostdb = new HostDatabase(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        this.unbindService(connection);
        if (this.hostdb != null) {
            this.hostdb.close();
            this.hostdb = null;
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
        setContentView(R.layout.act_portforwardlist);
        // connect with hosts database and populate list
        this.hostdb = new HostDatabase(this);
        host = hostdb.findHostById(hostId);
        {
            final String nickname = host != null ? host.getNickname() : null;
            final Resources resources = getResources();
            if (nickname != null) {
                this.setTitle(String.format("%s: %s (%s)", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list), nickname));
            } else {
                this.setTitle(String.format("%s: %s", resources.getText(R.string.app_name), resources.getText(R.string.title_port_forwards_list)));
            }
        }
        connection = new ServiceConnection() {

            public void onServiceConnected(ComponentName className, IBinder service) {
                TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
                hostBridge = bound.getConnectedBridge(host);
                updateHandler.sendEmptyMessage(-1);
            }

            public void onServiceDisconnected(ComponentName name) {
                hostBridge = null;
            }
        };
        this.updateList();
        this.registerForContextMenu(this.getListView());
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
                ListView lv = PortForwardListActivity.this.getListView();
                PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
                if (hostBridge != null) {
                    if (pfb.isEnabled())
                        hostBridge.disablePortForward(pfb);
                    else {
                        if (!hostBridge.enablePortForward(pfb))
                            Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
                    }
                    updateHandler.sendEmptyMessage(-1);
                }
            }
        });
        this.inflater = LayoutInflater.from(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem add = menu.add(R.string.portforward_menu_add);
        add.setIcon(android.R.drawable.ic_menu_add);
        add.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // build dialog to prompt user about updating
                final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
                final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
                final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(portForwardView).setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
                            final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
                            String type = HostDatabase.PORTFORWARD_LOCAL;
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    type = HostDatabase.PORTFORWARD_LOCAL;
                                    break;
                                case 1:
                                    type = HostDatabase.PORTFORWARD_REMOTE;
                                    break;
                                case 2:
                                    type = HostDatabase.PORTFORWARD_DYNAMIC5;
                                    break;
                            }
                            PortForwardBean pfb = new PortForwardBean(host != null ? host.getId() : -1, nicknameEdit.getText().toString(), type, sourcePortEdit.getText().toString(), destEdit.getText().toString());
                            if (hostBridge != null) {
                                hostBridge.addPortForward(pfb);
                                hostBridge.enablePortForward(pfb);
                            }
                            if (host != null && !hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        // Create menu to handle deleting and editing port forward
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
        menu.setHeaderTitle(pfb.getNickname());
        MenuItem edit = menu.add(R.string.portforward_edit);
        edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
                final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
                if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
                    typeSpinner.setSelection(0);
                else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
                    typeSpinner.setSelection(1);
                else
                    typeSpinner.setSelection(2);
                final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
                nicknameEdit.setText(pfb.getNickname());
                final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
                sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
                final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
                if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
                    destEdit.setEnabled(false);
                } else {
                    destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
                }
                typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> value, View view, int position, long id) {
                        destEdit.setEnabled(position != 2);
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
                new AlertDialog.Builder(PortForwardListActivity.this).setView(editTunnelView).setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (hostBridge != null)
                                hostBridge.disablePortForward(pfb);
                            pfb.setNickname(nicknameEdit.getText().toString());
                            switch(typeSpinner.getSelectedItemPosition()) {
                                case 0:
                                    pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
                                    break;
                                case 1:
                                    pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
                                    break;
                                case 2:
                                    pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
                                    break;
                            }
                            pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
                            pfb.setDest(destEdit.getText().toString());
                            // Use the new settings for the existing connection.
                            if (hostBridge != null)
                                updateHandler.postDelayed(new Runnable() {

                                    public void run() {
                                        hostBridge.enablePortForward(pfb);
                                        updateHandler.sendEmptyMessage(-1);
                                    }
                                }, LISTENER_CYCLE_TIME);
                            if (!hostdb.savePortForward(pfb))
                                throw new SQLException("Could not save port forward");
                            updateHandler.sendEmptyMessage(-1);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not update port forward", e);
                            // TODO Show failure dialog.
                        }
                    }
                }).setNegativeButton(android.R.string.cancel, null).create().show();
                return true;
            }
        });
        MenuItem delete = menu.add(R.string.portforward_delete);
        delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            public boolean onMenuItemClick(MenuItem item) {
                // prompt user to make sure they really want this
                new AlertDialog.Builder(PortForwardListActivity.this).setMessage(getString(R.string.delete_message, pfb.getNickname())).setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        updateHandler.sendEmptyMessage(-1);
                    }
                }).setNegativeButton(R.string.delete_neg, null).create().show();
                return true;
            }
        });
    }

    protected Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            PortForwardListActivity.this.updateList();
        }
    };

    protected void updateList() {
        if (hostBridge != null) {
            this.portForwards = hostBridge.getPortForwards();
        } else {
            if (this.hostdb == null)
                return;
            this.portForwards = this.hostdb.getPortForwardsForHost(host);
        }
        PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
        this.setListAdapter(adapter);
    }

    class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {

        class ViewHolder {

            public TextView nickname;

            public TextView caption;
        }

        private List<PortForwardBean> portForwards;

        public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
            super(context, R.layout.item_portforward, portForwards);
            this.portForwards = portForwards;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_portforward, null, false);
                holder = new ViewHolder();
                holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
                holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();
            PortForwardBean pfb = portForwards.get(position);
            holder.nickname.setText(pfb.getNickname());
            holder.caption.setText(pfb.getDescription());
            if (hostBridge != null && !pfb.isEnabled()) {
                holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
            return convertView;
        }
    }
}