java.io.FileInputStream Java Examples

The following examples show how to use java.io.FileInputStream. 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: TestCollectorE2EGreenPath.java    From verigreen with Apache License 2.0 7 votes vote down vote up
/**
    * 
    * Change the job name in the config.properties file
    * */
   public void changeConfigFileJobName(String job) throws IOException
   {

   	InputStream input = new FileInputStream(_path);

       BufferedReader reader = new BufferedReader(new InputStreamReader(input));
       StringBuilder out = new StringBuilder();
       String line, row = null;
	while ((line = reader.readLine()) != null) {
		row = line.toString();
		if(line.toString().contains("jenkins.jobName")){
			row = "jenkins.jobName=" + job;
		}
		out.append(row + "\n");
       }
       reader.close();
      
       OutputStream output = new FileOutputStream(_path);

	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
	writer.write(out.toString());
   	writer.close();
}
 
Example #2
Source File: FileUtils.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static byte[] getFileDigest(FileInputStream fin) throws IOException {
  try {
    MessageDigest digest = MessageDigest.getInstance("SHA256");

    byte[] buffer = new byte[4096];
    int read = 0;

    while ((read = fin.read(buffer, 0, buffer.length)) != -1) {
      digest.update(buffer, 0, read);
    }

    return digest.digest();
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example #3
Source File: GetORBPropertiesFileAction.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void getPropertiesFromFile( Properties props, String fileName )
{
    try {
        File file = new File( fileName ) ;
        if (!file.exists())
            return ;

        FileInputStream in = new FileInputStream( file ) ;

        try {
            props.load( in ) ;
        } finally {
            in.close() ;
        }
    } catch (Exception exc) {
        if (debug)
            System.out.println( "ORB properties file " + fileName +
                " not found: " + exc) ;
    }
}
 
Example #4
Source File: ProtobufParser.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Compile the protobuf and generate descriptor file.
 *
 * @param protoPath      protobuf file path
 * @param descriptorPath descriptor file path
 * @return {@link DescriptorProtos.FileDescriptorSet} object
 */
private static DescriptorProtos.FileDescriptorProto generateRootFileDescriptor(String protoPath,
                                                                              String descriptorPath) {
    String command = new ProtocCommandBuilder
            (protoPath, resolveProtoFolderPath(protoPath), descriptorPath).build();
    generateDescriptor(command);
    File initialFile = new File(descriptorPath);
    try (InputStream targetStream = new FileInputStream(initialFile)) {
        ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
        //to register all custom extensions in order to parse properly
        ExtensionHolder.registerAllExtensions(extensionRegistry);
        DescriptorProtos.FileDescriptorSet set = DescriptorProtos.FileDescriptorSet.parseFrom(targetStream,
                extensionRegistry);
        logger.debug("Descriptor file is parsed successfully. file:" , descriptorPath);
        if (set.getFileList().size() > 0) {
            return set.getFile(0);
        }
    } catch (IOException e) {
        throw new CLIInternalException("Error reading generated descriptor file '" + descriptorPath + "'.", e);
    }
    return null;
}
 
Example #5
Source File: DemoMmcifToPdbConverter.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void convert(File inFile, File outFile) throws IOException {

	MMcifParser parser = new SimpleMMcifParser();

	SimpleMMcifConsumer consumer = new SimpleMMcifConsumer();
	parser.addMMcifConsumer(consumer);
	parser.parse(new BufferedReader(new InputStreamReader(new FileInputStream(inFile))));

	// now get the protein structure.
	Structure cifStructure = consumer.getStructure();

	// and write it out as PDB format
	PrintWriter pr = new PrintWriter(outFile);
	for (Chain c : cifStructure.getChains()) {
			// we can override the chain name, the mmCIF chain names might have more than 1 character
			c.setName(c.getName().substring(0, 1));
			pr.print(c.toPDB());
			pr.println("TER");
	}

		pr.close();


	}
 
Example #6
Source File: SawReader.java    From tablesaw with Apache License 2.0 6 votes vote down vote up
/** Reads the TextColumn data from the given file and stuffs it into a new TextColumn */
private static TextColumn readTextColumn(
    String fileName, TableMetadata tableMetadata, ColumnMetadata columnMetadata)
    throws IOException {

  TextColumn textColumn = TextColumn.create(columnMetadata.getName());
  try (FileInputStream fis = new FileInputStream(fileName);
      SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
      DataInputStream dis = new DataInputStream(sis)) {

    int j = 0;
    while (j < tableMetadata.getRowCount()) {
      textColumn.append(dis.readUTF());
      j++;
    }
  }
  return textColumn;
}
 
Example #7
Source File: ZipUtil.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 将压缩文件中的内容解压到指定目录中<br>
 * 如果<code>baseDir</code>的值为空,则将文件解压到相同的目录中,目录名称为"zipFile_files"
 * @param zipFile
 *            压缩文件路径
 * @param baseDir
 *            解压的目标路径,可以为null
 * @throws IOException
 */
public static String upZipFile(String zipFile, String baseDir) throws IOException {
	File f = new File(zipFile);
	if (baseDir == null) {
		baseDir = f.getPath() + "_files";
	}
	ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
	ZipEntry ze;
	byte[] buf = new byte[1024];
	while ((ze = zis.getNextEntry()) != null) {
		File outFile = getRealFileName(baseDir, ze.getName());
		FileOutputStream os = new FileOutputStream(outFile);
		int readLen = 0;
		while ((readLen = zis.read(buf, 0, 1024)) != -1) {
			os.write(buf, 0, readLen);
		}
		os.close();
	}
	zis.close();
	return baseDir;
}
 
Example #8
Source File: TestSlive.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataWriting() throws Exception {
  long byteAm = 100;
  File fn = getTestFile();
  DataWriter writer = new DataWriter(rnd);
  FileOutputStream fs = new FileOutputStream(fn);
  GenerateOutput ostat = writer.writeSegment(byteAm, fs);
  LOG.info(ostat);
  fs.close();
  assertTrue(ostat.getBytesWritten() == byteAm);
  DataVerifier vf = new DataVerifier();
  FileInputStream fin = new FileInputStream(fn);
  VerifyOutput vfout = vf.verifyFile(byteAm, new DataInputStream(fin));
  LOG.info(vfout);
  fin.close();
  assertEquals(vfout.getBytesRead(), byteAm);
  assertTrue(vfout.getChunksDifferent() == 0);
}
 
Example #9
Source File: SampleAxis2Server.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private File copyServiceToFileSystem(String resourceName, String fileName) throws IOException {
    File file = new File(System.getProperty("basedir") + File.separator + "target" + File.separator + fileName);
    if (file.exists()) {
        FileUtils.deleteQuietly(file);
    }

    FileUtils.touch(file);
    OutputStream os = FileUtils.openOutputStream(file);

    InputStream is = new FileInputStream(
            FrameworkPathUtil.getSystemResourceLocation() + File.separator + "artifacts" + File.separator + "AXIS2"
                    + File.separator + "config" + File.separator + resourceName);
    if (is != null) {
        byte[] data = new byte[1024];
        int len;
        while ((len = is.read(data)) != -1) {
            os.write(data, 0, len);
        }
        os.flush();
        os.close();
        is.close();
    }
    return file;
}
 
Example #10
Source File: CaptureOperationsServlet.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Loads the application properties and populates a java.util.Properties
 * instance.
 * 
 * @param servletConfig
 *            The ServletConfig used to locate the application property
 *            file.
 * @return The application properties.
 */
private Properties loadApplicationProperties(ServletConfig servletConfig) {
    // read application properties from servlet context
    ServletContext ctx = servletConfig.getServletContext();
    String path = ctx.getRealPath("/");
    String appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
    Properties properties = new Properties();
    try {
        InputStream is = new FileInputStream(path + appConfigFile);
        properties.load(is);
        is.close();
        LOG.info("Loaded application properties from " + path + appConfigFile);
    } catch (IOException e) {
        LOG.error("Unable to load application properties from " + path + appConfigFile, e);
    }
    return properties;
}
 
Example #11
Source File: DiskLruCache.java    From candybar with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an unbuffered input stream to read the last committed value,
 * or null if no value has been committed.
 */
public InputStream newInputStream(int index) throws IOException {
    synchronized (DiskLruCache.this) {
        if (entry.currentEditor != this) {
            throw new IllegalStateException();
        }
        if (!entry.readable) {
            return null;
        }
        try {
            return new FileInputStream(entry.getCleanFile(index));
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}
 
Example #12
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a file, find only the properties that are setable by AppletViewer.
 *
 * @param inFile A Properties file from which we select the properties of
 *             interest.
 * @return     A Properties object containing all of the AppletViewer
 *             user-specific properties.
 */
private Properties getAVProps(File inFile) {
    Properties avProps  = new Properties();

    // read the file
    Properties tmpProps = new Properties();
    try (FileInputStream in = new FileInputStream(inFile)) {
        tmpProps.load(new BufferedInputStream(in));
    } catch (IOException e) {
        System.err.println(lookup("main.err.prop.cantread", inFile.toString()));
    }

    // pick off the properties we care about
    for (int i = 0; i < avDefaultUserProps.length; i++) {
        String value = tmpProps.getProperty(avDefaultUserProps[i][0]);
        if (value != null) {
            // the property exists in the file, so replace the default
            avProps.setProperty(avDefaultUserProps[i][0], value);
        } else {
            // just use the default
            avProps.setProperty(avDefaultUserProps[i][0],
                                avDefaultUserProps[i][1]);
        }
    }
    return avProps;
}
 
Example #13
Source File: FileUtil.java    From game-server with MIT License 6 votes vote down vote up
public static String readTxtFile(String filePath) {
    try {
        String encoding = "UTF-8";
        File file = new File(filePath);
        if (file.isFile() && file.exists()) { //判断文件是否存在
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            StringBuffer sb = new StringBuffer();
            while ((lineTxt = bufferedReader.readLine()) != null) {
                sb.append(lineTxt).append("\n");
            }
            read.close();
            return sb.toString();
        } else {
            log.warn("文件{}配置有误,找不到指定的文件", file);
        }
    } catch (Exception e) {
        log.error("读取文件内容出错", e);
    }
    return null;
}
 
Example #14
Source File: YamlConfigLoader.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MxisdConfig loadFromFile(String path) throws IOException {
    File f = new File(path).getAbsoluteFile();
    log.info("Reading config from {}", f.toString());
    Representer rep = new Representer();
    rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
    rep.getPropertyUtils().setAllowReadOnlyProperties(true);
    rep.getPropertyUtils().setSkipMissingProperties(true);
    Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
    try (FileInputStream is = new FileInputStream(f)) {
        MxisdConfig raw = yaml.load(is);
        log.debug("Read config in memory from {}", path);

        // SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
        // This is problematic for default config values and objects, to avoid NPEs.
        // Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
        MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);

        log.info("Loaded config from {}", path);
        return cfg;
    } catch (ParserException t) {
        throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
    }
}
 
Example #15
Source File: FileController.java    From DAFramework with MIT License 5 votes vote down vote up
@RequestMapping(value = "/download/{id}")
	public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
        	if(id != 0){
        		EFile fileInfo = fileDao.fetch(id);
        		if(fileInfo!= null){
        			String path = fileInfo.getPath();
//        			String suffix = path.split("\\.")[1];
					File file = new File(rootPath+path);
//                    String filename = fileInfo.getName()+"."+suffix;
                    InputStream fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    response.reset();
                    response.addHeader("Content-Disposition","attachment;filename="
                            + new String(java.net.URLEncoder.encode(fileInfo.getName(), "UTF-8")));
                    response.addHeader("Content-Length","" + file.length());
                    response.setContentType("application/octet-stream");
                    OutputStream toClient = new BufferedOutputStream(
                            response.getOutputStream());
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
        		}
        	}
        }catch(Exception e){
			LOG.error("下载失败,原因:"+e.getMessage());
		}
	}
 
Example #16
Source File: CreateBundle.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Properties readProperties(Vector <? extends Property> antProperties) throws IOException {
    Properties props = new Properties();
    for(Property prop : antProperties) {
        if(prop.getName()!=null) {
            if(prop.getValue()!=null) {
                props.setProperty(prop.getName(), prop.getValue());
            } else if(prop.getLocation()!=null) {
                props.setProperty(prop.getName(),
                        new File(prop.getLocation().getFileName()).getAbsolutePath());
            }
        } else if(prop.getFile()!=null || prop.getUrl()!=null) {
            InputStream is = null;
            try {
                is = (prop.getFile()!=null) ?
                    new FileInputStream(prop.getFile()) :
                    prop.getUrl().openStream();
                
                Properties loadedProps = new Properties();
                loadedProps.load(is);
                is.close();
                if ( prop.getPrefix() != null ) {
                    for(Object p : loadedProps.keySet()) {
                        props.setProperty(prop.getPrefix() + p,
                                loadedProps.getProperty(p.toString()));
                    }
                } else {
                    props.putAll(loadedProps);
                }
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    }
    
    return props;
}
 
Example #17
Source File: FileBasedKeyResolver.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void readCertificate(String publicKeyPath) throws CertificateException, IOException {

        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        try (FileInputStream fileInputStream = new FileInputStream(publicKeyPath)) {
            certificate = (X509Certificate) fact.generateCertificate(fileInputStream);
            publicKey = certificate.getPublicKey();
        }
    }
 
Example #18
Source File: TfLiteCommander.java    From next18-ai-in-motion with Apache License 2.0 5 votes vote down vote up
/** Memory-map the model file in Assets. */
public MappedByteBuffer loadModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = ASSET_MANAGER.openFd(MODEL_PATH);
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
 
Example #19
Source File: SslContextFactory.java    From debezium-incubator with Apache License 2.0 5 votes vote down vote up
/**
 * Return an {@link SslContext} containing all SSL configurations parsed
 * from the Properties file path
 * <p>
 * See {@link SslConfig} class for a list of valid config names
 *
 * @param sslConfigPath the SSL config file path required for the storage node
 * @return SslContext
 */
public static SslContext createSslContext(String sslConfigPath) throws GeneralSecurityException, IOException {
    if (sslConfigPath == null) {
        throw new CassandraConnectorConfigException("Please specify SSL config path in cdc.yml");
    }
    Properties props = new Properties();
    try (FileInputStream fis = new FileInputStream(sslConfigPath)) {
        props.load(fis);
        fis.close();
        SslConfig sslConfig = new SslConfig(props);
        return createSslContext(sslConfig);
    }
}
 
Example #20
Source File: BackupJob.java    From secrecy with Apache License 2.0 5 votes vote down vote up
@Override
public void onRun() throws Throwable {
    FileOutputStream fos = new FileOutputStream(backupFile);
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos, Config.BLOCK_SIZE));
    byte[] buffer = new byte[Config.BUFFER_SIZE];

    Iterator it = FileUtils.iterateFiles(backupPath, null, true);
    while (it.hasNext()) {
        File fileToBackup = ((File) it.next());
        EventBus.getDefault().post(new BackingUpFileEvent(backupPath.getAbsolutePath(), fileToBackup.getName()));
        ZipEntry newEntry = new ZipEntry(fileToBackup.getAbsolutePath());
        zos.putNextEntry(newEntry);

        BufferedInputStream in =
                new BufferedInputStream(new FileInputStream(fileToBackup), Config.BLOCK_SIZE);

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();

    }
    zos.closeEntry();
    zos.close();

    EventBus.getDefault().post(new BackUpDoneEvent(backupPath, backupFile));

}
 
Example #21
Source File: ZipUtil.java    From sc-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a directory to the current zip output stream
 * @param folder the directory to be  added
 * @param parentFolder the path of parent directory
 * @param zos the current zip output stream
 * @throws FileNotFoundException
 * @throws IOException
 */
private void addFolderToZip(File folder, String parentFolder,
                            ZipOutputStream zos) throws FileNotFoundException, IOException {
    for (File file : folder.listFiles()) {
        if (file.isDirectory()) {
            addFolderToZip(file, parentFolder + "/" + file.getName(), zos);
            continue;
        }

        zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));

        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(file));

        long bytesRead = 0;
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;

        while ((read = bis.read(bytesIn)) != -1) {
            zos.write(bytesIn, 0, read);
            bytesRead += read;
        }

        zos.closeEntry();

    }
}
 
