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,
Related
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;
}
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;
}
}
I am trying to send some userData while spawning a new instance but unfortunately it is not working. The code is:
For debugging purposes, I have just used an echo statement, but I cannot find any new file generated on the machine. I also checked the cloud-init logs in /var/log folder, but none of them are present.
Can anyone help me to figure out a way to debug this problem or is there something crucial that I am missing?
I am using C4.8xLarge instances for the reference.
public static String getUserData() throws UnsupportedEncodingException {
String userData = "";
userData = userData + "#!/bin/bash" + "\n";
userData += "echo hello > hello" + "\n";
String base64UserData = null;
try {
base64UserData = new String(Base64.encodeBase64(userData.getBytes("UTF-8")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return base64UserData;
}
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.setImageId(AMI_ID);
runInstancesRequest.setEbsOptimized(true);
runInstancesRequest.setInstanceType(INSTANCE_TYPE);
runInstancesRequest.setMinCount(1);
runInstancesRequest.setMaxCount(1);
runInstancesRequest.withSecurityGroups("JavaSecurityGroup1");
runInstancesRequest.withUserData(getUserData());
List<BlockDeviceMapping> map = new ArrayList<>();
map.add(new BlockDeviceMapping().withEbs(new EbsBlockDevice().withSnapshotId("snap-af8s67ef").withIops(9000).withVolumeSize(300).withVolumeType("io1")).withDeviceName("/dev/sdf"));
runInstancesRequest.withBlockDeviceMappings(map);
RunInstancesResult runInsRes = ec2.runInstances(runInstancesRequest);
Thanks!
After creating an instance, go into the EC2 web console and view the user data on the instance. You should be able to view it as plain text in the web console. If it isn't there, or if it contains something other than the two lines you are trying to set as the user data, then you will know there is an issue with the way you are setting the user data.
If it is there and looks correct, then you will need to look into the cloud-init service log /var/log/cloud-init-output.log on the created instance to see what the error is.
Edit: I just noticed you said the cloud-init logs are not present on the machine. What OS are you using for this server? It may not have the cloud-init service.
I am working on a samba client for Android. Given an IP address it should connect to it and browse the shared folders.
For this I use JCIFS. I dropped the jar in my Android project and added following code to connect to PC and get the list of files:
private void connectToPC() throws IOException {
String ip = "x.x.x.x";
String user = Constants.username + ":" + Constants.password;
String url = "smb://" + ip;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
SmbFile root= new SmbFile(url, auth);
String[] files = root.list();
for (String fileName : files) {
Log.d("GREC", "File: " + fileName);
}
}
And I get in return: jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
But the credentials are correct. I also tried with another samba client from the android market that uses JCIFS and it successfully connected to that ip, so obviously I am doing something wrong here but don't know what especially.
Any help is highly appreciated.
In the end I managed successfully to connect to PC. The issue turned out to be in the NtlmPasswordAuthentication(); constructor.
So, instead of this:
String user = Constants.username + ":" + Constants.password;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
I changed to this:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
Constants.username, Constants.password);
I don't know why, perhaps it's because of ":" special character, perhaps because of Android, but passing an empty domain name, the user name, and password separately to the constructor, solved the issue.
Since some people will get to this topic if they got a similar problem with android and JCIFS,
these are other common problems when trying to make it work:
*Put the .jar specifically in /libs folder of your android project (not just via "build path")
*Be sure that your project has internet permission What permission do I need to access Internet from an android application?
*Also be sure that your JCIFS code is running in a separate thread from the UI (in other words, use AsyncTask class) how to use method in AsyncTask in android?
*Code:
protected String doInBackground(String... params) {
SmbFile[] domains;
String username = USERNAME;
String password = PASSWORD;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
username, password);
try {
SmbFile sm = new SmbFile(SMB_URL, auth);
domains = sm.listFiles();
for (int i = 0; i < domains.length; i++) {
SmbFile[] servers = domains[i].listFiles();
for (int j = 0; j < servers.length; j++) {
Log.w(" Files ", "\t"+servers[j]);
}
}
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
these were the problems i encounter while trying to make work JCIFS on android, hope to help anyone, regards.
maybe i can help other people too.
I had the problem that i used thread.run() instead of thread.start() to execute the Smb-Code in a Runnable. I searched a lot of time for an answer but nothing fixed my problem.
But then a friend explained me the different between thread.run() and thread.start():
run(): Execute the Methode (for example the run() Methode of a Runnable) like a normal Method (synchronous)
start(): Start the Thread with the Runnable in an own task (asynchronous)
And for Smb you need a asynchronous Thread. Because of this you need to call thread.start()!
Maybe someone make the same mistake as i did.
I'm trying to configure twitter4j to stream tweets
I got (consumer key/secret, access token & access secret) from twitter already
I created a new java project and imported twiiter4j as a library
Now I want to know how to configure it ( http://twitter4j.org/en/configuration.html)
The first way :
Save a standard properties file named "twitter4j.properties". Place it to either the current directory, root of the classpath directory.
I'm using netbeans and want to know the file type I should choose when I create properties file and where exactly I have to place it?
Answer to your questions:
Select a normal text file type, add the contents and rename it to twitter4j.properties
You may place the file in the root folder of your project, or in any folder in the classpath. Just be sure the folder is in the classpath, thats what needs to be taken care of.
good day.
It's not a better way to use twitter4j.properties file in production for standalone application.
because you need to guarantee that no one from users can not read your secret keys.
In this reason, better to use configuration factory class with hardcoded secret keys and make configuration on the flow.
Check out this example it is for normal Twitter object but same method works for TwitterStream as well. Basically, use ConfigurationBuilder Twitter 4j with Netbeans.
Refer following code:
//Configuration for twitter4j
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*********************")
.setOAuthConsumerSecret("******************************************")
.setOAuthAccessToken("**************************************************")
.setOAuthAccessTokenSecret("******************************************");
//Example for fetching public tweets
//Sample which gives all tweets of Kim Kardarshian
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
int pageno = 1;
String user = "#KimKardashian";
List<Status> statuses = new ArrayList<Status>();
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
if (statuses.size() == size)
break;
}
catch(TwitterException e) {
e.printStackTrace();
}
}
//sample which gives "n" (here 10) tweets of particular user
try{
Twitter twitter = TwitterFactory.getSingleton();
Paging p = new Paging();
p.setCount(10);
statuses.addAll(twitter.getUserTimeline("user",p));
}catch(Exception e)
{ e.printStackTrace(); }
for (Status st:statuses) {
System.out.println(st.getText());
}