java.io.File Java Examples

The following examples show how to use java.io.File. 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: AuthTicketsHelper.java    From p4ic4idea with Apache License 2.0 8 votes vote down vote up
/**
 * Get all the tickets found in the specified file.
 * 
 * @param ticketsFile
 * @return - array of tickets found in the specified tickets file
 * @throws IOException
 *             - io exception from reading tickets file
 */
public static synchronized AuthTicket[] getTickets(File ticketsFile)
		throws IOException {
	AuthTicket[] tickets = EMPTY;
	List<Map<String, String>> authList = ticketsFile != null ? 
			getFileEntries(ticketsFile) : getMemoryEntries(ticketsMap);
	if (authList != null) {
		List<AuthTicket> ticketList = new ArrayList<AuthTicket>();
		for (Map<String, String> map : authList) {
			if (map != null) {
				String serverAddress = map.get(SERVER_ADDRESS_MAP_KEY);
				String userName = map.get(USER_NAME_MAP_KEY);
				String ticketValue = map.get(AUTH_VALUE_MAP_KEY);
				AuthTicket ticket = new AuthTicket(serverAddress,
						userName, ticketValue);
				ticketList.add(ticket);
			}
		}
		tickets = ticketList.toArray(new AuthTicket[0]);
	}
	return tickets;
}
 
Example #2
Source File: RunTest.java    From gemfirexd-oss with Apache License 2.0 7 votes vote down vote up
private static void generateUTF8OutFile(File FinalOutFile) throws IOException
{
    if (generateUTF8Out) 
    {
        keepfiles=true;
    	File UTF8OutFile = new File(UTF8OutName);
    	
    	// start reading the .out file back in, using default encoding
    	BufferedReader inFile = new BufferedReader(new FileReader(FinalOutFile));
    	FileOutputStream fos = new FileOutputStream(UTF8OutFile);
    	BufferedWriter bw = new BufferedWriter (new OutputStreamWriter(fos, "UTF-8"));  
    	int c;
    	while ((c = inFile.read()) != -1)
    		bw.write(c);
    	bw.flush();
    	bw.close();
    	fos.close();     
    }
}
 
