Run Alfresco Java code as Administrator - java

I'm trying to implement an action in which I will add permissions to all parent nodes. However, I need to run as admin to manage the permissions. Currently my code looks like this:
permissionService = serviceRegistry.getPermissionService();
//Read the username of the current user
final String loggedInUser = authenticationService.getCurrentUserName();
ChildAssociationRef childAssociationRef = nodeService.getPrimaryParent(actionedUponNodeRef);
//Get the parent NodeRef
NodeRef parent = childAssociationRef.getParentRef();
String fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
//Iterate till you get to document library
while(!fileName.contains("documentLibrary")){
ChildAssociationRef childAssociationRef2 = nodeService.getPrimaryParent(parent);
parent = childAssociationRef2.getParentRef();
//Have to declare a final variable in order to access it in the RunAsWork
final NodeRef ref = parent;
fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
RunAsWork<?> raw = new RunAsWork<Object>() {
public Object doWork() throws Exception {
//Set permission to this folder for the logged in user
permissionService.setPermission(ref, loggedInUser, PermissionService.CONTRIBUTOR, true);
return null;
}
};
//Run as admin
AuthenticationUtil.runAs(raw, "admin");
}
The exception that I get is pretty obvious:
SEVERE: 04210027 Access Denied. You do not have the appropriate permissions to perform this operation.
Any suggestions?
Thanks

To detail the answer from Krutik, you should wrap code in a runAsSystem block like this:
final permissionService = serviceRegistry.getPermissionService();
//Read the username of the current user
final String loggedInUser = authenticationService.getCurrentUserName();
ChildAssociationRef childAssociationRef = nodeService.getPrimaryParent(actionedUponNodeRef);
//Get the parent NodeRef
NodeRef parent = childAssociationRef.getParentRef();
String fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
//Iterate till you get to document library
while(!fileName.contains("documentLibrary")){
ChildAssociationRef childAssociationRef2 = nodeService.getPrimaryParent(parent);
parent = childAssociationRef2.getParentRef();
//Have to declare a final variable in order to access it in the RunAsWork
final NodeRef ref = parent;
fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
public Object doWork() throws Exception {
permissionService.setPermission(ref, loggedInUser, PermissionService.CONTRIBUTOR, true);
return "";
}
});
}

Try with AuthenticationUtil.runAsSystemmethod in alfresco.

AuthenticationUtil.runAsSystem(() -> {
// do your work
return null;
});

Related

Create website Tab in Teams using MS Graph Java

