How to check PDF corrupted or not in Java 1.6, and move corrupted PDF to some folder - java-6

i want to check PDF corrupted or not before moving to destination folder from source folder. if corrupted i have to move to some different (corrupted) folder.
I am using below code, it is working fine for pdf not corrupted files but if files is corrupted i can't move pdf to another folder.
Please help me why i cant move pdf file if corrupted, even i closed pdfreader.
PdfReader reader = new PdfReader(srcPdfFilePath);
if (reader != null){
n = reader.getNumberOfPages();
if (n > 0) {
pdfStatus = true;
} else {
pdfStatus = false;
}
}
else {
pdfStatus = false;
}
finally{
reader.close();
}
if (pdfStatus) {
MoveFile(srcPdfFilePath, destPdfFilePath);
} else {
MoveFile(srcPdfFilePath, errorPdfFilePath);
}
to move file i am using.
MoveFile (String oldFile, String newFile)
if(oldFile.renameTo(newFile))

Related

How to list Internal/External storage files absolute path in xamarin.android

I have searched and tried so many tutorials but i haven't got any working code for listing internal/external storage files absolute path.
I do have code for access only one file from internal storage -
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "test.mp3");
Thanks in advance
This code gets the external storage path. It return the emulated copy if there is no actual removable device.
var _path = GetExternalFilesDirs(null);
string Datapath;
foreach (var spath in _path)
{
if (spath == null) //just loop on if there is no card inserted
continue;
if (Android.OS.Environment.InvokeIsExternalStorageEmulated(spath))
{ //Emulated
Datapath = spath.AbsolutePath.ToString();
}
else if (Android.OS.Environment.InvokeIsExternalStorageRemovable(spath))
{ //removable
Datapath = spath.AbsolutePath.ToString();
break;
}
}

Silverlight app freezes on Mac when file saved

Pretty simple code to launch SaveFileDialog and then save data.
Opens prompt, I can select where I save, it saves file and then whole tab/app freezes. Obviously works fine on Windows/IE. Any suggestions?
private void SavePDFFile()
{
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "pdf",
Filter = string.Format("Document(.{0})|*.{0}", "pdf"),
FilterIndex = 1,
DefaultFileName = DateTime.Now.ToString("HHmmMMddyyyy")
};
var saveClicked = saveFileDialog.ShowDialog();
if (!saveClicked.HasValue || !saveClicked.Value) return;
var fileStream = saveFileDialog.OpenFile();
try
{
this.IsBusy = true;
fileStream.Write(this.PDFData, 0, this.PDFData.Length);
fileStream.Close();
}
catch (Exception ex)
{
this.DisplayErrorMessage("Error saving PDF file", ex);
}
finally
{
this.IsBusy = false;
}
}
Answering my own question. This is nothing to do with code itself. It is security issue. In order to allow this code to execute on Mac (and it seems new versions of IE as well) you need to give it more permissions.
On IE you need to add website to list of Trusted sites.
On Mac - you need to set Silverlight to run in "Unsafe" mode. This is in Preferences/Security/Silverlight and need to select website, hold "Option" key and then open dropdown to see that option. Took a while to find it..
#katit I also faced this issue while working on a Silverlight OOB application.. my app was working fine in Windows but in Mac it got freezed and I have to force quit to use it again.
I was actually reading a PDF (stored in field type - 'varbinary') from server and storing it to user's local machine.
The solution worked for me is to download file chunks in parts (I used buffer size - 1 MB).
Not sure what file size you are using when your application gets freeze.. but I think, writing 'PDFData' to filestream in small parts may help you.
Also, add filestream.Flush(); (see highlighted in below code) in your code and see if this helps:
private void SavePDFFile()
{
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "pdf",
Filter = string.Format("Document(.{0})|*.{0}", "pdf"),
FilterIndex = 1,
DefaultFileName = DateTime.Now.ToString("HHmmMMddyyyy")
};
var saveClicked = saveFileDialog.ShowDialog();
if (!saveClicked.HasValue || !saveClicked.Value) return;
var fileStream = saveFileDialog.OpenFile();
try
{
this.IsBusy = true;
fileStream.Write(this.PDFData, 0, this.PDFData.Length);
**filestream.Flush();**
fileStream.Close();
}
catch (Exception ex)
{
this.DisplayErrorMessage("Error saving PDF file", ex);
}
finally
{
this.IsBusy = false;
}
}

How to remove Objects from PDF File using PDFClown

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.
So far I am trying to do this with a ContentScanner:
public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);
private int count = 0;
public void scan(ContentScanner level) {
if (level == null)
return;
while (level.moveNext()) {
ContentObject object = level.getCurrent();
if (object instanceof ContainerObject) {
// Scan the inner level!
scan(level.getChildLevel());
} else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
AffineTransform ctm = level.getState().getCtm();
Color<?> strokeColor = level.getState().getStrokeColor();
Color<?> fillColor = level.getState().getFillColor();
if (checkWhite(fillColor) && checkWhite(strokeColor)) {
level.remove();
} else {
LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
}
} else {
LOG.info("Object:" + object);
}
}
}
It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):
Document targetDoc = new File().getDocument();
targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
Page page = targetDoc.getPages().get(0);
Contents contents = page.getContents();
FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
filterWhitePathScanner.scan(new ContentScanner(contents));
LOG.info("White Paths: " + filterWhitePathScanner.getCount());
targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);
The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?
Thanks,
Thomas
Finally found the solution in the Java doc:
You have to call contents.flush(); to persist the changes into the pdf file.
So I added this line to the PDF handling code before calling save and it works!

