According to halacha, ejaculation of semen should take place only in the context of vaginal intercourse (or anal intercourse, according to some opinions). Ejaculation at other times raises concerns about hotza'at zera levatalah, generally translated as wasting of seed, or hashchatat zera, the destruction of seed. There is much rabbinic debate about the scope of this prohibition but it clearly subsumes a number of issues:
1) The withdrawal method of birth control is prohibited. This is derived from the story of Er and Onan (Genesis 38) where God's displeasure with this practice is expressed.
2) Male masturbation is prohibited. This means that masturbation is not the method of choice when procuring a semen sample. Similarly, this practice cannot be recommended for the solution of medical problems without careful rabbinic consultation.
3) Barrier methods of contraception that do not allow the flow of semen into the vagina are prohibited. This is the problem with the use of condoms, which are almost never allowed. Some authorities feel that diaphragms and sponges also present this problem.
4) Producing a semen sample for diagnosis and/or treatment of infertility is not a simple procedure to permit within halacha. While there is room for leniency for the purpose of allowing the couple to have children, most rabbis will want some workup done first on the wife before allowing the husband to submit such a sample.