Example #22
Source File: UserAvatarAction.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String returnAvatarStream() {
	AvatarConfig config = this.getAvatarManager().getConfig();
	String stype = config.getStyle();
	if (null == stype || AvatarConfig.STYLE_DEFAULT.equals(stype)) {
		return super.returnAvatarStream();
	} else if (AvatarConfig.STYLE_GRAVATAR.equals(stype)) {
		return super.extractGravatar();
	}
	try {
		String url = this.getAvatarManager().getAvatarUrl(this.getUsername());
		if (null == url) {
			return this.extractDefaultAvatarStream();
		}
		MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
		this.setMimeType(mimeTypesMap.getContentType(url));
		File avatar = this.getAvatarManager().getAvatarResource(this.getUsername());
		if (null == avatar) {
			return this.extractDefaultAvatarStream();
		}
		this.setInputStream(new FileInputStream(avatar));
	} catch (Throwable t) {
		_logger.info("local avatar not available", t);
		return this.extractDefaultAvatarStream();
       }
	return SUCCESS;
}
 
Example #23
Source File: AnnoLabelledArrayCellsTest.java    From xlsmapper with Apache License 2.0 5 votes vote down vote up
/**
 * 書き込みテスト - 結合の考慮
 */
@Test
public void test_save_labelled_array_cell_merged() throws Exception {

    // テストデータの作成
    final MergedSheet outSheet = new MergedSheet();

    outSheet.labelMerged = Arrays.asList("あ", "い", "う");
    outSheet.valueMerged = Arrays.asList("今日は良い天気", "ですね。", "明日も晴れると良いですね。");
    outSheet.labelAndValueMerged = Arrays.asList("ABCD", "EFG", "HIJ");

    // ファイルへの書き込み
    XlsMapper mapper = new XlsMapper();
    mapper.getConfiguration().setContinueTypeBindFailure(true);

    File outFile = new File(OUT_DIR, outFilename);
    try(InputStream template = new FileInputStream(templateFile);
            OutputStream out = new FileOutputStream(outFile)) {

        mapper.save(template, out, outSheet);
    }

    // 書き込んだファイルを読み込み値の検証を行う。
    try(InputStream in = new FileInputStream(outFile)) {
        SheetBindingErrors<MergedSheet> errors = mapper.loadDetail(in, MergedSheet.class);

        MergedSheet sheet = errors.getTarget();

        assertThat(sheet.positions).containsAllEntriesOf(outSheet.positions);
        assertThat(sheet.labels).containsAllEntriesOf(outSheet.labels);

        assertThat(sheet.labelMerged).containsExactlyElementsOf(outSheet.labelMerged);
        assertThat(sheet.valueMerged).containsExactlyElementsOf(outSheet.valueMerged);
        assertThat(sheet.labelAndValueMerged).containsExactlyElementsOf(outSheet.labelAndValueMerged);

    }
}
 
