Search in sources :

Example 1 with AppException

use of org.edgegallery.appstore.domain.shared.exceptions.AppException in project appstore-be by EdgeGallery.

the class AppUtil method addImageFileInfo.

private void addImageFileInfo(String parentDir, String imgZipPath) {
    if (!StringUtils.isEmpty(imgZipPath)) {
        try {
            // add image zip to mf file
            File mfFile = getFile(parentDir, MF_EXTENSION);
            new BasicInfo().rewriteManifestWithImage(mfFile, imgZipPath, keyPath, keyPwd);
            // add image zip to TOSCA.meta file
            String toscaMeta = parentDir + "/TOSCA-Metadata/TOSCA.meta";
            File metaFile = new File(toscaMeta);
            String contentFile = imgZipPath.substring(parentDir.length() + 1);
            String contentName = "Name: " + contentFile + "\n";
            if (!FileUtils.readFileToString(metaFile, StandardCharsets.UTF_8).contains(contentName)) {
                FileUtils.writeStringToFile(metaFile, contentName, StandardCharsets.UTF_8, true);
                FileUtils.writeStringToFile(metaFile, "Content-Type: image\n", StandardCharsets.UTF_8, true);
            }
        } catch (Exception e) {
            LOGGER.error("add image file info to package failed {}", e.getMessage());
            throw new AppException("failed to add image info to package.", ResponseConst.RET_ADD_IMAGE_INFO_FAILED, ".mf or TOSCA-Metadata/TOSCA.meta");
        }
    }
}
Also used : AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) BasicInfo(org.edgegallery.appstore.domain.model.releases.BasicInfo) ZipFile(java.util.zip.ZipFile) AFile(org.edgegallery.appstore.domain.model.releases.AFile) IAppdFile(org.edgegallery.appstore.domain.model.appd.IAppdFile) File(java.io.File) AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) RestClientException(org.springframework.web.client.RestClientException) FileNotFoundException(java.io.FileNotFoundException) CMSException(org.bouncycastle.cms.CMSException) FileOperateException(org.edgegallery.appstore.domain.shared.exceptions.FileOperateException) IOException(java.io.IOException)

Example 2 with AppException

use of org.edgegallery.appstore.domain.shared.exceptions.AppException in project appstore-be by EdgeGallery.

the class AppUtil method loadZipIntoPackage.

/**
 * load file and analyse file list.
 *
 * @param fileAddress file storage object url.
 */
public void loadZipIntoPackage(String fileAddress, String fileParent) {
    // get unzip  temp folder under csar folder
    try {
        File tempFolder = new File(fileParent);
        FileUtils.deleteDirectory(tempFolder);
        if (!tempFolder.exists() && !tempFolder.mkdirs()) {
            LOGGER.error("Create upload path failed");
            throw new FileOperateException("create download file error", ResponseConst.RET_MAKE_DIR_FAILED);
        }
        unzipApplicationPackage(fileAddress, fileParent);
        File file = new File(fileParent);
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            String imgZipPath = getImgZipPath(fileParent, files);
            addImageFileInfo(fileParent, imgZipPath);
        }
    } catch (IOException e) {
        LOGGER.error("Failed to add image zip to package {} ", e.getMessage());
        throw new AppException(ADD_IMAGE_FILE_FAILED, ResponseConst.RET_IMAGE_TO_PACKAGE_FAILED);
    }
}
Also used : AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) AFile(org.edgegallery.appstore.domain.model.releases.AFile) IAppdFile(org.edgegallery.appstore.domain.model.appd.IAppdFile) File(java.io.File) FileOperateException(org.edgegallery.appstore.domain.shared.exceptions.FileOperateException)

Example 3 with AppException

use of org.edgegallery.appstore.domain.shared.exceptions.AppException in project appstore-be by EdgeGallery.

the class AppUtil method compressFile.

private void compressFile(ZipOutputStream out, File file, String dir) throws IOException {
    try (FileInputStream fis = new FileInputStream(file)) {
        out.putNextEntry(new ZipEntry(dir));
        int j;
        byte[] buffer = new byte[1024];
        while ((j = fis.read(buffer)) > 0) {
            out.write(buffer, 0, j);
        }
    } catch (FileNotFoundException e) {
        LOGGER.error("createCompressedFile: can not find param file, {}", e.getMessage());
        throw new AppException("can not find file", ResponseConst.RET_COMPRESS_FAILED);
    }
}
Also used : AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) ZipEntry(java.util.zip.ZipEntry) FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream)

