Xpages JavaBean static Notes Object cause error saving - xpages

In this JavaBean, I wrote some object as (static). But when I reach the logDoc.save() method, it returns error. Removing all (static), all run fine.
The error in console was:
HTTP JVM: lotus.domino.local.Document method: save, row: -1:
NotesException: Notes error: You are not authorized to perform that operation
or
HTTP JVM:lotus.domino.local.NotesBase method: CheckObject, row: -1:
NotesException: Object has been removed or recycled
depending on ACL settings for Anonymous.
Anyone can explain me whot's the problem with static objects here?
public class AnyRest extends CustomServiceBean implements Serializable {
private static final long serialVersionUID = 3548995909847938225L;
private (static) Database logDB=null;
private (static) Document logDoc=null;
private (static) RichTextItem logBody=null;
private (static) void log(String text) {
if (logDB==null) logDB= ExtLibUtil.getCurrentDatabase();
try {
if (logDoc==null) {
logDoc=logDB.createDocument();
logDoc.replaceItemValue("form","log");
logBody=logDoc.createRichTextItem("Body");
}
logBody.appendText(text);
logBody.addNewLine();
logDoc.save();
} catch(NotesException ne) {
logStackTrace(ne);
}
}
private (static) void destroyLog() {
try {
if (logDoc!=null) {
logDoc.save();
logDoc.recycle();
logDoc=null;
}
if (logDB!=null) {
logDB.recycle();
logDB=null;
}
} catch (Exception e) {
logStackTrace(e);
}
}
public String doPost(String strObject){
//do useful things
log("useful post data")
}
}

Domino objects are not serializable.
You should use Domino objects within a class method only.
Store in class fields data like:
Domino server's name,
path to database,
view's name,
document's id or a list of documents' ids,
document item's values,
This way you can easily get the Domino objects again when you need them.
But, never store Domino objects like session, database, view and document in class fields.
(Unless you instantiate the class at every request new and with it the fields - but this is definitely not the case when you use "static".)

Backend objects retrieved via the provided sessions, like that, will be recycled at the end of each request. You should rewrite the class to re-retrieve the Document each request, either creating a new one each time or stashing the UNID of the doc when it’s created, and then using getDocumentByUNID.

Related

spring: share value between annotated beans like jsf applicationscope

I am working on a project with jsf 2.2 on the web side and spring 4 on the business side. I have a web filter which receives a parameter from the request url. From this parameter I have to connect to a database. There are cases where there are different databases possible, so depending on the parameter I have to initiate a different database connection. The web filter looks like this:
#Component
public final class SecurityFilter implements Filter
{
#Autowired
private CommonEao commonEao;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest)request;
String instance = req.getParameter("instance");
//I would like to have something here like:
// springContext.addParameter("instance", instance);
String company = req.getParameter("company");
commonEao.getConfiguration(company);
... Do stuff
}
}
How does it works? The commonEao contains methods to make queries to the database (JPA/Eclipselink...). At initialization, no entityManager is present in commonEao since it is injected in SecurityFilter before the doFilter is executed when an url is requested. After the url is requested, the instance of the database to use is known through the 'instance' request parameter.
When the method commonEao.getConfiguration(company) is invoked, the first thing that should happen is to create an entity Manager:
#Repository
public final class CommonEao extends AbstractEao
{
public final void getConfiguration(final String company)
{
if (entityManager == null)
{
//I would like to have something here like:
// String instance = springContext.getParameter("instance");
createEntityManager(instance);
}
else ...
}
}
As you can see, when the first time the url is requested, no entityManager exists and it needs to be created based on the instance name provided by the request. Based on the instance name the properties files containing database connection parameters will be used the call the Persistence.createEntityManagerFactory functionality... etc etc... :)
What is the idea? The idea that I had, as you can see in my comments, is to put a parameter in some global context/container that is available for all Spring beans. This idea comes from the JSF world, where you can create a managed bean, annotate it with applicationscope, define a variable in it, and access this variable from any jsf managed bean through injecting the application scoped bean with the managedproperty annotation:
#ManagedBean
public final class SomeJsfBean
{
#ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
private void method()
{
applicationBean.setInstanceName("instance");
}
}
#ManagedBean
public final class AnotherJsfBean
{
#ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
private void method()
{
String instance = applicationBean.getInstanceName();
}
}
I have some restrictions though. I want to use a global object of Spring. I don't have any XML config in my project. Spring is configured like this and nothing more:
#Configuration
#ComponentScan(value = { "megan.fox.is.hot", "as.is.lindsay.lohan" })
public class SpringConfiguration
{
}
I have looked in many places, something I found was fetching a property from PropertyPlaceholderConfigurer and stuff like that, but I didn't understand how it works and mainly it looks way too complex for what i need: just sharing one variable.
There must be an easy solution like in the JSF world, but i suspect i am looking for the wrong name in the Spring world! :)
Any help is greatly appreciated, this is the last thing I need to fix in my project!