Example #24
Source File: BigButtonResource.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@GET
@Path("report")
@Produces(MediaType.APPLICATION_XML)
public Response downloadReport() {

       ProgressView progressView = SFLocalContext.getDefault().getRegressionRunner().getProgressView(0, 0);
	
	if(progressView.getReportFile() == null) {
		
		return Response.
                   status(Status.NOT_FOUND).
                entity(new XmlResponse("Report file not found or not ready")).
                build();
		
	}

       StreamingOutput stream = new StreamingOutput() {
           @Override
           public void write(OutputStream out) throws IOException, WebApplicationException {
               try(InputStream in = new FileInputStream(progressView.getReportFile())) {
                   int read;
                   byte[] bytes = new byte[1024];

                   while((read = in.read(bytes)) != -1) {
                       out.write(bytes, 0, read);
                   }
               } catch(Exception e) {
                   logger.error(e.getMessage(), e);
                   throw new WebApplicationException(e);
               }
           }
       };

	return Response
			.ok(stream)
			.header("content-disposition",
					"attachment; filename = "
							+ "bb_report.csv").build();
	
}
 
Example #25
Source File: CAdESSignerTest.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
private byte[] readContent(String parmFile) {
	byte[] result = null;
	try {
		File file = new File(parmFile);
		FileInputStream is = new FileInputStream(parmFile);
		result = new byte[(int) file.length()];
		is.read(result);
		is.close();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
	return result;
}
 
Example #26
Source File: KualiBatchFileAdminAction.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    KualiBatchFileAdminForm fileAdminForm = (KualiBatchFileAdminForm) form;
    String filePath = BatchFileUtils.resolvePathToAbsolutePath(fileAdminForm.getFilePath());
    File file = new File(filePath).getAbsoluteFile();
    
    if (!file.exists() || !file.isFile()) {
        throw new RuntimeException("Error: non-existent file or directory provided");
    }
    File containingDirectory = file.getParentFile();
    if (!BatchFileUtils.isDirectoryAccessible(containingDirectory.getAbsolutePath())) {
        throw new RuntimeException("Error: inaccessible directory provided");
    }
    
    BatchFile batchFile = new BatchFile();
    batchFile.setFile(file);
    if (!SpringContext.getBean(BatchFileAdminAuthorizationService.class).canDownload(batchFile, GlobalVariables.getUserSession().getPerson())) {
        throw new RuntimeException("Error: not authorized to download file");
    }
    
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength((int) file.length());

    InputStream fis = new FileInputStream(file);
    IOUtils.copy(fis, response.getOutputStream());
    response.getOutputStream().flush();
    return null;
}
 
