public String uploadFile() {

    File file = new File("f://import.xml");

    byte[] fileContent;
    try {
      fileContent = FileUtils.readFileToByteArray(file);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    UploadFileRequest uploadFileRequest =
        new UploadFileRequest()
            .withFileType(FileType.DD)
            .withFileName("12345.xml")
            .withFileFormat("BE_SCHEME")
            .withSchemeType(SchemeType.CORE)
            .withCreditorSchemeId("CreditorSchemeName");

    UploadFileResponse uploadFileResponse = filesService.uploadFile(uploadFileRequest, fileContent);

    logger.info(uploadFileResponse.getData().getId());

    return uploadFileResponse.getData().getId();
  }
Beispiel #2
0
  protected void run(
      Site site,
      Container container,
      File file,
      String originalFilename,
      String displayName,
      Group permittedGroup,
      Person person,
      EducationalResourceType type)
      throws FenixServiceException, DomainException, IOException {

    final VirtualPath filePath = getVirtualPath(site, container);

    Collection<FileSetMetaData> metaData =
        createMetaData(person.getName(), displayName, site.getAuthorName(), type);

    final byte[] bs = FileUtils.readFileToByteArray(file);

    checkSiteQuota(site, bs.length);

    FileContent fileContent =
        new FileContent(filePath, originalFilename, displayName, metaData, bs, permittedGroup);

    container.addFile(fileContent);
  }
 public static byte[] readFileToByteArray(File file) {
   try {
     return FileUtils.readFileToByteArray(file);
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
Beispiel #4
0
 public byte[] readAsBytes() throws DescriptorIOException {
   try {
     return FileUtils.readFileToByteArray(new File(locator.getURI().getPath()));
   } catch (IOException ex) {
     throw new DescriptorIOException("Cannot read descriptor: " + locator.getLastName(), ex);
   }
 }
  @RolesAllowed({PFI_ADMIN, PFI_USER})
  @WebMethod
  public FitxerBean downloadFileUsingEncryptedFileID(String encryptedFileID)
      throws WsI18NException, Throwable {

    FitxerJPA.enableEncryptedFileIDGeneration();
    try {
      long fitxerID = HibernateFileUtil.decryptFileID(encryptedFileID);

      // Checks
      Fitxer fitxer = fitxerLogicaEjb.checkBasic(fitxerID);

      FitxerBean fitxerBean = new FitxerBean(fitxer);

      byte[] data = FileUtils.readFileToByteArray(FileSystemManager.getFile(fitxerID));

      DataHandler dh = new DataHandler(new ByteArrayDataSource(data, fitxerBean.getMime()));

      fitxerBean.setData(dh);

      System.gc();

      return fitxerBean;

    } finally {
      FitxerJPA.disableEncryptedFileIDGeneration();
    }
  }
  protected void attachmentDownload(T entity, String attachmentId) {
    try {
      AttachmentFileService attachmentFileService =
          SpringContextHolder.getBean(AttachmentFileService.class);
      AttachmentFile attachmentFile = attachmentFileService.findOne(attachmentId);
      if (attachmentFile != null
          && entity.getId().toString().equals(attachmentFile.getEntityId())
          && entity.getClass().getName().equals(attachmentFile.getEntityClassName())) {
        HttpServletResponse response = ServletActionContext.getResponse();
        ServletUtils.setFileDownloadHeader(response, attachmentFile.getFileRealName());
        response.setContentType(attachmentFile.getFileType());

        DynamicConfigService dynamicConfigService =
            SpringContextHolder.getBean(DynamicConfigService.class);
        String rootPath = dynamicConfigService.getFileUploadRootDir();
        File diskFile =
            new File(
                rootPath
                    + attachmentFile.getFileRelativePath()
                    + File.separator
                    + attachmentFile.getDiskFileName());
        logger.debug("Downloading attachment file from disk: {}", diskFile.getAbsolutePath());
        ServletUtils.renderFileDownload(response, FileUtils.readFileToByteArray(diskFile));
      }
    } catch (Exception e) {
      logger.error("Download file error", e);
    }
  }
Beispiel #7
0
 public static byte[] byteArray(File file) {
   try {
     return FileUtils.readFileToByteArray(file);
   } catch (IOException ioe) {
     throw new CLIException(REASON_IO_ERROR, ioe);
   }
 }
Beispiel #8
0
  /**
   * Retrieve the asset from the persistent cache. If the asset is not in the cache, or loading from
   * the cache failed then this function returns null.
   *
   * @param id MD5 of the requested asset
   * @return Asset from the cache
   */
  private static Asset getFromPersistentCache(MD5Key id) {

    if (id == null || id.toString().length() == 0) {
      return null;
    }

    if (!assetIsInPersistentCache(id)) {
      return null;
    }

    File assetFile = getAssetCacheFile(id);

    try {
      byte[] data = FileUtils.readFileToByteArray(assetFile);
      Properties props = getAssetInfo(id);

      Asset asset = new Asset(props.getProperty(NAME), data);

      if (!asset.getId().equals(id)) {
        log.error("MD5 for asset " + asset.getName() + " corrupted");
      }

      assetMap.put(id, asset);

      return asset;
    } catch (IOException ioe) {
      log.error("Could not load asset from persistent cache", ioe);
      return null;
    }
  }
  @Test
  public void buildRevisionFromMapValidMapWithAttachments() throws Exception {

    // lets the get the attachment encoded

    File file = TestUtils.loadFixture("fixture/bonsai-boston.jpg");

    byte[] unencodedAttachment = FileUtils.readFileToByteArray(file);
    byte[] encodedAttachment = this.encodeAttachment(unencodedAttachment);

    Map<String, Map<String, Object>> attachments = new HashMap<String, Map<String, Object>>();
    Map<String, Object> bonsai = createAttachmentMap(encodedAttachment, "image/jpeg", false);

    attachments.put("bonsai-boston.jpg", bonsai);
    documentRev.put("_attachments", attachments);

    DocumentRevision revision =
        DocumentRevisionBuilder.buildRevisionFromMap(documentURI, documentRev);

    Assert.assertNotNull(revision);
    Assert.assertEquals(body, revision.getBody().asMap());
    Assert.assertEquals(revision.getId(), "someIdHere");
    Assert.assertEquals(revision.getRevision(), "3-750dac460a6cc41e6999f8943b8e603e");
    Assert.assertEquals(revision.getAttachments().size(), 1);
    ByteArrayInputStream expected = new ByteArrayInputStream(unencodedAttachment);
    InputStream actual = revision.getAttachments().get("bonsai-boston.jpg").getInputStream();
    Assert.assertTrue(TestUtils.streamsEqual(expected, actual));
  }
  @Before
  public void setup() throws IOException {
    CouchConfig config = super.getCouchConfig(CLOUDANT_TEST_DB_NAME + System.currentTimeMillis());
    remoteDb =
        new CouchClientWrapper(
            config.getRootUri(), config.getRequestInterceptors(), config.getResponseInterceptors());
    bodyOne =
        DocumentBodyFactory.create(
            FileUtils.readFileToByteArray(TestUtils.loadFixture(documentOneFile)));
    bodyTwo =
        DocumentBodyFactory.create(
            FileUtils.readFileToByteArray(TestUtils.loadFixture(documentTwoFile)));

    CouchClientWrapperDbUtils.deleteDbQuietly(remoteDb);
    remoteDb.createDatabase();
  }
Beispiel #11
0
 @Nullable
 public static byte[] getBytesFromFile(@NotNull String filename) {
     try {
         return FileUtils.readFileToByteArray(new File(filename));
     } catch (Exception e) {
         return null;
     }
 }
Beispiel #12
0
 private void serveZip(SCSSProcessorBase processor, OutputStream out, String outputFilename)
     throws ZipException, IOException {
   File exported = processor.exportZip();
   response.setContentType("application/zip");
   response.setHeader(
       "Content-Disposition", String.format("attachment; filename=compiled-%s", outputFilename));
   out.write(FileUtils.readFileToByteArray(exported));
 }
Beispiel #13
0
 private byte[] getHash(String algorithm) {
   try {
     MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
     messageDigest.update(FileUtils.readFileToByteArray(this));
     return messageDigest.digest();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Beispiel #14
0
  @Test
  public void testBunzip2() throws IOException, ArchiveException {
    final File inputFile = new File(inputUrl.getPath(), "pol.txt.bz2");
    final File outputFile = File.createTempFile("output", "txt");

    new Tar().bunzip2(inputFile, outputFile);

    assertEquals("PlayOnLinux", new String(FileUtils.readFileToByteArray(outputFile)));
  }
 public PacketCacheFile(String plugin, File file) {
   this.plugin = plugin;
   try {
     this.fileData = FileUtils.readFileToByteArray(file);
   } catch (IOException e) {
     e.printStackTrace();
   }
   this.fileName = FileUtil.getFileName(file.getPath());
 }
 // 添加一个导出用户信息excel表格的方法
 public String exportUserRole() throws Exception {
   String fileName = "考勤系统用户报表";
   query = p("queryName");
   queryMap.put("roleId", p("roleType"));
   ListData<User> listData = userService.getListData(query, queryMap, 0, 0);
   File file = excelHelperService.exportUserRoleExcel(fileName, listData.getList());
   byte[] bytes = FileUtils.readFileToByteArray(file);
   return renderFile(bytes, fileName + ".xls");
 }
 public static void logImage(String command, File image, boolean success) {
   byte[] bytes = new byte[0];
   try {
     bytes = new Base64().encode(FileUtils.readFileToByteArray(image));
   } catch (IOException e) {
     log("logImage", e.getMessage(), false);
   }
   logImage(command, new String(bytes, StandardCharsets.UTF_8), success);
 }
Beispiel #18
0
 // 文件的下载
 @RequestMapping("download")
 public ResponseEntity<byte[]> download() throws IOException {
   File file = new File("d:/PLSQLDeveloper.zip");
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   headers.setContentDispositionFormData("attachment", "dict.txt");
   headers.setContentLength(file.length());
   return new ResponseEntity<byte[]>(
       FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
 }
Beispiel #19
0
 protected String checkStringBlob(String filename, boolean usefilename, String targetExt)
     throws Exception {
   File file = FileUtils.getResourceFileFromContext(filename);
   byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file);
   Blob blob = Blobs.createBlob(bytes);
   if (usefilename) {
     blob.setFilename(filename);
   }
   return check(blob, targetExt);
 }
Beispiel #20
0
 public void makePath(String path, File file, boolean failOnExists, boolean retryOnConnLoss)
     throws IOException, KeeperException, InterruptedException {
   makePath(
       path,
       FileUtils.readFileToByteArray(file),
       CreateMode.PERSISTENT,
       null,
       failOnExists,
       retryOnConnLoss);
 }
 private ByteArrayInputStream readFileToMemory(File f) {
   try {
     return new ByteArrayInputStream(FileUtils.readFileToByteArray(f));
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   return null;
 }
Beispiel #22
0
  @Test
  public void testUncompress_withSymbolicLinks() throws IOException, ArchiveException {
    final File inputFile = new File(inputUrl.getPath(), "tarLink.tar.gz");
    final File temporaryDirectory = Files.createTempDir();

    temporaryDirectory.deleteOnExit();

    final List<File> extractedFiles = new Extractor().uncompress(inputFile, temporaryDirectory);

    final File file1 = new File(temporaryDirectory, "file1.txt");
    final File file2 = new File(temporaryDirectory, "file1_link.txt");

    assertTrue(file1.exists());
    assertTrue(file2.exists());

    assertEquals("file1content", new String(FileUtils.readFileToByteArray(file1)));
    assertEquals("file1content", new String(FileUtils.readFileToByteArray(file2)));

    assertTrue(java.nio.file.Files.isSymbolicLink(Paths.get(file2.getPath())));
  }
Beispiel #23
0
  public static X509Certificate loadCertificate(String certFileName) throws Exception {
    File fl = new File(certBasePath + certFileName);

    InputStream str = new ByteArrayInputStream(FileUtils.readFileToByteArray(fl));

    X509Certificate retVal =
        (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(str);

    str.close();

    return retVal;
  }
 static {
   try {
     TMP_DIR.mkdirs();
     TMP_DIR.deleteOnExit();
     LARGE_IMAGE_FILE = new File(TestUtils.class.getClassLoader().getResource("300k.png").toURI());
     LARGE_IMAGE_BYTES = FileUtils.readFileToByteArray(LARGE_IMAGE_FILE);
     SIMPLE_TEXT_FILE =
         new File(TestUtils.class.getClassLoader().getResource("SimpleTextFile.txt").toURI());
     SIMPLE_TEXT_FILE_STRING = FileUtils.readFileToString(SIMPLE_TEXT_FILE, UTF_8);
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
Beispiel #25
0
 /**
  * Create an asset from a file.
  *
  * @param file File to use for asset
  * @return Asset associated with the file
  * @throws IOException
  */
 public static Asset createAsset(URL url) throws IOException {
   // Create a temporary file from the downloaded URL
   File newFile = File.createTempFile("remote", null, null);
   try {
     FileUtils.copyURLToFile(url, newFile);
     if (!newFile.exists() || newFile.length() < 20) return null;
     Asset temp =
         new Asset(FileUtil.getNameWithoutExtension(url), FileUtils.readFileToByteArray(newFile));
     return temp;
   } finally {
     newFile.delete();
   }
 }
 static {
   try {
     TMP_DIR.mkdirs();
     TMP_DIR.deleteOnExit();
     LARGE_IMAGE_FILE = resourceAsFile("300k.png");
     LARGE_IMAGE_BYTES = FileUtils.readFileToByteArray(LARGE_IMAGE_FILE);
     LARGE_IMAGE_PUBLISHER = createPublisher(LARGE_IMAGE_BYTES, /* chunkSize */ 1000);
     SIMPLE_TEXT_FILE = resourceAsFile("SimpleTextFile.txt");
     SIMPLE_TEXT_FILE_STRING = FileUtils.readFileToString(SIMPLE_TEXT_FILE, UTF_8);
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
  @Test
  public void buildRevisionFromMapValidMapWithAttachmentsDataExcluded() throws Exception {

    Assume.assumeFalse(
        "Not running test as 'buildRevisionFromMap' can't retrieve the "
            + "attachment with cookie authentication enabled",
        TestOptions.COOKIE_AUTH);

    // lets the get the attachment encoded

    File file = TestUtils.loadFixture("fixture/bonsai-boston.jpg");

    byte[] unencodedAttachment = FileUtils.readFileToByteArray(file);
    byte[] encodedAttachment = this.encodeAttachment(unencodedAttachment);

    // create a revision on a couchDB instance so we can test the download
    // of attachments
    Map<String, Object> remoteDoc = new HashMap<String, Object>();
    remoteDoc.put("_id", "someIdHere");
    Map<String, Map<String, Object>> remoteAttachments = new HashMap<String, Map<String, Object>>();
    Map<String, Object> remoteBonsai = createAttachmentMap(encodedAttachment, "image/jpeg", false);

    remoteAttachments.put("bonsai-boston.jpg", remoteBonsai);
    remoteDoc.put("_attachments", remoteAttachments);

    remoteDb.create(remoteDoc);

    // build up the test json map

    Map<String, Map<String, Object>> attachments = new HashMap<String, Map<String, Object>>();
    Map<String, Object> bonsai = createAttachmentMap(encodedAttachment, "image/jpeg", true);

    attachments.put("bonsai-boston.jpg", bonsai);
    documentRev.put("_attachments", attachments);

    URI uri = new URI(remoteDb.getCouchClient().getRootUri().toString() + "/" + "someIdHere");

    // create the document revision and test

    DocumentRevision revision = DocumentRevisionBuilder.buildRevisionFromMap(uri, documentRev);

    Assert.assertNotNull(revision);
    Assert.assertEquals(body, revision.getBody().asMap());
    Assert.assertEquals(revision.getId(), "someIdHere");
    Assert.assertEquals(revision.getRevision(), "3-750dac460a6cc41e6999f8943b8e603e");
    Assert.assertEquals(revision.getAttachments().size(), 1);
    InputStream attachmentInputStream =
        revision.getAttachments().get("bonsai-boston.jpg").getInputStream();
    InputStream expectedInputStream = new ByteArrayInputStream(unencodedAttachment);
    Assert.assertTrue(TestUtils.streamsEqual(expectedInputStream, attachmentInputStream));
  }
Beispiel #28
0
 @RequestMapping("/download")
 @ResponseBody
 public ResponseEntity<byte[]> ExportBindAccount(String path, HttpSession session)
     throws IOException {
   path = new String(path.getBytes("ISO8859-1"), "UTF-8");
   String filePath = session.getServletContext().getRealPath("/") + path;
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   String outputName = Utils.getFileName(path);
   headers.setContentDispositionFormData(
       "attachment", new String(outputName.getBytes("GB2312"), "ISO_8859_1"));
   return new ResponseEntity<byte[]>(
       FileUtils.readFileToByteArray(new File(filePath)), headers, HttpStatus.OK);
 }
Beispiel #29
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String fileName = "";

    try {
      fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");

      File file = new File(imageDirectory + fileName);
      if (!file.exists()) {
        file = new File(imageTempDirectory + fileName);
      }
      if (!file.exists()) {
        fileName = request.getParameter("fileName");

        // report file delivery validates the filename against the username
        // of the user in session for security purposes.
        ReportUser user = (ReportUser) request.getSession().getAttribute(ORStatics.REPORT_USER);
        if (user == null || fileName.indexOf(user.getName()) < 0) {
          String message = "Not Authorized...";
          response.getOutputStream().write(message.getBytes());

          return;
        }

        file = new File(reportGenerationDirectory + fileName);
      }

      String contentType = ORUtil.getContentType(fileName);

      response.setContentType(contentType);
      if (contentType != ReportEngineOutput.CONTENT_TYPE_HTML) {
        response.setHeader(
            "Content-disposition", "inline; filename=" + StringUtils.deleteWhitespace(fileName));
      }

      byte[] content = FileUtils.readFileToByteArray(file);

      response.setContentLength(content.length);

      ServletOutputStream ouputStream = response.getOutputStream();
      ouputStream.write(content, 0, content.length);
      ouputStream.flush();
      ouputStream.close();
    } catch (Exception e) {
      log.warn(e);

      String message = "Error Loading File...";
      response.getOutputStream().write(message.getBytes());
    }
  }
Beispiel #30
0
  private void testUncompress(String fileName) throws IOException, ArchiveException {
    final File inputFile = new File(inputUrl.getPath(), fileName);
    final File temporaryDirectory = Files.createTempDir();

    temporaryDirectory.deleteOnExit();

    final List<File> extractedFiles = new Extractor().uncompress(inputFile, temporaryDirectory);

    assertTrue(new File(temporaryDirectory, "directory1").isDirectory());
    final File file1 = new File(temporaryDirectory, "file1.txt");
    final File file2 = new File(temporaryDirectory, "file2.txt");
    final File file0 = new File(new File(temporaryDirectory, "directory1"), "file0.txt");

    assertTrue(file1.exists());
    assertTrue(file2.exists());
    assertTrue(file0.exists());

    assertEquals("file1content", new String(FileUtils.readFileToByteArray(file1)));
    assertEquals("file2content", new String(FileUtils.readFileToByteArray(file2)));
    assertEquals("file0content", new String(FileUtils.readFileToByteArray(file0)));

    assertEquals(5, extractedFiles.size());
  }