Sharepoint search file and copy from one location to another - java

String searchFile = "fileName.txt";
GraphServiceClient graphClient = (GraphServiceClient) GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
User me = graphClient.me().buildRequest().get();
ISiteRequestBuilder siteReq = graphClient.sites("sharepointSiteId");
IDriveRequestBuilder driveReq = siteReq.drive();
IDriveItemRequestBuilder driveRootReq = driveReq.root();
IDriveItemRequestBuilder source = driveRootReq.itemWithPath("sourcePath");
IDriveItemRequestBuilder destination = driveRootReq.itemWithPath("destinationPath");
IDriveItemCollectionRequestBuilder childrenReq = source.children();
String sourceId = source.buildRequest().get().id;
String destinationId = destination.buildRequest().get().id;
IDriveItemSearchCollectionPage searchResult = source.search(searchFile).buildRequest().get();
DriveItem fileResult = null;
for(DriveItem driveItem : searchResult.getCurrentPage()){
fileResult = driveItem;
}
if(fileResult!=null){
ItemReference parentReference = new ItemReference();
parentReference.id = destinationId;
driveReq.items(fileResult.id).copy(searchFile, parentReference).buildRequest().post();
}
I have this Java code to search a file on a sharepoint site location and copy it to another one.
It works ok but it has a bug, I cannot seem to be able to limit the search only to the source path and instead the search the whole site for the files with that name, so if I got multiple files with that name in the site it will bring them all in the results and that can mess up my copy.
Any one can help me solve this?
PS. if you have any pointers also to optimise this code they are also welcome.

Related

Java MicrosoftGraph Sharepoint search file in Other User Drive

Hi Guys i need some help, i got a super user in sharepoint and drive,
I need to create a application in java that when a username and filename is passed to it, will go into the users drive and look for the filename passed and return the file-Id for it. i by chance the user has multiple files with the same name i need to return the latest one.
I have tried multiple ways but it does not seem to work
here is a copy of my code
GraphServiceClient graphClient = (GraphServiceClient) GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
IDriveItemRequestBuilder sDriveReq = graphClient.users(userEmail).drive().root();
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
IDriveItemSearchCollectionRequest searchRequest = sDriveReq.search(encodedFileName).buildRequest();
IDriveItemSearchCollectionPage searchResult = searchRequest.get();
DriveItem fileResult = null;
for (DriveItem driveItem : searchResult.getCurrentPage()) {
fileResult = driveItem;
}

fetching files from SFTP

