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

时间:2014-01-28 12:14:27

标签: java osgi datasource cq5 aem

我正在尝试在Adobe CQ5捆绑包中的OSGi中获取servlet的DataSourcePool实例,但标准方法不起作用。我以前通过Activator获取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;
    }
}

但是自从我开始在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

当我尝试在MyServlet.java中获取DataSourcePool时,来自cz.package.Activator.getDataSourcePool()的返回值;一片空白。我也尝试使用@Reference,但它在编译和运行servlet后只给出了HTTP 403 Forbidden错误。

感谢您的帮助

修改

这就是我的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{

    }
}

这是我收到的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)

我尝试检查日志,但没有任何内容(只是找不到/favicon.ico的信息)

EDIT2 当我将请求更改为POST并将servlet更改为处理POST请求时,错误消息将更改为HTTP 500

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

2 个答案:

答案 0 :(得分:0)

这是一个开始订购问题。您假设该服务已经可用并在您的软件包启动之前注册,但该假设是不安全的(事实上,null表明它是不真实的。)

您应该将声明式服务与@Reference批注一起使用。我不明白为什么你说这会导致HTTP Forbidden错误......这些事情之间没有联系。

答案 1 :(得分:0)

从日志中看,您的servlet未解析,当您点击URL中的路径时 -
对于'GET'请求,调用DefaultGetServlet是

  

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


对于'POST'请求,调用SlingPostServlet

  

这将永远不会起作用,因为servlet的路径不存在,并且不能在该位置保存数据。

要验证您的路径实际已解析为servlet,您可以转到/system/console/servletresolver

检查路径是否解析为servlet

从goto /system/console/components开始,搜索你的servlet并检查状态。如果它不是活动的,请展开组件以获取详细信息,并检查是否满足所有引用
您可以拖尾日志并尝试激活组件并检查是否生成了任何错误,然后相应地进行修复。
在此处分享您的错误日志,以备您需要进一步的帮助。

重新激活组件的日志中会出现错误,这些组件在调用servlet路径时没有看到,因为在部署bundle时最初会生成它们。