Polling from a network directory - windows

I have been working on the following project, some background:
I am an intern currently developing a new search system for my organization. The current setup is microsoft sharepoint 2013 in which the users upload files etc.. and on the other hand is the system I am developing which indexes all data being uploaded to apache SOLR.
I have been succesfull in mapping the sharepoint content repository to a network drive, and I can manually start my program to start indexing the conent of this network drive to SOLR using the Solrj api.
The problem I am facing however is that I am unable to poll events from this network drive. In my test build which ran local I used a watcher service to launch code (reindex documents, delete indexes) on file create, file modify and file delete.
This does not work unfortunantly with a url pointing to a network drive :(.
So the big question: Is there any API / library available for polling events from network drives?
Any help would be extemely appreciated !

So I fnally figured this one out, tried looking at .net's variant of the watcher service (system.io.filesystemwatcher) and i was having the same problem. I finally got it working by using java.io.FileAlterationMonitor / observer.
Code:
public class UNCWatcher {
// A hardcoded path to a folder you are monitoring .
public static final String FOLDER =
"A:\\Department";
public static void main(String[] args) throws Exception {
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
try {
// "file" is the reference to the newly created file
System.out.println("File created: "
+ file.getCanonicalPath());
if(file.getName().endsWith(".docx")){
System.out.println("Uploaded resource is of type docx, preparing solr for indexing.");
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "
+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "
+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
System.out.println("Starting monitor service");
monitor.start();
}
}

Related

Saving an image to a newly created folder with Uri?

The app i am creating is supposed to save a picture in a sub folder of the pictures folder. As long as i save the picture to the base folder it works fine, but it returns an error as soon as i try to target the subfolder. Permission for writing/reading external storage are given. Do i need to create the folder another way to use it? How do i get the URI of the folder itself?
The error for v1 is: "Failed to write destination file".
The error for v2 is: "Unknown or unsupported URL:content://media/external/images/media/ProxF/"
private void captureImage(ImageCapture imageCapture)
{
//Folder
File dir = new File(getExternalStoragePublicDirectory(DIRECTORY_PICTURES) +"/ProxF");
try{
if(dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
}catch(Exception e){
e.printStackTrace();
}
//MEDIA API
String FotoString="picture1";
ContentValues contentValues=new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, FotoString);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
//Saving to the picture folder - working
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//V1 - not working
File folder = new File(getExternalStoragePublicDirectory(DIRECTORY_PICTURES).toString() + "/ProxF/");
Uri uri1=Uri.fromFile(folder);
//V2 - not working
Uri uri2 = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI+"/ProxF/")
ImageCapture.OutputFileOptions fileOptions= new ImageCapture.OutputFileOptions.Builder(getContentResolver(),uri,contentValues).build();
imageCapture.takePicture(fileOptions, Executors.newCachedThreadPool(), new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
runOnUiThread(() -> Toast.makeText(KameraAc.this, "Image Saved ",Toast.LENGTH_SHORT).show());
startCamera();
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
runOnUiThread(() -> Toast.makeText(KameraAc.this, "Failed to save: "+exception.getMessage(), Toast.LENGTH_SHORT).show());
startCamera();
}
});
}

update profile image functionality is not working while hosting as jar

Hi I am new to Springboot I was trying to develop a application, One of its functionality is to upload profile Image. It was working fine in STS but when I pack it in jar and hosting it on AWS EC2 envirnment I am getting some error while processing that image
Error:
handler for profile picture:
#PostMapping("/process-contact")
public String processContact(#ModelAttribute Contact contact, #RequestParam("profileImage") MultipartFile file,
HttpSession session) {
try {
contact.setUser(user);
user.getContacts().add(contact);
// processing and uploading photo
if (file.isEmpty()) {
System.out.println("File is empty");
contact.setImage("contact.png");
} else {
//Processing Image
InputStream inputStream = file.getInputStream();
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
Files.copy(inputStream, paths, StandardCopyOption.REPLACE_EXISTING);
contact.setImage(file.getOriginalFilename());
}
// Success Message
session.setAttribute("message", new Message("Your contact is added...", "success"));
this.userRepository.save(user);
System.out.println("Successfully Added");
} catch (Exception E) {
E.printStackTrace();
// Failed message
session.setAttribute("message", new Message("Something went wrong "+E.getMessage(), "danger"));
}
return "normal/add_contact_form";
}
It is working fine in IDE after some research I found way of writing data in jar is diffrent could some please help me how can I implemenr it for jar also.
Thankyou
all you need to do is replace this line:
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
With:
Path paths = Paths.get(new FileSystemResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
THat will work like charm.

Google Drive Api Pdf export from Google Doc generate empty response

I'm using the export Google Drive API to retrieve a Google Doc as Pdf: https://developers.google.com/drive/v3/reference/files/export
I'm having the following problem: for documents bigger than a certain size (I don't know exactly the threshold, but it happens even with relatively small files around 1,5 MB) the API return a 200 response code with a blank result (normally it should contains the pdf data as byte stream), as you can see in the following screenshot:
I can successfully export the file via GoogleDrive/GoogleDoc UI with the "File -> Download as.. -> Pdf" command, despite it takes a bit of time.
Here is the file used for test (1.180 KB exported from Google Doc), I shared it so you can access to try export:
https://docs.google.com/document/d/18Cz7kHfEiDLeTWHyyoOi6U4kFQDMeg0D-CCJzILMMCk/edit?usp=sharing
Here is the (Java) code I'm using to perform the operation:
#Override
public GoogleDriveDocumentContent downloadFileContentAsPDF(String executionGoogleUser, String fileId) {
GoogleDriveDocumentContent documentContent = new GoogleDriveDocumentContent();
String conversionMimeType = "application/pdf";
try {
getLogger().info("GDrive APIs - Downloading file content in PDF format ...");
InputStream gDriveFileData = getDriveService(executionGoogleUser).files()
.export(fileId, conversionMimeType)
.executeMediaAsInputStream();
getLogger().info("GDrive APIs - File content as PDF format downloaded.");
documentContent.setFileName(null);
documentContent.setMimeType(conversionMimeType);
documentContent.setData(gDriveFileData);
} catch (IOException e) {
throw new RuntimeException(e);
}
return documentContent;
}
Does anyone has the same issue and know how to solve it?
The goal is to generate a pdf from a Google Doc.
Thanks
I think you should try using media downloadeder you will have to alter it for Google drive rather than storage service.
{
// Create the service using the client credentials.
var storageService = new StorageService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APP_NAME_HERE"
});
// Get the client request object for the bucket and desired object.
var getRequest = storageService.Objects.Get("BUCKET_HERE", "OBJECT_HERE");
using (var fileStream = new System.IO.FileStream(
"FILE_PATH_HERE",
System.IO.FileMode.Create,
System.IO.FileAccess.Write))
{
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
getRequest.MediaDownloader.ProgressChanged += Download_ProgressChanged;
getRequest.Download(fileStream);
}
}
static void Download_ProgressChanged(IDownloadProgress progress)
{
Console.WriteLine(progress.Status + " " + progress.BytesDownloaded);
}
Code ripped from here

