What code analysis tools do you use for your Java projects? What code analysis tools do you use on your Java projects? I am interested in all kinds static code analysis tools (FindBugs, PMD, and any others) code coverage tools (Cobertura, Emma, and any others) any other instrumentation-based tools anything else, if I'm missing something If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting. How can I Java webstart multiple, dependent, native libraries? Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA. When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used. I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically compiling?Packaging Java apps for the Windows/Linux desktop I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run. Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own? Edit: I should perhaps mention that I am unable to spend a lot of money on a commercial solution. IKVM and Licensing I have been looking into IKVMing Apache's FOP project to use with our .NET app. It's a commercial product, and looking into licensing, IKVM runs into some sticky areas because of its use of GNU Classpath. From what I've seen, no one can say for sure if this stuff can be used in a commercial product. Has anyone used IKVM, or an IKVM'd product, in a commercial product? Here's what I've found so far: IKVM license page, which notes that one dll contains code from other projects, their license GPLv2 + Classpath Exception Saxon for .NET is generated with IKVM, but released under the Apache license... Anyone have experience with this? How can I determine the IP of my router/gateway in Java? How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP? This is somewhat easy in .NET if you know your way around. But how do you do it in Java? Arrays of Arrays in Java This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. I'd prefer to do it RIGHT. :) Here is the situation: I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this: Summer (5-1 to 8-31) Spring (3-1 to 4-30) Fall (9-1 to 10-31) Winter (11-1 to 2-28) An example might be: If I'm in group A, here would be my allowed times: Winter: Mondays only Spring: Tues, Thurs, Sat Summer: Any Day Fall: Tues, Thurs, Sat If I was writing this in PHP I would use arrays like this: I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish. I will also need to setup arrays to determine what season I'm in: Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any). Thanks, folks! How do you begin designing a large system? It's been mentioned to me that I'll be the sole developer behind a large new system. Among other things I'll be designing a UI and database schema. I'm sure I'll receive some guidance, but I'd like to be able to knock their socks off. What can I do in the meantime to prepare, and what will I need to keep in mind when I sit down at my computer with the spec? A few things to keep in mind: I'm a college student at my first real programming job. I'll be using Java. We already have SCM set up with automated testing, etc...so tools are not an issue. What's the best way to get started with OSGI? What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module? I'm interested in using OSGi in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using Spring Dynamic Modules for OSGi(tm) Service Platforms. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls? @Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example. @david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig? Java JPanel redraw issues I have a Java swing application with a panel that contains three JComboBoxes that do not draw properly. The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value. The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel. All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me. Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time. Has anyone else seen this and found a different way to force a redraw of the combo boxes? Best Method to run a Java Application as a *nix Daemon or Windows Service? I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the Java Service Wrapper, the Apache Commons project 'jsvc', and the Apache Commons project 'procrun'. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there. Why aren't Enumerations Iterable? In Java 5 and above you have the foreach loop, which works magically on anything that implements Iterable: However, Enumerable still does not implement Iterable, meaning that to iterate over an Enumeration you must do the following: Does anyone know if there is a reason why Enumeration still does not implement Iterable? Edit: As a clarification, I'm not talking about the language concept of an enum, I'm talking a Java-specific class in the Java API called 'Enumeration'. Java Logging vs Log4J Is it still worth to add the log4j library to a Java 5 project just to log let's say some exceptions to a file with some nice rollover settings. Or will the standard util.logging facility do the job as well? What do you think? Passing null to a method I am in the middle of reading the excellent Clean Code One discussion is regarding passing nulls into a method. It represents different ways of handling this: I prefer the assertions approach, but I don't like the fact that assertions are turned off by default. The book finally states: In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. It doesn't really go into how you would enforce this restriction? Do any of you have strong opinions either way. Alternatives to System.exit(1) For various reasons calling System.exit is frowned upon when writing Java Applications, so how can I notify the calling process that not everything is going according to plan? Edit: The 1 is a standin for any non-zero exit code. How do you get the ethernet address using Java? I would like to retrieve the ethernet address of the network interface that is used to access a particular website. How can this be done in Java? Solution Note that the accepted solution of getHardwareAddress is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing. Checking the results of a Factory in a unit test I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has worked correctly? I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it. Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used. Is Java "pass-by-reference" or "pass-by-value"? I always thought Java was pass-by-reference; however I've seen a couple of blog posts (for example, this blog) that claim it's not. I don't think I understand the distinction they're making. What is the explanation? Regex to match against something that is not a specific substring I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring. Example: Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. Thanks to @Kibbee for verifying that this works in C# as well. Is there a way to generalize an Apache ANT target? We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT. Find all drive letters in Java For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows. I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it). Any help? EDIT: I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically. When can DataInputStream.skipBytes(n) not skip n bytes? The Sun Documentation for DataInput.skipBytes states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility." Other than reaching end of file, why might skipBytes() not skip the right number of bytes? (The DataInputStream I am using will either be wrapping a FileInputStream or a PipedInputStream.) If I definitely want to skip n bytes and throw an EOFException if this causes me to go to the end of the file, should I use readFully() and ignore the resulting byte array? Or is there a better way? Where did all the java applets go? When java was young, people were excited about writing applets. They were cool and popular, for a little while. Now, I never see them anymore. Instead we have flash, javascript, and a plethora of other web app-building technologies. Why don't sites use java applets anymore? I'm also curious: historically, why do you think this occurred? What could have been done differently to keep Java applets alive? How do I create a spring bean for a Java double primitive? I'd like to create a spring bean that holds the value of a double. Something like: How to escape text for regular expression in Java Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input. Mocking Static Blocks in Java My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it staticInit. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock staticInit with JMockit to not do anything. Let's see this in example. Will be changed to So that we can do the following in a JUnit. However this solution also comes with its own problems. You can't run DependentClassTest and ClassWithStaticInitTest on the same JVM since you actually want the static block to run for ClassWithStaticInitTest. What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner? How can I get Axis 1.4 to not generate several prefixes for the same XML namespace? I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form: As you can see, several prefixes are defined for the same namespace, e.g. the namespace http://example.com/schema/common has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace. This causes a problem with the Saxon XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes. Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace? Saving Java Object Graphs as XML file What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)? What's the best way to build a string of delimited items in Java? While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this: I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization. In Ruby, I can do something like this instead, which feels much more elegant: But since Java lacks a join command, I couldn't figure out anything equivalent. So, what's the best way to do this in Java? How does one record audio from a Javascript based webapp? I'm trying to write a web-app that records WAV files (eg: from the user's microphone). I know Javascript alone can not do this, but I'm interested in the least proprietary method to augment my Javascript with. My targeted browsers are Firefox for PC and Mac (so no ActiveX). Please share your experiences with this. I gather it can be done with Flash (but not as a WAV formated file). I gather it can be done with Java (but not without code-signing). Are these the only options? @dominic-mazzoni I'd like to record the file as a WAV because because the purpose of the webapp will be to assemble a library of good quality short soundbites. I estimate upload will be 50 MB, which is well worth it for the quality. The app will only be used on our intranet. UPDATE: There's now an alternate solution thanks to JetPack's upcoming Audio API: See https://wiki.mozilla.org/Labs/Jetpack/JEP/18 Is GCJ (GNU Compiler for Java) a viable tool for publishing a webapp? Is it really viable to use GCJ to publish server-side applications? Webapps? My boss is convinced that compiling our (my) webapp into a binary executable is a brilliant idea. (Then again, he likes nice, small simple things with blinky lights that he can understand.) He instinctively sees no issues with this, while I only see an endless series of problems and degradations. Once I start talking to him about the complexity of our platform, and more in depth specifics of byte code, JVMs, libraries, differences between operating systems, processor architectures, etc...well...his eyes glaze over, he smiles and he has made it clear he thinks I'm being childishly resistive. Why does he want a single magic executable? He sees a couple of "benefits": If it is a binary executable, then it is hard to reverse engineer and circumvent any licensing. Management lives in constant fear that this is happening, even though we sell into larger corporates who generally do not do cheat with server software. There is that vision of downloading this magic executable, running it, and everything works. (No more sending me out to do customer installations, which is not that frequent.) So, I've done my obligatory 20 minutes of googling, and now I am here. A bit of background on my application: What it is made from: Java 6 (Sun's JVM) AspectJ 1.6 Tomcat 6 Hibernate 3 Spring 2 another two dozen supporting jar files What it does A streaming media CMS Performance sensitive Deployed on Linux, Solaris, Windows (and developed on a Mac) As you can probably gather, I'm highly skeptical of this "compiling Java to native code" thing. It sound like where Mono (VB on Linux) was back in 2000. But am I being overly pessimistic? Is it viable? Should I actually spend the time (days if not weeks) to try this out? There is one other similar thread (Java Compiler Options to produce .exe files) but it is a bit too simple, the links dated, and not really geared towards a server-side question. Your informed opinions will be highly cherished, my dear SOpedians! TIA! Java Open Source Workflow Engines What is the best open source java workflow framework (e.g. OSWorkflow, jBPM, XFlow etc.)? How do you crash a JVM? I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory. Anybody has any idea? Apache Axis ConfigurationException I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception: org.apache.axis.ConfigurationException: No service named is available any idea? When does System.gc() do anything I know that garbage collection is automated in Java. But I understood that if you write System.gc() in your code the Java VM may or may not decide at runtime to do a garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the VM decide to do (or not do) a GC when it sees a System.gc()? Are there maybe examples in which case it is a good idea to put this in your code? How to debug a JSP tomcat service using eclipse? I would like to debug my separately running JSP/Struts/Tomcat/Hibernate application stack using the Eclipse IDE debugger. How do I setup the java JVM and eclipse so that I can set breakpoints, monitor variable values, and see the code that is currently executing? Can I add maven repositories in the command line? I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like: The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle. How do I send an SMTP Message from Java? Possible Duplicate: How do you send email from a Java app using Gmail? How do I send an SMTP Message from Java? How do I add a namespace reference to a SOAP response with Apache Axis2 and WSDL2Java I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious: I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once. I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API. JPA Multiple Transaction Managers I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application. I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback. A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit. Anyone ever see an issue? In your config, would you have two transaction managers? Would you have txManager1 and txManager2? That's what I have with JPA, two different Spring beans that are transaction managers. Phantom Referenced Objects Phantom References serve for post-mortem operations. The Java specification states that a phantom referenced object will not be deallocated until the phantom-reference itself is cleaned. My question is: What purpose does this feature (object not deallocated) serve? (The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing). Auto-generating Unit-Tests for legacy Java-code What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects. Easiest way to merge a release into one JAR file Is there a tool or script which easily merges a bunch of JAR files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable. The concrete case is a Java restructured text tool. I would like to run it with something like: java -jar rst.jar As far as I can tell, it has no dependencies which indicates that it shouldn't be an easy single-file tool, but the downloaded ZIP file contains a lot of libraries. As you can see, it is somewhat desirable to not need to do this manually. So far I've only tried AutoJar and ProGuard, both of which were fairly easy to get running. It appears that there's some issue with the constant pool in the JAR files. Apparently jrst is slightly broken, so I'll make a go of fixing it. The Maven pom.xml file was apparently broken too, so I'll have to fix that before fixing jrst ... I feel like a bug-magnet :-) Update: I never got around to fixing this application, but I checked out Eclipse's "Runnable JAR export wizard" which is based on a fat JAR. I found this very easy to use for deploying my own code. Some of the other excellent suggestions might be better for builds in a non-Eclipse environment, oss probably should make a nice build using Ant. (Maven, so far has just given me pain, but others love it.) Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language? I wonder why would a C++, C#, Java developer want to learn a dynamic language? Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language? What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years? Update After seeing the first few responses it is clear that there are two issues. My main interest would be something that is justifiable to the employer as an expense. That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, the employers are usually looking for some "real" benefit. How do you authenticate against an Active Directory server using Spring Security? I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server. I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6. If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even trying to connect to the server to begin with. Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly. Here are my security-related beans: How does the Java for each loop work? What would the equivalent for loop look like without using the for each syntax? How to check if a String contains another String in a case insensitive manner in Java? Say I have two strings, I want to perform a check returning that s2 is contained within s1. I can do this with: I am pretty sure that contains() is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like: All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity? Where to find Java 6 JSSE/JCE Source Code? Where can I download the JSSE and JCE source code for the latest release of Java? The source build available at https://jdk6.dev.java.net/ does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages. Not being able to debug these classes makes solving SSL issues incredibly difficult. Reading quicken data files Looking for an open source library, for C++, Java, C# or Python, for reading the data from Quicken .qdf files. @Swati: Quicken .qif format is for transfer only and is not kept up to date by the application like the .qdf file is. Writing post data from one java servlet to another I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there") This is causing a server error, and the second servlet is never invoked. force Maven2 to copy dependencies into target/lib How do I get my project's runtime dependencies copied into the target/lib folder? As it is right now, after mvn clean install the target folder contains only my project's jar, but none of the runtime dependencies. What is your favorite hot-key in Eclipse? I've been using Visual Studio with Re-Sharper for the past few years and have recently taken a gig at a Java shop where we use Eclipse. Googling for Eclipse hotkeys has returned a bunch of 'Top 10 Hot-Key' posts, but that's about it. What are your favorite hotkeys? And which are essential? Does having many unused beans in a Spring Bean Context waste significant resources? My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it. My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now. Any ideas? How do I have a socket accept connections only from the localhost (in Java)? I have a java app (not running in any application container) which listens on a ServerSocket for connections. I would like it to only accept connections which come from localhost. Currently, after a connection is accepted, it checks the peer IP and rejects it if it is not the loopback address, but I know that peer IP addresses can be spoofed. So, if possible, I'd prefer to bind to a socket that only listens on the loopback interface; is this possible? I've tried a few different things (such as specifying "127.0.0.1" as the local address when calling bind()) with no luck. Thanks in advance. Thank you all for your help. I'm embarrassed to admit that this was all my mistake. Our application listens on two different ports, and I was binding one to the loopback interface but testing against the other. When I actually try to telnet to the correct port, everything works fine (i.e., binding to "127.0.0.1" does exactly what it's supposed to). As for spoofing the loopback address, you guys are right. I shouldn't have made it sound like the primary concern. Really, the desired behavior is to only take local connections, and binding to only the local interface is a more direct way of achieving that than accepting all connections and then closing non-local ones. CSV API for Java Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it. A quick google has found http://flatpack.sourceforge.net/ which looks promising. I just wanted to check what others are using before I couple myself to this API. Standard concise way to copy a file in Java? It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution. Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution? Best way to extract a timezone from a mail Date header in Java? I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)? Should domain objects and simple JavaBeans be unit tested? Should simple JavaBeans that have only simple getters and setters be unit tested?? What about Beans with some logic in getters and setters? Is static metaprogramming possible in Java? I am a fan of static metaprogramming in C++. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it? How do you specify a port range for Java sockets? In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit the port lookup to a specific range? Thanks in advance, Roland Low Java single process thread limit in Red Hat Linux I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0_02 or 1.6.0_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more. This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS. In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a java.lang.OutOfMemoryError: unable to create new native thread This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation). The output of "ulimit -a" is as follows: core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited file size (blocks, -f) unlimited max locked memory (kbytes, -l) 4 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 7168 virtual memory (kbytes, -v) unlimited The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but this post seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well). I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of: Error occurred during initialization of VM Cannot create VM thread. Out of system resources. I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated. Edits: Running the thread-limit program mentioned by plinth, there was no failure until it tried to create the 1529th thread. The issue also did not occur using a 1.4 JVM (does occur with 1.6.0_02 and 1.6.0_04 JVMs, can't test with a 1.5 JVM at the moment). The code for the thread test I'm using is as follows: If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me). More Edit: It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model. cURL equivalent in JAVA I am tasked with writing an authentication component for an open source JAVA app. We have an in-house authentication widget that uses https. I have some example php code that accesses the widget which uses cURL to handle the transfer. My question is whether or not there is a port of cURL to JAVA, or better yet, what base package will get me close enough to handle the task? Update: This is in a nutshell, the code I would like to replicate in JAVA: Heath, I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response. Wait until any of Future is done I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished). Currently they are presented as Future, so I need something like Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance. I could try using and decrease countdown when task is complete and do , but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures. All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like in c#. Are there any well known solutions for such kind of problem? UPDATE: Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine. Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received. How to do query auto-completion/suggestions in Lucene? I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it! I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated! To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.