Example #3
Source File: SQLiteUtils.java    From chuck with Apache License 2.0 6 votes vote down vote up
private static String extractDatabase(Context context) {
    try {
        File external = context.getExternalFilesDir(null);
        File data = Environment.getDataDirectory();
        if (external != null && external.canWrite()) {
            String dataDBPath = "data/" + context.getPackageName() + "/databases/chuck.db";
            String extractDBPath = "chuckdb.temp";
            File dataDB = new File(data, dataDBPath);
            File extractDB = new File(external, extractDBPath);
            if (dataDB.exists()) {
                FileChannel in = new FileInputStream(dataDB).getChannel();
                FileChannel out = new FileOutputStream(extractDB).getChannel();
                out.transferFrom(in, 0, in.size());
                in.close();
                out.close();
                return extractDB.getAbsolutePath();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #4
Source File: v340Updater.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public void executeUpgrade(AlpineQueryManager qm, Connection connection) throws SQLException {
    LOGGER.info("Recreating table PROJECT_PROPERTY");
    DbUtil.dropTable(connection, "PROJECT_PROPERTY"); // Will be dynamically recreated

    LOGGER.info("Deleting search engine indices");
    IndexManager.delete(IndexManager.IndexType.LICENSE);
    IndexManager.delete(IndexManager.IndexType.PROJECT);
    IndexManager.delete(IndexManager.IndexType.COMPONENT);
    IndexManager.delete(IndexManager.IndexType.VULNERABILITY);

    LOGGER.info("Deleting Dependency-Check work directory");
    try {
        final String DC_ROOT_DIR = Config.getInstance().getDataDirectorty().getAbsolutePath() + File.separator + "dependency-check";
        FileDeleteStrategy.FORCE.delete(new File(DC_ROOT_DIR));
    } catch (IOException e) {
        LOGGER.error("An error occurred deleting the Dependency-Check work directory", e);
    }
}
 
Example #5
Source File: CompilationScope.java    From cuba with Apache License 2.0 6 votes vote down vote up
private void collectInformation(String rootClassName) throws ClassNotFoundException {
    if (processed.contains(rootClassName)) {
        return;
    }

    File srcFile = sourceProvider.getSourceFile(rootClassName);
    processed.add(rootClassName);

    TimestampClass timeStampClazz = javaClassLoader.getTimestampClass(rootClassName);
    if (timeStampClazz != null) {
        if (FileUtils.isFileNewer(srcFile, timeStampClazz.timestamp)) {
            compilationNeeded.add(rootClassName);
        } else if (!srcFile.exists()) {
            throw new ClassNotFoundException(
                    String.format("Class %s not found. No sources found in file system.", rootClassName));
        }

        for (String dependencyName : timeStampClazz.dependencies) {
            collectInformation(dependencyName);
        }
    } else {
        compilationNeeded.add(rootClassName);
    }
}
 
Example #6
Source File: FileIOUtils.java    From Android-UtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * 将输入流写入文件
 *
 * @param file   文件
 * @param is     输入流
 * @param append 是否追加在文件末
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromIS(File file, final InputStream is, boolean append) {
    if (!FileUtils.createOrExistsFile(file) || is == null) return false;
    OutputStream os = null;
    try {
        os = new BufferedOutputStream(new FileOutputStream(file, append));
        byte data[] = new byte[1024];
        int len;
        while ((len = is.read(data, 0, 1024)) != -1) {
            os.write(data, 0, len);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(is, os);
    }
}
 
Example #7
Source File: PasswordManagerTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test (enabled=false)
public void testStrongEncryptionAndDecryption() throws IOException {
  String password = UUID.randomUUID().toString();
  String masterPassword = UUID.randomUUID().toString();
  File masterPwdFile = getMasterPwdFile(masterPassword);
  State state = new State();
  state.setProp(ConfigurationKeys.ENCRYPT_KEY_LOC, masterPwdFile.toString());
  state.setProp(ConfigurationKeys.ENCRYPT_USE_STRONG_ENCRYPTOR, true);
  try{
    StrongTextEncryptor encryptor = new StrongTextEncryptor();
    encryptor.setPassword(masterPassword);
    String encrypted = encryptor.encrypt(password);
    encrypted = "ENC(" + encrypted + ")";
    String decrypted = PasswordManager.getInstance(state).readPassword(encrypted);
    Assert.assertEquals(decrypted, password);
  }
  catch (EncryptionOperationNotPossibleException e) {
    //no strong encryption is supported
  }
}
 
Example #8
Source File: TestBug4179766.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the data from the class file for the specified class.  If
 * the file can't be found, or the class is not one of the
 * special ones listed below, return null.
 *    Bug4179766Class
 *    Bug4179766Resource
 */
private byte[] getClassData(String className) {
    boolean shouldLoad = className.equals("Bug4179766Class");
    shouldLoad = shouldLoad || className.equals("Bug4179766Resource");

    if (shouldLoad) {
        try {
            File file = new File(System.getProperty("test.classes", "."), className+CLASS_SUFFIX);
            FileInputStream fi = new FileInputStream(file);
            byte[] result = new byte[fi.available()];
            fi.read(result);
            return result;
        } catch (Exception e) {
            return null;
        }
    } else {
        return null;
    }
}
 
Example #9
Source File: LogDialog.java    From DebugDrawer with Apache License 2.0 6 votes vote down vote up
private void share() {
    LumberYard.getInstance(getContext())
        .save(new LumberYard.OnSaveLogListener() {
            @Override
            public void onSave(File file) {
                Intent sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("text/plain");
                sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                Intents.maybeStartActivity(getContext(), sendIntent);
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
}
 
Example #10
Source File: PersonalizationHelper.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
public static void removeAllUserHistoryDictionaries(final Context context) {
    synchronized (sLangUserHistoryDictCache) {
        for (final ConcurrentHashMap.Entry<String, SoftReference<UserHistoryDictionary>> entry
                : sLangUserHistoryDictCache.entrySet()) {
            if (entry.getValue() != null) {
                final UserHistoryDictionary dict = entry.getValue().get();
                if (dict != null) {
                    dict.clear();
                }
            }
        }
        sLangUserHistoryDictCache.clear();
        final File filesDir = context.getFilesDir();
        if (filesDir == null) {
            Log.e(TAG, "context.getFilesDir() returned null.");
            return;
        }
        final boolean filesDeleted = FileUtils.deleteFilteredFiles(
                filesDir, new DictFilter(UserHistoryDictionary.NAME));
        if (!filesDeleted) {
            Log.e(TAG, "Cannot remove dictionary files. filesDir: " + filesDir.getAbsolutePath()
                    + ", dictNamePrefix: " + UserHistoryDictionary.NAME);
        }
    }
}
 
Example #11
Source File: FakeApiTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * User not found
 */
@Test
public void shouldSee404AfterTestEndpointParameters() {
    BigDecimal number = null;
    Double _double = null;
    String patternWithoutDelimiter = null;
    byte[] _byte = null;
    Integer integer = null;
    Integer int32 = null;
    Long int64 = null;
    Float _float = null;
    String string = null;
    File binary = null;
    LocalDate date = null;
    OffsetDateTime dateTime = null;
    String password = null;
    String paramCallback = null;
    api.testEndpointParameters()
            .numberForm(number)
            ._doubleForm(_double)
            .patternWithoutDelimiterForm(patternWithoutDelimiter)
            ._byteForm(_byte).execute(r -> r.prettyPeek());
    // TODO: test validations
}
 
Example #12
Source File: CarreraRecover.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private static void recoverFromKVFile(File file) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    while (true) {
        String topic = reader.readLine();
        if (topic == null) return;
        String key = reader.readLine();
        if (key == null) return;
        long hashId = Long.valueOf(reader.readLine());
        int partition = Integer.valueOf(reader.readLine());
        String tag = reader.readLine();
        String value = reader.readLine();
        Result result = recoverProducer.sendWithPartition(topic, partition, hashId, value, key, tag);
        LOGGER.info("result={}.topic={},key={},hashId={},partition={},tag={},value.len={}",
                result, topic, key, hashId, partition, tag, value.length());
    }
}
 
Example #13
Source File: CordovaResourceApi.java    From cordova-amazon-fireos with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a stream to the given URI.
 * @return Never returns null.
 * @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
 *     resolved before being passed into this function.
 * @throws Throws an IOException if the URI cannot be opened.
 */
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
    assertBackgroundThread();
    switch (getUriType(uri)) {
        case URI_TYPE_FILE: {
            File localFile = new File(uri.getPath());
            File parent = localFile.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }
            return new FileOutputStream(localFile, append);
        }
        case URI_TYPE_CONTENT:
        case URI_TYPE_RESOURCE: {
            AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
            return assetFd.createOutputStream();
        }
    }
    throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
 
Example #14
Source File: FileUtils.java    From Neptune with Apache License 2.0 5 votes vote down vote up
/**
 * 拷贝so库,每次新安装插件覆盖更新原来的so库
 */
private static boolean findAndCopyNativeLib(Context context, ZipFile apk, String cpuArch, String libDir) {
    PluginDebugLog.installFormatLog(TAG, "findAndCopyNativeLib start to extract native lib for ABI: %s", cpuArch);
    boolean installResult = false;
    Enumeration<? extends ZipEntry> entries = apk.entries();
    ZipEntry entry;
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        String name = entry.getName();
        if (!name.startsWith(APK_LIB_DIR_PREFIX + cpuArch)
                || !name.endsWith(APK_LIB_SUFFIX)) {
            continue;
        }

        InputStream entryInputStream = null;
        try {
            entryInputStream = apk.getInputStream(entry);
            String libName = name.substring(name.lastIndexOf("/") + 1);
            PluginDebugLog.installFormatLog(TAG, "libDir: %s, soFileName: %s", libDir, libName);
            File libFile = new File(libDir, libName);

            if (libFile.exists()) {
                PluginDebugLog.installFormatLog(TAG, "soFileName: %s already exist, delete it", libName);
                libFile.delete();
            }
            // copy zip entry to lib dir
            installResult = copyToFile(entryInputStream, libFile);
        } catch (Exception e) {
            // ignore
        } finally {
            closeQuietly(entryInputStream);
        }
    }
    return installResult;
}
 
Example #15
Source File: Config.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static File dir_custom(Boolean force) throws Exception {
	File dir = new File(base(), DIR_CUSTOM);
	if (force) {
		if ((!dir.exists()) || dir.isFile()) {
			FileUtils.forceMkdir(dir);
		}
	}
	return dir;
}
 
Example #16
Source File: bug6698013.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public File getParentDirectory(File dir) {
    if (dir == null) {
        return null;
    }

    return new VirtualFile(dir.getPath(), true).getParentFile();
}
 
Example #17
Source File: Downsampler.java    From tectonicus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Shared(File inputDir, File outputDir, ImageFormat format, float compressionLevel, Color backgroundColor, final int tileWidth, final int tileHeight)
{
	this.inputDir = inputDir;
	this.outputDir = outputDir;
	
	this.tileWidth = tileWidth;
	this.tileHeight = tileHeight;
	
	this.imageFormat = format;
	this.imageCompressionLevel = compressionLevel;
	this.backgroundColor = backgroundColor;
}
 
Example #18
Source File: SkriptCommand.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private static File getScriptFromArgs(final CommandSender sender, final String[] args, final int start) {
	String script = StringUtils.join(args, " ", start, args.length);
	File f = getScriptFromName(script);
	if (f == null){
		Skript.error(sender, (script.endsWith("/") || script.endsWith("\\") ? m_invalid_folder : m_invalid_script).toString(script));
		return null;
	}
	return f;
}
 
Example #19
Source File: Configurator.java    From oasp4j-ide with Apache License 2.0 5 votes vote down vote up
/**
 * @param currentFile is the {@link File} to check.
 * @return <code>true</code> if the file is accepted as template, <code>false</code> if the file should be ignored.
 */
private boolean isAcceptFile(File currentFile) {

  if (currentFile.getName().endsWith(".bak")) {
    return false;
  }
  return true;
}
 
Example #20
Source File: Py2To3.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected int doActionOnResource(IResource next, IProgressMonitor monitor) {
    this.refresh = new ArrayList<IContainer>();
    AbstractRunner runner = UniversalRunner.getRunner(natureUsed);
    if (next instanceof IContainer) {
        this.refresh.add((IContainer) next);
    } else {
        this.refresh.add(next.getParent());
    }

    String dir = next.getLocation().toOSString();
    File workingDir = new File(dir);
    if (!workingDir.exists()) {
        Log.log("Received file that does not exist for 2to3: " + workingDir);
        return 0;
    }
    if (!workingDir.isDirectory()) {
        workingDir = workingDir.getParentFile();
        if (!workingDir.isDirectory()) {
            Log.log("Unable to find working dir for 2to3. Found invalid: " + workingDir);
            return 0;
        }
    }
    ArrayList<String> parametersWithResource = new ArrayList<String>(parameters);
    parametersWithResource.add(0, dir);
    Tuple<String, String> tup = runner.runCodeAndGetOutput(RUN_2_TO_3_CODE,
            parametersWithResource.toArray(new String[0]), workingDir, monitor);
    IOConsoleOutputStream out = MessageConsoles.getConsoleOutputStream("2To3", UIConstants.PY_INTERPRETER_ICON);
    try {
        out.write(tup.o1);
        out.write("\n");
        out.write(tup.o2);
    } catch (IOException e) {
        Log.log(e);
    }
    return 1;
}
 
Example #21
Source File: PythonEnvUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares PythonEnvironment to start python process.
 *
 * @param config The Python configurations.
 * @param entryPointScript The entry point script, optional.
 * @param tmpDir The temporary directory which files will be copied to.
 * @return PythonEnvironment the Python environment which will be executed in Python process.
 */
static PythonEnvironment preparePythonEnvironment(
	ReadableConfig config,
	String entryPointScript,
	String tmpDir) throws IOException {
	PythonEnvironment env = new PythonEnvironment();

	// 1. set the path of python interpreter.
	String pythonExec = config.getOptional(PYTHON_CLIENT_EXECUTABLE)
		.orElse(System.getenv(PYFLINK_CLIENT_EXECUTABLE));
	if (pythonExec != null) {
		env.pythonExec = pythonExec;
	}

	// 2. setup temporary local directory for the user files
	tmpDir = new File(tmpDir).getAbsolutePath();
	Path tmpDirPath = new Path(tmpDir);
	tmpDirPath.getFileSystem().mkdirs(tmpDirPath);
	env.tempDirectory = tmpDir;

	// 3. append the internal lib files to PYTHONPATH.
	if (System.getenv(ConfigConstants.ENV_FLINK_OPT_DIR) != null) {
		String pythonLibDir = System.getenv(ConfigConstants.ENV_FLINK_OPT_DIR) + File.separator + "python";
		env.pythonPath = getLibFiles(pythonLibDir).stream()
			.map(p -> p.toFile().getAbsolutePath())
			.collect(Collectors.joining(File.pathSeparator));
	}

	// 4. copy relevant python files to tmp dir and set them in PYTHONPATH.
	if (config.getOptional(PYTHON_FILES).isPresent()) {
		List<Path> pythonFiles = Arrays.stream(config.get(PYTHON_FILES).split(FILE_DELIMITER))
			.map(Path::new).collect(Collectors.toList());
		addToPythonPath(env, pythonFiles);
	}
	if (entryPointScript != null) {
		addToPythonPath(env, Collections.singletonList(new Path(entryPointScript)));
	}
	return env;
}
 
Example #22
Source File: LocalFileUtils.java    From systemds with Apache License 2.0 5 votes vote down vote up
public static void deleteFileIfExists(String dir, boolean fileOnly) 
{
	File fdir = new File(dir);
	
	if( fdir.exists() ) 
	{
		if( fileOnly ) //delete single file
			fdir.delete();
		else //recursively delete entire directory
			rDelete(fdir);	
	}
}
 
Example #23
Source File: Random.java    From blip with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void work3(String s) throws IOException {
    Und u = readUnd(s);

    new File(s + "-pc").mkdir();
    List<Und> lu = UndSeparator.go(u);

    pf("%s - %d", s, lu.size());
    int i = 0;

    for (Und u2 : lu) {
        u2.graph(f("%s-pc/%04d-%d", s, u2.n, i++));
    }

}
 
Example #24
Source File: AbstractJhlClientAdapter.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public SVNDiffSummary[] diffSummarize(File path, SVNRevision pegRevision,
		SVNRevision startRevision, SVNRevision endRevision, int depth,
		boolean ignoreAncestry) throws SVNClientException {
	String target = fileToSVNPath(path, false);
	return this.diffSummarize(target, pegRevision, startRevision,
			endRevision, depth, ignoreAncestry);
}
 
Example #25
Source File: ZoneInfoFile.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Void run() {
    try {
        String libDir = System.getProperty("java.home") + File.separator + "lib";
        try (DataInputStream dis = new DataInputStream(
                 new BufferedInputStream(new FileInputStream(
                     new File(libDir, "tzdb.dat"))))) {
            load(dis);
        }
    } catch (Exception x) {
        throw new Error(x);
    }
    return null;
}
 
Example #26
Source File: CalendarDaoICalFileImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean writeCalendarFile(final Calendar calendar, final String calType, final String calId) {
    final File fCalendarFile = getCalendarFile(calType, calId);
    OutputStream os = null;
    try {
        os = new BufferedOutputStream(new FileOutputStream(fCalendarFile, false));
        final CalendarOutputter calOut = new CalendarOutputter(false);
        calOut.output(calendar, os);
    } catch (final Exception e) {
        return false;
    } finally {
        FileUtils.closeSafely(os);
    }
    return true;
}
 
Example #27
Source File: MultimediaPickerFragment.java    From NoNonsense-FilePicker with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Here we check if the file is an image, and if thus if we should create views corresponding
 * to our image layouts.
 *
 * @param position 0 - n, where the header has been subtracted
 * @param file     to check type of
 * @return the viewtype of the item
 */
@Override
public int getItemViewType(int position, @NonNull File file) {
    if (isMultimedia(file)) {
        if (isCheckable(file)) {
            return VIEWTYPE_IMAGE_CHECKABLE;
        } else {
            return VIEWTYPE_IMAGE;
        }
    } else {
        return super.getItemViewType(position, file);
    }
}
 
Example #28
Source File: PersistentProvenanceRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public long getContainerUsableSpace(String containerName) throws IOException {
    Map<String, File> map = configuration.getStorageDirectories();

    File container = map.get(containerName);
    if(container != null) {
        return FileUtils.getContainerUsableSpace(container.toPath());
    } else {
        throw new IllegalArgumentException("There is no defined container with name " + containerName);
    }
}
 
Example #29
Source File: MailService.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private MimeMessagePreparator prepareTemplateBuildMimeMessagePreparator(String from, List<String> to, String subject, String mailMessageUrlOrBody, Map<String, Object> templateModelValues, final String attachmentUrl, final Boolean isPlainMessage) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
		String content = StringUtils.EMPTY;
		if(isPlainMessage) {
			content = mailContentBuilderService.buildPlainTextMail(mailMessageUrlOrBody, templateModelValues);
		} else {
			if(!isHttpUrl(mailMessageUrlOrBody)) {
				File template = new ClassPathResource("templates/".concat(mailMessageUrlOrBody).concat(".html")).getFile();
				content = mailContentBuilderService.buildPlainTextMail(FileUtils.readFileToString(template, "UTF-8"), templateModelValues);
			} else {
				content = processTemplate(mailMessageUrlOrBody, templateModelValues);
			}
		}
		messageHelper.setText(content, true);
	};
	return messagePreparator;
}
 
Example #30
Source File: FileUtil.java    From pandora with Apache License 2.0 5 votes vote down vote up
public static Intent getFileIntent(String filePath, String fileType) {
    File file = new File(filePath);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Uri uri = FileProvider.getUriForFile(Utils.getContext(),
            Utils.getContext().getPackageName() + ".pdFileProvider", file);
    intent.setDataAndType(uri, TextUtils.isEmpty(fileType) ? getFileType(filePath) : fileType);
    return intent;
}