package org.odroid.server.services; import static com.google.common.base.Preconditions.checkArgument; import static org.odroid.server.fs.FileSystemUtils.createDir; import static org.odroid.server.fs.FileSystemUtils.saveFile; import static org.springframework.util.DigestUtils.md5DigestAsHex; import static org.springframework.util.StringUtils.isEmpty; import java.io.File; import java.io.IOException; import java.util.List; import org.odroid.server.dao.ApplicationDAO; import org.odroid.server.entities.Application; import org.odroid.server.entities.ApplicationDataType; import org.odroid.server.exception.ApplicationNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ApplicationService { // TODO checkIfExists guava, exception hierarchy @Autowired private ApplicationDAO applicationDAO; @Value("${os.filestore}") private String APP_FILESTORE; public Application createApp(Application app) { checkArgument(app.getHash() == null, "Hash mustn't be set!");// TODO // resources checkArgument(!isEmpty(app.getName()), "Name must be set");// TODO // resources app.setHash(uniqueHash()); return applicationDAO.persistOrMerge(app); } private String uniqueHash() { String currenTime = String.valueOf(System.nanoTime()); return new String(md5DigestAsHex(currenTime.getBytes())); } public Application getApplicationForHash(String hash) { Application a = applicationDAO.getApplicationForHash(hash); checkIfApplicationExists(a, hash); return a; } public Application lock(String hash) { return changeApplicationActiveStatus(hash, Boolean.FALSE); } public Application unlock(String hash) { return changeApplicationActiveStatus(hash, Boolean.TRUE); } private Application changeApplicationActiveStatus(String hash, Boolean active) { Application a = applicationDAO.getApplicationForHash(hash); checkIfApplicationExists(a, hash); a.setActive(active); a = applicationDAO.persistOrMerge(a); return a; } public List<Application> getAllApplications() { return applicationDAO.getAllApplications(); } // TODO - co ma zwracać? // TODO - dodać walidację, zawartości pliku, może w ApplicationDataType?? public String addData(String hash, ApplicationDataType type, byte[] data) throws IOException { Application a = getApplicationForHash(hash); checkIfApplicationExists(a, hash); File appDir = createDir(APP_FILESTORE, hash); saveFile(appDir.getAbsolutePath(), type.name().toLowerCase(), data); return new String(data); } // TODO Aspect?? private void checkIfApplicationExists(Application a, String hash) { if (a == null) { throw new ApplicationNotFoundException("No application found for hash: " + hash); } } }