Guice and RequestScoped behaviour in multiple threads

I am using Guice's RequestScoped and Provider in order to get instances of some classes during a user request. This works fine currently. Now I want to do some job in a background thread, using the same instances created during request.
However, when I call Provider.get(), guice returns an error:
Error in custom provider, com.google.inject.OutOfScopeException: Cannot
access scoped object. Either we are not currently inside an HTTP Servlet
request, or you may have forgotten to apply
com.google.inject.servlet.GuiceFilter as a servlet
filter for this request.
afaik, this is due to the fact that Guice uses thread local variables in order to keep track of the current request instances, so it is not possible to call Provider.get() from a thread different from the thread that is handling the request.
How can I get the same instances inside new threads using Provider? It is possible to achieve this writing a custom scope?
I recently solved this exact problem. There are a few things you can do. First, read up on ServletScopes.continueRequest(), which wraps a callable so it will execute as if it is within the current request. However, that's not a complete solution because it won't forward #RequestScoped objects, only basic things like the HttpServletResponse. That's because #RequestScoped objects are not expected to be thread safe. You have some options:
If your entire #RequestScoped hierarchy is computable from just the HTTP response, you're done! You will get new instances of these objects in the other thread though.
You can use the code snippet below to explicitly forward all RequestScoped objects, with the caveat that they will all be eagerly instantiated.
Some of my #RequestScoped objects couldn't handle being eagerly instantiated because they only work for certain requests. I extended the below solution with my own scope, #ThreadSafeRequestScoped, and only forwarded those ones.
Code sample:
public class RequestScopePropagator {
private final Map<Key<?>, Provider<?>> requestScopedValues = new HashMap<>();
#Inject
RequestScopePropagator(Injector injector) {
for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
Key<?> key = entry.getKey();
Binding<?> binding = entry.getValue();
// This is like Scopes.isSingleton() but we don't have to follow linked bindings
if (binding.acceptScopingVisitor(IS_REQUEST_SCOPED)) {
requestScopedValues.put(key, binding.getProvider());
}
}
}
private final BindingScopingVisitor<Boolean> IS_REQUEST_SCOPED = new BindingScopingVisitor<Boolean>() {
#Override
public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
return scopeAnnotation == RequestScoped.class;
}
#Override
public Boolean visitScope(Scope scope) {
return scope == ServletScopes.REQUEST;
}
#Override
public Boolean visitNoScoping() {
return false;
}
#Override
public Boolean visitEagerSingleton() {
return false;
}
};
public <T> Callable<T> continueRequest(Callable<T> callable) {
Map<Key<?>, Object> seedMap = new HashMap<>();
for (Map.Entry<Key<?>, Provider<?>> entry : requestScopedValues.entrySet()) {
// This instantiates objects eagerly
seedMap.put(entry.getKey(), entry.getValue().get());
}
return ServletScopes.continueRequest(callable, seedMap);
}
}
I have faced the exact same problem but solved it in a different way. I use jOOQ in my projects and I have implemented transactions using a request scope object and an HTTP filter.
But then I created a background task which is spawned by the server in the middle of the night. And the injection is not working because there is no request scope.
Well. The solutions is simple: create a request scope manually. Of course there is no HTTP request going on but that's not the point (mostly). It is the concept of the request scope. So I just need a request scope that exists alongside my background task.
Guice has an easy way to create a request scope: ServletScope.scopeRequest.
public class MyBackgroundTask extends Thread {
#Override
public void run() {
RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
try ( RequestScoper.CloseableScope ignored = scope.open() ) {
doTask();
}
}
private void doTask() {
}
}
Oh, and you probably will need some injections. Be sure to use providers there, you want to delay it's creation until inside the created scope.
Better use ServletScopes.transferRequest(Callable) in Guice 4

