Java Code Examples for org.apache.commons.io.FileUtils#copyInputStreamToFile()

The following examples show how to use org.apache.commons.io.FileUtils#copyInputStreamToFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileService.java    From yfs with Apache License 2.0 6 votes vote down vote up
/**
 * 存储文件的底层方法
 *
 * @param clusterProperties
 * @param relativePath
 * @param inputStream
 * @throws Exception
 */
public static void store(ClusterProperties clusterProperties, String relativePath, InputStream inputStream, Map<String, String> systemMetas, Map<String, String> userMetas) throws IOException {
    String fullPath = getFullPath(clusterProperties, relativePath);
    File file = new File(fullPath);
    if (file.exists()) {
        file.delete();
        //赋予新的iNode
        file = new File(fullPath);
    }
    FileUtils.copyInputStreamToFile(inputStream, file);
    String crc32 = String.valueOf(FileUtils.checksumCRC32(file));
    if (systemMetas.containsKey(CommonConstant.CRC32)) {
        if (!systemMetas.get(CommonConstant.CRC32).equals(crc32)) {
            throw new RuntimeException("File[" + relativePath + "]'s crc32 doesn't match");
        }
    } else {
        systemMetas.put(CommonConstant.CRC32, crc32);
    }
    FileAttributes.setXattr(systemMetas, fullPath);
    FileAttributes.setXattr(userMetas, fullPath);
}
 
Example 2
Source File: CreateMojo.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private void copyDefaultErrorTemplates() throws IOException {
    File templateDirectory = new File(root, Constants.TEMPLATES_SRC_DIR);
    File error = new File(templateDirectory, "error");
    if (error.mkdirs()) {
        getLog().debug(error.getAbsolutePath() + " directory created");
    }

    // Copy 404
    InputStream is = CreateMojo.class.getClassLoader().getResourceAsStream("templates/error/404.thl.html");
    FileUtils.copyInputStreamToFile(is, new File(error, "404.thl.html"));
    IOUtils.closeQuietly(is);

    // Copy 500
    is = CreateMojo.class.getClassLoader().getResourceAsStream("templates/error/500.thl.html");
    FileUtils.copyInputStreamToFile(is, new File(error, "500.thl.html"));
    IOUtils.closeQuietly(is);

    // Copy pipeline
    is = CreateMojo.class.getClassLoader().getResourceAsStream("templates/error/pipeline.thl.html");
    FileUtils.copyInputStreamToFile(is, new File(error, "pipeline.thl.html"));
    IOUtils.closeQuietly(is);
}
 
Example 3
Source File: AvroToRestJsonEntryConverterTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private void testConversion(RestEntry<JsonObject> expected, WorkUnitState actualWorkUnitState) throws DataConversionException, IOException, JSONException {
  Schema schema = new Schema.Parser().parse(getClass().getResourceAsStream("/converter/nested.avsc"));
  GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);

  File tmp = File.createTempFile(this.getClass().getSimpleName(), null);
  tmp.deleteOnExit();
  try {
    FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("/converter/nested.avro"), tmp);
    DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(tmp, datumReader);
    GenericRecord avroRecord = dataFileReader.next();

    AvroToRestJsonEntryConverter converter = new AvroToRestJsonEntryConverter();
    RestEntry<JsonObject> actual = converter.convertRecord(null, avroRecord, actualWorkUnitState).iterator().next();

    Assert.assertEquals(actual.getResourcePath(), expected.getResourcePath());
    JSONAssert.assertEquals(expected.getRestEntryVal().toString(), actual.getRestEntryVal().toString(), false);

    converter.close();
    dataFileReader.close();
  } finally {
    if (tmp != null) {
      tmp.delete();
    }
  }
}
 
Example 4
Source File: UploadApi.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 上传资源文件到服务器磁盘
 *
 * @param file   待上传的资源文件
 * @param type   文件类型: 1.视频 2.PPT 3.PDF 4.动画 5.WORD 6.音频 7.录屏 10.EXCEL 11.MP4+PPT关联 12.图片 13.压缩文件 14.文档
 * @param source 文件平台来源:1.项目培训 2.视频课 3.直播课 4.试题库 5.圈子 6.工作坊 7.备课 8.账户
 * @param desc   文件描述
 * @param own    是否私有化:公开(false)或私有(true)
 * @return JsonResult封装的对象
 */
