/*
  * GET list of file system exports
  *
  * @param id the URN of a ViPR File system
  *
  * @return File system exports list.
  */
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("/{id}/exports")
 public FileSystemExportList getFileSystemExportListInternal(@PathParam("id") URI id) {
   ArgValidator.checkFieldUriType(id, FileShare.class, "id");
   FileShare fs = _fileService.queryResource(id);
   checkFileShareInternal(fs);
   return _fileService.getFileSystemExportList(id);
 }
  public static void main(String[] args) {
    try {
      FileService h = (FileService) Naming.lookup("//localhost/fileService");
      h.write("test.txt", 1, "SuperGuterText");
      System.out.println(h.read("test.txt", 1));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /*
  * POST to create a new export
  */
 @POST
 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("/{id}/exports")
 public TaskResourceRep exportInternal(@PathParam("id") URI id, FileSystemExportParam param)
     throws InternalException {
   ArgValidator.checkFieldUriType(id, FileShare.class, "id");
   FileShare fs = _fileService.queryResource(id);
   checkFileShareInternal(fs);
   return _fileService.export(id, param);
 }
  @Async
  @Override
  public void processImage(URI uri) throws Exception {
    File image = fileService.get(uri);
    final BufferedImage bufferedImage = ImageIO.read(image);

    for (ImageStyle imageStyle : imageStyles.values()) {
      BufferedImage styledImage = imageStyle.process(bufferedImage);
      File imageFile = fileService.create(buildGeneratedImagePath(imageStyle, uri));
      ImageIO.write(styledImage, FilenameUtils.getExtension(image.getName()), imageFile);
    }
  }
Esempio n. 5
0
  @Test
  public void copy() throws IOException {
    File file = new File(filename);
    Assert.assertTrue(file.exists());
    File copy = new File(copyFilename);
    FileUtils.copyFile(file, copy);

    PalsFile palsFile = fileService.createFile(copy);
    palsFile.setName("name");
    palsFile.setContentType("ct");
    PalsFile palsFileCopy = fileService.copy(palsFile);

    Assert.assertEquals(palsFileCopy, palsFile);
  }
  public static void main(String[] args) throws IOException {
    File file = new File("src" + File.separatorChar + "GarageTotals.txt");

    TextFormatStrategy format = new GarageTotalsFormatter();
    FileService fs = new FileService(new TextReader(format), new TextWriter(format));
    List<Map> fileContent = fs.readFile(file);
    System.out.println(fileContent);
    Map<String, String> map = new HashMap<>();
    map.put("Date", LocalDate.now().toString());
    map.put("TotalHours", "193");
    map.put("TotalFees", "1987");
    List<Map> data = new ArrayList();
    data.add(map);
    System.out.println(data.get(0));
    fs.writeToFile(data, file, false);
  }
  /*
   * POST to create
   */
  @POST
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public TaskResourceRep createFileSystemInternal(FileSystemParam param) {
    TenantOrg tenant = _permissionsHelper.getRootTenant();
    TaskResourceRep rep = null;
    if (!_permissionsHelper.userHasGivenRole(
        getUserFromContext(), tenant.getId(), Role.SYSTEM_ADMIN, Role.TENANT_ADMIN)) {
      rep = new TaskResourceRep();
      _log.error(
          "Unable to process the request as Only [system_admin, tenant_admin] can provision file systems for object");
      rep.setMessage("Only [system_admin, tenant_admin] can provision file systems for object");
      rep.setState(Operation.Status.error.name());
      return rep;
    }
    try {
      rep =
          _fileService.createFSInternal(param, _internalProject, tenant, INTERNAL_FILESHARE_FLAGS);
    } catch (Exception ex) {
      rep = new TaskResourceRep();
      _log.error("Exception occurred while creating file system due to:", ex);
      rep.setMessage(ex.getMessage());
      rep.setState(Operation.Status.error.name());
    }

    return rep;
  }
 /*
  * POST to deactivate filesystem
  */
 @POST
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("/{id}/deactivate")
 public TaskResourceRep deactivateFileSystemInternal(
     @PathParam("id") URI id, FileSystemDeleteParam param) throws InternalException {
   ArgValidator.checkFieldUriType(id, FileShare.class, "id");
   FileShare fs = _fileService.queryResource(id);
   checkFileShareInternal(fs);
   TenantOrg tenant = _permissionsHelper.getRootTenant();
   if (!_permissionsHelper.userHasGivenRole(
       getUserFromContext(), tenant.getId(), Role.SYSTEM_ADMIN, Role.TENANT_ADMIN)) {
     throw APIException.forbidden.onlyAdminsCanDeactivateFileSystems(
         Role.SYSTEM_ADMIN.toString(), Role.TENANT_ADMIN.toString());
   }
   return _fileService.deactivateFileSystem(id, param);
 }
Esempio n. 9
0
  /**
   * 开始下载文件
   *
   * @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null
   * @return 已下载文件大小
   * @throws Exception
   */
  public int download(DownloadProgressListener listener) throws Exception {
    try {
      RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
      if (this.fileSize > 0) randOut.setLength(this.fileSize);
      randOut.close();
      URL url = new URL(this.downloadUrl);

      if (this.data.size() != this.threads.length) {
        this.data.clear();

        for (int i = 0; i < this.threads.length; i++) {
          this.data.put(i + 1, 0); // 初始化每条线程已经下载的数据长度为0
        }
      }

      for (int i = 0; i < this.threads.length; i++) { // 开启线程进行下载
        int downLength = this.data.get(i + 1);

        if (downLength < this.block && this.downloadSize < this.fileSize) { // 判断线程是否已经完成下载,否则继续下载
          this.threads[i] =
              new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
          this.threads[i].setPriority(7);
          this.threads[i].start();
        } else {
          this.threads[i] = null;
        }
      }

      this.fileService.save(this.downloadUrl, this.data);
      boolean notFinish = true; // 下载未完成

      while (notFinish) { // 循环判断所有线程是否完成下载
        Thread.sleep(900);
        notFinish = false; // 假定全部线程下载完成

        for (int i = 0; i < this.threads.length; i++) {
          if (this.threads[i] != null && !this.threads[i].isFinish()) { // 如果发现线程未完成下载
            notFinish = true; // 设置标志为下载没有完成

            if (this.threads[i].getDownLength() == -1) { // 如果下载失败,再重新下载
              this.threads[i] =
                  new DownloadThread(
                      this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
              this.threads[i].setPriority(7);
              this.threads[i].start();
            }
          }
        }

        if (listener != null) listener.onDownloadSize(this.downloadSize); // 通知目前已经下载完成的数据长度
      }

      fileService.delete(this.downloadUrl);
    } catch (Exception e) {
      print(e.toString());
      throw new Exception("file download fail");
    }
    return this.downloadSize;
  }
Esempio n. 10
0
  /**
   * 构建文件下载器
   *
   * @param downloadUrl 下载路径
   * @param fileSaveDir 文件保存目录
   * @param threadNum 下载线程数
   */
  public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
    try {
      this.context = context;
      this.downloadUrl = downloadUrl;
      fileService = new FileService(this.context);
      URL url = new URL(this.downloadUrl);
      if (!fileSaveDir.exists()) fileSaveDir.mkdirs();
      this.threads = new DownloadThread[threadNum];

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5 * 1000);
      conn.setRequestMethod("GET");
      conn.setRequestProperty(
          "Accept",
          "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
      conn.setRequestProperty("Accept-Language", "zh-CN");
      conn.setRequestProperty("Referer", downloadUrl);
      conn.setRequestProperty("Charset", "UTF-8");
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.connect();
      if (BuildConfig.DEBUG) printResponseHeader(conn);

      if (conn.getResponseCode() == 200) {
        this.fileSize = conn.getContentLength(); // 根据响应获取文件大小
        if (this.fileSize <= 0) throw new RuntimeException("Unkown file size ");

        String filename = getFileName(conn); // 获取文件名称
        this.saveFile = new File(fileSaveDir, filename); // 构建保存文件
        Map<Integer, Integer> logdata = fileService.getData(downloadUrl); // 获取下载记录

        if (logdata.size() > 0) { // 如果存在下载记录
          for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
            data.put(entry.getKey(), entry.getValue()); // 把各条线程已经下载的数据长度放入data中
        }

        if (this.data.size() == this.threads.length) { // 下面计算所有线程已经下载的数据长度
          for (int i = 0; i < this.threads.length; i++) {
            this.downloadSize += this.data.get(i + 1);
          }

          print("已经下载的长度" + this.downloadSize);
        }

        // 计算每条线程下载的数据长度
        this.block =
            (this.fileSize % this.threads.length) == 0
                ? this.fileSize / this.threads.length
                : this.fileSize / this.threads.length + 1;
      } else {
        throw new RuntimeException("server no response ");
      }
    } catch (Exception e) {
      print(e.toString());
      throw new RuntimeException("don't connection this url");
    }
  }
  void share() {
    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    String imgPath = FileService.createShareImage(bm, this);
    String title = getString(R.string.pwdsetting_share_detail);
    String text = getString(R.string.pwdsetting_share_text);

    shareMsg(title, title, text, imgPath);
  }
 @Override
 public void remove(Update update) {
   logger.debug("Attempting to persist Update: " + update);
   String fileData = update.getFileData();
   getSession().delete(update);
   fileService.removeFile(fileData);
   logger.debug("Deleted Update: " + update);
 }
 @Override
 public void persist(Update update) throws IOException {
   logger.debug("Attempting to persist Update: " + update);
   update.setFileData(fileService.saveMultipartFile(update.getFile()));
   update.setFileName(update.getFile().getOriginalFilename());
   update.setFileSize(update.getFile().getSize());
   getSession().persist(update);
   logger.debug("Persisted Update: " + update);
 }
 /*
  * DELETE filesystem export
  */
 @DELETE
 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("/{id}/exports/{protocol},{secType},{perm},{root_mapping}")
 public TaskResourceRep unexportInternal(
     @PathParam("id") URI id,
     @PathParam("protocol") String protocol,
     @PathParam("secType") String securityType,
     @PathParam("perm") String permissions,
     @PathParam("root_mapping") String rootUserMapping,
     @QueryParam("subDirectory") String subDirectory)
     throws InternalException {
   ArgValidator.checkFieldUriType(id, FileShare.class, "id");
   FileShare fs = _fileService.queryResource(id);
   checkFileShareInternal(fs);
   return _fileService.unexport(
       id, protocol, securityType, permissions, rootUserMapping, subDirectory);
 }
 /*
  * GET task status
  */
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("/{id}/tasks/{op_id}/")
 public TaskResourceRep getTaskInternal(@PathParam("id") URI id, @PathParam("op_id") URI op_id)
     throws DatabaseException {
   ArgValidator.checkFieldUriType(id, FileShare.class, "id");
   FileShare fs = _fileService.queryResource(id);
   checkFileShareInternal(fs);
   return toTask(fs, op_id.toString());
 }
Esempio n. 16
0
 @RequestMapping(
     value = "/contacts/files/{contactId}/attachments/{attachmentId}/check",
     method = GET)
 public void checkFile(@PathVariable Long contactId, @PathVariable Long attachmentId) {
   logger.debug("checking attachment {} from contact {}", attachmentId, contactId);
   File file = fileService.getAttachment(contactId, attachmentId);
   if (!file.exists()) {
     throw new RuntimeException("error happened during file download");
   }
 }
  @Override
  public Map<String, URL> getGeneratedImagesUrls(URI uri) throws Exception {
    Map<String, URL> generatedImages = new HashMap();

    for (ImageStyle imageStyle : imageStyles.values()) {
      generatedImages.put(
          imageStyle.getKey(), fileService.getUrl(buildGeneratedImagePath(imageStyle, uri)));
    }

    return generatedImages;
  }
Esempio n. 18
0
  @Test
  public void copyList() throws IOException {
    List<PalsFile> fileList = new ArrayList<PalsFile>();
    for (int i = 0; i < 4; ++i) {
      File file = new File(filename);
      Assert.assertTrue(file.exists());
      File copy = new File(copyFilename);
      FileUtils.copyFile(file, copy);
      PalsFile palsFile = fileService.createFile(copy);
      palsFile.setName("name");
      palsFile.setContentType("ct");
      fileList.add(palsFile);
    }

    List<PalsFile> copyList = fileService.copy(fileList);

    for (int i = 0; i < copyList.size(); ++i) {
      Assert.assertEquals(copyList.get(i), fileList.get(i));
    }
  }
Esempio n. 19
0
  @Test
  public void saveFile() throws IOException {
    File file = new File(filename);
    Assert.assertTrue(file.exists());
    File copy = new File(copyFilename);
    FileUtils.copyFile(file, copy);

    PalsFile palsFile = fileService.createFile(copy);
    fileService.save(palsFile);
    palsFile = fileService.get(palsFile.getId());

    Assert.assertEquals(palsFile.getData().length(), 10314752);
    Assert.assertFalse(copy.exists());

    InputStream is = new FileInputStream(file);
    byte[] buffer = new byte[palsFile.getData().length()];
    is.read(buffer, 0, buffer.length);
    for (int i = 0; i < buffer.length; ++i) {
      Assert.assertEquals(buffer[i], palsFile.getData().getData()[i]);
    }
    is.close();

    fileService.deleteFile(palsFile);
  }
  /**
   * Undo the release of a file system
   *
   * @param id the URN of a ViPR file system to undo
   * @return the updated file system
   * @throws InternalException
   */
  @POST
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Path("/{id}/release/undo")
  public FileShareRestRep undoReleaseFileSystemInternal(@PathParam("id") URI id)
      throws InternalException {

    ArgValidator.checkFieldUriType(id, FileShare.class, "id");
    FileShare fs = _fileService.queryResource(id);
    checkFileShareInternal(fs);

    URI releasedProject = fs.getOriginalProject();
    if (releasedProject == null) {
      throw APIException.forbidden.onlyPreviouslyReleasedFileSystemsCanBeUndone();
    }

    Project project = _permissionsHelper.getObjectById(releasedProject, Project.class);
    ArgValidator.checkEntity(project, releasedProject, false);
    ArgValidator.checkFieldNotNull(project.getTenantOrg(), "tenantOrg");
    ArgValidator.checkFieldNotNull(project.getTenantOrg().getURI(), "tenantOrg");

    fs.setTenant(new NamedURI(project.getTenantOrg().getURI(), fs.getLabel()));
    fs.setProject(new NamedURI(releasedProject, fs.getLabel()));
    fs.setOriginalProject(null);
    fs.clearInternalFlags(INTERNAL_FILESHARE_FLAGS);
    _dbClient.updateAndReindexObject(fs);

    // audit against the new project, not the old dummy internal project
    auditOp(
        OperationTypeEnum.UNDO_RELEASE_FILE_SYSTEM,
        true,
        null,
        fs.getId().toString(),
        project.getId().toString());

    return map(fs);
  }
Esempio n. 21
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int index;

    DatastoreService ds;
    MemcacheService ms;
    BlobstoreService bs;
    URLFetchService us;
    FileService fs;

    Map<String, List<BlobKey>> blobMap;
    BlobKey blobKey;
    BlobInfoFactory blobInfoFactory;
    BlobInfo blobInfo;

    int postCount;
    int postIndex;
    String postType;
    String postText;
    String postDelpw;
    String postShowgallery;
    DataObj dataObj;
    String filelink;

    String picUrl;
    HTTPResponse picRes;
    List<HTTPHeader> headerList;
    String picMime;
    String[] fileNamePart;
    AppEngineFile picFile;
    FileWriteChannel writeChannel;

    PostObj postObj;
    List<PostObj> postObjList;
    String linkID;

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");

    try {
      ds = DatastoreServiceFactory.getDatastoreService();
      ms = MemcacheServiceFactory.getMemcacheService();
      bs = BlobstoreServiceFactory.getBlobstoreService();
      us = URLFetchServiceFactory.getURLFetchService();
      fs = FileServiceFactory.getFileService();
      blobInfoFactory = new BlobInfoFactory(ds);

      blobMap = bs.getUploads(req);
      postCount = Integer.valueOf(req.getParameter("input_post_count"));
      postObjList = new ArrayList<PostObj>();

      for (postIndex = 0; postIndex < postCount; postIndex++) {
        try {
          postType = req.getParameter("input_post_type_" + postIndex);
          if (postType == null) {
            continue;
          }

          postText = req.getParameter("input_post_text_" + postIndex);
          postDelpw = req.getParameter("input_post_delpw_" + postIndex);
          postShowgallery = req.getParameter("input_post_showgallery_" + postIndex);
          if (postShowgallery == null) {
            postShowgallery = "";
          }

          if (postType.equals("file") == true) {
            blobKey = blobMap.get("input_post_file_" + postIndex).get(0);
            if (blobKey == null) {
              throw new Exception();
            }

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = blobKey;
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          } else if (postType.equals("url") == true) {
            picUrl = postText;

            picRes = us.fetch(new URL(picUrl));
            headerList = picRes.getHeaders();
            picMime = "application/octet-stream";
            for (index = 0; index < headerList.size(); index++) {
              if (headerList.get(index).getName().compareToIgnoreCase("Content-Type") == 0) {
                picMime = headerList.get(index).getValue();
                break;
              }
            }

            fileNamePart = picUrl.split("/");

            picFile = fs.createNewBlobFile(picMime, fileNamePart[fileNamePart.length - 1]);
            writeChannel = fs.openWriteChannel(picFile, true);
            writeChannel.write(ByteBuffer.wrap(picRes.getContent()));
            writeChannel.closeFinally();

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = fs.getBlobKey(picFile);
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          }
        } catch (Exception e) {
        }
      }

      linkID = postFile(us, postObjList);

      if (req.getParameter("specflag") != null) {
        resp.getWriter().print("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      } else {
        resp.sendRedirect("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      }
    } catch (Exception e) {
    }
  }
  /**
   * Release a file system from its current tenant & project for internal object usage
   *
   * @param id the URN of a ViPR file system to be released
   * @return the updated file system
   * @throws InternalException
   */
  @POST
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Path("/{id}/release")
  public FileShareRestRep releaseFileSystemInternal(@PathParam("id") URI id)
      throws InternalException {

    ArgValidator.checkFieldUriType(id, FileShare.class, "id");
    FileShare fs = _fileService.queryResource(id);

    // if the FS is already marked as internal, we can skip all this logic
    // and just return success down at the bottom
    if (!fs.checkInternalFlags(Flag.INTERNAL_OBJECT)) {
      URI tenantURI = fs.getTenant().getURI();
      if (!_permissionsHelper.userHasGivenRole(
          getUserFromContext(), tenantURI, Role.TENANT_ADMIN)) {
        throw APIException.forbidden.onlyAdminsCanReleaseFileSystems(Role.TENANT_ADMIN.toString());
      }

      // we can't release a fs that has exports
      FSExportMap exports = fs.getFsExports();
      if ((exports != null) && (!exports.isEmpty())) {
        throw APIException.badRequests.cannotReleaseFileSystemExportExists(
            exports.keySet().toString());
      }

      // we can't release a fs that has shares
      SMBShareMap shares = fs.getSMBFileShares();
      if ((shares != null) && (!shares.isEmpty())) {
        throw APIException.badRequests.cannotReleaseFileSystemSharesExists(
            shares.keySet().toString());
      }

      // files systems with pending operations can't be released
      if (fs.getOpStatus() != null) {
        for (String opId : fs.getOpStatus().keySet()) {
          Operation op = fs.getOpStatus().get(opId);
          if (Operation.Status.pending.name().equals(op.getStatus())) {
            throw APIException.badRequests.cannotReleaseFileSystemWithTasksPending();
          }
        }
      }

      // file systems with snapshots can't be released
      Integer snapCount = _fileService.getNumSnapshots(fs);
      if (snapCount > 0) {
        throw APIException.badRequests.cannotReleaseFileSystemSnapshotExists(snapCount);
      }

      TenantOrg rootTenant = _permissionsHelper.getRootTenant();

      // we can't release the file system to the root tenant if the root tenant has no access
      // to the filesystem's virtual pool
      ArgValidator.checkFieldNotNull(fs.getVirtualPool(), "virtualPool");
      VirtualPool virtualPool =
          _permissionsHelper.getObjectById(fs.getVirtualPool(), VirtualPool.class);
      ArgValidator.checkEntity(virtualPool, fs.getVirtualPool(), false);
      if (!_permissionsHelper.tenantHasUsageACL(rootTenant.getId(), virtualPool)) {
        throw APIException.badRequests.cannotReleaseFileSystemRootTenantLacksVPoolACL(
            virtualPool.getId().toString());
      }

      fs.setOriginalProject(fs.getProject().getURI());
      fs.setTenant(new NamedURI(rootTenant.getId(), fs.getLabel()));
      fs.setProject(new NamedURI(_internalProject.getId(), fs.getLabel()));
      fs.addInternalFlags(INTERNAL_FILESHARE_FLAGS);
      _dbClient.updateAndReindexObject(fs);

      // audit against the source project, not the new dummy internal project
      auditOp(
          OperationTypeEnum.RELEASE_FILE_SYSTEM,
          true,
          null,
          fs.getId().toString(),
          fs.getOriginalProject().toString());
    }

    return map(fs);
  }
Esempio n. 23
0
  public void generate(Liquidation liquidation, OutputStream out) {
    Validate.notNull(liquidation.getPdfFile(), "Missing liquidation file");
    String name;
    InputStream in;
    try {
      ZipOutputStream zipOutputStream = new ZipOutputStream(out);
      name = fileService.getAbstractBillFileName(liquidation, "pdf");
      in = fileService.getInputStream(liquidation.getPdfFile());
      addZipEntry(in, zipOutputStream, name);

      BillingModel model = liquidation.getModel();
      boolean includeBills =
          model == null || model.getIncludePdfBills() != null || model.getIncludePdfBills();
      boolean includeDetails =
          model == null || model.getIncludePdfDetails() != null || model.getIncludePdfDetails();

      if (includeBills) {
        for (Bill bill : liquidation.getBills()) {
          if (MathUtils.isNotZero(bill.getAmount()) && bill.getPdfFile() != null) {
            name = fileService.getAbstractBillFileName(bill, "pdf");
            in = fileService.getInputStream(bill.getPdfFile());
            addZipEntry(in, zipOutputStream, FORMAT_BILL_FOLDER + name);
          } else {
            LOG.debug(
                "No se incluye la factura de {}: carece de fichero asociado",
                bill.getSender().getName());
          }
        }
      }

      if (includeDetails) {
        for (Bill bill : liquidation.getBills()) {
          if (bill.getLiquidationDetailFile() != null
              && MathUtils.isNotZero(bill.getLiquidationTotalAmount())) {
            name = fileService.getAbstractBillFileName(bill, "pdf");
            in = fileService.getInputStream(bill.getLiquidationDetailFile());
            addZipEntry(in, zipOutputStream, FORMAT_DETAILS_FOLDER + name);
          }
        }
      }

      // Generamos el report
      try {
        Date from = liquidation.getDateFrom();
        Date to = liquidation.getDateTo();
        ByteArrayOutputStream reportOutputStream = new ByteArrayOutputStream();
        Company company = liquidation.getSender().as(Company.class);
        reportGenerator.generate(from, to, company, null, null, reportOutputStream);
        ByteArrayInputStream reportInputStream =
            new ByteArrayInputStream(reportOutputStream.toByteArray());
        String fileName = fileService.getAbstractBillFileName(liquidation, "xls");
        addZipEntry(reportInputStream, zipOutputStream, fileName);
      } catch (Exception ignore) {
        LOG.error("Error al adjuntar el report", ignore);
      }
      zipOutputStream.flush();
      zipOutputStream.close();
    } catch (Exception ex) {
      throw new RuntimeException("Error al generar el ZIP con la liquidación", ex);
    }
  }
 @Override
 public void deleteGeneratedImages(URI uri) throws Exception {
   for (ImageStyle imageStyle : imageStyles.values()) {
     fileService.delete(buildGeneratedImagePath(imageStyle, uri));
   }
 }