Top Eclipse (IDE) features I can’t live without

(If you are in Windows, replace “Cmd” for “Ctrl”, and “Option” for “Alt”)

Cmd + 1: Create variables out of function’s outputs, get suggestions to fix issues.

“Shift + Cmd + T”: Open Type.

“Shift + Cmd + R”: Open Resource.

Select element and press “Option + Cmd + R” to rename a class, variable, method, the refactor will be performed throughout the entire project flawlessly.

Select element and press “Cmd + T”: Show Type Hierarchy, great to know what classes implement an interface, or what classes extend an abstract class.

New FrostWire 5.7.2 with uTP support

Download FrostWire 5.7.2 for Windows (Bitcoin, Litecoin, Dogecoin enabled .torrent)
Download FrostWire 5.7.2 for MacOSX (.torrent)
Download FrostWire 5.7.2 for Debian/Ubuntu (.torrent)

This release is all about performance and stability.

Some users have complained about what happens to their internet connection when using FrostWire heavily, so we’ve finally added uTP support to solve these issues.

FrostWire can now deal with bandwidth congestion issues in a way that won’t compromise your internet experience while you use it.

You can, for example, see how FrostWire will automatically adjust its transfer speeds to cede network resources to other programs in your computer, like your web browser while surfing the web or streaming a movie from Netflix.

If the connection is not being used by any other software FrostWire will automatically use as much bandwidth as it can, and you don’t have to do this manually using the existing throttling controls, and all this while not clogging up your router’s memory.

Another benefit of having added uTP is that some WiFi/DSL/Cable routers won’t have issues with packet data overflow when torrenting with FrostWire, which in some cases can completely drop the internet connection forcing you to restart your router to reconnect to the Internet.

We’ve also taken care of very important user experience details, that should make FrostWire easier to understand for new users, as well as smaller usability bugs and crashes that have been fixed.

Here’s the full list of changes.

frostwire (5.7.2) stable; urgency=high
  * uTP support enabled.
  * Multiple crash fixes.
  * UX: playable single file torrents now can be played from transfer list.
  * UX: Fixes UI Thread freeze when opening Options > Search.
  * UX: Better error reporting when a torrent can't be fetched from a
        magnet connection.
  * Spanish translation update by @dennistobar.
-- FrostWire Team <contact@frostwire.com> Fri, 11 Apr 2014 14:22:10 -0500

Love FrostWire?
Consider donating. bitcoin – dogecoin – $1 – $5 – $10 – $25 – paypal

[SOLVED] Java7 SMTP Issue (Caused by: sun.security.pkcs11.wrapper.PKCS11Exception)

So you had your little program that would use AWS to send emails, and all of a sudden after a Java 7 update you get a stack trace like this:

[java]
javax.mail.MessagingException: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465;
nested exception is:
javax.net.ssl.SSLException: Server key
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1962)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:196)

Caused by: javax.net.ssl.SSLException: Server key
at sun.security.ssl.Handshaker.throwSSLException(Handshaker.java:1274)

Caused by: java.security.spec.InvalidKeySpecException: Could not create EC public key
at sun.security.pkcs11.P11ECKeyFactory.engineGeneratePublic(P11ECKeyFactory.java:169)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)

Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_DOMAIN_PARAMS_INVALID
at sun.security.pkcs11.wrapper.PKCS11.C_CreateObject(Native Method)
at sun.security.pkcs11.P11ECKeyFactory.generatePublic(P11ECKeyFactory.java:233)
[/java]

It seems like the SSL Socket Factory in Java 7 is missing some of the Ciphers when it comes to setting up SSL socket cipher suits (see SSLSocket.setEnabledCipherSuites)

so… the question is now,
how do I tell java mail to use the cipher suit I used to use in java 6?

Easy, when you’re setting up your Session properties, make sure to include the following key:

[java]properties.put(“mail.smtp.ssl.ciphersuites”,”SSL_RSA_WITH_RC4_128_MD5 SSL_RSA_WITH_RC4_128_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA TLS_DHE_DSS_WITH_AES_128_CBC_SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA SSL_RSA_WITH_DES_CBC_SHA SSL_DHE_RSA_WITH_DES_CBC_SHA SSL_DHE_DSS_WITH_DES_CBC_SHA SSL_RSA_EXPORT_WITH_RC4_40_MD5 SSL_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA TLS_EMPTY_RENEGOTIATION_INFO_SCSV”);[/java]

which specifies in a space separated String a list of tokens that represent the cipher suites the SSL sockets will use. At some point that list gets split into a String[] and passed to SSLSocket.setEnabledCipherSuites.

This is how my session properties look like in case you want to know:

