diff options
author | Christian Schneppe <christian@pix-art.de> | 2016-11-19 23:07:54 +0100 |
---|---|---|
committer | Christian Schneppe <christian@pix-art.de> | 2016-11-19 23:07:54 +0100 |
commit | d783cec97084a12873ca62b5fcd64620056ec01b (patch) | |
tree | 65e63d03dd4ab7a834c343ba593c8cd8917620cb /libs/MemorizingTrustManager/example/src/de | |
parent | 969ba45c56adaaa056f04464cd98aec115c9611b (diff) |
reformat code
Diffstat (limited to 'libs/MemorizingTrustManager/example/src/de')
-rw-r--r-- | libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/JULHandler.java | 258 | ||||
-rw-r--r-- | libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/MTMExample.java | 232 |
2 files changed, 254 insertions, 236 deletions
diff --git a/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/JULHandler.java b/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/JULHandler.java index 6d183eb60..2cd70d0c5 100644 --- a/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/JULHandler.java +++ b/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/JULHandler.java @@ -34,136 +34,146 @@ import java.util.logging.Logger; * If there are no {@code DebugLogSettings} configured, then all messages sent * to JUL will be logged. * </p> - * + * * @author Florian Schmaus - * */ @SuppressWarnings("deprecation") public class JULHandler extends Handler { - /** Implement this interface to toggle debug logging. - */ - public interface DebugLogSettings { - public boolean isDebugLogEnabled(); - } - - private static final String CLASS_NAME = JULHandler.class.getName(); - - /** - * The global LogManager configuration. - * <p> - * This configures: - * <ul> - * <li> JULHandler as the default handler for all log messages - * <li> A default log level FINEST (300). Meaning that log messages of a level 300 or higher a - * logged - * </ul> - * </p> - */ - private static final InputStream LOG_MANAGER_CONFIG = new StringBufferInputStream( + /** + * Implement this interface to toggle debug logging. + */ + public interface DebugLogSettings { + public boolean isDebugLogEnabled(); + } + + private static final String CLASS_NAME = JULHandler.class.getName(); + + /** + * The global LogManager configuration. + * <p> + * This configures: + * <ul> + * <li> JULHandler as the default handler for all log messages + * <li> A default log level FINEST (300). Meaning that log messages of a level 300 or higher a + * logged + * </ul> + * </p> + */ + private static final InputStream LOG_MANAGER_CONFIG = new StringBufferInputStream( // @formatter:off -"handlers = " + CLASS_NAME + '\n' + -".level = FINEST" -); + "handlers = " + CLASS_NAME + '\n' + + ".level = FINEST" + ); // @formatter:on - // Constants for Android vs. JUL debug level comparisons - private static final int FINE_INT = Level.FINE.intValue(); - private static final int INFO_INT = Level.INFO.intValue(); - private static final int WARN_INT = Level.WARNING.intValue(); - private static final int SEVE_INT = Level.SEVERE.intValue(); - - private static final Logger LOGGER = Logger.getLogger(CLASS_NAME); - - /** A formatter that creates output similar to Android's Log.x. */ - private static final Formatter FORMATTER = new Formatter() { - @Override - public String format(LogRecord logRecord) { - Throwable thrown = logRecord.getThrown(); - if (thrown != null) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, false); - pw.write(logRecord.getMessage() + ' '); - thrown.printStackTrace(pw); - pw.flush(); - return sw.toString(); - } else { - return logRecord.getMessage(); - } - } - }; - - private static DebugLogSettings sDebugLogSettings; - private static boolean initialized = false; - - public static void initialize() { - try { - LogManager.getLogManager().readConfiguration(LOG_MANAGER_CONFIG); - initialized = true; - } catch (IOException e) { - Log.e("JULHandler", "Can not initialize configuration", e); - } - if (initialized) LOGGER.info("Initialzied java.util.logging logger"); - } - - public static void setDebugLogSettings(DebugLogSettings debugLogSettings) { - if (!isInitialized()) initialize(); - sDebugLogSettings = debugLogSettings; - } - - public static boolean isInitialized() { - return initialized; - } - - public JULHandler() { - setFormatter(FORMATTER); - } - - @Override - public void close() {} - - @Override - public void flush() {} - - @Override - public boolean isLoggable(LogRecord record) { - final boolean debugLog = sDebugLogSettings == null ? true : sDebugLogSettings - .isDebugLogEnabled(); - - if (record.getLevel().intValue() <= FINE_INT) { - return debugLog; - } - return true; - } - - /** JUL method that forwards log records to Android's LogCat. */ - @Override - public void publish(LogRecord record) { - if (!isLoggable(record)) return; - - final int priority = getAndroidPriority(record.getLevel()); - final String tag = substringAfterLastDot(record.getSourceClassName()); - final String msg = getFormatter().format(record); - - Log.println(priority, tag, msg); - } - - /** Helper to convert JUL verbosity levels to Android's Log. */ - private static int getAndroidPriority(Level level) { - int value = level.intValue(); - if (value >= SEVE_INT) { - return Log.ERROR; - } else if (value >= WARN_INT) { - return Log.WARN; - } else if (value >= INFO_INT) { - return Log.INFO; - } else { - return Log.DEBUG; - } - } - - /** Helper to extract short class names. */ - private static String substringAfterLastDot(String s) { - return s.substring(s.lastIndexOf('.') + 1).trim(); - } + // Constants for Android vs. JUL debug level comparisons + private static final int FINE_INT = Level.FINE.intValue(); + private static final int INFO_INT = Level.INFO.intValue(); + private static final int WARN_INT = Level.WARNING.intValue(); + private static final int SEVE_INT = Level.SEVERE.intValue(); + + private static final Logger LOGGER = Logger.getLogger(CLASS_NAME); + + /** + * A formatter that creates output similar to Android's Log.x. + */ + private static final Formatter FORMATTER = new Formatter() { + @Override + public String format(LogRecord logRecord) { + Throwable thrown = logRecord.getThrown(); + if (thrown != null) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw, false); + pw.write(logRecord.getMessage() + ' '); + thrown.printStackTrace(pw); + pw.flush(); + return sw.toString(); + } else { + return logRecord.getMessage(); + } + } + }; + + private static DebugLogSettings sDebugLogSettings; + private static boolean initialized = false; + + public static void initialize() { + try { + LogManager.getLogManager().readConfiguration(LOG_MANAGER_CONFIG); + initialized = true; + } catch (IOException e) { + Log.e("JULHandler", "Can not initialize configuration", e); + } + if (initialized) LOGGER.info("Initialzied java.util.logging logger"); + } + + public static void setDebugLogSettings(DebugLogSettings debugLogSettings) { + if (!isInitialized()) initialize(); + sDebugLogSettings = debugLogSettings; + } + + public static boolean isInitialized() { + return initialized; + } + + public JULHandler() { + setFormatter(FORMATTER); + } + + @Override + public void close() { + } + + @Override + public void flush() { + } + + @Override + public boolean isLoggable(LogRecord record) { + final boolean debugLog = sDebugLogSettings == null ? true : sDebugLogSettings + .isDebugLogEnabled(); + + if (record.getLevel().intValue() <= FINE_INT) { + return debugLog; + } + return true; + } + + /** + * JUL method that forwards log records to Android's LogCat. + */ + @Override + public void publish(LogRecord record) { + if (!isLoggable(record)) return; + + final int priority = getAndroidPriority(record.getLevel()); + final String tag = substringAfterLastDot(record.getSourceClassName()); + final String msg = getFormatter().format(record); + + Log.println(priority, tag, msg); + } + + /** + * Helper to convert JUL verbosity levels to Android's Log. + */ + private static int getAndroidPriority(Level level) { + int value = level.intValue(); + if (value >= SEVE_INT) { + return Log.ERROR; + } else if (value >= WARN_INT) { + return Log.WARN; + } else if (value >= INFO_INT) { + return Log.INFO; + } else { + return Log.DEBUG; + } + } + + /** + * Helper to extract short class names. + */ + private static String substringAfterLastDot(String s) { + return s.substring(s.lastIndexOf('.') + 1).trim(); + } } diff --git a/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/MTMExample.java b/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/MTMExample.java index 52e20dff6..31e37bd00 100644 --- a/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/MTMExample.java +++ b/libs/MemorizingTrustManager/example/src/de/duenndns/mtmexample/MTMExample.java @@ -28,116 +28,124 @@ import de.duenndns.ssl.MemorizingTrustManager; * Example to demonstrate the use of MemorizingTrustManager on HTTPS * sockets. */ -public class MTMExample extends Activity implements OnClickListener -{ - MemorizingTrustManager mtm; - - TextView content; - HostnameVerifier defaultverifier; - EditText urlinput; - String text; - Handler hdlr; - - /** Creates the Activity and registers a MemorizingTrustManager. */ - @Override - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - JULHandler.initialize(); - requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); - setContentView(R.layout.mtmexample); - - - // set up gui elements - findViewById(R.id.connect).setOnClickListener(this); - content = (TextView)findViewById(R.id.content); - urlinput = (EditText)findViewById(R.id.url); - - // register handler for background thread - hdlr = new Handler(); - - // Here, the MemorizingTrustManager is activated for HTTPS - try { - // set location of the keystore - MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks"); - - // register MemorizingTrustManager for HTTPS - SSLContext sc = SSLContext.getInstance("TLS"); - mtm = new MemorizingTrustManager(this); - sc.init(null, new X509TrustManager[] { mtm }, - new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - HttpsURLConnection.setDefaultHostnameVerifier( - mtm.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier())); - - // disable redirects to reduce possible confusion - HttpsURLConnection.setFollowRedirects(false); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** Updates the screen content from a background thread. */ - void setText(final String s, final boolean progress) { - text = s; - hdlr.post(new Runnable() { - public void run() { - content.setText(s); - setProgressBarIndeterminateVisibility(progress); - } - }); - } - - /** Spawns a new thread connecting to the specified URL. - * The result of the request is displayed on the screen. - * @param urlString a HTTPS URL to connect to. - */ - void connect(final String urlString) { - new Thread() { - public void run() { - try { - URL u = new URL(urlString); - HttpsURLConnection c = (HttpsURLConnection)u.openConnection(); - c.connect(); - setText("" + c.getResponseCode() + " " - + c.getResponseMessage(), false); - c.disconnect(); - } catch (Exception e) { - setText(e.toString(), false); - e.printStackTrace(); - } - } - }.start(); - } - - /** Reacts on the connect Button press. */ - @Override - public void onClick(View view) { - String url = urlinput.getText().toString(); - setText("Loading " + url, true); - setProgressBarIndeterminateVisibility(true); - connect(url); - } - - /** React on the "Manage Certificates" button press. */ - public void onManage(View view) { - final ArrayList<String> aliases = Collections.list(mtm.getCertificates()); - ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, aliases); - new AlertDialog.Builder(this).setTitle("Tap Certificate to Delete") - .setNegativeButton(android.R.string.cancel, null) - .setAdapter(adapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - try { - String alias = aliases.get(which); - mtm.deleteCertificate(alias); - setText("Deleted " + alias, false); - } catch (KeyStoreException e) { - e.printStackTrace(); - setText("Error: " + e.getLocalizedMessage(), false); - } - } - }) - .create().show(); - } +public class MTMExample extends Activity implements OnClickListener { + MemorizingTrustManager mtm; + + TextView content; + HostnameVerifier defaultverifier; + EditText urlinput; + String text; + Handler hdlr; + + /** + * Creates the Activity and registers a MemorizingTrustManager. + */ + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + JULHandler.initialize(); + requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); + setContentView(R.layout.mtmexample); + + + // set up gui elements + findViewById(R.id.connect).setOnClickListener(this); + content = (TextView) findViewById(R.id.content); + urlinput = (EditText) findViewById(R.id.url); + + // register handler for background thread + hdlr = new Handler(); + + // Here, the MemorizingTrustManager is activated for HTTPS + try { + // set location of the keystore + MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks"); + + // register MemorizingTrustManager for HTTPS + SSLContext sc = SSLContext.getInstance("TLS"); + mtm = new MemorizingTrustManager(this); + sc.init(null, new X509TrustManager[]{mtm}, + new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HttpsURLConnection.setDefaultHostnameVerifier( + mtm.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier())); + + // disable redirects to reduce possible confusion + HttpsURLConnection.setFollowRedirects(false); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Updates the screen content from a background thread. + */ + void setText(final String s, final boolean progress) { + text = s; + hdlr.post(new Runnable() { + public void run() { + content.setText(s); + setProgressBarIndeterminateVisibility(progress); + } + }); + } + + /** + * Spawns a new thread connecting to the specified URL. + * The result of the request is displayed on the screen. + * + * @param urlString a HTTPS URL to connect to. + */ + void connect(final String urlString) { + new Thread() { + public void run() { + try { + URL u = new URL(urlString); + HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); + c.connect(); + setText("" + c.getResponseCode() + " " + + c.getResponseMessage(), false); + c.disconnect(); + } catch (Exception e) { + setText(e.toString(), false); + e.printStackTrace(); + } + } + }.start(); + } + + /** + * Reacts on the connect Button press. + */ + @Override + public void onClick(View view) { + String url = urlinput.getText().toString(); + setText("Loading " + url, true); + setProgressBarIndeterminateVisibility(true); + connect(url); + } + + /** + * React on the "Manage Certificates" button press. + */ + public void onManage(View view) { + final ArrayList<String> aliases = Collections.list(mtm.getCertificates()); + ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, aliases); + new AlertDialog.Builder(this).setTitle("Tap Certificate to Delete") + .setNegativeButton(android.R.string.cancel, null) + .setAdapter(adapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + try { + String alias = aliases.get(which); + mtm.deleteCertificate(alias); + setText("Deleted " + alias, false); + } catch (KeyStoreException e) { + e.printStackTrace(); + setText("Error: " + e.getLocalizedMessage(), false); + } + } + }) + .create().show(); + } } |