I'm trying to use Graph Api to create a tab in my Microsoft Teams Channel but I kept getting error about the program finished with non-zero exit value 1.
public static void createTab(){
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
TeamsTab newTab = new TeamsTab();
newTab.configuration.contentUrl = "https://www.google.com/?client=safari";
newTab.configuration.entityId = null;
newTab.configuration.removeUrl = null;
newTab.configuration.websiteUrl = "https://www.google.com/?client=safari";
newTab.displayName = "New Website Tab";
//Post New Tab
graphClient.teams("teams-id").channels("channel-id")
.tabs().buildRequest().expand("teamsApp").post(newTab);
}
This is my code, can someone please have a look?
Just for the heck of it, try this:
public void createTab() {
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
TeamsTab newTab = new TeamsTab();
User me = newTab.graphClient.getMe().buildRequest().get();
newTab.configuration.contentUrl = "https://www.google.com/?client=safari";
newTab.configuration.entityId = null;
newTab.configuration.removeUrl = null;
newTab.configuration.websiteUrl = "https://www.google.com/?client=safari";
newTab.displayName = "New Website Tab";
//Post New Tab
newTab.graphClient.getMe().teams("teams-id").channels("channel-id")
.getTab().buildRequest().post();
}
```

Is there any ways to save image to Salesforce by using Salesforce APEX

We are integrating WSO2 ESB with Salesforce. We need to insert image into Salesforce Object(Lead). Images are downloaded in some directory. i want to know efficient ideas to complete this task.i have some ideas like
Convert image to Base64 Encoding, then send request to Salesforce APEX.
Insert Image as BLOB into Database,then fetch that BLOB from DB, stores into byte array and finally push that into Salesforce.
But i don't know best and efficient way to do this. If you have some ideas/possibilities kindly share it to me.
Note: For writing Salesforce related task, separate SF Team is here. what i need here is ways/possibilities to achieve this task. Java Class also possible.
Awaiting for your response!!!
You can save it as content version, Now a days Attachments are deprecated.
public with sharing class ContentVersionUtil {
public ContentVersionUtil() {
}
public static Id createDocument(Id parentId, String fileName, String data, Id contentDocumentId) {
ContentVersion versionData = new ContentVersion();
versionData.ContentLocation = 'S';
versionData.ContentDocumentId = contentDocumentId;
versionData.VersionData = Blob.valueOf(data);
versionData.Title = fileName;
versionData.PathOnClient = filename;
insert versionData;
ContentDocumentLink conDocLink = new ContentDocumentLink();
conDocLink.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :versionData.Id].ContentDocumentId;
conDocLink.LinkedEntityId = parentId;
conDocLink.ShareType = 'V';
insert conDocLink;
return conDocLink.Id;
}
public static Id createDocument(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
public static Id createDocumentafterformat(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
}
Test class:
#isTest
public with sharing class ContentVersionUtilTest {
#TestSetup
static void makeData(){
Account acc = new Account (Name = 'Test Account');
insert acc;
Contact cont = new Contact (LastName = 'Raj', AccountId = acc.Id);
insert cont;
}
#isTest
static void test_content_version_creation_0 () {
Contact eachContact = [SELECT Id from Contact LIMIT 1];
ContentVersionUtil util = new ContentVersionUtil ();
Id conDocLinkId = ContentVersionUtil.createDocument(eachContact.Id, 'testFile', 'csv', 'Some important Data');
System.assertEquals(eachContact.Id, [SELECT Id, LinkedEntityId from ContentDocumentLink WHERE Id =: conDocLinkId].LinkedEntityId);
}
}

in Realm, Why is SyncUser.logInAsync() not entering onSuccess() or onError()?

I am currently trying to login to create a login to realm, but I am unable to access a SyncUser because my logInAsync is not entering the onSuccess or onError method. The onSuccess method returns a SyncUser, but this is not occurring. My code is
String authURL = "https://my-realm.us1a.cloud.realm.io";
String email = "testemail#gmail.com";
String password = "testPassword";
SyncCredentials credentials = SyncCredentials.usernamePassword(email, password, true);
RealmAsyncTask task = SyncUser.logInAsync(credentials, authURL, new SyncUser.Callback<SyncUser>() {
#Override
public void onSuccess(SyncUser result) {
user = result;
}
#Override
public void onError(ObjectServerError error) {
System.out.println("failed");
}
});
String url = "realms://unbranded-metal-bacon.us1a.cloud.realm.io/~/travelin";
config = user.createConfiguration(url).build();
I have a private SyncUser user declared above. In the last line, I am getting a null object reference because user is null. What is the reason that I am not entering onSuccess or onError?
Auth URL is wrong, need to be
String authURL = "https://my-realm.us1a.cloud.realm.io/auth";
Also, SyncUser.logInAsync() runs in background so this line need to be inside onSuccess(), otherwise User will be null
config = user.createConfiguration(url).build();

JPA.em().find returns null for existing object

I have a problem with JPA in play framework 2.1. Here is my situation:
I have action method which handles sign up for my application (User fills email and password and submits the form). In this method I check if the user exists in my database and if not I create new one. Here is simplified code which shows how it works:
public Result signUpSubmit(String email, String password) {
User existingUser = (User) User.find("SELECT u FROM User u WHERE u.email=?", email).get(0);
if (existingUser != null) {
// code which handles existing user
} else {
User newUser = new User(email, password);
Users.persistUserAsync(newUser); // calls JPA.em().persist(newUser) asynchronously
// but I wait until the save is done
// After this call I have new row in DB with newUser (with assigned id)
System.out.println(newUser.id); // prints id which was assigned to new user in DB
User u = (User)JPA.em().find(User.class, newUser.id)
System.out.println(u.id); // throws NullPointer exception, because u is null
}
return renderJapid();
}
Can you tell me the reason why I get the null from the second find query?
public boolean persistUserAsync(User) {
final ModelCreatingJob modelCreatingJob = new ModelCreatingJob(user);
final Promise<Boolean> promisedSave = modelCreatingJob.now();
final Boolean saved = promisedSave.get(20000L);
return saved;
}
The ModelCreatingJob does only this:
return JPA.withTransaction(new F.Function0<Boolean>() {
#Override
public Boolean apply() throws UserLockedException, UserNotFoundException {
return model.validateAndCreate();
}
});
Strange is that when I remove first find (just leave newUser = null) on second find I get valid user object.

YouTube API: How to obtain text of Related videos, given a video's URL?

I have a pretty straight forward task -
Given the URL of a video, I want to extract information of its Related videos (and by information I mean their Title, Tags, Description).
I use Java version of the YouTube API and couldn't find out how to do that quickly. Also, this site: https://developers.google.com/youtube/2.0/developers_guide_java provides some information. The code they provide is:
if (videoEntry.getRelatedVideosLink() != null) {
String feedUrl = videoEntry.getRelatedVideosLink().getHref();
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);
}
I don't know how to create a videoEntry given only the URL..
You can use this:
class YouTubeVideoInfo {
private String channel;
private String url;
private long views;
private int comments;
private int ratings;
private int likes;
private int dislikes;
private String thumbnail;
private String title;
.....
}
public static final String YOUTUBE_GDATA_SERVER = "http://gdata.youtube.com";
public static final String USER_FEED_PREFIX = YOUTUBE_GDATA_SERVER + "/feeds/api/users/";
public static final String UPLOADS_FEED_SUFFIX = "/uploads";
...............
public YouTubeVideoInfo getVideoInfo(YouTubeService service, String channel, String url) {
VideoFeed videoFeed = service.getFeed(
new URL(USER_FEED_PREFIX + channel + UPLOADS_FEED_SUFFIX), VideoFeed.class);
List<VideoEntry> videoEntries = videoFeed.getEntries();
for (VideoEntry videoEntry : videoEntries) {
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
if (mediaGroup != null && mediaGroup.getPlayer() != null && videoEntry.getTitle() != null) {
if (url.equals(mediaGroup.getPlayer().getUrl())) {
String title = videoEntry.getTitle().getPlainText();
MediaKeywords keywords = mediaGroup.getKeywords();
MediaPlayer mediaPlayer = mediaGroup.getPlayer();
final YtStatistics statistics = videoEntry.getStatistics();
final YouTubeVideoInfo videoInfo = new YouTubeVideoInfo(channel,
mediaPlayer.getUrl(), statistics != null
? statistics.getViewCount() : 0);
if (videoEntry.getComments() != null
&& videoEntry.getComments().getFeedLink() != null)
videoInfo.comments =
videoEntry.getComments().getFeedLink().getCountHint();
final Rating rating = videoEntry.getRating();
if (rating != null)
videoInfo.ratings = rating.getNumRaters();
final YtRating ytRating = videoEntry.getYtRating();
if (ytRating != null) {
videoInfo.likes = ytRating.getNumLikes();
videoInfo.dislikes = ytRating.getNumDislikes();
}
final List<MediaThumbnail> thumbnails = mediaGroup.getThumbnails();
if (!thumbnails.isEmpty())
videoInfo.thumbnail = thumbnails.get(thumbnails.size() / 2).getUrl();
if (videoEntry.getTitle() != null)
videoInfo.title = videoEntry.getTitle().getPlainText();
return videoInfo;
}
}
.... // exception handling
I have got a method to do what I intended to. I did not require name of the Channel (username that uploaded the video). All I need is a URL. YouTube has an ID corresponding to each video. For example, for the video: http://www.youtube.com/watch?v=f3q3JkNUPmI , the ID is "f3q3JkNUPmI" (without the quotes). So, all you need to do is to create a String containing the feed link that you want to get. This can be created as:
String Video_Related_Feed="https://gdata.youtube.com/feeds/api/videos/f3q3JkNUPmI/related?v=2" (don't replace https with http -- it does not work)
Obviously, one can automate this .. I'm just giving the hard-coded example.
Now get the actual Feed based on this address:
VideoFeed videoFeed = service.getFeed(new URL(Video_Related_Feed), VideoFeed.class);
This feed contains VideoEntry of the Related videos (corresponding to our original URL), each of which can be accessed by a for loop:
for (VideoEntry ve : videoFeed.getEntries()) { insert your code here }
References: https://developers.google.com/youtube/2.0/reference
andhttps://developers.google.com/youtube/2.0/developers_guide_java
(sorry, I had to write last link like that because I couldn't post more than 2 URLs).
I hope this helps someone.

Categories

Resources