001 package org.codehaus.mojo.properties;
002
003 /*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements. See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership. The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License. You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied. See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022 import org.apache.maven.plugin.AbstractMojo;
023 import org.apache.maven.plugin.MojoExecutionException;
024 import org.apache.maven.project.MavenProject;
025
026 import java.io.File;
027 import java.io.FileNotFoundException;
028 import java.io.FileOutputStream;
029 import java.io.IOException;
030 import java.util.Properties;
031
032 /**
033 * @author <a href="mailto:zarars@gmail.com">Zarar Siddiqi</a>
034 * @version $Id: AbstractWritePropertiesMojo.java 8861 2009-01-21 15:35:38Z pgier $
035 */
036 public abstract class AbstractWritePropertiesMojo extends AbstractMojo
037 {
038
039 /**
040 * @parameter default-value="${project}"
041 * @required
042 * @readonly
043 */
044 protected MavenProject project;
045
046 /**
047 * The properties file that will be used when writing properties.
048 *
049 * @parameter
050 * @required
051 */
052 protected File outputFile;
053
054 protected void writeProperties( Properties properties, File file )
055 throws MojoExecutionException
056 {
057 FileOutputStream fos = null;
058 try
059 {
060 fos = new FileOutputStream( file );
061 properties.store( fos, "Properties" );
062 }
063 catch ( FileNotFoundException e )
064 {
065 getLog().error( "Could not create FileOutputStream: " + fos );
066 throw new MojoExecutionException( e.getMessage(), e );
067 }
068 catch ( IOException e )
069 {
070 getLog().error( "Error writing properties: " + fos );
071 throw new MojoExecutionException( e.getMessage(), e );
072 }
073
074 try
075 {
076 fos.close();
077 }
078 catch ( IOException e )
079 {
080 getLog().error( "Error closing FileOutputStream: " + fos );
081 throw new MojoExecutionException( e.getMessage(), e );
082 }
083 }
084
085 protected void validateOutputFile()
086 throws MojoExecutionException
087 {
088 if ( outputFile.isDirectory() )
089 {
090 throw new MojoExecutionException( "outputFile must be a file and not a directory" );
091 }
092 // ensure path exists
093 if ( outputFile.getParentFile() != null )
094 {
095 outputFile.getParentFile().mkdirs();
096 }
097 }
098 }