Download a zip file and unzip to internal storage Android Xamarin cross platform app

Is there any way to download and unzip a file from a remote server using Xamarin cross platform application.
I use the PC:Storage librray to interact with Files and folders
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MyAppRoot\\F1",CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("firstfile.txt",
CreationCollisionOption.ReplaceExisting);
await file.WriteAllTextAsync("my content");
This is the way i created a folder F1 inside app root folder and creates a files firstfile.txt and write some comtent to it. But how can i do the same with a zip file ?
Download the zip file , unzip contents to folder .
Also how can i see the folders / files created while running the application ? Is any IsoStoreSpy kind of tools available for Xamarin android emulator ?
step one, get the file:
Xamarin helps Downloading the file
Here's their download task in case that link moves/dies:
public static async Task<int> CreateDownloadTask(string urlToDownload, IProgress<DownloadBytesProgress> progessReporter)
{
int receivedBytes = 0;
int totalBytes = 0;
WebClient client = new WebClient();
using (var stream = await client.OpenReadTaskAsync(urlToDownload))
{
byte[] buffer = new byte[4096];
totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);
for (;;)
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
await Task.Yield();
break;
}
receivedBytes += bytesRead;
if (progessReporter != null)
{
DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
progessReporter.Report(args);
}
}
}
return receivedBytes;
}
you'll want to write that data thats being downloaded, so add to their method a file handler and do something like
await zipFile.WriteAsync(buffer, 0, bytesRead);
then there's the unzipping, I know I've downloaded Microsofts Compression NuGet before... glancing at some code I've used DeflateStream in the System.IO.Compression namespace to decompress stuff.
and as you already have something for handling local file I won't mention anything for that.

Cannot read two consecutive files with a Windows Service using StreamReader object

I need to be able to read lines of a file with a StreamReader processed by a FileSystemWatcher in a Windows service.
I've read and tried everything that made sense online, but it still doesn't work. When I'm attahced to my Windows service process (local machine using Visual Studio 2010), the whole thing works flawlessly!
When I try to run it (on my local machine) without attaching to it and debugging it, the second file never makes it through and I get the following msg:
"The process cannot access the file 'C:\Projects\Data\VendingStats\20121213_AZM_Journey_MIS.txt' because it is being used by another process." I do not have this file open anywhere else on my machine. It is just sitting in a directory. I then copy it in a directory and the FSW takes over (and the code below).
Can someone please tell me what I need to do to get this to work? I don't know why it works fine when I'm attached to and debugging it, but it doesn't work when I send the files through without being attached and debugging it. I feel it's defeintiely something on my local box that I need to disable, etc --- I don't know.....
I noticed that the error occurs even before it gets into the "using" statement, because the second file is never copied to the temp directory for it to be processed.
I noticed in my StackTrace, I'm getting the following error:
system.io.__error.winioerror(int32 errorcode string maybefullpath)
Here is my code:
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Projects\Data\VendingStats");
Watcher.EnableRaisingEvents = true;
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Filter = "*.txt";
Watcher.IncludeSubdirectories = false;
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
string targetPath = #"C:\Temp\VendorStats";
// Use Path class to manipulate file and directory paths.
FileInfo fi = new FileInfo(e.FullPath); // full name of path & file in the FSW directory
string destFile = Path.Combine(targetPath, fi.Name);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
// To copy a file to another location and
File.Copy(e.FullPath, destFile, true);
// Set attribute to READONLY
if (fi.IsReadOnly == false)
fi.Attributes = FileAttributes.ReadOnly;
GetCruiseLineShipName(destFile, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(destFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
filename = e.FullPath;
//How many lines should be loaded?
int NumberOfLines = 39;
//Read the number of lines and put them in the array
for (int i = 1; i < NumberOfLines; i++)
{
ListLines[i] = sr.ReadLine();
switch (i)
{
case 3:
int idx = ListLines[i].IndexOf(":");
string timeLine = ListLines[i].Substring(idx + 1);
dt = GetDate(Convert.ToDateTime(timeLine.Substring(1)));
break;
//more code here of the same
}
}
//InsertData into database }
}
catch (Exception ex)
{
EventLog.WriteEntry("VendorStats", "Error in the Main:" + "\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.InnerException);
return;
}
}
The bottom line to solving this was to put the method (that was spawned by the FileSystemWatcher) to sleep for "X" amount of seconds until Windows completely releases the resources to the previous and present files as well as the folder.
It was the FileSystemWatcher that actaully had a hold on the resources.
Here is some sample code:
private static void Watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
Thread.Sleep(10000);
GetCruiseLineShipName(e.FullPath, ref cruiseLine, ref shipName);
using (StreamReader sr = new StreamReader(File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read)))
{

Resources