I have a scheduler job configured and created an action class by extending org.quartz.StatefulJob
In execute method of Action Class (Shown below) , What would be the best way to get reference to CompanyHome in execute method ?
My objctive to create a file in company home directory , when the action invoke. Any suggesion ?
Have you tried using NodeLocatorService?
https://docs.alfresco.com/4.0/concepts/node-locator-available.html.
For example:
NodeRef companyHomeNodeRef = registry.getNodeLocatorService().getNode(CompanyHomeNodeLocator.NAME, null, null);
Please implement a method like this
public NodeRef getCompanyHomeNodeReference() {
NodeRef companyHomeNodeRef = null;
companyHomeNodeRef = (NodeRef)AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
public Object doWork() throws Exception {
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore"));
ResultSet rs = serviceRegistry.getSearchService().query(storeRef, SearchService.LANGUAGE_XPATH,
"/app:company_home");
Object companyHome = null;
try {
if (rs.length() == 0) {
LOG.error("Didn't find Company Home ");
throw new AlfrescoRuntimeException("Didn't find Company Home");
}
final NodeRef companyHomeNodeRef1 = rs.getNodeRef(0);
if(companyHomeNodeRef1 == null) {
LOG.info("Didn't find Company Homes");
}else {
companyHome = companyHomeNodeRef1;
}
} finally {
rs.close();
}
return companyHome;
}
});
return companyHomeNodeRef;
}
import as below:
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.repository.StoreRef;
please see how the critical code is placed in AuthenticationUtil (this is very important).
And then use below code to create a file:
fileFolderService.create(companyNodeRef, "yourfilename", ContentModel.TYPE_CONTENT);
Add this bean in service-context.xml
<bean id="yourObj" class="MoveMonthlyDataAction">
<property name="serviceRegistry">
<ref bean="ServiceRegistry" />
</property>
</bean>
and mention in MoveMonthlyDataAction . java as below,
public class MoveMonthlyDataAction {
ServiceRegistry serviceRegistry;
public void execute(){
// your code
}
// getter and setter
}
Hope this will help.
Related
I am working on drool dtable xls file with spring.
i have implemented the business rules in xls file using external location and then with the help of kie services i am executing rules.
Following is the code snippet that's how i am loading rules in engine.
at the start of spring initialization i am calling init() method
see below spring configuration.
<bean id="droolsService" class="com.example.drools.DroolsServiceImpl" init-method="init">
Java Code
public void init() {
LOG.info("inside init");
KieSession kieSession;
for (RequestType type : droolsMap.keySet()) {
try {
kieSession = getKieSession(this.getDroolsMap().get(type));
droolsRules.put(type, kieSession);
} catch (Exception e) {
LOG.error("Failed to load kiesession:", e);
throw new RuntimeException(e);
}
}
}
private KieSession getKieSession(final String file) throws DroolsParserException, IOException, BiffException {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
InputStream stream = null;
String drl = null;
String RULE_PATH = "src/main/resources/";
SpreadsheetCompiler converter = new SpreadsheetCompiler();
//Workbook workbook = Workbook.getWorkbook(DroolsServiceImpl.class.getResourceAsStream(file));
Workbook workbook = Workbook.getWorkbook(new FileInputStream(file));
LOG.info("Loading rule file " + file);
for (Sheet sheet : workbook.getSheets()) {
LOG.info("Loading Sheet " + sheet.getName());
stream = new FileInputStream(file);
drl = converter.compile(stream, sheet.getName());
//StringReader reader = new StringReader(drl);
String DRL_FILE = RULE_PATH + sheet.getName() + ".drl";
System.out.println("Drool file added ::: " + DRL_FILE);
kfs.write(DRL_FILE, ResourceFactory.newReaderResource(new StringReader(drl)));
stream.close();
}
KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
KieSessionConfiguration conf = SessionConfiguration.newInstance();
KieSession ksession = kieContainer.newKieSession(conf);
if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
StringBuilder sb = new StringBuilder("Errors:");
for (Message msg : errors) {
sb.append("\n " + msg);
}
try {
throw new Exception(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null)
stream.close();
if (workbook != null)
workbook.close();
}
}
return ksession;
}
Everything working perfect but the problem is i am not able to scan the file changes. If files is modified then i have to restart the server in order to sync the changes.
I have tried listener to load specific init() method after xls dtable has any changes but its not working , same old result is coming.
I have tried kiescanner but i am not able to get the concept.
KieScanner is loading maven kjar so how do i suppose to create kjar.
I just wanted to kie api scan if any changes in the drool file and try to reload whole changes in kiecontainer without server restarting.
Found the answer myself, Posting because it will help someone who needed.
What I did , I have used apache VFS File Monitor-
DefaultFileMonitor fm = new DefaultFileMonitor(new CustomFileListener());
When file will modified , create or get deleted it will call CustomFileListener.
Following is the implementation of CustomFileListener.
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class CustomFileListener implements FileListener {
private static final Logger LOG = LoggerFactory.getLogger(CustomFileListener.class);
#Override
public void fileCreated(FileChangeEvent fileChangeEvent) throws Exception {
}
#Override
public void fileDeleted(FileChangeEvent fileChangeEvent) throws Exception {
}
#Override
public void fileChanged(FileChangeEvent fileChangeEvent) throws Exception {
LOG.debug(" Under FileChanged Method");
LOG.debug(" File has been changed hence reinitializing init method = " + fileChangeEvent.getFile().getName().getPath());
XmlWebApplicationContext xmlWebApplicationContext =
(XmlWebApplicationContext) ContextLoader.getCurrentWebApplicationContext();
DefaultListableBeanFactory defaultListableBeanFactory =
(DefaultListableBeanFactory) xmlWebApplicationContext.getBeanFactory();
DroolsServiceImpl droolsService = (DroolsServiceImpl) defaultListableBeanFactory.getBean("droolsService");
droolsService.init();
}
}
What i did when the file will change, It will call fileChanged method.
In that i have fetched cached bean(DroolServiceImpl) from ContextLoader.getCurrentWebApplicationContext(); and called its init() method.
So this it will reload whole process and reinitialize the KieModule,KieRepository.
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());
}
I wrote my app that reads RSS feed. It works super with one channel which I have in beans.xml like this:
<feed:inbound-channel-adapter id="news"
channel="inputRssFeedChannel"
url="http://feeds.feedburner.com/Techcrunch">
<int:poller fixed-rate="5000" max-messages-per-poll="100"/>
</feed:inbound-channel-adapter>
<int:service-activator input-channel="inputRssFeedChannel"
ref="rssPrintOutService"
method="printRss"
output-channel="nullChannel"/>
Every time it just calls RssHandler which deal with SyndEntry. But what should I do if I'd like to read few rss urls (2,5,20 or etc...)?
Create your own implementation of org.springframework.integration.core.MessageSource and use it in input-channel reference like the following:
<int:inbound-channel-adapter id="newsInput" ref="newsReader">
<int:poller fixed-rate="1" time-unit="SECONDS" max-messages-per-poll="1"/>
</int:inbound-channel-adapter>
<bean id="newsReader" class="blog.NewsReader">
<property name="fetcherListener">
<bean class="blog.helper.FetcherEventListenerImpl"/>
</property>
<property name="urls">
<list>
<value>http://www.gridshore.nl/feed/</value>
<value>https://spring.io/blog.atom</value>
<value>http://feeds.foxnews.com/foxnews/video?format=xml</value>
</list>
</property>
</bean>
The class NewsReader uses list mentioned in urls propriety and retrieve the feed.
Please refer to the receive method below.
public class NewsReader implements MessageSource, InitializingBean {
private static Logger logger = LoggerFactory.getLogger(NewsReader.class);
private FeedFetcherCache feedInfoCache;
private FeedFetcher feedFetcher;
private FetcherListener fetcherListener;
private List<String> urls;
#Override
public Message receive() {
List<SyndFeed> feeds = obtainFeedItems();
return MessageBuilder.withPayload(feeds)
.setHeader("feedid", "newsfeed").build();
}
private List<SyndFeed> obtainFeedItems() {
List<SyndFeed> feed = new ArrayList<>();
try {
for (String url : urls) {
feed.add(feedFetcher.retrieveFeed(new URL(url)));
}
} catch (IOException e) {
logger.error("IO Problem while retrieving feed", e);
} catch (FeedException e) {
logger.error("Feed Problem while retrieving feed", e);
} catch (FetcherException e) {
logger.error("Fetcher Problem while retrieving feed", e);
}
return feed;
}
#Override
public void afterPropertiesSet() throws Exception {
feedInfoCache = HashMapFeedInfoCache.getInstance();
feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
if (fetcherListener != null) {
feedFetcher.addFetcherEventListener(fetcherListener);
}
}
public void setFetcherListener(FetcherListener fetcherListener) {
this.fetcherListener = fetcherListener;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
In case you want to take a look of my complete code:
git clone https://github.com/BikashShaw/MultipleRSSFeedRead.git
Issues with custom workflow activity in CRM 2013 On-prem
I'm trying to pass the Manager of the System
here is the code that I'm running, it gets to setting the MANAGER and stops
I put the ran the FetchXML seperatly and it does return a value so I know what bit works
public class CaseAccountManagerManagersLookup : CodeActivity
{
// Inputs
[Input("Enter Case")]
[ReferenceTarget("incident")]
public InArgument<EntityReference> CA { get; set; }
// Outputs
[Output("Manager Output")]
[ReferenceTarget("systemuser")]
public OutArgument<EntityReference> AMOUT { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
// Context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//Create the tracing service
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
// get the account and renewals manager ID's
var CASE = CA.Get<EntityReference>(executionContext);
tracingService.Trace("Case ID = " + CASE.Id);
try
{
// FETCH
string fetchXml = string.Format(#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='incident'>
<attribute name='title' />
<attribute name='incidentid' />
<order attribute='title' descending='false' />
<filter type='and'>
<condition attribute='incidentid' operator='eq' value='{0}' />
</filter>
<link-entity name='contact' from='contactid' to='customerid' alias='ak'>
<link-entity name='account' from='accountid' to='parentcustomerid' alias='al'>
<link-entity name='systemuser' from='systemuserid' to='bc_dssalesperson' alias='am'>
<attribute name='parentsystemuserid' />
</link-entity>
</link-entity>
</link-entity>
</entity>
</fetch>", CASE.Id);
EntityCollection case_results = service.RetrieveMultiple(new FetchExpression(fetchXml));
//tracingService.Trace("fetch has run");
if (case_results.Entities.Count != 0)
{
foreach (var a in case_results.Entities)
{
//if (a.Attributes.Contains("ai_parentsystemuserid"))
//{
tracingService.Trace("set manager id next");
var MANAGERID = (EntityReference)a.Attributes["parentsystemuserid"];
tracingService.Trace("manager id set");
AMOUT.Set(executionContext, MANAGERID);
throw new InvalidOperationException("Want to see trace");
//}
}
}
tracingService.Trace("end ");
}
catch (Exception e)
{
throw new InvalidPluginExecutionException("Plugin - CaseAccountManagerManagerLookup - " + e.Message);
}
finally
{
throw new InvalidOperationException("Want to see trace");
}
}
}
Try to use am.parentsystemuserid instead of just parentsystemuserid.
Are you sure that the guid that you are passing is in the correct form?
{8B8099A6-8B89-E411-883D-D89D676552A0}
this is what i get from the export but you are writing
8B8099A6-8B89-E411-883D-D89D676552A0
Also are you sure about the record that you are trying to retrieve? Is the chain complete with data?
case-> contact -> account -> parent user -> parent user ?
I'm having some serious issues with Fluent Nhibernate in my ASP.NET WebForms app when trying to modify a child object and then saving the parent object.
My solution is currently made of 2 projects :
Core : A class library where all entities & repositories classes are located
Website : The ASP.NET 4.5 WebForms application
Here is my simple mapping for my Employee object:
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.DateCreated);
Map(x => x.Username);
Map(x => x.FirstName);
Map(x => x.LastName);
HasMany(x => x.TimeEntries).Inverse().Cascade.All().KeyColumn("Employee_id");
}
}
Here is my my mapping for the TimeEntry object:
public class TimeEntryMap : ClassMap<TimeEntry>
{
public TimeEntryMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.DateCreated);
Map(x => x.Date);
Map(x => x.Length);
References(x => x.Employee).Column("Employee_id").Not.Nullable();
}
}
As stated in the title, i'm using one session per request in my web app, using this code in Gobal.asax:
public static ISessionFactory SessionFactory = Core.SessionFactoryManager.CreateSessionFactory();
public static ISession CurrentSession
{
get { return (ISession)HttpContext.Current.Items["current.session"]; }
set { HttpContext.Current.Items["current.session"] = value; }
}
protected Global()
{
BeginRequest += delegate
{
System.Diagnostics.Debug.WriteLine("New Session");
CurrentSession = SessionFactory.OpenSession();
};
EndRequest += delegate
{
if (CurrentSession != null)
CurrentSession.Dispose();
};
}
Also, here is my SessionFactoryManager class:
public class SessionFactoryManager
{
public static ISession CurrentSession;
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("Website.Properties.Settings.WebSiteConnString")))
.Mappings(m => m
.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
.BuildSessionFactory();
}
public static ISession GetSession()
{
return (ISession)HttpContext.Current.Items["current.session"];
}
}
Here is one of my repository class, the one i use to handle the Employee's object data operations:
public class EmployeeRepository<T> : IRepository<T> where T : Employee
{
private readonly ISession _session;
public EmployeeRepository(ISession session)
{
_session = session;
}
public T GetById(int id)
{
T result = null;
using (ITransaction tx = _session.BeginTransaction())
{
result = _session.Get<T>(id);
tx.Commit();
}
return result;
}
public IList<T> GetAll()
{
IList<T> result = null;
using (ITransaction tx = _session.BeginTransaction())
{
result = _session.Query<T>().ToList();
tx.Commit();
}
return result;
}
public bool Save(T item)
{
var result = false;
using (ITransaction tx = _session.BeginTransaction())
{
_session.SaveOrUpdate(item);
tx.Commit();
result = true;
}
return result;
}
public bool Delete(T item)
{
var result = false;
using (ITransaction tx = _session.BeginTransaction())
{
_session.Delete(_session.Load(typeof (T), item.Id));
tx.Commit();
result = true;
}
return result;
}
public int Count()
{
var result = 0;
using (ITransaction tx = _session.BeginTransaction())
{
result = _session.Query<T>().Count();
tx.Commit();
}
return result;
}
}
Now, here is my problem. When i'm trying to insert Employee(s), everything is fine. Updating is also perfect... well, as long as i'm not updating one of the TimeEntry object referenced in the "TimeEntries" property of Employee...
Here is where an exception is raised (in a ASPX file of the web project):
var emp = new Employee(1);
foreach (var timeEntry in emp.TimeEntries)
{
timeEntry.Length += 1;
}
emp.Save();
Here is the exception that is raised:
[NonUniqueObjectException: a different object with the same identifier
value was already associated with the session: 1, of entity:
Core.Entities.Employee]
Basically, whenever I try to
Load an employee and
Modify one of the saved TimeEntry, I get that exception.
FYI, I tried replacing the SaveOrUpdate() in the repository for Merge(). It did an excellent job, but when creating an object using Merge(), my object never gets it's Id set.
I also tried creating and flushing the ISession in each function of my repository. It made no sense because as soon as i was trying to load the TimeEntries property of an Employee, an exception was raised, saying the object could not be lazy-loaded as the ISession was closed...
I'm at lost and would appreciate some help. Any suggestion for my repository is also welcome, as i'm quite new to this.
Thanks you guys!
This code
var emp = new Employee(1);
foreach (var timeEntry in emp.TimeEntries)
{
timeEntry.Length += 1;
}
emp.Save();
is creating a new Employee object, presumable with an ID of 1 passed through the constructor. You should be loading the Employee from the database, and your Employee object should not allow the ID to be set since you are using an identity column. Also, a new Employee would not have any TimeEntries and the error message clearly points to an Employee instance as the problem.
I'm not a fan of transactions inside repositories and I'm really not a fan of generic repositories. Why is your EmployeeRepository a generic? Shouldn't it be
public class EmployeeRepository : IRepository<Employee>
I think your code should look something like:
var repository = new EmployeeRepository(session);
var emp = repository.GetById(1);
foreach (var timeEntry in emp.TimeEntries)
{
timeEntry.Length += 1;
}
repository.Save(emp);
Personally I prefer to work directly with the ISession:
using (var txn = _session.BeginTransaction())
{
var emp = _session.Get<Employee>(1);
foreach (var timeEntry in emp.TimeEntries)
{
timeEntry.Length += 1;
}
txn.Commit();
}
This StackOverflow Answer gives an excellent description of using merge.
But...
I believe that you are facing issues with setting up a correct session pattern for your application.
I you suggest to take a look at session-per-request pattern
where in you create a single NHibernate session object per request. the session is opened when the request is received and closed/flushed on generating a response.
Also make sure that instead of using SessionFactory.OpenSession() to get a session try using SessionFactory.GetCurrentSession() which puts the onus on NHibernate to return you the current correct session.
I hope this pushes you in the right direction.