[java]
Properties properties = new Properties();
properties.put(“mail.transport.protocol”, “smtp”);
properties.put(“mail.smtp.auth”, true);
properties.put(“mail.smtp.ssl.enable”,true);
properties.put(“mail.smtp.port”, emailSMTPPort);
properties.put(“mail.smtp.host”, emailSMTPHost);
properties.put(“mail.smtp.ssl.ciphersuites”,”SSL_RSA_WITH_RC4_128_MD5 SSL_RSA_WITH_RC4_128_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA TLS_DHE_DSS_WITH_AES_128_CBC_SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA SSL_RSA_WITH_DES_CBC_SHA SSL_DHE_RSA_WITH_DES_CBC_SHA SSL_DHE_DSS_WITH_DES_CBC_SHA SSL_RSA_EXPORT_WITH_RC4_40_MD5 SSL_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA TLS_EMPTY_RENEGOTIATION_INFO_SCSV”);
[/java]

Cheers, don’t forget to tip If I saved your ass.

How to obtain the coordinates of the JTable cell a mouse is hovering over, useful for tooltips within cell renderers.

    public String getToolTipText(MouseEvent event) {
        /*
         * This is a Java Swing lesson on how to obtain the coordinates of the current cell
         * as you hover with the mouse on a JTable.
         * 
         * You cannot use the renderer component, since it seems that once the table is done
         * stamping the cells with it, the instance of the renderer is not the one under the mouse
         * as it will always yield negative coordinates, for example, our debugger showed that this
         * renderer's coordinates were always (-95,-25)...
         * 
         * What we did in this case, to show labels for the specific components inside the renderer
         * was to get the mouse coordinates, and translate its coordinates to the coordinates of the
         * current Cell Rectangle.
         * 
         * One interesting gotcha in the process is that you cannot alter the event coordinates and then
         * try to use event.getPoint() since event.getPoint() will always give you a new instance of Point
         * so we keep a copy of that Point and then translate that point.
         * 
         * tags: java, swing, table, get current cell coordinates, get table cell coordinates under mouse
         */
        try {
            Component[] components = this.getComponents();
            Point p = event.getPoint();
            int row = table.rowAtPoint(p);
            int col = table.columnAtPoint(p);
            Rectangle currentCell = table.getCellRect(row, col, false);
            p.translate(-currentCell.x, -currentCell.y);

            for (Component c : components) {
                JComponent jc = (JComponent) c;
                if (jc.isVisible() && jc.getBounds().contains(p)) {
                    return jc.getToolTipText(event);
                }
            }
        } catch (Throwable t) {
            //don't risk painting the table over a tooltip
        }
        return super.getToolTipText(event);
    }

java: How to get all the files inside a folder and its subfolders without recursion

Most programmers will do this in a recursive fashion, but doing that is putting yourself at risk of hitting a stack overflow error, and it’s 20% slower (according to my tests). Here’s my first implementation of a method that will return just the files (cause I didn’t need the folders, you can always hack it to your needs). This is part of FrostWire for Android and FrostWire for Desktop, all the code is available under the GPL at our github repository.

[java]
/** Given a folder path it’ll return all the files contained within it and it’s subfolders
* as a flat set of Files.
*
* Non-recursive implementation, up to 20% faster in tests than recursive implementation. 🙂
*
* @author gubatron
* @param folder
* @param extensions If you only need certain files filtered by their extensions, use this string array (without the “.”). or set to null if you want all files. e.g. [“txt”,”jpg”] if you only want text files and jpegs.
*
* @return The set of files.
*/
public static Collection getAllFolderFiles(File folder, String[] extensions) {
Set results = new HashSet();
Stack subFolders = new Stack();
File currentFolder = folder;
while (currentFolder != null && currentFolder.isDirectory() && currentFolder.canRead()) {
File[] fs = null;
try {
fs = currentFolder.listFiles();
} catch (SecurityException e) {
}

if (fs != null && fs.length > 0) {
for (File f : fs) {
if (!f.isDirectory()) {
if (extensions == null || FilenameUtils.isExtension(f.getName(), extensions)) {
results.add(f);
}
} else {
subFolders.push(f);
}
}
}

if (!subFolders.isEmpty()) {
currentFolder = subFolders.pop();
} else {
currentFolder = null;
}
}
return results;
}
[/java]

Here’s the FilenameUtils if you want the isExtension() implementation and it’s dependencies, you can always code your own there

jar dependencies if you plan to use the cling UPnP library in your android project

This took me quite a while and lots of runtime errors, here are the minimum jars I needed to add to my project since now cling when used on android needs jetty, and damn jetty is broken into a thousand little jars for maximum modularity.

