Get all Alfresco users (from Java AMP) - alfresco

I want to get the usernames (Strings) of all users in Alfresco.
My code is running as an AMP within Alfresco itself.
How to do that?
I tried using PersonService but it outputs no results, even though I have several users in Alfresco (created via the Share admin interface):
RunAsWork runAsWork = new RunAsWork() {
#Override
public Object doWork() throws Exception {
return personService.getPeople("*", null, null, new PagingRequest(1000));
}
};
PagingResults<PersonInfo> results =
(PagingResults<PersonInfo>) AuthenticationUtil.runAsSystem(runAsWork);
System.out.println("Number of users: " + results.getTotalResultCount());
while (results.hasMoreItems()) {
for (PersonInfo info : results.getPage()) {
System.out.println("User: " + info.getUserName());
}
}

PersonService personService = documentService.serviceRegistry.getPersonService();
PagingResults<PersonInfo> users = personService.getPeople("*", new ArrayList<QName>(), new ArrayList<Pair<QName,Boolean>>(), new PagingRequest(personService.countPeople()));
logger.info("The number of users in the system" + personService.countPeople());
do {
List<PersonInfo> personInfos = users.getPage();
for(PersonInfo personInfo : personInfos) {
logger.info("User Name: " + personInfo.getUserName());
}
} while(users.hasMoreItems());
This code will log all the users in alfresco