I want to fetch files from SFTP which are created after a given timestamp(time of last pull) in java. I am using j2ssh as of now. Please let me know if some other API supports such a feature.
Jsch supports the ls command which will bring you back all the attributes of the remote file. You can write a little code to eliminate the files you want to retrieve from there.
Java Doc: http://epaul.github.io/jsch-documentation/javadoc/
This example compares the remote file timestamps to find the oldest file, it wouldn't be much of a stretch to modify it to compare your last run date against the remote file date, then do the download as part of the loop.
Code from Finding file size and last modified of SFTP file using Java
try {
list = Main.chanSftp.ls("*.xml");
if (list.isEmpty()) {
fileFound = false;
}
else {
lsEntry = (ChannelSftp.LsEntry) list.firstElement();
oldestFile = lsEntry.getFilename();
attrs = lsEntry.getAttrs();
currentOldestTime = attrs.getMTime();
for (Object sftpFile : list) {
lsEntry = (ChannelSftp.LsEntry) sftpFile;
nextName = lsEntry.getFilename();
attrs = lsEntry.getAttrs();
nextTime = attrs.getMTime();
if (nextTime < currentOldestTime) {
oldestFile = nextName;
currentOldestTime = nextTime;
}
}

Listing public folders

I'm writing a program for importing contacts from an ERP system to Outlook. Different emails will receive different lists of contacts from ERP. The idea here is, in each email I have a public contact folder that can be accessed by a technical user. The technical user can write contacts into this folder. Here is the code for searching the folder:
protected FolderId findFolderId(String folderDisplayName, String userEmail) throws Exception {
Mailbox userMailbox = new Mailbox(userEmail);
FolderId contactRootFolder = new FolderId(WellKnownFolderName.Root, userMailbox);
FolderId result = null;
FolderView view = new FolderView(Integer.MAX_VALUE);
view.setPropertySet(new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName));
view.setTraversal(FolderTraversal.Deep);
FindFoldersResults findFolderResults = this.service.findFolders(contactRootFolder, view);
//find specific folder
for (Folder f : findFolderResults) {
if (folderDisplayName.equals(f.getDisplayName())) {
result = f.getId();
}
}
return result;
}
The service object is created as follows:
this.service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(userName, passWord);
this.service.setCredentials(credentials);
try {
this.service.setUrl(new URI(URL));
} catch (URISyntaxException e) {
LOGGER.error(e);
}
Where URL is the end point for the Exchange server (for Office 365 it is https://outlook.office365.com/EWS/Exchange.asmx).
The code works with Office 2010, I get the Id from that folder, connect to it and save the contacts. After the migration to Office 365, we can't find the public folder. It can just find a folder with the name "PeoplePublicData". (I don't even know that folder exists.)
Throttling in Office365 means your code will only return the first 1000 folder in the Mailbox so if what your looking for isn't within that result set that would be one reason. I would suggest you get rid of
FolderView view = new FolderView(Integer.MAX_VALUE);
and change it to
FolderView view = new FolderView(1000);
and then page the results https://msdn.microsoft.com/en-us/library/office/dn592093(v=exchg.150).aspx which will allow you to get all the Folder in a Mailbox. Also unless you are looking for something in the Non_IPM_Subtree of the Mailbox start the search with MsgFolderRoot eg
FolderId contactRootFolder = new FolderId(WellKnownFolderName.MsgFolderRoot, userMailbox);
That will reduce the number of folders returned.
Also why don't you use a SearchFilter to search for the folder you are after eg https://msdn.microsoft.com/en-us/library/office/dd633627(v=exchg.80).aspx this would eliminate the need to page the results,

Overriding authentication behavior in jclouds

I'm looking to leverage RackSpace's CloudFiles platform for large object storage (word docs, images, etc). Following some of their guides, I found a useful code snippet, that looks like it should work, but doesn't in my case.
Iterable<Module> modules = ImmutableSet.<Module> of(
new Log4JLoggingModule());
Properties properties = new Properties();
properties.setProperty(LocationConstants.PROPERTY_ZONE, ZONE);
properties.setProperty(LocationConstants.PROPERTY_REGION, "ORD");
CloudFilesClient cloudFilesClient = ContextBuilder.newBuilder(PROVIDER)
.credentials(username, apiKey)
.overrides(properties)
.modules(modules)
.buildApi(CloudFilesClient.class);
The problem is that when this code executes, it tries to log me in the IAD (Virginia) instance of CloudFiles. My organization's goal is to use the ORD (Chicago) instance as primary to be colocated with our cloud and use DFW as a back up environment. The login response results in the IAD instance coming back first, so I'm assuming JClouds is using that. Browsing around, it looks like the ZONE/REGION attributes are ignored for CloudFiles. I was wondering if there is any way to override the code that comes back for authentication to loop through the returned providers and choose which one to login to.
Update:
The accepted answer is mostly good, with some more info available in this snippet:
RestContext<CommonSwiftClient, CommonSwiftAsyncClient> swift = cloudFilesClient.unwrap();
CommonSwiftClient client = swift.getApi();
SwiftObject object = client.newSwiftObject();
object.getInfo().setName(FILENAME + SUFFIX);
object.setPayload("This is my payload."); //input stream.
String id = client.putObject(CONTAINER, object);
System.out.println(id);
SwiftObject obj2 = client.getObject(CONTAINER,FILENAME + SUFFIX);
System.out.println(obj2.getPayload());
We are working on the next version of jclouds (1.7.1) that should include multi-region support for Rackspace Cloud Files and OpenStack Swift. In the meantime you might be able to use this code as a workaround.
private void uploadToRackspaceRegion() {
Iterable<Module> modules = ImmutableSet.<Module> of(new Log4JLoggingModule());
String provider = "swift-keystone"; //Region selection is limited to swift-keystone provider
String identity = "username";
String credential = "password";
String endpoint = "https://identity.api.rackspacecloud.com/v2.0/";
String region = "ORD";
Properties overrides = new Properties();
overrides.setProperty(LocationConstants.PROPERTY_REGION, region);
overrides.setProperty(Constants.PROPERTY_API_VERSION, "2");
BlobStoreContext context = ContextBuilder.newBuilder(provider)
.endpoint(endpoint)
.credentials(identity, credential)
.modules(modules)
.overrides(overrides)
.buildView(BlobStoreContext.class);
RestContext<CommonSwiftClient, CommonSwiftAsyncClient> swift = context.unwrap();
CommonSwiftClient client = swift.getApi();
SwiftObject uploadObject = client.newSwiftObject();
uploadObject.getInfo().setName("test.txt");
uploadObject.setPayload("This is my payload."); //input stream.
String eTag = client.putObject("jclouds", uploadObject);
System.out.println("eTag = " + eTag);
SwiftObject downloadObject = client.getObject("jclouds", "test.txt");
System.out.println("downloadObject = " + downloadObject.getPayload());
context.close();
}
Use swift as you would Cloud Files. Keep in mind that if you need to use Cloud Files CDN stuff, the above won't work for that. Also, know that this way of doing things will eventually be deprecated.

How to download a file from TestResource using JAVA OTA (COM4J)

Actually I need to download the XLS file from Test Resource using Resource ID in java
Can any one help me out Please
I tried with below pece of code but m missing something on it
IQCResourceFolderFactory rft = tdc.queryInterface(IQCResourceFolderFactory.class)​;
Com4jObject dfe = rft.item(3252);
IQCResourceFactory fds = dfe.queryInterface(IQCResourceFactory.class);
IList C = fds.newList("");
System.out.println(C.count());
above code throw me "Null pointer exception in Com4jObject dfe = rft.item(3252);
Please Help
Thanks in advance
Successfully downloaded the desired files from Test Resources by providing Resource Folder ID
Here is the working source code :
ITDConnection6 QCConnection = ClassFactory.createTDConnection();
QCConnection object should be declared with ITDConnection6 to access all QC attributes
IQCResourceFolderFactory resourceFolderFactory = QCConnection.qcResourceFolderFactory().queryInterface(IQCResourceFolderFactory.class);
IList folders = resourceFolderFactory.newList("");
for(Com4jObject rec : folders)
{
IQCResourceFolder resourceFolder = rec.queryInterface(IQCResourceFolder.class);
if(resourceFolder.id().toString().equals(properties.getProperty("ResourceFolderID")))
{
Com4jObject objResourceFactory = resourceFolder.qcResourceFactory();
IQCResourceFactory resourceFactory = objResourceFactory.queryInterface(IQCResourceFactory.class);
IList resources = resourceFactory.newList("");
for(Com4jObject objResource : resources)
{
IQCResource resource = objResource.queryInterface(IQCResource.class); ;
IResourceStorage resourceStorage = resource.queryInterface(IResourceStorage.class);
resourceStorage.downloadResource("D:\\", true);
}
}
}

Categories

Resources