How to set the path of the file writer to location of the jar using it? - tinylog

So i recently switch from starting the jar file from a service rather than a script that first goes to the relevant directory. Is there a way to make sure that the path to the jar file is used instead of wherever the service started it? Inside the application i use the code below to get the correct path.
try {
Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
workPath = p.getParent().toString();
if( workPath.matches(".*[lib]")) { // Meaning used as a lib
workPath = Path.of(workPath).getParent().toString();
}
settingsFile = Path.of(workPath, "settings.xml");
} catch (URISyntaxException e) {
Logger.error(e);
}

Store your work path as system property:
try {
Path p = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
workPath = p.getParent().toString();
if(workPath.matches(".*[lib]")) { // Meaning used as a lib
workPath = Path.of(workPath).getParent().toString();
}
System.setProperty("tinylog.directory", workPath); // Set work path as system property
settingsFile = Path.of(workPath, "settings.xml");
} catch (URISyntaxException e) {
Logger.error(e);
}
Use the system property in tinylog.properties:
writer = file
writer.file = #{tinylog.directory}/log.txt
writer.format = {date: HH:mm:ss.SSS} {level}: {message}

Related

Google script: Download web image and save it in a specific drive folder

I need to download an image with GS and save it in a specific drive folder.
I'm able to save the image in the root folder but i cannot save it in a specific folder:
function downloadFile(fileURL,folder) {
var fileName = "";
var fileSize = 0;
var response = UrlFetchApp.fetch(fileURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var folder = DriveApp.getFoldersByName(folder);
if (folder != null) {
var file = DriveApp.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
}
Question: what have I to add to use the variable "folder"?
I found a lot of examples with "DocList" Class that is not in use anymore
Many thanks
Well, I guess GAS has make a lot of progress on developing its API, the function
createFile(blob) of an object Folder will do the job:
https://developers.google.com/apps-script/reference/drive/folder#createfileblob
// Create an image file in Google Drive using the Maps service.
var blob = Maps.newStaticMap().setCenter('76 9th Avenue, New York NY').getBlob();
DriveApp.getRootFolder().createFile(blob);
It's quite late for the answer but just incase some one runs into the situation.
Are you familiar with this app? It does exactly what you're asking for.
However, if you want to re-create this for your own purposes, I would change your declaration of variable file to read as such:
var file = folder.next().createFile(fileBlob);
when you create your variable folder, the method you use creates a FolderIterator, not a single folder. You have to call the next() method to get a Folder object.
To be precise with your script and avoid saving to an incorrect-but-similarly-named folder, I would recommend passing the folder ID to your script rather than the folder Name. If you pass the folder ID, you could declare folder as:
var folder = DriveApp.getFolderById(folder);
and then continue the script as you have it written. I hope that helps.
Working on similar problem, I came up with the solution below to save a file to a folder. If the folder doesn't exist it creates it, otherwise it saves the file specified by "FOLDER_NAME"
var folderExists = checkFolderExists("FOLDER_NAME");
if (folderExists) {
saveFolder = DriveApp.getFolderById(folderExists);
} else {
saveFolder = DriveApp.createFolder("FOLDER_NAME");
}
// Make a copy of the file in the root drive.
var file = DriveApp.getFileById(sheetID);
// Take the copy of the file created above and move it into the folder:
var newFile = DriveApp.getFolderById(saveFolder.getId()).addFile(file);
// Remove the copy of the file in the root drive.
var docfile = file.getParents().next().removeFile(file);
Further to Eric's answer, I have also provided a utility function that checks if the folder exists. It's reusable in any project.
function checkFolderExists(fName) {
try {
var folderId;
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
folderName = folder.getName();
if (folderName == fName) {
folderId = folder.getId();
}
}
} catch(e) {
log("Services::checkFolderExists()" + e.toString());
throw e;
}
return folderId;
}

java.io.FileNotFoundException - Can't read my properties file

Eclipse/Linux - Java Web Application.
I added a file named dao.properties to my project. I put it in a package : com.cdp.dao . My class which uses this file is in the same package.
When I try to load it I have a
java.io.FileNotFoundException
/myproject/src/com/cdp/dao/dao.properties (No such file or directory) OR
dao.properties (No such file or directory)
This my code :
Properties prop;
FileInputStream fis;
File file = new File("/myproject/src/com/cdp/dao/dao.properties");
//File file = new File("dao.properties"); doesn't work either
try {
prop = new Properties();
fis = new FileInputStream(file);
prop.load(fis);
dbUrl = prop.getProperty("dbUrl");
user = prop.getProperty("user");
pwd = prop.getProperty("pwd");
driver = prop.getProperty("driver");
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use
this.getClass().getResourceAsStream("dao.properties");
to load the properties file
From Class, the path is relative to the package of the class unless
you include a leading slash, so if you don't want to use the current package,
include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/dir/SomeTextFile.txt");
but if you need to use classpath use just filename like below
InputStream in = this.getClass().getResourceAsStream("dao.properties");

Equivalent method to fetchCompleteState in RTC java plain api

Is there any equivalent method for fetchCompleteState on versionableManager to fetch data of historic files? I'm having troubles with retrieving file name of file added in previous changelists. Here is example:
Changelist 1:
add file: src/newFile.java
Changelist 2:
modify file: src/newFile.java
Changelist 3:
rename file: src/newFile.java -> src/newFile_rename.java
And now when I'm trying to get file name or file path of file in changelist 1 using following code:
// change is IChange, versionableManager is IVersionableManager
// method getFilePath retrieve file path using ancestors
file = versionableManager.fetchCompleteState(change.afterState(), monitor);
if (file instanceof IFolder) {
IFolder folder = (IFolder) file;
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = folder.getName();
} else {
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = ((FileItem) file).getName();
}
I'm getting name and path of renamed file. How to get it's old name and path?
Ok found the solution:
IFileItemHandle fileItemHandle = (IFileItemHandle) IFileItem.ITEM_TYPE.createItemHandle(change.afterState().getItemId(), change.afterState().getStateId());
file = versionableManager.fetchCompleteState(fileItemHandle, monitor);
if (file instanceof IFolder) {
IFolder folder = (IFolder) file;
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = folder.getName();
} else {
relativePath = getFilePath(file, workspaceConnection.configuration(changeSet.getComponent()), monitor);
fileName = ((FileItem) file).getName();
}
But still having isses with resolving file path. Anyways this is a big step.

Programmatically move files after virus scan

Is it possible to move files programmatically based on virus scan status?
What I want to do is have a set of folders:
Incoming
Scanned
Scanned/Clean
Scanned/Infected
Not Scanned
Files would be dropped into the Incoming folder. At that point, I would like to kick off the antivirus and scan the files in the Incoming folder. Once complete, the files would then need to be moved to the appropriate folder, either Clean or Infected. If, for whatever reason, the file could not be scanned or had trouble scanning, it would be moved to the Not Scanned folder.
I was hoping there would be a way to script this out. Has anyone ever done anything like this before?
public void Scan()
{
string[] uploadPath = Directory.GetFiles(ConfigurationManager.AppSettings["UploadPath"]);
foreach(string filePath in uploadPath)
{
string fileName = Path.GetFileName(filePath);
string cleanPath = Path.Combine(ConfigurationManager.AppSettings["CleanPath"], fileName);
try
{
Process AV = new Process();
AV.StartInfo.UseShellExecute = false;
AV.StartInfo.RedirectStandardOutput = true;
AV.StartInfo.FileName = ConfigurationManager.AppSettings["VSApp"];
AV.StartInfo.Arguments = " -Scan -ScanType 3 -file " + ConfigurationManager.AppSettings["UploadPath"] + " -DisableRemediation";
AV.Start();
string output = AV.StandardOutput.ReadToEnd();
AV.WaitForExit();
if (AV.ExitCode == 0)
{
File.Move(filePath, cleanPath);
}
else if (AV.ExitCode == 2)
{
using (TextWriter tw = new StreamWriter(ConfigurationManager.AppSettings["FailedPath"] + fileName + ".txt"))
{
tw.WriteLine("2");
tw.Close();
}
using (TextWriter tw1 = new StreamWriter(ConfigurationManager.AppSettings["FailedFiles"] + fileName + ".txt"))
{
tw1.WriteLine(AV.StandardOutput);
tw1.Close();
}
File.Delete(filePath);
}
AV.Close();
}
catch (Exception ex)
{
if (ex.ToString().Contains("Could not find file"))
{
string failedFile = ConfigurationManager.AppSettings["FailedPath"] + fileName + ".txt";
string failedFileDesc = ConfigurationManager.AppSettings["FailedPath"] + fileName + "_ErrorDesc" + ".txt";
using (TextWriter tw = new StreamWriter(failedFile))
{
tw.WriteLine("2");
tw.Close();
}
using (TextWriter tw1 = new StreamWriter(failedFileDesc))
{
tw1.WriteLine(ex.ToString());
tw1.Close();
}
}
else
{
Thread.Sleep(2000);
if (runCounter == 0)
{
Scan();
}
runCounter++;
string errorFile = ConfigurationManager.AppSettings["ProcessErrorPath"] + fileName + ".txt";
using (TextWriter tw = new StreamWriter(errorFile))
{
tw.WriteLine(ex.ToString());
tw.Close();
}
}
}
}
}
I created this as a Windows Service. My OnStart method creates my FileSystemWatcher to watch the Upload Path. For On Created, I have a method that runs my Scan method and creates my counter and sets it to 0. My On Error event just logs. I had an issue where the FileSystemWatcher was trying to open the file before it had been uploaded, hence why I added the sleep.
Finally, I am using Microsoft Forefront's command line scanner. File path: C:\Program Files\Microsoft Security Client\mpcmdrun.exe.
Let me know if any questions.

Zend move_uploaded_file Failure

I have spent a couple hours trying to add a simple upload file option to my Zend application. I have double checked all of the necessary permissions and everything works fine. Quite simply, I have it uploading nicely to a temporary folder but once I have it in that temp folder, I can't get it to move to its permanent storage location. Below is the code that keeps failing...
To be precise, the code fails with the $uploaded die statement. I thought it might be an issue since I am sending it to the Model rather than handling it right in the Action but that didn't solve the problem either. Can anyone point me in the right direction? I just can't get the file out of the temprorary directly and into the permenant storage locatoin I want.
Thank you!
//This is the action that is called when form is submitted.
function addImageAction()
{
$imgForm = new Admin_Form_ImageUploadForm();
$imgForm->setAction('/admin/media/add-image');
$imgForm->setMethod('post');
$this->view->form = $imgForm;
if($this->getRequest()->isPost())
{
if(!$imgForm->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
$this->_redirect('/admin/media/add-image');
}
if($imgForm->image->isUploaded())
{
$imageModel = new Admin_Model_Image();
$imageId = $imageModel->addImage($imgForm->image->getFileName());
$this->_redirect('/admin/media/view-image/'.$imageId);
}
}
}
Block #2 - The Model
public function addImage($image)
{
// Process the New File
// Check to see if Filename is already in Database
$select = $this->select();
$select->where('filename=?', $image);
$row = $this->fetchRow($select);
if ($row)
{
die("Filename already exists in Database. Please try another file.");
}
// Move file to Storage Directory
// Check/Create Storage Directoy (YYYYMMDD)
// Temporarily set MEDIA_DIR
$mediaDir = APPLICATION_PATH . '/../public/media/uploads/';
$destinationDir = $mediaDir . date('Ymd');
if (!is_dir($destinationDir)){
$storageDir = mkdir($destinationDir);
}
// Save Image
$uploaded = is_uploaded_file($image);
if (!$uploaded) {
die("Image has not been uploaded");
}
$image_saved = move_uploaded_file($image, $destinationDir);
if(!$image_saved)
{
die("Image could not be moved");
}
// Create Alternative Sizes
// Save Data to Database Tables
$dateObject = new Zend_Date();
$row = $this->createRow();
$row->filename = $image;
$row->date_added = $dateObject->get(Zend_Date::TIMESTAMP);
$row->date_modified = $dateObject->get(Zend_Date::TIMESTAMP);
$row->save();
// Fetch the ID of the newly created row
$id = $this->_db->lastInsertId();
// Retrieve IPTC Data
// Retrieve EXIF Data
// Return Image ID
return $id;
}
receive() method moves the file using move_uploaded_file(). So the file you work with is not uploaded anymore, it's normal file. You should use standard copy() function instead.