Theory of spontaneous emission noise in open resonators and its application to lasers and optical amplifiers