@PostMapping("disk-upload")
public JsonResult upload(@RequestParam("file") MultipartFile file, byte type, byte source, String desc, boolean own) {
    String url = null;
    printUpload(file, type, source, desc, own);
    try {
        if (file != null && file.getSize() > 0) {
            String fileName = file.getOriginalFilename();
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(ROOT_DISK_NAME, fileName));
            url = ROOT_DISK_NAME + fileName;
        }
    } catch (Exception e) {
        log.error("资源分类上传到服务器本地磁盘异常" + e.getMessage(), e);
        return JsonResultMethod.code_500();
    }
    log.info("文件记录成功,上传成功");
    return new JsonResult(JsonResultEnum.SUCCESS.getCode(), "资源上传成功", url);  //url需要nginx做资源代理
}
 
Example 5
Source File: ProcessingManagerTest.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
void init() throws IOException
{
   InputStream is=ProcessingManager.class.getResourceAsStream("size-test.zip");
   
   File tmp_folder = Files.createTempDir();
   File output = new File (tmp_folder, "size-test.zip");
   FileUtils.copyInputStreamToFile(is, output);
   is.close();
   
   sample = output;
}
 
Example 6
Source File: FileUtil.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public File getFileFromRawResource(int resourceId, String filename) throws IOException {
  File file = new File(context.getFilesDir() + "/" + filename);

  if (!file.exists()) {
    FileUtils.copyInputStreamToFile(context.getResources().openRawResource(resourceId), file);
  }

  return file;
}
 
Example 7
Source File: FileUploadDownloadHelper.java    From inception with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the input stream to a temporary file. The file is deleted if the object behind marker
 * is garbage collected. The temporary file will keep its extension based on the specified file
 * name.
 *
 * @param fileUpload The file upload handle to write to the temporary file
 * @param marker The object to whose lifetime the temporary file is bound
 * @return A handle to the created temporary file
 */
public File writeFileUploadToTemporaryFile(FileUpload fileUpload, Object marker)
    throws IOException
{
    String fileName = fileUpload.getClientFileName();
    File tmpFile = File.createTempFile(INCEPTION_TMP_FILE_PREFIX, fileName);
    log.debug("Creating temporary file for [{}] in [{}]", fileName, tmpFile.getAbsolutePath());
    fileTracker.track(tmpFile, marker);
    try (InputStream is = fileUpload.getInputStream()) {
        FileUtils.copyInputStreamToFile(is, tmpFile);
    }
    return tmpFile;
}
 
Example 8
Source File: ElasticDownloader.java    From ES-Fastloader with Apache License 2.0 5 votes vote down vote up
private void copyURLToFile(URL source,
                           File destination,
                           int connectionTimeout,
                           int readTimeout,
                           Proxy proxy) throws IOException {
    final URLConnection connection = proxy != null ? source.openConnection(proxy) : source.openConnection();
    connection.setConnectTimeout(connectionTimeout);
    connection.setReadTimeout(readTimeout);
    FileUtils.copyInputStreamToFile(connection.getInputStream(), destination);
}
 
Example 9
Source File: IPTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
public IPTools() {
	try {
		File dbFile = new File(UKDataContext.getContext().getEnvironment().getProperty("web.upload-path"), "ipdata/ipdata.db") ;
		if(!dbFile.exists()){
			FileUtils.copyInputStreamToFile(IPTools.class.getClassLoader().getResourceAsStream(IP_DATA_PATH),dbFile);
		}
		_searcher = new DbSearcher(new DbConfig(),dbFile.getAbsolutePath());
	} catch (DbMakerConfigException | IOException e) {
		e.printStackTrace();
	} 
}
 
Example 10
Source File: SAMBoxPdfLoadServiceTest.java    From pdfsam with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void encWithPwd() throws IOException, InterruptedException, TimeoutException {
    File testFile = folder.newFile("PDFsamTest.pdf");
    FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("/enc_test_pdfsam.pdf"), testFile);
    PdfDocumentDescriptor descriptor = PdfDocumentDescriptor.newDescriptor(testFile, "test");
    List<PdfDocumentDescriptor> toLoad = Arrays.asList(new PdfDocumentDescriptor[] { descriptor });
    assertEquals(PdfDescriptorLoadingStatus.INITIAL, descriptor.loadingStatus().getValue());
    descriptor.moveStatusTo(PdfDescriptorLoadingStatus.REQUESTED);
    victim.load(toLoad, RequiredPdfData.DEFAULT);
    assertEquals(1, toLoad.size());
    PdfDocumentDescriptor item = toLoad.get(0);
    assertNotNull(item);
    waitOrTimeout(() -> PdfDescriptorLoadingStatus.LOADED_WITH_USER_PWD_DECRYPTION == descriptor.loadingStatus()
            .getValue(), timeout(seconds(2)));
}
 