The people api returns list of users
http://server:port/alfresco/service/api/people
or try this by injecting
serviceRegistry
try {
Set<String> authorities = serviceRegistry.getAuthorityService().getAllAuthorities(AuthorityType.USER);
for (String authority : authorities) {
NodeRef person = serviceRegistry.getPersonService().getPerson(authority);
Map<QName, Serializable> properties = serviceRegistry.getNodeService().getProperties(person);
String fullName=properties.get(ContentModel.PROP_FIRSTNAME) +" "+properties.get(ContentModel.PROP_LASTNAME);
System.out.println("User Full Name "+fullName);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this will help you.

It might be an issue with the authentication from your amp, you may try this:
(PagingResults) AuthenticationUtil.runAs(runAsWork, AuthenticationUtil.getSystemUserName());
It is the same thing as you did but I had trouble with runAsSystem before on an old repo. Else there are more way of messing up with the person service here PersonService.PersonInfo

Related

How to display scores form Firebase

I have a quiz app and I would like to display scores on last screen, however I have an issue how to do it.
Here' how my score script looks like:
{
//Zliczanie punktów i wyświetlanie wyniku
public static int pointssum = 0;
public Text points;
private string user;
private Text scoresboard;
USers users = new USers();
void Start()
{
points = GetComponent<Text>();
Posttodb();
}
void Update()
{
points.text = "Poprawne odpowiedzi: " + pointssum;
}
private void Posttodb()
{
user = nazwagracza.Playernick;
if (user!= null)
{
USers users = new USers();
RestClient.Put("https://quizgame-inz.firebaseio.com/" + user + ".json", users);
}
}
private void Getdata()
{
RestClient.GetArray<USers>("https://quizgame-inz.firebaseio.com/.json?orderBy='scores'&startAt=0").Then(response =>
{
users = response;
});
}
}
I tried to assign this data to user value but I'm getting error cannot implicitly convert type.
Can you please help we with this?
users is of type USers .. it is not an array.
You did probably mean e.g.
// Returns an array of USers
RestClient.GetArray<USers>("https://quizgame-inz.firebaseio.com/.json?orderBy='scores'&startAt=0").Then(response =>
{
// get the first instance
users = response[0];
});
or make users of type
USers[] users;
depending on your needs.
Due to the naming and description it sounds like you would want to do the latter since you want to display all scores, not only the best one.

How to access already existing data in Realm cloud using Xamarin Forms?

I’m using Realm for my Xamarin forms App.I have synced my data in Sql server with Realm cloud.Now I want to view the data which is there in Realm cloud in my Xamarin Forms App.
I used code
public ListsViewModel()
{
LogoutCommand = new Command(Logout);
AddressCommand = new Command(AddList);
//TaskLists = new IQueryable<Address>();
IQueryable<Address> TaskLists = Enumerable.Empty<Address>().AsQueryable();
//AddList();
}
private void AddList()
{
_realm = Realm.GetInstance();
TaskLists = _realm.All<Address>();
TaskLists.Count();
}
My TaskLists.Count() gives 0.But my ROS has the data from sql server and they both are in sync.And I'm able to Login to my Realm Object Server through my Xamarin Forms App.But my Xamarin Forms app is not syncing with my ROS that is the data which is there in my Realm object server is not displaying in my APP.I want to display the data of Address class in my App.The data of address class is put through SQL server.I just Have to retrieve the data of Address class. I even tried using SyncConfiguration.
private async void AddList()
{
User user = null;
try
{
user = User.Current;
}
catch (Exception ex)
{
HandleException(ex);
}
if (user == null)
{
try
{
user = await NavigationService.Prompt<LoginViewModel, User>();
}
catch (Exception ex)
{
HandleException(ex);
}
}
else
{
var uri = user.ServerUri;
Constants.Server.SyncHost = $"{uri.Host}:{uri.Port}";
}
var config = new SyncConfiguration(user, Constants.Server.SyncServerUri)
{
ObjectClasses = new[] { typeof(Address) }
};
_realm = Realm.GetInstance(config);
//_realm = Realm.GetInstance();
TaskLists = _realm.All<Address>();
_realm.Write(() =>
{
_realm.Add(new Address { ID = 8, ZipCode = "Judson123" });
});
TaskLists.Count();
}
Still I’m not able to fix it.Please Help me with this.

Set a job to failed using Hangfire with ASP.NET?

I have an ASP.NET app which sends emails whenever the user signs up in the web site. I'm using hangfire in order to manage the jobs and postal in order to send emails.
It all works great, but here's the thing:
I want the superuser to change how many times the APP can send the email before deleting the job.
Here's my code
public static void WelcomeUser(DBContexts.Notifications not)
{
try{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(#"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
Postal.EmailService service = new Postal.EmailService(engines);
WelcomeUserMail welcomeUserMail = new WelcomeUserMail();
welcomeUserMail.To = not.ReceiverEmail;
welcomeUserMail.UserEmail = not.ReceiverEmail;
welcomeUserMail.From = BaseNotification.GetEmailFrom();
service.Send(welcomeUserMail);
}
catch(Exception e)
{
DBContexts.DBModel dbModel = new DBModel();
DBContexts.Notifications notificacionBD = dbModel.Notifications.Find(not.NotificationID);
notificacionBD.Status = false;
notificacionBD.Timestamp = DateTime.Now;
notificacionBD.Error = e.Message;
int numberOfRetriesAllowed = ParameterHelper.getNumberOfRetriesAllowed();
if (notificacionBD.Retries > numberOfRetriesAllowed)
{
//In this case Hangfire won't put this job in the failed section but rather in the processed section.
dbModel.SaveChanges();
}
else
{
notificacionBD.Retries++;
dbModel.SaveChanges();
throw new Exception(e.Message);
}
}
}
Why not just add attributes to handle it automatically?
[AutomaticRetry(Attempts = 10, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
public void MyTask(){
//doing stuff
}
Or you could just make your own attribute that mimics the AutommaticRetryAttribute class but you handle it how you want?
https://github.com/HangfireIO/Hangfire/blob/a5761072f18ff4caa80910cda4652970cf52e693/src/Hangfire.Core/AutomaticRetryAttribute.cs

Get property of person Alfresco in JAVA

I'm using Alfresco 5.1 Community, and i'm trying to get a property value of a current person logged for example, in the user I have:
"{http://www.someco.org/model/people/1.0}customProperty"
How can I obtain this in java?
Is a custom property, so, in http://localhost:8080/alfresco/service/api/people it does not appear. How can I do this?
I try this to obtain at least nodeRef:
protected ServiceRegistry getServiceRegistry() {
ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration();
if (config != null) {
// Fetch the registry that is injected in the activiti spring-configuration
ServiceRegistry registry = (ServiceRegistry) config.getBeans().get(ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
if (registry == null) {
throw new RuntimeException("Service-registry not present in ProcessEngineConfiguration beans, expected ServiceRegistry with key" + ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
}
return registry;
}
throw new IllegalStateException("No ProcessEngineConfiguration found in active context");
}
public void writeToCatalina() {
PersonService personService = getServiceRegistry().getPersonService();
System.out.println("test");
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println(name);
NodeRef personRef = personService.getPerson(name);
System.out.println(personRef);
}
But I got:
No ProcessEngineConfiguration found in active context
Help me !
You can query Alfresco using CMIS and call the API:
GET /alfresco/service/api/people/{userName}.
For first you can define the method to create the session CmisSession:
public Session getCmisSession() {
logger.debug("Starting: getCmisSession()");
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, url + ATOMPUB_URL);
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.AUTH_HTTP_BASIC, "true");
parameter.put(SessionParameter.USER, username);
parameter.put(SessionParameter.PASSWORD, password);
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
List<Repository> repositories = factory.getRepositories(parameter);
return repositories.get(0).createSession();
}
Then execute the query (this method returns more than one result, you probably need to change it):
public void doQuery(String cql, int maxItems) {
Session cmisSession = getCmisSession();
OperationContext oc = new OperationContextImpl();
oc.setMaxItemsPerPage(maxItems);
ItemIterable<QueryResult> results = cmisSession.query(cql, false, oc);
for (QueryResult result : results) {
for (PropertyData<?> prop : result.getProperties()) {
logger.debug(prop.getQueryName() + ": " + prop.getFirstValue());
}
}
}
If you need to get the token, use this:
public String getAuthenticationTicket() {
try {
logger.info("ALFRESCO: Starting connection...");
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("user", username);
params.put("password", password);
Source result = restTemplate.getForObject(url + AFMConstants.URL_LOGIN_PARAM, Source.class, params);
logger.info("ALFRESCO: CONNECTED!");
XPathOperations xpath = new Jaxp13XPathTemplate();
return xpath.evaluateAsString("//ticket", result);
}
catch (RestClientException ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
catch (Exception ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
}
You need to obtain your user noderef using this API then access its properties this way!
Edit : You need to inject service registry on your bean!
String name = AuthenticationUtil.getFullyAuthenticatedUser()
You can use this. Let me know if it works.
This will give you current logged in user name and detail.
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println("Current user:"+name);
PersonService personService=serviceRegistry.getPersonService();
NodeRef node=personService.getPerson(name);
NodeService nodeService=serviceRegistry.getNodeService();
Map<QName, Serializable> props=nodeService.getProperties(node);
for (Entry<QName, Serializable> entry : props.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}

Directory levels Quotas on remote shared folder

I have 2 servers in AD (2008R2)
On one of them I have shared folder (c:\Shared\dirForUserAAA ==> \DC1\dir1)
On other one I have c# program that must manage folder quota on \DC1\dir1
Is it possible and how it can be done?
I try to use this piece of code, but it works only on local paths :(
public static void SetQuotaToFolder(string UNCPathForQuota, int quotaLimitBytes)
{
if (!Directory.Exists(UNCPathForQuota))
{
Directory.CreateDirectory(UNCPathForQuota);
}
// Create our interface
IFsrmQuotaManager FSRMQuotaManager = new FsrmQuotaManagerClass();
IFsrmQuota Quota = null;
try
{
// First we need to see if there is already a quota on the directory.
Quota = FSRMQuotaManager.GetQuota(UNCPathForQuota);
// If there is quota then we just set it to our new size
Quota.QuotaLimit = quotaLimitBytes;
}
catch (COMException e)
{
unchecked
{
if (e.ErrorCode == (int)0x80045301)
{
// There is no quota on this directory so we need to create it.
Quota = FSRMQuotaManager.CreateQuota(UNCPathForQuota);
// And then set our desired quota
Quota.QuotaLimit = quotaLimitBytes;
}
else
{
// some other COM exception occured so we return the error
Console.WriteLine(e);
return;
}
}
}
catch (Exception e)
{
// Generic error handling would go here
Console.WriteLine(e);
return;
}
// and finally we commit our changes.
Quota.Commit();
}
}
Old Question, but if someone needs a hint:
Open a RemotePowershell on the server where your folders are saved. Then use the Cmdlets from here
Some code snippets:
Open Runspace:
public static Runspace CreateAndOpen(string domain, string username, string password, string computername)
{
string userName = username + "#" + domain;
var securePassword = password.ToSecureString();
PSCredential credential = new PSCredential(username, securePassword);
var connectionInfo = new WSManConnectionInfo(false, computername, 5985, "/wsman", shellUri, credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
connectionInfo.OpenTimeout = 2 * 60 * 1000; // 2 minutes
Runspace powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
powershellRunspace.Open();
return powershellRunspace;
}
Set a quota on a path
public void SetQuotaTemplateOnPath(Runspace runspace, string path, string template)
{
using (var pipe = runspace.CreatePipeline())
{
var newFsrmQuotaCommand = new Command("New-FsrmQuota");
newFsrmQuotaCommand.Parameters.Add("Path", path);
newFsrmQuotaCommand.Parameters.Add("Template", template);
newFsrmQuotaCommand.Parameters.Add("Confirm", false);
pipe.Commands.Add(newFsrmQuotaCommand);
var results = pipe.Invoke();
if (pipe.Error.Count > 0)
{
//Handle error
}
}
}

Resources