Request DTO map to Domain Model

I have the following Domain Model:
public class DaybookEnquiry : Entity
{
public DateTime EnquiryDate { get; set; }
[ForeignKey("EnquiryType")]
public int DaybookEnquiryTypeId { get; set; }
public string AccountNumber { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
#region Navigation Properties
public virtual User User { get; set; }
public virtual DaybookEnquiryType EnquiryType { get; set; }
public virtual ICollection<DaybookQuoteLine> QuoteLines { get; set; }
#endregion
}
This is inside of a project named DomainModel. Entity is just a base class which my domain models inherit from, it contains an Id field.
I then have other projects inside my solution called ServiceInterface and ServiceModel. ServiceInterface contains all my services for my application and ServiceModel contains my DTO's and routes etc.. I'm trying to follow the guidelines set out here: Physical Project Structure
My EnquiriesService contains a method to create a new enquiry in my database using a repository:
public void Post(CreateEnquiry request)
{
// Not sure what to do here..
// _repository.Insert(request);
}
My CreateEnquiry request looks like so:
[Api("POST a single Enquiry for Daybook.")]
[Route("/enquiries", "POST")]
public class CreateEnquiry : IReturnVoid { }
As you can see, the CreateEnquiry request object is empty. Do I need to add properties to it to match my Domain Model and then use AutoMapper or something similar to map the fields to my Domain Model and pass that into my repository?
The Insert method on my repository looks like so:
public virtual void Insert(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
DbContext.SaveChanges();
}
Yes. Your Service request, in this case CreateEnquiry needs to have all the properties you need in order to do whatever it is you want to do!
I've seen two different models for Create vs Update:
Use one request objects called, say, SetEnquiry that has a nullable id field. When null and using the POST HTTP verb, it internally creates a new object. And when not null and using the PATCH HTTP verb, it internally updates an object. You can use ServiceStack's implementation of AbstractValidator<T> to add logic such as if POST then id field needs to be null; and if PATCH then id field cannot be null. This will help ensure your data is always as it needs to be.
Create two request objects -- one for Create and one for Update. The Create doesn't even have an id field, and the Update has one and requires it. You can use the same validation technique used above, except applied to each class independently, so you don't need the conditional check of if this verb do this; if that verb do that.
How you map to your data model is up to you. You can use something like AutoMapper or you can use ServiceStack's built-in TranslateTo and PopulateWith methods. I personally take a middle ground: I created my own object extension methods called MapTo and MapFrom that interally call TranslateTo and PopulateWith respectively. Why did I do this? Because then I control those extensions inside my own namespaces and when I need to do special mappings (like a column name doesn't match up, or one object is more complex than the other, or I simply want to ignore a particular column from one of the objects) I simply overload the MapTo and MapFrom with explicit types, giving it higher specificity than the generic methods.
So back to your question specifically. Assuming you're using the built in TranslateTo your service method might look like this:
public void Post(CreateEnquiry request)
{
_repository.Insert(request.TranslateTo<Enquiry>());
}
One more thing: I generally return the object itself when doing a Create and Update. As fields can change (auto-calculated fields, for example) I like to return the object back to the caller. This is preference and has no real bearing on the answer I'm giving you. Just throwing it out there!

Managed Beans and TabContainer

