C++/winRT CreateFolderAsync - how to check for existing folder? - c++-winrt

I'm attempting to update a file in a folder. First I need to check if the folder exists and if not create one and then create an empty file in that folder.
A try/catch with CreationCollisionOption of FailIfExists or OpenIfExists
does not work if the folder does not exist.;
The other options: GenerateUniqueName and ReplaceExisting are not appropiate.
code:............
//get the storage folder
StorageFolder _storageFolder = ApplicationData::Current().LocalFolder();
//get one of it's sub folders
StorageFolder _turboCalc = nullptr; //no default constructor
bool _folderFound = false;
try {
_turboCalc = co_await _storageFolder.CreateFolderAsync(L"TurboCalc", CreationCollisionOption::OpenIfExists); //create sub folder in sub folde
//_turboCalc = co_await _storageFolder.CreateFolderAsync(L"TurboCalc", CreationCollisionOption::FailIfExists); //create sub folder in sub folde
}
catch (winrt::hresult_error const& ex) {
_folderFound = false;
}
StorageFile _fileDoubles = nullptr; //no default constructor
if (!_folderFound) { //creae the folder and an empty file
_turboCalc = co_await _storageFolder.CreateFolderAsync(L"TurboCalc");
_fileDoubles = co_await _turboCalc.CreateFileAsync(L"FileDoubles.dbo", CreationCollisionOption::ReplaceExisting); //create file in sub folder
}

This is the behavior of a co-routine. Prob;em solved

Related

Read resource file from inside SonarQube Plugin

