简体   繁体   English

OSGi软件包-获取DataSourcePool以在Adobe CQ5中的servlet中使用

[英]OSGi bundle - get DataSourcePool for use in servlet in Adobe CQ5

I'm trying to get DataSourcePool instance for servlet in OSGi in Adobe CQ5 bundle but the standard approach doesn't work. 我正在尝试在Adobe CQ5捆绑软件中获取OSGi中servlet的DataSourcePool实例,但是标准方法不起作用。 I used to get DataSourcePool via Activator like this 我曾经通过这样的激活器来获取DataSourcePool

public class Activator implements BundleActivator {
    private DataSourcePool source;

    public void start(BundleContext context) throws Exception {
        ServiceReference dspRef = context.getServiceReference(DataSourcePool.class.getName());
        source = (DataSourcePool)context.getService(dspRef);
    }

    public static DataSourcePool getDataSourcePool(){
        return source;
    }
}

but since I started to develop in Eclipse, this doesn't work anymore. 但是自从我开始在Eclipse中开发以来,这不再起作用。 I have this project structure in Eclipse 我在Eclipse中有这个项目结构

project-default
project-default-bundle
\src
   \main
       \java
          \cz
             \package
                \sub1
                \sub2
                \Activator.java
           \other
              \package
                 \servlets
                    \MyServlet.java

project-default-components
project-default-content

When I try to get the DataSourcePool in MyServlet.java, the return value from cz.package.Activator.getDataSourcePool(); 当我尝试在MyServlet.java中获取DataSourcePool时,返回值来自cz.package.Activator.getDataSourcePool();。 is null. 一片空白。 I also tried to use @Reference but it just gives me HTTP 403 Forbidden error after compiling and running the servlet. 我也尝试使用@Reference,但是在编译和运行Servlet之后,它只会给我HTTP 403 Forbidden错误。

Thanks for any help 谢谢你的帮助

EDIT 编辑

This is what my servlet looks like 这就是我的servlet的样子

package my.pckg.servlets;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.sql.DataSource;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.commons.datasource.poolservice.DataSourcePool;

@Component(immediate = true)
@Service(value=javax.servlet.Servlet.class)
@Properties(value={
        @Property(name="sling.servlet.methods", value={"GET"}),
        @Property(name="sling.servlet.paths", value={"/myservices/saveandinvite"})
})
public class SaveAndInvitePeople extends SlingAllMethodsServlet{

    private static final long serialVersionUID = 7923689671005539630L;
    private static final Logger log = LoggerFactory.getLogger(SaveAndInvitePeople.class);

    @Reference
    private DataSourcePool source;
    //private DataSourcePool dataSourcePool = null;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
        log.info("doGet");
        /*this.dataSourcePool = Activator.getDataSourcePool();
        if(this.dataSourcePool == null){
            log.info("datasourcepool == null!");
        }*/
        if(this.source == null){
            log.info("datasourcepool == null!");
        }
        try{
            //DataSource ds = (DataSource)this.dataSourcePool.getDataSource("myConnection");
            DataSource ds = (DataSource)this.source.getDataSource("myConnection");
            if(ds == null){
                log.error("DataSource is null!");
                return;
            }
            log.info("datasource not null! gonna try to get connection!");
            Connection con = null;
            try{
                con = ds.getConnection();
            }catch(Exception e){
                log.error("Exception "+e.getClass().getName()+": "+e.getMessage());
            }finally{
                if(con != null){
                    try{
                        con.close();
                    }catch(Exception e){
                        log.error("Exception "+e.getClass().getName()+": "+e.getMessage());
                    }
                }
            }
            log.info("looks OK!");
        }catch(Exception e){
            log.error("Exception "+e.getClass().getName()+": "+e.getMessage());
        }
    }

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{

    }
}

And this is the HTTP 403 Forbidden message I get. 这是我收到的HTTP 403 Forbidden消息。

Forbidden

Cannot serve request to /myservice/saveandinvite/ in org.apache.sling.servlets.get.DefaultGetServlet

