2022-03-17 17:17:15 +01:00
package org.gcube.smartgears.persistence ;
import static org.gcube.smartgears.utils.Utils.fileAt ;
import static org.gcube.smartgears.utils.Utils.notNull ;
import java.io.File ;
2022-03-21 11:17:07 +01:00
import java.nio.file.Files ;
import java.nio.file.Paths ;
2022-03-17 17:17:15 +01:00
2022-06-24 15:45:43 +02:00
import javax.xml.bind.annotation.XmlAccessType ;
import javax.xml.bind.annotation.XmlAccessorType ;
import javax.xml.bind.annotation.XmlAttribute ;
import javax.xml.bind.annotation.XmlRootElement ;
2022-03-17 17:17:15 +01:00
import org.gcube.common.validator.annotations.NotEmpty ;
import org.gcube.common.validator.annotations.NotNull ;
2022-06-24 15:45:43 +02:00
@XmlRootElement ( name = " persistence " )
@XmlAccessorType ( XmlAccessType . FIELD )
2022-03-17 17:17:15 +01:00
public class LocalPersistence implements PersistenceWriter {
2022-06-24 15:45:43 +02:00
@XmlAttribute ( name = " location " ) @NotNull @NotEmpty
2022-03-17 17:17:15 +01:00
private String location ;
protected LocalPersistence ( ) { }
public LocalPersistence ( String location ) {
notNull ( " persistence location " , location ) ;
this . location = location ;
validate ( ) ;
}
public String getLocation ( ) {
return location ;
}
public void setLocation ( String location ) {
this . location = location ;
}
@Override
public File writefile ( String path ) {
notNull ( " relative path " , path ) ;
return fileAt ( new File ( location , path ) . getAbsolutePath ( ) ) . toWrite ( ) ;
}
@Override
public File file ( String path ) {
notNull ( " relative path " , path ) ;
return fileAt ( new File ( location , path ) . getAbsolutePath ( ) ) . toRead ( ) ;
}
public void validate ( ) {
File locationDir = new File ( location ) ;
if ( ! ( locationDir . exists ( ) & & locationDir . isDirectory ( ) & & locationDir . canRead ( ) & & locationDir . canWrite ( ) ) )
throw new IllegalStateException ( " invalid node configuration: home " + location + " does not exist or is not a directory or cannot be accessed in read/write mode " ) ;
}
2022-03-21 11:17:07 +01:00
@Override
public long getFreeSpace ( ) {
try {
return Files . getFileStore ( Paths . get ( location ) ) . getUsableSpace ( ) ;
} catch ( Exception e ) {
return - 1 ;
}
}
2022-03-17 17:17:15 +01:00
}