I ask this squestion on behalf of one of my developers. Haven't looked into details myself.
Assume you have a simple managed bean (=contact) This bean has a method to get the contacts firstName.
I can open an xpage and bind the bean to a computedText Field #{contact.firstName}
In our application we use a tabContainer to have multiple documents of the same type ( contact ) open.
How do I have to use my bean in the container?
faces-config.xml:
<managed-bean>
<managed-bean-name>person</managed-bean-name>
<managed-bean-class>com.package.Person</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Java Bean Class:
public class Person implements Serializable {
private String strDocumentID;
private Document docData;
private String strFirstName;
private String strLastName;
private static final long serialVersionUID = 2934723410254681213L;
public Person() {
//setting the DocumentUniqueID of the current in a tab opened document
//attention: there could be more than one open tab, all with different documents
//and even different document types; and it is possible to switch back and forth between tabs
//DocumentId = ???;
//Setting the values from the stored document to the object
//setValues();
}
private void setValues() {
try {
Session session=NotesContext.getCurrent().getCurrentSession();
Database currdb=session.getCurrentDatabase();
docData=currdb.getDocumentByUNID(DocumentId);
setStrFirstName(docData.getItemValueString("FirstName"));
setStrLastName(docData.getItemValueString("LastName"));
} catch (NotesException e) {
throw new FacesException("Could not open document for documentId "+ DocumentId, e);
}
}
public Document getDataDocument() {
return docData;
}
public void setDataDocument(Document docData) {
this.docData = docData;
}
public String getDocumentId() {
return DocumentId;
}
public void setDocumentId(String documentId) {
DocumentId = documentId;
}
public String getStrFirstName() {
return strFirstName;
}
public void setStrFirstName(String strFirstName) {
this.strFirstName = strFirstName;
}
public String getStrLastName() {
return strLastName;
}
public void setStrLastName(String strLastName) {
this.strLastName = strLastName;
}
}
Custom Control with computed field:
person.strFirstName
So, the problem is the constructor of the Person Class. It needs to get the "link" to the opened document when the document is opened in a tab and everytime when switched back to this tab. And this without the use of any Data source, because this is what should be done by the managed bean itself.
So, hope that helped to get a little bit more understanding of the problem.
If not, please ask again.
My advice:
make another meta bean implementing map interface. Alter its getter to instantiate and return your data bean. Binding may be then:
meta[someparamwithunid].field
And save would be:
meta[someparamwithunid].setValues()
Like this:
public class People implments java.util.Map {
Map<String,Person> people = new HashMap<String,Person>();
public Person get(String unid) {
if people.keySet().contains(unid) {
return people.get(unid)
} else {
// make instance and store it in people map, return it
}
// implement other methods
}
With view scope I think there is no problem with concurrency.
Frantisek points into the right direction. Your request bean would not be a person bean, but a people bean. You then can use an expression like
#{people[index].name}
to refer to a specific person. People would be the managed bean and the index could either be the UNID or the tab number. I find the later one easier to implement. you need to have a loadPerson(index) = UNID function to load an existing person. More information on the use of Expression language can be found here:
Sun Oracle JSF documentation or in some Course materials.
Hope that helps.
I'm not sure if this bean will work in the requestScope because you have probably a lot of partial refreshes with the tabcontainer (maybe try change it to a higher level scope).

Adding custom control with a collection property to a SharePoint Page Layout

I have created a custom control with a collection property per the example on How do you build an ASP.NET custom control with a collection property?
When the control is added to a common ASP.Net aspx page it works as expected. However, when added to a Page Layout in Sharepoint the following error is thrown:
Unable to cast object of type 'System.Web.UI.CollectionBuilder' to type 'System.Collections.Generic.List`1[mytypes.mytype]'.
The code is pretty much identical to the code provided by the example shown in the link above. I do not think the fault lies in the control as it works fine in a plain web project.
I dont think you can use generic lists in sharepoint. Use an ArrayList or customised List collection instead (use asp:ListItem as an exampe, it has its own collection type)
[ParseChildren(true, "Names")]
public class MyControl : Control {
private List<PersonName> names;
public MyControl() {
names = new List<PersonName>();
}
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public List<PersonName> Names {
get { return this.names; }
}
}
public class PersonName {
public string Name { get; set; }
}
UPDATE
Ahh i see the problem now, it is not to do with the generic list, it is because of the way you are doing the initialization.
Create a private variable to hold the list private List<PersonName> names;
Ensure that the property does not have a setter

Resources