Request Progress:

      0 (2014-01-29 11:51:40) TIMER_START{Request Processing}
      0 (2014-01-29 11:51:40) COMMENT timer_end format is {<elapsed msec>,<timer name>} <optional message>
      0 (2014-01-29 11:51:40) LOG Method=GET, PathInfo=/myservice/saveandinvite/
      0 (2014-01-29 11:51:40) TIMER_START{ResourceResolution}
      0 (2014-01-29 11:51:40) TIMER_END{0,ResourceResolution} URI=/myservice/saveandinvite/ resolves to Resource=, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite, resource=[SyntheticResource, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite]
      0 (2014-01-29 11:51:40) LOG Resource Path Info: SlingRequestPathInfo: path='/myservice/saveandinvite', selectorString='null', extension='null', suffix='/'
      0 (2014-01-29 11:51:40) TIMER_START{ServletResolution}
      0 (2014-01-29 11:51:40) TIMER_START{resolveServlet(, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite, resource=[SyntheticResource, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite])}
      2 (2014-01-29 11:51:40) TIMER_END{2,resolveServlet(, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite, resource=[SyntheticResource, type=sling:syntheticResourceProviderResource, path=/myservice/saveandinvite])} Using servlet org.apache.sling.servlets.get.DefaultGetServlet
      2 (2014-01-29 11:51:40) TIMER_END{2,ServletResolution} URI=/myservice/saveandinvite/ handled by Servlet=org.apache.sling.servlets.get.DefaultGetServlet
      2 (2014-01-29 11:51:40) LOG Applying Requestfilters
      2 (2014-01-29 11:51:40) LOG Calling filter: org.apache.sling.bgservlets.impl.BackgroundServletStarterFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: org.apache.sling.i18n.impl.I18NFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.designimporter.CanvasPageDeleteRequestFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.core.impl.WCMRequestFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: cz.devsoft.hartmann.project20130901v01.impl.filters.LoggingFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.adobe.granite.optout.impl.OptOutFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.theme.impl.ThemeResolverFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet
      2 (2014-01-29 11:51:40) LOG Calling filter: org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter
      2 (2014-01-29 11:51:40) LOG RedirectFilter did not redirect (request extension does not match)
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.core.impl.warp.TimeWarpFilter
      2 (2014-01-29 11:51:40) LOG Applying Componentfilters
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.core.impl.WCMComponentFilter
      2 (2014-01-29 11:51:40) LOG Calling filter: com.day.cq.wcm.core.impl.WCMDebugFilter
      2 (2014-01-29 11:51:40) TIMER_START{org.apache.sling.servlets.get.DefaultGetServlet#0}
      2 (2014-01-29 11:51:40) LOG Using org.apache.sling.servlets.get.impl.helpers.StreamRendererServlet to render for extension=null
      2 (2014-01-29 11:51:40) LOG Applying Error filters
      2 (2014-01-29 11:51:40) LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
      2 (2014-01-29 11:51:40) TIMER_START{handleError:status=403}
      6 (2014-01-29 11:51:40) TIMER_END{4,handleError:status=403} Using handler /libs/sling/servlet/errorhandler/default.jsp
     22 (2014-01-29 11:51:40) LOG Found processor for post processing ProcessorConfiguration: {contentTypes=[text/html],order=-1, active=true, valid=true, processErrorResponse=true, pipeline=(generator=Config(type=htmlparser, config={}), transformers=(Config(type=linkchecker, config={}), Config(type=mobile, config=org.apache.sling.jcr.resource.JcrPropertyMap@49f984de), Config(type=mobiledebug, config=org.apache.sling.jcr.resource.JcrPropertyMap@1c8230c3), Config(type=contentsync, config=org.apache.sling.jcr.resource.JcrPropertyMap@274f60d4), serializer=Config(type=htmlwriter, config={}))}
     23 (2014-01-29 11:51:40) TIMER_END{23,Request Processing} Dumping SlingRequestProgressTracker Entries
ApacheSling/2.2 (Day-Servlet-Engine/4.1.42, OpenJDK 64-Bit Server VM 1.7.0_51, Linux 2.6.32-431.3.1.el6.x86_64 amd64)

I tried to check logs but there is nothing(just info message that /favicon.ico couldn't be found) 我试图检查日志,但没有任何内容(只是显示/favicon.ico的信息消息)

EDIT2 When I change the request to POST and the servlet to handle POST requests, the error msg changes to HTTP 500 EDIT2当我将请求更改为POST并将servlet更改为处理POST请求时,错误msg更改为HTTP 500

javax.jcr.RepositoryException: org.apache.sling.api.resource.PersistenceException: Resource at '/myservices/saveandinvite' is not modifiable

This is a start ordering issue. 这是开始订购的问题。 You assume that the service is already available and registered before your bundle starts, but that assumption is unsafe (and in fact the null shows it to be untrue). 您假设该服务在捆绑包启动之前已经可用并已注册,但是这种假设是不安全的(实际上,null表明它是不正确的)。

You should use Declarative Services with the @Reference annotation. 您应该将声明式服务与@Reference注释一起使用。 I don't understand why you say this leads to an HTTP Forbidden error... there is no connection between these things. 我不明白您为什么说这会导致HTTP禁止错误...这些东西之间没有任何联系。

From the logs it appears your servlet isn't resolved and when you hit the path in URL - 从日志中看来,您的servlet尚未解析,当您点击URL中的路径时-
For 'GET' request DefaultGetServlet is invoked 对于“ GET”请求,调用DefaultGetServlet

2 (2014-01-29 11:51:40) TIMER_END{2,ServletResolution} URI=/myservice/saveandinvite/ handled by Servlet=org.apache.sling.servlets.get.DefaultGetServlet 2(2014-01-29 11:51:40)TIMER_END {2,ServletResolution} URI = / myservice / saveandinvite /由Servlet = org.apache.sling.servlets.get.DefaultGetServlet处理


For 'POST' request SlingPostServlet is invoked 对于“ POST”请求,调用SlingPostServlet

This will never work as the path for your servlet is non existent and no data can be saved at that location. 由于您的Servlet路径不存在,因此无法在该位置保存任何数据,因此它将永远无法工作。

To verify your path actually resolved to servlet, you can check if the path resolves to servlet by going to /system/console/servletresolver 要验证您的路径是否实际解析为servlet,您可以转到/system/console/servletresolver检查该路径是否解析为servlet。

To start with goto /system/console/components and search for your servlet and check the status. 首先转到/system/console/components并搜索您的servlet并检查状态。 If its not Active, expand the component for details and check that all references are satisfied. 如果未激活,请展开该组件以获取详细信息,并检查是否满足所有引用要求。

You could tail your logs and try activating the component and check if there are any errors generated and proceed accordingly to fix those. 您可以尾随日志并尝试激活该组件,然后检查是否生成了任何错误,并进行相应的修复。
Share your error logs here in case you need further help. 如果您需要进一步的帮助,请在此处共享错误日志。

There will be errors in logs on reactivating the component which you don't see while calling the servlet path as they initially would get generated when your bundle is deployed. 重新激活组件时,日志中会出现错误,您在调用servlet路径时不会看到这些错误,因为最初在部署捆绑软件时会生成这些错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM