View Javadoc

1   /*
2    *  Copyright 2010 Felix Roethenbacher
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package ch.syabru.nagios.broker.impl;
17  
18  import java.io.FileWriter;
19  import java.io.IOException;
20  import java.io.Writer;
21  
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  import org.springframework.beans.factory.annotation.Required;
25  import org.springframework.core.io.Resource;
26  
27  import ch.syabru.nagios.broker.ExternalCommand;
28  import ch.syabru.nagios.broker.ExternalCommandHandler;
29  import ch.syabru.nagios.broker.ExternalCommandHandlerException;
30  
31  /**
32   * External command handler implementation.
33   *
34   * @author Felix Roethenbacher
35   *
36   */
37  public class ExternalCommandHandlerImpl implements ExternalCommandHandler {
38      private final Logger logger = LoggerFactory.getLogger(this.getClass());
39  
40      private Resource nagiosCommandFile;
41  
42      @Override
43      public void submitExternalCommand(ExternalCommand command)
44      throws ExternalCommandHandlerException
45      {
46          if (!nagiosCommandFile.exists())
47              throw new ExternalCommandHandlerException(
48                      "Nagios external command file not found [" +
49                      nagiosCommandFile.getDescription() + "]");
50          Writer writer = null;
51          try {
52              writer = new FileWriter(
53                      nagiosCommandFile.getFile(), true);
54              command.writeCommand(writer);
55              writer.flush();
56          } catch (IOException e) {
57              throw new ExternalCommandHandlerException(
58                      "Error submitting external command", e);
59          } finally {
60              if (writer != null) {
61                  try {
62                      writer.close();
63                  } catch (IOException e) {
64                      logger.error("Error closing writer", e);
65                  }
66              }
67          }
68      }
69  
70      @Required
71      public void setNagiosCommandFile(Resource nagiosCommandFile) {
72          this.nagiosCommandFile = nagiosCommandFile;
73      }
74  }