Example 4 with AppException

use of org.edgegallery.appstore.domain.shared.exceptions.AppException in project appstore-be by EdgeGallery.

the class PackageService method unpublishPackage.

/**
 * unpublish a package.
 *
 * @param appId app id
 * @param packageId package id
 * @param user user info
 * @param isAdmin if admin role
 */
public void unpublishPackage(String appId, String packageId, User user, boolean isAdmin) {
    App app = appRepository.find(appId).orElseThrow(() -> new EntityNotFoundException(App.class, appId, ResponseConst.RET_APP_NOT_FOUND));
    Release release = app.findByPackageId(packageId).orElseThrow(() -> new UnknownReleaseExecption(packageId, ResponseConst.RET_PACKAGE_NOT_FOUND));
    release.checkPermission(user, isAdmin, ResponseConst.RET_NO_ACCESS_OFFSHELF_PACKAGE);
    if (release.getStatus() != EnumPackageStatus.Published) {
        LOGGER.error("Package status is {}, unpublish failed", release.getStatus());
        throw new AppException("The application can be taken off shelf only after it is published.", ResponseConst.RET_OFFSHELF_NO_PUBLISH);
    }
    release.setStatus(EnumPackageStatus.Unpublished);
    packageRepository.updateRelease(release);
    if (!app.hasPublishedRelease()) {
        app.setStatus(EnumAppStatus.UnPublish);
        appRepository.store(app);
    }
    LOGGER.info("Take {} off shelf successfully", app.getAppName());
}
Also used : App(org.edgegallery.appstore.domain.model.app.App) AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) EntityNotFoundException(org.edgegallery.appstore.domain.shared.exceptions.EntityNotFoundException) UnknownReleaseExecption(org.edgegallery.appstore.domain.model.releases.UnknownReleaseExecption) Release(org.edgegallery.appstore.domain.model.releases.Release)

Example 5 with AppException

use of org.edgegallery.appstore.domain.shared.exceptions.AppException in project appstore-be by EdgeGallery.

the class UploadHelper method uploadBigSoftware.

/**
 * upload Big Software.
 *
 * @param softPath package path
 * @param req request body
 * @param csrfToken token
 * @param cookie cookie
 * @param hostUrl request url
 * @return JSONObject
 */