Example 11
Source File: JarTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void unjar(File source, String sub, File dist, boolean force) {
	try (JarFile jarFile = new JarFile(source)) {
		FileUtils.forceMkdir(dist);
		Enumeration<? extends JarEntry> entrys = jarFile.entries();
		while (entrys.hasMoreElements()) {
			JarEntry entry = entrys.nextElement();
			String name = entry.getName();
			if (!StringUtils.startsWith(name, sub)) {
				continue;
			}
			name = name.replace(sub, "").trim();
			if (name.length() < 2) {
				continue;
			}
			if (entry.isDirectory()) {
				File dir = new File(dist, name);
				FileUtils.forceMkdir(dir);
			} else {
				File file = new File(dist, name);
				if (file.exists() && force) {
					file.delete();
				}
				if (!file.exists()) {
					try (InputStream in = jarFile.getInputStream(entry)) {
						FileUtils.copyInputStreamToFile(in, file);
					}
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 12
Source File: DocumentStore.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Saves the content to a file and returns the aboslute path of the file.
 * 
 * @param document
 * @param filePath
 * @return
 * @throws ElexisException
 */
public String saveContentToFile(IDocument document, String filePath) throws ElexisException{
	Optional<InputStream> in = getService(document.getStoreId()).loadContent(document);
	if (in.isPresent()) {
		try {
			File file = new File(filePath);
			FileUtils.copyInputStreamToFile(in.get(), file);
			return file.getAbsolutePath();
		} catch (IOException e) {
			throw new ElexisException("cannot save content", e);
		}
	}
	return null;
}
 
Example 13
Source File: HomePageUI.java    From dubbo-switch with Apache License 2.0 5 votes vote down vote up
private FileResource getFileResource(String path,String type){
    InputStream inputStream = null;
    try {
        ClassPathResource resource = new ClassPathResource(path);
        inputStream = resource.getInputStream();
        File tempFile = File.createTempFile("ds_" + System.currentTimeMillis(), type);
        FileUtils.copyInputStreamToFile(inputStream, tempFile);
        return new FileResource(tempFile);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 14
Source File: QrcodeUtilsTest.java    From qrcode-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQrcodeWithLogo() throws Exception {
    try (InputStream inputStream = ClassLoader.getSystemResourceAsStream("logo.png")) {
        File logoFile = Files.createTempFile("logo_", ".jpg").toFile();
        FileUtils.copyInputStreamToFile(inputStream, logoFile);
        logger.info("{}",logoFile);
        byte[] bytes = QrcodeUtils.createQrcode(content, 800, logoFile);
        Path path = Files.createTempFile("qrcode_with_logo_", ".jpg");
        generatedQrcodePaths.add(path);
        logger.info("{}",path.toAbsolutePath());
        Files.write(path, bytes);
    }
}
 
Example 15
Source File: SnowflakeFileTransferAgent.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
static private boolean pushFileToLocal(String stageLocation,
                                       String filePath,
                                       String destFileName,
                                       InputStream inputStream,
                                       FileBackedOutputStream fileBackedOutStr)
throws SQLException
{


  // replace ~ with user home
  stageLocation = stageLocation.replace("~",
                                        systemGetProperty("user.home"));
  try
  {
    logger.debug("Copy file. srcFile={}, destination={}, destFileName={}",
                 filePath, stageLocation, destFileName);

    File destFile = new File(
        SnowflakeUtil.concatFilePathNames(
            stageLocation,
            destFileName,
            localFSFileSep));

    if (fileBackedOutStr != null)
    {
      inputStream = fileBackedOutStr.asByteSource().openStream();
    }
    FileUtils.copyInputStreamToFile(inputStream, destFile);
  }
  catch (Exception ex)
  {
    throw new SnowflakeSQLException(ex, SqlState.INTERNAL_ERROR,
                                    ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                    ex.getMessage());
  }

  return true;
}
 
Example 16
Source File: WebpackAssetsServiceTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetCSSAssetPathsFromManifestJson() throws IOException {
    try (InputStream is = getClass().getResourceAsStream("/com/thoughtworks/go/server/service/webpackassetstest/good-manifest.json")) {
        FileUtils.copyInputStreamToFile(is, manifestFile);
    }

    Set<String> assetPaths = webpackAssetsService.getCSSAssetPathsFor("single_page_apps/agents", "single_page_apps/new_dashboard");
    assertThat(assetPaths.size(), is(2));
    assertThat(assetPaths, hasItems("/go/assets/webpack/single_page_apps/agents.css",
            "/go/assets/webpack/single_page_apps/new_dashboard.css"));
}
 
Example 17
Source File: WorkflowBuilderTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Test
public void testBuildDefaultWF() throws IOException {
    BpmnModel model = workflowBldr.defaultDocumentApprove();

    InputStream in = ProcessDiagramGenerator.generatePngDiagram(model);
    FileUtils.copyInputStreamToFile(in, new File("target/default_diagram.png"));
    IOUtils.closeQuietly(in);
}
 
Example 18
Source File: URLTools.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
public static void download(String url,File to) throws IOException
{
	HttpURLConnection con = openConnection(url);
	FileUtils.copyInputStreamToFile(con.getInputStream(),to);
	close(con);
}
 
Example 19
Source File: JsonWorkspaceServiceTest.java    From pdfsam with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test(expected = RuntimeException.class)
public void loadBrokenWorkspace() throws IOException {
    File file = folder.newFile();
    FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("/broken_workspace.json"), file);
    victim.loadWorkspace(file);
}
 
Example 20
Source File: DocApproveTest.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Test
    public void testDynamicDeploy() throws Exception {
        String fakeGroup = "fakeGroup";
        String procId = Workflow.PROCESS_ID_DOC_APPROVAL + "-" + fakeGroup;
        // 1. Build up the model from scratch
        BpmnModel model = new BpmnModel();
        Process process = new Process();
        model.addProcess(process);
        process.setId(procId);

        process.addFlowElement(createStartEvent());

        //pub.addAttribute(createExpression("documentWorkflow.publish(execution)"));
        //pub.setImplementation("${documentWorkflow.publish(execution)}");
//        pub.setExtensionId(BpmnXMLConstants.ACTIVITI_EXTENSIONS_NAMESPACE,
//                BpmnXMLConstants.ATTRIBUTE_TASK_SERVICE_EXTENSIONID);


        UserTask submitTask = new UserTask();
        submitTask.setId("submitDocUserTask");
        submitTask.setName("Submit Document for Approval");
        process.addFlowElement(submitTask);
        process.addFlowElement(createSequenceFlow("start", submitTask.getId()));
        SubProcess sub = createSubProcess();
        process.addFlowElement(sub);

        process.addFlowElement(createSequenceFlow(submitTask.getId(), sub.getId()));

        BoundaryEvent boundaryEvent = new BoundaryEvent();
        boundaryEvent.setId("rejectedErrorBoundaryEvent");
        boundaryEvent.setName("Rejected Error Event");
        boundaryEvent.setAttachedToRef(sub);
        ErrorEventDefinition errorDef = new ErrorEventDefinition();
        errorDef.setErrorCode("errorDocRejected");
        boundaryEvent.addEventDefinition(errorDef);
        process.addFlowElement(boundaryEvent);

        process.addFlowElement(createSequenceFlow(boundaryEvent.getId(), submitTask.getId(), "Rejected"));
        ServiceTask pub = new ServiceTask();
        pub.setId("publishDocServiceTask");
        pub.setName("Publish Approved Document");
        pub.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION);
        pub.setImplementation("${documentWorkflow.publish(execution)}");

        process.addFlowElement(pub);
        process.addFlowElement(createSequenceFlow(sub.getId(), pub.getId()));

        process.addFlowElement(createEndEvent());
        process.addFlowElement(createSequenceFlow(pub.getId(), "end"));

        // 2. Generate graphical information
        new BpmnAutoLayout(model).execute();

        // 3. Deploy the process to the engine
        Deployment deployment = this.repositoryService.createDeployment()
                .addBpmnModel("dynamic-model.bpmn", model).name("Dynamic process deployment")
                .deploy();

        // 4. Start a process instance
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(procId);

        // 6. Save process diagram to a file
        InputStream processDiagram = repositoryService.getProcessDiagram(processInstance.getProcessDefinitionId());
        FileUtils.copyInputStreamToFile(processDiagram, new File("target/diagram.png"));

        // 7. Save resulting BPMN xml to a file
        InputStream processBpmn = repositoryService.getResourceAsStream(deployment.getId(), "dynamic-model.bpmn");
        FileUtils.copyInputStreamToFile(processBpmn, new File("target/process.bpmn20.xml"));
    }