These are the one jars that I needed to not have any more runtime (class not found) errors

jetty-security-8.1.8.v20121106.jar
jetty-http-8.1.8.v20121106.jar
jetty-continuation-8.1.8.v20121106.jar
jetty-io-8.1.8.v20121106.jar
jetty-util-8.1.8.v20121106.jar
jetty-server-8.1.8.v20121106.jar
jetty-servlet-8.1.8.v20121106.jar
jetty-client-8.1.8.v20121106.jar
servlet-api-3.0.jar

How to check if a Java Process is running on any local Virtual Machine programmatically

Quick and dirty way to check if a Java Process is already running.
Useful if you need to run cronjobs periodically and you don’t know how long they might take, you can add this check at the beginning of your main, and it’ll look for all the local virtual machines that have a main class named like the “processName” string passed to it.

In other words, a quick and dirty programatic jps-like function you can add to your util toolset.

[java]
public static boolean isJavaProcessRunning(String processName) {
boolean result = false;

try {
HostIdentifier hostIdentifier = new HostIdentifier(“local://localhost”);
MonitoredHostProvider hostProvider = new MonitoredHostProvider(hostIdentifier);

MonitoredHost monitoredHost;
try {
monitoredHost = MonitoredHost.getMonitoredHost(hostIdentifier);
} catch (MonitorException e1) {
e1.printStackTrace();
return false;
}

Set activeVms = (Set) monitoredHost.activeVms();
int thisProcessCount = 0;
for (Integer activeVmId : activeVms) {
try {
VmIdentifier vmIdentifier = new VmIdentifier(“//” + String.valueOf(activeVmId) + “?mode=r”);
MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmIdentifier);
if (monitoredVm != null) {
String mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);
if (mainClass.toLowerCase().contains(processName.toLowerCase())) {
thisProcessCount++;
if (thisProcessCount > 1) {
result = true;
break;
}
}
}

} catch (MonitorException e) {
e.printStackTrace();
}
}

} catch (URISyntaxException e) {
e.printStackTrace();
} catch (MonitorException e) {
e.printStackTrace();
}

return result;
}
[/java]

Enjoy

Android: Changing TextView alpha transparency across different target SDKs

Sometimes you may need to make a TextView (label) look a little transparent to make emphasis on other parts of your UI. The .setAlpha() function on TextView is not supported after later in the SDK. Here’s a static workaround you can place on some sort of UIUtils class you may have in your project.

[java]
/**
* Android devices with SDK below target=11 do not support textView.setAlpha().
* This is a work around.
* @param v – the text view
* @param alpha – a value from 0 to 255. (0=transparent, 255=fully visible)
*/
public static void setTextViewAlpha(TextView v, int alpha) {
v.setTextColor(v.getTextColors().withAlpha(alpha));
v.setHintTextColor(v.getHintTextColors().withAlpha(alpha));
v.setLinkTextColor(v.getLinkTextColors().withAlpha(alpha));

Drawable[] compoundDrawables = v.getCompoundDrawables();
for (int i=0 ; i < compoundDrawables.length; i++) { Drawable d = compoundDrawables[i]; if (d != null) { d.setAlpha(alpha); } } } [/java] Enjoy, and above all CODE!

Java: Have a JTable’s column preferred width adjusted perfectly to the size of the longest string in the model

Here’s a utility method I’ve coded for FrostWire’s partial download dialog. With it I’m able to adjust a JTable’s column by iterating over the table’s column model data and calculating the exact dimensions required to render the longest string found. You can specify a maximum width (to avoid some really long strings from screwing up the display) and some right padding in case you need some breathing room.

Enjoy

[java]
/**
* It will adjust the column width to match the widest element.
* (You might not want to use this for every column, consider some columns might be really long)
* it assumes model and jtable != null
*/
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table) {

if (columnIndex > model.getColumnCount()-1) {
//invalid column index
return;
}

if (!model.getColumnClass(columnIndex).equals(String.class)) {
return;
}

String longestValue = “”;
for (int row = 0; row < model.getRowCount(); row++) { String strValue = (String) model.getValueAt(row, columnIndex); if (strValue != null && strValue.length() > longestValue.length()) {
longestValue = strValue;
}
}

Graphics g = table.getGraphics();

try {
int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g).getWidth();
table.getColumnModel().getColumn(columnIndex).setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth)+rightPadding);
} catch (Exception e) {
table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
e.printStackTrace();
}

}
[/java]

Note, make sure you invoke this guy only once, usually after the table has been first painted (you could override paint()) or after the model data has been updated (if it gets to be updated and you feel like autoadjusting a particular column)