Example #27
Source File: Uploader.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a upload file section to the request
 *
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
            + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
            + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}
 
Example #28
Source File: SocketUtils.java    From JavaLinuxNet with Apache License 2.0 5 votes vote down vote up
public static int getFd(final FileInputStream stream )  {
    try {
        final FileDescriptor fd = getFileDescriptor(stream);
        return getFileHandle(fd);
    } catch (final Exception shoutNotHappen) {
        throw new JVMException(shoutNotHappen);
    }
}
 
Example #29
Source File: DocumentHelper.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public static boolean writeFromFile(File fromFile, DocumentFile file) {
    if (file == null)
        return false;
    try {
        return DocumentUtil.writeFromInputStream(ContextHolder.getContext(), new FileInputStream(fromFile), file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #30
Source File: DataOutputTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void testSequentialWriter() throws IOException
{
    File file = FileUtils.createTempFile("dataoutput", "test");
    final SequentialWriter writer = new SequentialWriter(file, 32);
    DataOutputStreamAndChannel write = new DataOutputStreamAndChannel(writer, writer);
    DataInput canon = testWrite(write);
    write.flush();
    write.close();
    DataInputStream test = new DataInputStream(new FileInputStream(file));
    testRead(test, canon);
    test.close();
    Assert.assertTrue(file.delete());
}