I am developing a plugin using org.sonarsource.sonarqube:sonar-plugin-api:6.3. I am trying to access a file in my resource folder. The reading works fine in unit testing, but when it is deployed as a jar into sonarqube, it couldn't locate the file.
For example, I have the file Something.txt in src/main/resources. Then, I have the following code
private static final String FILENAME = "Something.txt";
String template = FileUtils.readFile(FILENAME);
where FileUtils.readFile would look like
public String readFile(String filePath) {
try {
return readAsStream(filePath);
} catch (IOException ioException) {
LOGGER.error("Error reading file {}, {}", filePath, ioException.getMessage());
return null;
}
}
private String readAsStream(String filePath) throws IOException {
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
if (inputStream == null) {
throw new IOException(filePath + " is not found");
} else {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
}
This question is similar with reading a resource file from within a jar. I also have tried with /Something.txt and Something.txt, both does not work.If I put the file Something.txt in the classes folder in sonarqube installation folder, the code will work.
Try this:
File file = new File(getClass().getResource("/Something.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
String something = IOUtils.toString(reader);
Your should not use getContextClassLoader(). see Short answer: never use the context class loader!

inserting image into mongo from java result in a strange error

I have the following code for saving image in mongodb:
public static void insertImage() throws Exception {
String newFileName = "mkyong-java-image";
File imageFile = new File("c:\\JavaWebHosting.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
}
And I got this from this link:
link for code
But when I use that I get the following error and I do not know how to fix it ... Can anyone help?
Exception in thread "main" java.lang.NullPointerException
at com.mongodb.gridfs.GridFS.<init>(GridFS.java:97)
for more explanation the error is at exactly this line:
GridFS gfsPhoto = new GridFS(db, "photo");
Update:
Here is the code for creating db connection
public static DB getDBConnection() {
// If it's not connected to the database, make connection
if (db == null) {
initialize();
makeConnections();
}
return db;
}
private static void makeConnections() {
MongoCredential credential = MongoCredential.createMongoCRCredential(dbUser, dbName, dbPass.toCharArray());
MongoClient mongoClient;
try {
mongoClient = new MongoClient(new ServerAddress(dbHost, Integer.parseInt(dbPort)), Arrays.asList(credential));
db = mongoClient.getDB(dbName);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
Update:
String newFileName = "mkyong-java-image";
File imageFile = new File("D:/1.jpg");
db = MongoDB.getDBConnection();
collection = db.getCollection("test");
// create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo");
// get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
// set a new filename for identify purpose
gfsFile.setFilename(newFileName);
// save the image file into mongoDB
gfsFile.save();
// print the result
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// get image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
// save it into a new image file
imageForOutput.writeTo("D:\\JavaWebHostingNew.jpg");
// remove the image file from mongoDB
// gfsPhoto.remove(gfsPhoto.findOne(newFileName));
System.out.println("Done");

Delete a File from the apps private storage directory - Android

I am having a bit of trouble trying to delete a file from the applications private storage directory that I have programmatically created and compressed.
The problem I am facing is that it's not recognising that the file exists when I call file.exists(), and so it will not delete the file.
This is the code I'm using to delete the file
public static void deleteImageFromPrivateArea( final String fileUri )
{
final File file;
boolean isFileDeleted;
if ( isFilePathPrefixPresent( fileUri ) )
{//file name checking
file = new File( fileUri );
}
else
{
file = new File( "file://" + fileUri );
}
if ( file.exists() )
{
isFileDeleted = file.delete();
if ( ! isFileDeleted )
{
throw new IllegalStateException( "File was not deleted" );
}
}
}
To clear things up, I know that the fileUri I'm passing through is the location of a file that currently exists. I have checked with a filemanager app.
I have the permissions set up in the manifests xml.
What I believe is happening is that this code is getting the path of the currently existing file, and setting up a new file but not writing the data to it thus this new file does not exist in android.
So what I think I need to do is get the existing file (maybe not in the form of a Uri, but the actual file) and then call .delete() as then the file would exist.
Or
After setting up this new file with the fileUri, write the data to it using an OutputfileStream - this would not be my preferred method though.
-but I'm not entirely sure.
would be easier just to pass the filename as a parameter then do
File mydir = getFilesDir(); //get your internal directory
File myFile = new File(mydir, filename);
myFile.delete();
With help from BradR I found the best solution.
I used *getExternalFilesDir( Environment.DIRECTORY_PICTURES )* to get the pictures 2. directory in the applications private storage area.
Created a new file with the given imageUri and then used this to get the filename of the file.
Reinitialized the File to create a new file using the ExternalFilesDir and filename
Check that the file exists and delete it.
#
public static void deleteImageFromPrivateArea( final Context context, final String imageUri )
{
String filename;
File file;
final File dir = context.getExternalFilesDir( Environment.DIRECTORY_PICTURES );
if ( isFilePathPrefixPresent( imageUri ) )
{
file = new File( imageUri );
}
else
{
file = new File( "file://" + imageUri );
}
filename = file.getName();
file = new File( dir, filename );
if ( file.exists() )
{
try
{
file.delete();
}
catch ( Exception e )
{
throw new IllegalStateException( "File wasn't deleted" );
}
}
else
{
throw new IllegalStateException( "File was doesn't exist" );
}
}

Upload file, check for same file name

Hi i'am using this utils, to make file upload and delete upload. MVC 4 LINQ to SQL.
I would like to check if file is already uploaded, and if, make a meassage
to try new file.
Can you help me, getting started, to add code for this ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CFire2.SupplyConUtils
{
public static class FileUpload
{
public static char DirSeparator =
System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = "Content" +
DirSeparator + "SupplyUpload" + DirSeparator;
public static string UploadFile(HttpPostedFileBase file)
{
// Check if we have a file
if (null == file) return "";
// Make sure the file has content
if (!(file.ContentLength > 0)) return "";
string fileName = file.FileName;
string fileExt = Path.GetExtension(file.FileName);
// Make sure we were able to determine a proper
// extension
if (null == fileExt) return "";
// Check if the directory we are saving to exists
if (!Directory.Exists(FilesPath))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(FilesPath);
}
//// Set our full path for saving
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Save our file
file.SaveAs(path);
// Return the filename
return fileName;
}
public static void DeleteFile(string fileName)
{
// Don't do anything if there is no name
if (fileName.Length == 0) return;
// Set our full path for deleting
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Check if our file exists
if (File.Exists(path))
{
// Delete our file
File.Delete(path);
}
}
}
}
The MSDN docs for HttpPostedFileBase.FileName says
When overridden in a derived class, gets the fully qualified name of
the file on the client.
So probably you need to add this line to correctly execute your check
string fileName = Path.GetFileName(file.FileName);
and then
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"),
fileName);
if(File.Exists(path))
return "The file has been already uploaded!
....

Store images into a specified location on local system

I am using Play Framework 2.0.4. Here is my code that I have tried :
public static Result save() throws FileNotFoundException {
Form<Tenant> tenantForm = form(Tenant.class).bindFromRequest();
Form<Ten> tenForm = form(Ten.class).bindFromRequest();
Long tenantid = tenForm.get().tenant_id;
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart picture = body.getFile("logo_url");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
tenantForm.get().logo_url = file.getPath();
tenantForm.get().save();
return redirect(
routes.Application.index()
);
} else {
flash("error", "Missing file");
return redirect(
routes.Project.ctstenant(0,"name","asc","","",tenantid)
);
}
}
It will stores the image in temp folder. I want it to store in a specified folder. With the example will be appreciated.
Thanks for the help.
You can move your file from TEMP folder to your file storage directory. Below is the example how to move your uploaded file :
// define file storage path
public static final String fileStoragePath = "D:\\filestorage\\";
// handle form submit action
public static Result save() {
// bind request logic
...
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
// log message to console
Logger.info("Original file name = " + fileName +
" with Content Type " + contentType);
// Rename or move the file to the storage directory
if (file.renameTo(new File(fileStoragePath + fileName))) {
Logger.info("Success moving file to " + file.getAbsolutePath());
} else {
Logger.info("Failed moving file on " + file.getAbsolutePath());
}
// save your file name or using blob (it is your choice)
...
}
}
Note that, path defined on fileStoragePath must be available before to successfully moving or renaming the uploaded file.