Error inherits module: Windows azure blobstore in gwt and not GAE Blobstore

I used Windows Azure SDK for java in gwt, and obtain this problem in gwt:
No source code is available for type com.microsoft.windowsazure.services.core.storage.CloudStorageAccount; did you forget to inherit a required module?
Any idea?, for example correct value for <inherits name ="....."/>
this is the code, but the problem not is the code, is the correct value for inherits name:
public class StorageSmple {
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;" +
"AccountName=xxxxxx;" +
"AccountKey=xxxxxxx";
public void executeProgram()
{
try
{
CloudStorageAccount account;
CloudBlobClient serviceClient;
CloudBlobContainer container;
CloudBlockBlob blob;
account = CloudStorageAccount.parse(storageConnectionString);
serviceClient = account.createCloudBlobClient();
// Container name must be lower case.
container = serviceClient.getContainerReference("gettingstarted");
container.createIfNotExist();
// Set anonymous access on the container.
BlobContainerPermissions containerPermissions;
containerPermissions = new BlobContainerPermissions();
containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
container.uploadPermissions(containerPermissions);
// Upload an image file.
blob = container.getBlockBlobReference("image");
File fileReference = new File ("www.xxx/a254.png");
blob.upload(new FileInputStream(fileReference), fileReference.length());
// At this point the image is uploaded.
// Next, create an HTML page that lists all of the uploaded images.
MakeHTMLPage(container);
System.out.println("Processing complete.");
System.out.println("Open index.html to see the images stored in your storage account.");
}catch (Exception e){
System.out.print("Exception encountered: ");
System.out.println(e.getMessage());
}
}
// Create an HTML page that can be used to display the uploaded images.
// This example assumes all of the blobs are for images.
public void MakeHTMLPage(CloudBlobContainer container) throws FileNotFoundException, URISyntaxException
{
// Enumerate the uploaded blobs.
for (ListBlobItem blobItem : container.listBlobs()) {
HTMLPanel b = new HTMLPanel("<img src='" + blobItem.getUri() + "'/><br/>");
RootPanel.get().add(b);
}
}
}
I'm not too familiar with Azure, but I highly suspect that the Azure Java SDK is to be used on the server side. There must be code in this SDK that is not emulated by GWT.
Any code that is not already emulated by GWT (see here for a list of emulated classes) must be accompanied by GWT-translatable sources (see <super-source/> here).

Delete a directory from Isolated storage windows phone 7

I created a directory named "MyFolder" and wrote some text files there. Now, I want delete that directory and I am using the following code:
public void DeleteDirectory(string directoryName)
{
try
{
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!string.IsNullOrEmpty(directoryName) && currentIsolatedStorage.DirectoryExists(directoryName))
{
currentIsolatedStorage.DeleteDirectory(directoryName);
textBox1.Text = "deleted";
}
}
}
catch (Exception ex)
{
// do something with exception
}
}
I tried with
DeleteDirectory("MyFolder")
DeleteDirectory("IsolatedStore\\MyFolder")
however it didn't delete that directory. Any idea to solve that?
Have you deleted all of the contents of that directory?
http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.deletedirectory(v=vs.80).aspx
says (although it isn't the windows phone version of the documentation):
A directory must be empty before it is deleted. The deleted directory cannot be recovered once deleted.
The Deleting Files and Directories example demonstrates the use of the DeleteDirectory method.

Resources