public JSONObject uploadBigSoftware(String softPath, JSONObject req, String csrfToken, String cookie, String hostUrl) {
    JSONObject ret = new JSONObject();
    String progressId = req.getString("progressId");
    LOGGER.info("progressId query: {}}", progressId);
    PackageUploadProgress progress = progressFacade.getProgress(progressId).getBody();
    if (progress == null) {
        throw new AppException("process not exist.");
    }
    File soft = new File(softPath);
    try (FileInputStream input = new FileInputStream(soft)) {
        String fileName = soft.getName();
        LOGGER.info("--------start upload software--------" + fileName);
        JSONObject header = new JSONObject();
        UUID uuid = UUID.randomUUID();
        String fileId = uuid.toString().replace("-", "");
        header.put("X-File-id", fileId);
        header.put("X-File-Name", fileName);
        header.put("X-File-size", soft.length());
        header.put("X-Uni-Crsf-Token", csrfToken);
        header.put("X_Requested_With", "XMLHttpRequest");
        header.put("Content-Type", "application/octet-stream");
        header.put("Cache-Control", "no-cache");
        header.put("Host", hostUrl.split(":")[0] + ":" + hostUrl.split(":")[1]);
        long i = 0;
        long j;
        int count = 1;
        UploadPackageEntity upPackage = new UploadPackageEntity();
        upPackage.setFileName(fileName);
        upPackage.setFileIdentify(System.currentTimeMillis());
        upPackage.setCookie(cookie);
        upPackage.setCsrfToken(csrfToken);
        long length = soft.length();
        long totalSize = length;
        upPackage.setTotalSie(totalSize);
        // shard size 9437980
        byte[] buffer = new byte[AppConfig.FILE_SIZE];
        int shardTotal = (int) (totalSize / AppConfig.FILE_SIZE);
        while (length > AppConfig.FILE_SIZE && input.read(buffer, 0, AppConfig.FILE_SIZE) != -1) {
            header.put("Content-Length", AppConfig.FILE_SIZE);
            j = i + AppConfig.FILE_SIZE;
            header.put("X-File-start", i);
            header.put("X-File-end", j);
            String url = AppConfig.UPLOAD_PATH.replace("${taskName}", req.getString("taskName")) + count;
            upPackage.setShardCount(count);
            ret = uploadFileShard(header, "https://" + hostUrl + url, upPackage, req, buffer);
            if (ret.getInteger("retCode") == -1) {
                updateProgressStatus(progress, Consts.FAILED);
                LOGGER.error("upload failed: {}", ret);
                return ret;
            }
            LOGGER.info("upload file:" + fileName + "-total size:" + totalSize + "-already upload:" + i);
            // update upload progress
            if (count % 10 == 0) {
                progress.setProgress(String.valueOf(count * 100 / shardTotal));
                progressFacade.updateProgress(progress);
            }
            i = j;
            count++;
            length = length - AppConfig.FILE_SIZE;
        }
        byte[] ednBuffer = new byte[(int) length];
        int readCount = input.read(ednBuffer);
        if (readCount == -1) {
            updateProgressStatus(progress, Consts.FAILED);
            LOGGER.error("upload failed: {}", ret.toString());
            return ret;
        }
        header.put("Content-Length", length);
        header.put("X-File-start", i);
        header.put("X-File-end", soft.length());
        String url = AppConfig.UPLOAD_PATH.replace("${taskName}", req.getString("taskName")) + count;
        upPackage.setShardCount(count);
        ret = uploadFileShard(header, "https://" + hostUrl + url, upPackage, req, ednBuffer);
        LOGGER.info("upload file:" + fileName + "-total size:" + totalSize + "-already upload:" + soft.length());
        LOGGER.info(fileName + " Upload package finished.");
        // update upload progress to 100%
        progress.setProgress("100");
        updateProgressStatus(progress, Consts.SUCCESS);
        return ret;
    } catch (IOException e) {
        LOGGER.error("uploadBigSoftware IOException");
    }
    updateProgressStatus(progress, Consts.FAILED);
    ret.put("retCode", -1);
    LOGGER.error("upload failed: {}", ret.toString());
    return ret;
}
Also used : AppException(org.edgegallery.appstore.domain.shared.exceptions.AppException) JSONObject(com.alibaba.fastjson.JSONObject) IOException(java.io.IOException) UUID(java.util.UUID) File(java.io.File) FileInputStream(java.io.FileInputStream) PackageUploadProgress(org.edgegallery.appstore.infrastructure.persistence.meao.PackageUploadProgress)

Aggregations

AppException (org.edgegallery.appstore.domain.shared.exceptions.AppException)57 File (java.io.File)29 IOException (java.io.IOException)28 AFile (org.edgegallery.appstore.domain.model.releases.AFile)20 ZipFile (java.util.zip.ZipFile)16 IAppdFile (org.edgegallery.appstore.domain.model.appd.IAppdFile)14 Gson (com.google.gson.Gson)11 Release (org.edgegallery.appstore.domain.model.releases.Release)11 FileInputStream (java.io.FileInputStream)10 HttpHeaders (org.springframework.http.HttpHeaders)10 RestClientException (org.springframework.web.client.RestClientException)10 HttpEntity (org.springframework.http.HttpEntity)9 SwImgDesc (org.edgegallery.appstore.domain.model.app.SwImgDesc)8 EntityNotFoundException (org.edgegallery.appstore.domain.shared.exceptions.EntityNotFoundException)8 FileOutputStream (java.io.FileOutputStream)7 JsonObject (com.google.gson.JsonObject)6 TypeToken (com.google.gson.reflect.TypeToken)5 BufferedInputStream (java.io.BufferedInputStream)5 InputStream (java.io.InputStream)5 ZipEntry (java.util.zip.ZipEntry)5