2

我正在使用实体类构建一个 Restful Web 服务。我已经编写了我的代码,并且运行良好。但是,当我再次尝试检查此 Web 服务时,我的 Web 服务没有响应。然后我尝试调试它,发现部署服务时我的实体管理器实例始终为空。我没有更改persistent.xml 中的任何内容。下面是我的 persistence.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="WebServerPrjPU" transaction-type="JTA">
    <jta-data-source>org.dicprj.ws</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>

我还在这里粘贴我的服务代码:

package service;
import javax.ejb.Stateless;
import database.entity.Bordercountries;
import database.entity.Coordinates;
import database.entity.Countries;
import database.entity.Fullcountries;
import database.entity.Gdp;
import database.entity.Hdi;
import database.entity.Landarea;
import database.entity.Populations;
import database.entity.Uncode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

/**
 * REST Web Service
 *
 * @author Manish
 */
@Stateless
@Path("generic")
public class countriesInfo {

    @PersistenceContext(unitName = "WebServerPrjPU")
    private EntityManager em;

    /**
     * Creates a new instance of countriesInfo
     */
    public countriesInfo() {
    }

    /**
     * Retrieves representation of an instance of database.entity.countriesInfo
     *
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    /**
     * PUT method for updating or creating an instance of countriesInfo
     *
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/xml")
    public void putXml(String content) {
    }

    protected EntityManager getEntityManager() {
        return em;
    }

    @GET
    @Path("countryinfo/{id}")
    @Produces("application/xml")
    public countryXML getCountryInfo(@PathParam("id") String id) {
        countryXML emptyOb = new countryXML();
        if (id == "") {
            return emptyOb;
        }
        String codeISO3 = GetISO3FrmCountryName(id);
        if (codeISO3 == "") {
            return emptyOb;
        }

        return GetXMLFromISO3(codeISO3);
    }
    @GET
    @Path("orderBy/{criteria}/{order}")
    @Produces("text/plain")
    public List<countryXML> GetConutryInfoByCriteria(@PathParam("criteria") String criteria, @PathParam("order")int ascending){
        boolean bAsc= true;
        if(ascending==0){
            bAsc = false;
        }
        if(criteria.equalsIgnoreCase("population")){
            return GetSortedCountryOnPoputaltion(bAsc);
        }else if(criteria.equalsIgnoreCase("gdp")){
            return GetSortedCountryOnGDP(bAsc);
        }else if(criteria.equalsIgnoreCase("landarea")){
            return GetSortedCountryOnLandArea(bAsc);
        }else if(criteria.equalsIgnoreCase("hdi")){
            return GetSortedCountryOnHDI(bAsc);
        }else{
            List<countryXML>list = new ArrayList<countryXML>();
            countryXML emptyOb = new countryXML();
            list.add(emptyOb);
            return list;
        }
    }

    @GET
    @Path("checkborder/{country1}/{country2}")
    @Produces("text/plain")
    public String CheckBorderCountries(@PathParam("country1") String con1, @PathParam("country2") String con2) {
        if (AreBorderCountries(con1, con2)) {
            return "Both are border Countries";
        } else {
            return "Countries are not border countries";
        }
    }

    @GET
    @Path("frompos/{lat}/{lon}")
    @Produces("application/xml")
    public countryXML GetCountryFrmPosition(@PathParam("lat") double latitude, @PathParam("lon") double longitude) {
        String codeIso3 = GetISO3FrmCoOrdinates(latitude, longitude);
        return GetXMLFromISO3(codeIso3);
    }
    private String GetISO3FrmCountryName(String name) {
//        javax.persistence.Query q = getEntityManager().createNamedQuery("Countries.findByNameListEN", Countries.class).setParameter("nameListEN", name);
//        Countries countryOb = (Countries) q.getSingleResult();
//        return countryOb.getCodeISO3();
        //First get code corresponding to the country name from fullCountryTable as user gives smaal names and counntry table has big names
        try {
            javax.persistence.Query q = getEntityManager().createNamedQuery("Fullcountries.findByCountryName", Fullcountries.class).setParameter("countryName", name);
            Fullcountries FullcountryOb1 = (Fullcountries) q.getSingleResult();
            return FullcountryOb1.getIsoAlpha3();
        }catch (NoResultException E) {
            System.out.println("There are no results from the query in Function GetISO3FrmCountryName" + E);
            return "";
        }

    }

    private boolean AreBorderCountries(String nameEn1, String nameEn2) {
        //First get code corresponding to the country name from fullCountryTable as user gives smaal names and counntry table has big names
        try {
            javax.persistence.Query q = getEntityManager().createNamedQuery("Fullcountries.findByCountryName", Fullcountries.class).setParameter("countryName", nameEn1);
            Fullcountries FullcountryOb1 = (Fullcountries) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Fullcountries.findByCountryName", Fullcountries.class).setParameter("countryName", nameEn2);
            Fullcountries FullcountryOb2 = (Fullcountries) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Bordercountries.findByNameListEN", Bordercountries.class).setParameter("nameListEN", nameEn1);
            List<Bordercountries> borderCountryOb1 = q.getResultList();
            Iterator<Bordercountries> iter = borderCountryOb1.iterator();
            while (iter.hasNext()) {
                Bordercountries inBorderTable = (Bordercountries) iter.next();
                if (inBorderTable.getCodeISO3().equalsIgnoreCase(FullcountryOb2.getIsoAlpha3())) {
                    return true;
                }
            }

            return false;
        } catch (NoResultException E) {
            System.out.println("There are no results from the query in Function AreBorderCountries" + E);
            return false;
        }
    }

    private String GetISO3FrmCoOrdinates(double lat, double lon) {
        try {
            javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
            javax.persistence.criteria.CriteriaQuery<Coordinates> cq = cb.createQuery(Coordinates.class);
            javax.persistence.criteria.Root<Coordinates> mRoot = cq.from(Coordinates.class);
            javax.persistence.criteria.Predicate pValid1 = cb.lessThanOrEqualTo(mRoot.<Double>get("hasMinLongitude"), lon);
            javax.persistence.criteria.Predicate pValid2 = cb.greaterThanOrEqualTo(mRoot.<Double>get("hasMaxLongitude"), lon);
            javax.persistence.criteria.Predicate pValid3 = cb.lessThanOrEqualTo(mRoot.<Double>get("hasMinLatitude"), lat);
            javax.persistence.criteria.Predicate pValid4 = cb.greaterThanOrEqualTo(mRoot.<Double>get("hasMaxLatitude"), lat);
            javax.persistence.Query finalQuery = getEntityManager().createQuery(cq.select(mRoot).where(cb.and(pValid1, pValid2, pValid3, pValid4)));
            finalQuery.setMaxResults(1);
            Coordinates ob = (Coordinates) finalQuery.getSingleResult();
            return ob.getCodeISO3();
        } catch (NoResultException E) {
            System.out.println("There are no results from the query in FUnction GetISO3FrmCoOrdinates" + E);
            return "";
        }
    }

    private countryXML GetXMLFromISO3(String iso3Code) {
        try {
            javax.persistence.Query q = getEntityManager().createNamedQuery("Uncode.findByCodeISO3", Uncode.class).setParameter("codeISO3", iso3Code);
            Uncode unCodeOb = (Uncode) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Fullcountries.findByIsoAlpha3", Fullcountries.class).setParameter("isoAlpha3", iso3Code);
            Fullcountries fullCountryInfoOb = (Fullcountries) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Populations.findByCodeISO3", Populations.class).setParameter("codeISO3", iso3Code);
            Populations populationOb = (Populations) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Gdp.findByCodeISO3", Gdp.class).setParameter("codeISO3", iso3Code);
            Gdp gdpOb = (Gdp) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Landarea.findByCodeISO3", Landarea.class).setParameter("codeISO3", iso3Code);
            Landarea landArea = (Landarea) q.getSingleResult();

            q = getEntityManager().createNamedQuery("Hdi.findByCodeISO3", Hdi.class).setParameter("codeISO3", iso3Code);
            Hdi hdiOb = (Hdi) q.getSingleResult();

            countryXML xmlOb = new countryXML();
            xmlOb = xmlOb.SetUnCode(unCodeOb.getCodeUN().toString()).SetNameEn(fullCountryInfoOb.getCountryName()).SetCapitalName(fullCountryInfoOb.getCapital()).SetPopulation(populationOb.getPopulationTotal().toString());
            xmlOb.SetGDP(gdpOb.getGDPTotalInCurrentPrices().toString()).SetLandArea(landArea.getLandAreaTotal().toString()).SetHDI(hdiOb.getTotal().toString());
            return xmlOb;
        } catch (NoResultException E) {
            System.out.println("There are no results from the query in FUnction GetXMLFromISO3" + E);
            countryXML emptyOb = new countryXML();
            return emptyOb;
        }
    }

    private List<countryXML> GetSortedCountryOnPoputaltion(boolean asc) {
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery<Populations> cq = cb.createQuery(Populations.class);
        javax.persistence.criteria.Root<Populations> mRoot = cq.from(Populations.class);
        if (asc) {
            cq = cq.select(mRoot).orderBy(cb.asc(mRoot.<Double>get("populationTotal")));
        } else {
            cq = cq.select(mRoot).orderBy(cb.desc(mRoot.<Double>get("populationTotal")));
        }
        javax.persistence.Query finalQuery = getEntityManager().createQuery(cq);
        finalQuery.setMaxResults(10);
        List<Populations> list = finalQuery.getResultList();
        List<countryXML>listResult = new ArrayList<countryXML>();
        Iterator<Populations>iter = list.iterator();
        while(iter.hasNext()){
            Populations rowOb = iter.next();
            listResult.add(GetXMLFromISO3(rowOb.getCodeISO3()));
        }
        return listResult;
    }
      private List<countryXML> GetSortedCountryOnGDP(boolean asc) {
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery<Gdp> cq = cb.createQuery(Gdp.class);
        javax.persistence.criteria.Root<Gdp> mRoot = cq.from(Gdp.class);
        if (asc) {
            cq = cq.select(mRoot).orderBy(cb.asc(mRoot.<Double>get("GDPTotalInCurrentPrices")));
        } else {
            cq = cq.select(mRoot).orderBy(cb.desc(mRoot.<Double>get("GDPTotalInCurrentPrices")));
        }
        javax.persistence.Query finalQuery = getEntityManager().createQuery(cq);
        finalQuery.setMaxResults(10);
        List<Gdp> list = finalQuery.getResultList();
        List<countryXML>listResult = new ArrayList<countryXML>();
        Iterator<Gdp>iter = list.iterator();
        while(iter.hasNext()){
            Gdp rowOb = iter.next();
            listResult.add(GetXMLFromISO3(rowOb.getCodeISO3()));
        }
        return listResult;
    }
     private List<countryXML> GetSortedCountryOnLandArea(boolean asc) {
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery<Landarea> cq = cb.createQuery(Landarea.class);
        javax.persistence.criteria.Root<Landarea> mRoot = cq.from(Landarea.class);
        if (asc) {
            cq = cq.select(mRoot).orderBy(cb.asc(mRoot.<Double>get("landAreaTotal")));
        } else {
            cq = cq.select(mRoot).orderBy(cb.desc(mRoot.<Double>get("landAreaTotal")));
        }
        javax.persistence.Query finalQuery = getEntityManager().createQuery(cq);
        finalQuery.setMaxResults(10);
        List<Landarea> list = finalQuery.getResultList();
        List<countryXML> listResult = new ArrayList<countryXML>();
        Iterator<Landarea> iter = list.iterator();
        while (iter.hasNext()) {
            Landarea rowOb = iter.next();
            listResult.add(GetXMLFromISO3(rowOb.getCodeISO3()));
        }
        return listResult;
    }
    private List<countryXML> GetSortedCountryOnHDI(boolean asc) {
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery<Hdi> cq = cb.createQuery(Hdi.class);
        javax.persistence.criteria.Root<Hdi> mRoot = cq.from(Hdi.class);
        if (asc) {
            cq = cq.select(mRoot).orderBy(cb.asc(mRoot.<Double>get("Total")));
        } else {
            cq = cq.select(mRoot).orderBy(cb.desc(mRoot.<Double>get("Total")));
        }
        javax.persistence.Query finalQuery = getEntityManager().createQuery(cq);
        finalQuery.setMaxResults(10);
        List<Hdi> list = finalQuery.getResultList();
        List<countryXML> listResult = new ArrayList<countryXML>();
        Iterator<Hdi> iter = list.iterator();
        while (iter.hasNext()) {
            Hdi rowOb = iter.next();
            listResult.add(GetXMLFromISO3(rowOb.getCodeISO3()));
        }
        return listResult;
    }
}

这是我的 glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_faodata_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="faodata"/>
        <property name="User" value="root"/>
        <property name="Password" value="manish"/>
        <property name="URL" value="jdbc:mysql://localhost:3306/faodata?zeroDateTimeBehavior=convertToNull"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="org.dicprj.ws" object-type="user" pool-name="mysql_faodata_rootPool"/>
</resources>

glasshfish 服务器显示错误

INFO: file:/E:/Data/Study/Home/DIC_PROJ1/WebServer/WebServerPrj/build/web/WEB-INF/classes/_WebServerPrjPU logout successful
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
INFO: file:/E:/Data/Study/Home/DIC_PROJ1/WebServer/WebServerPrj/build/web/WEB-INF/classes/_WebServerPrjPU login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor@1c14aa61].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor@1c14aa61] from index [0] 
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer@4d7f4bab] from index [1] 
INFO: EJB5181:Portable JNDI names for EJB countriesInfo: [java:global/WebServerPrj/countriesInfo, java:global/WebServerPrj/countriesInfo!service.countriesInfo]
INFO: Registering the Jersey servlet application, named org.netbeans.rest.application.config.ApplicationConfig, at the servlet mapping, /webresources/*, with the Application class of the same name
INFO: WEB0671: Loading application [WebServerPrj] at [/WebServerPrj]
INFO: WebServerPrj was successfully deployed in 409 milliseconds.
SEVERE: Error when configuring to use the EJB interceptor binding API. JAX-RS EJB support is disabled.
java.lang.reflect.InvocationTargetException
    at sun.reflect.GeneratedMethodAccessor183.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.jersey.server.impl.ejb.EJBComponentProviderFactoryInitilizer.initialize(EJBComponentProviderFactoryInitilizer.java:80)
    at com.sun.jersey.spi.container.servlet.WebComponent.configure(WebComponent.java:574)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.configure(ServletContainer.java:311)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:608)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1453)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:1093)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:189)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
    at com.sun.ejb.containers.BaseContainer.registerSystemInterceptor(BaseContainer.java:3386)
    at com.sun.ejb.containers.InternalInterceptorBindingImpl.registerInterceptor(InternalInterceptorBindingImpl.java:100)
    ... 36 more

INFO: Initiating Jersey application, version 'Jersey: 1.11.1 03/31/2012 06:49 PM'
INFO: Instantiated the Application class org.netbeans.rest.application.config.ApplicationConfig
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException

谁能解释配置或代码中可能有什么问题?提前致谢。

4

0 回答 0