1414import java .nio .file .OpenOption ;
1515import java .nio .file .Path ;
1616import java .nio .file .Paths ;
17+ import java .nio .file .StandardCopyOption ;
1718import java .nio .file .StandardOpenOption ;
1819
1920import static com .google .common .base .Throwables .propagate ;
@@ -36,21 +37,37 @@ public class FileConfig {
3637 tokens .pushBack (); // give the closing brace to parent
3738 }
3839
40+ InputStream openStream () throws IOException {
41+ return getUpdatePath ().openStream ();
42+ }
43+
44+ void update (InputStream is ) throws IOException {
45+ Path t = Files .createTempFile (getPath ().getParent (), getPath ().getFileName ().toString (), ".tmp" );
46+
47+ try (OutputStream os = Files .newOutputStream (t ,
48+ StandardOpenOption .CREATE , StandardOpenOption .WRITE )) {
49+ ByteStreams .copy (is , os );
50+ } catch (IOException e ) {
51+ logger .error ("unable to write file" , e );
52+ }
53+
54+ try {
55+ Files .move (t , getPath (), StandardCopyOption .ATOMIC_MOVE , StandardCopyOption .REPLACE_EXISTING );
56+ } catch (IOException e ) {
57+ logger .error ("unable to rename" , e );
58+ }
59+ }
60+
3961 void apply () {
40- logger .info ("replacing {} with {}" , path , updatePath );
62+ logger .info ("replacing {} with {}" , getPath (), getUpdatePath () );
4163 try {
42- Files .createDirectories (path .getParent ());
64+ Files .createDirectories (getPath () .getParent ());
4365 } catch (IOException e ) {
4466 logger .error ("unable to create path" , e );
4567 }
4668
47- try (InputStream is = updatePath .openStream ()) {
48- try (OutputStream os = Files .newOutputStream (path ,
49- StandardOpenOption .CREATE , StandardOpenOption .WRITE )) {
50- ByteStreams .copy (is , os );
51- } catch (IOException e ) {
52- logger .error ("unable to replace file" , e );
53- }
69+ try (InputStream is = openStream ()) {
70+ update (is );
5471 } catch (IOException e ) {
5572 logger .error ("unable to download update" , e );
5673 throw propagate (e );
0 commit comments