Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > JAX-RCP, Web Services


Автор: hestia 27.8.2007, 10:47
Доброго всем время суток!  smile 

Делаю веб сервис. Вопрос такой:
Во всех описаниях стоит, что мне необходим файл mapping.xml. сгенерировать его можно якобы с помощью jwsdp. потом запустить wscompile и готово.  wscompile у меня нет, как впрочем и jwsdp, где его можно скачать и как правильно настроить. на сановской странице можно скачать только заригистрированным пользователям. 

и второй вопрос. 

мне необходимо, что бы мой ejb-jar.xml выглядел так
Код

<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" version="2.1"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">


у меня он использует ejb-jar_2_0.dtd

он этого не видит, возможно старая версия xdoclet. где можно скачать новую и как ее установить для MyEclipse 6.0.

Заранее всех благодарю

Автор: eXcile 27.8.2007, 11:07
wsdp - это пакет разработчика web сервисов. wscompile входит в состав j2ee_sdk

Автор: hestia 27.8.2007, 11:18
где я могу скачать этот пакет и как мне правильно сделать настройки. 

Автор: sandello 30.8.2007, 21:26
Чем пользуешься. Могу описать, как сделать WS на JBoss 4.2.0

Автор: hestia 1.9.2007, 20:05
Цитата(sandello @ 30.8.2007,  21:26)
Чем пользуешься. Могу описать, как сделать WS на JBoss 4.2.0

работаю под MyEclipse 6.0. Использую JBoss 4.0.5. Необходимо создать веб сервесы на J2EE 1.4. попробывала XFire но что-то не пошло, не знаю, можно ли его использовать для J2EE 1.4.

если поможете, буду очень признательна  smile 

Автор: Tony 2.9.2007, 10:12
jax-ws ? http://www.netbeans.org/kb/50/jaxws20.html Правда там с NetBeans. Я делал под Eclipse, полу4илось. smile 

Автор: sandello 3.9.2007, 06:42
Рабочий пример WS на JBoss 4.2.0 (ес-но, немного покоцаный  smile )

Код

package com.company.project.vendor.ws;

import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.logging.Logger;
import org.jboss.ws.annotation.WebContext;

import com.company.project.AVPair;
import com.company.project.vendor.IProductManager;
import com.company.project.vendor.IServiceManager;
import com.company.project.vendor.IUserManager;
import com.company.project.vendor.IUserSubscriptionManager;
import com.company.project.vendor.Reply;
import com.company.project.vendor.SystemError;
import com.company.project.vendor.access.RightsChecker;
import com.company.project.vendor.data.AMemEntity;
import com.company.project.vendor.data.Abonent;
import com.company.project.vendor.data.EProlongation;
import com.company.project.vendor.data.PersistenceUtil;
import com.company.project.vendor.data.Product;
import com.company.project.vendor.data.Service;
import com.company.project.vendor.data.Subscription;
import com.company.project.vendor.ws.client.AdapterPms4BossSoapService;
import com.company.project.vendor.ws.client.AdapterSms4BossSoapService;
import com.company.project.vendor.ws.client.bean.OperateResult;
import com.company.project.vendor.ws.client.bean.ProductInfo;
import com.company.project.vendor.ws.client.bean.ServiceInfo;
import com.company.project.vendor.ws.client.bean.UserInfo;

@WebService (name = "UserSubscriptionManager", targetNamespace = "http://soapservice.boss", serviceName = "manager")
@SOAPBinding (style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL)
@WebContext (contextRoot = "billing", urlPattern = "/manager")
@Stateless (name = "MemOperationsProxy")
@Local ({IServiceManager.class, IUserManager.class, IProductManager.class})
public class MemOperationsProxyBean implements IProductManager, IServiceManager, IUserManager, IUserSubscriptionManager {
  private Logger debugger = Logger.getLogger(MemOperationsProxyBean.class);

  private DateFormat formatter;

  @PersistenceContext (name = "AbonentManager")
  private EntityManager entityManager;

  private AdapterSms4BossSoapService smsClient = null;
  private AdapterPms4BossSoapService pmsClient = null;

  private RightsChecker checker;

  public static final Set<Integer> ALLOWED_PRODUCT_TYPE=new HashSet<Integer>();
  static{
    ALLOWED_PRODUCT_TYPE.add(1);
  }


  public MemOperationsProxyBean() {
  }

  @PostConstruct
  public void init() {
    String DEBUG_HEADER = "init: ";
    debugger.debug(DEBUG_HEADER + "start");
    formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    try {
      MemClientFactory soapClient = new MemClientFactory();
      smsClient = soapClient.getSmsClientInstance();
      pmsClient = soapClient.getPmsClientInstance();

      checker=new RightsChecker();
    } catch (Exception e) {
      debugger.error("Can't initialize", e);
    }
    debugger.debug(DEBUG_HEADER + "stop");
  }

  @WebMethod (operationName = "addUser")
  public Reply add(@WebParam (name = "memId")String memId,
      @WebParam (name = "userName")String name,
      @WebParam (name = "password")String password,
      @WebParam (name = "areaId")String areaId,
      @WebParam (name = "userAddress")String addr,
      @WebParam (name = "parentControlLevel")int rating,
      @WebParam (name = "cardNumber")String card) {
    String DEBUG_HEADER = "add: ";
    debugger.debug(DEBUG_HEADER + "start");

    try {
      UserInfo info = new UserInfo(memId, name, "", areaId, password, addr, "", 0, 0, 0, "", 0, 0, 0, 0, 0, 0, rating,
          card);

      OperateResult operateResult = smsClient.addUser(info);
      if (operateResult.getReturnCode() != 0) {
        return new Reply(Errors.MEM_ERROR, operateResult.toString());
      }

      Abonent abonent = new Abonent();
      abonent.setMemId(memId);
      abonent.setName(name);
      abonent.setPassword(password);
      abonent.setArea(areaId);
      abonent.setRating(rating);
      abonent.setCardNumber(card);
      abonent.setAddress(addr);
      abonent.setSuspend(false);


      entityManager.persist(abonent);

      Reply ret = new Reply(SystemError.OK, operateResult.toString());
      debugger.debug(DEBUG_HEADER + "stop " + ret);
      return ret;
    } catch (Exception e) {
      debugger.error(e, e);
      return new Reply(Errors.COMMON_ERROR);
    }
  }

  @WebMethod (operationName = "delUser")
  public Reply del(@WebParam (name = "memId")String userId) {
    String DEBUG_HEADER = "del: ";
    debugger.debug(DEBUG_HEADER + "start");
    Abonent abonent = PersistenceUtil.selectByMemId(Abonent.class, userId, entityManager);

    try {
      OperateResult operateResult = smsClient.delUser(userId, "");
      if (operateResult.getReturnCode() != 0) {
        return new Reply(Errors.MEM_ERROR, operateResult.toString());
      }
      if (abonent != null) {
        entityManager.remove(abonent);
      }
      Reply ret = new Reply(SystemError.OK, operateResult.toString());
      debugger.debug(DEBUG_HEADER + "stop " + ret);
      return ret;
    } catch (Exception e) {
      debugger.error(e, e);
      return new Reply(Errors.COMMON_ERROR);
    }
  }

  @WebMethod (operationName = "modifyUser")
  public Reply modify(@WebParam (name = "memId")String userId,
      @WebParam (name = "userName")String name,
      @WebParam (name = "password")String password,
      @WebParam (name = "areaId")String areaId,
      @WebParam (name = "userAddress")String addr,
      @WebParam (name = "parentControlLevel")int rating,
      @WebParam (name = "cardNumber")String card) throws EntityNotFoundException {
    String DEBUG_HEADER = "modify: ";
    debugger.debug(DEBUG_HEADER + "start");
    Abonent abonent = getEntity(Abonent.class, userId);

    try {
      UserInfo info = new UserInfo(userId, name, "", areaId, password, addr, "", 0, 0, 0, "", 0, 0, 0, 0, 0, 0, rating, card);

      OperateResult operateResult = smsClient.modifyUserInfo(info);
      if (operateResult.getReturnCode() != 0) {
        return new Reply(Errors.MEM_ERROR, operateResult.toString());
      }
      abonent.setName(name);
      abonent.setPassword(password);
      abonent.setArea(areaId);
      abonent.setRating(rating);
      abonent.setCardNumber(card);
      abonent.setAddress(addr);

      Reply ret = new Reply(SystemError.OK, operateResult.toString());
      debugger.debug(DEBUG_HEADER + "stop" + ret);
      return ret;
    } catch (Exception e) {
      debugger.error(e, e);
      return new Reply(Errors.COMMON_ERROR);
    }

  }

  private void addLocalSubscription(int continueType, String start, String stop, Abonent abonent, Product product) throws ParseException {
    String DEBUG_HEADER = "addLocalSubscription: ";
    debugger.debug(DEBUG_HEADER + "start");
    Subscription subscription = findSubscription(abonent, product);
    if (subscription == null) {
      debugger.debug(DEBUG_HEADER + "create new subscription");
      subscription = new Subscription();
      subscription.setProduct(product);
      subscription.setAbonent(abonent);
      entityManager.persist(subscription);
      abonent.getSubList().add(subscription);
    }
    debugger.debug(DEBUG_HEADER + "subscription " + subscription.getId());
    subscription.setStart(formatter.parse(start));
    subscription.setStop(formatter.parse(stop));

    if (continueType == 0) {
      subscription.setProlongation(EProlongation.NONE);
    }
    else {
      subscription.setProlongation(EProlongation.AUTO);
    }
    debugger.debug(DEBUG_HEADER + "stop");
  }

  private OperateResult memOrder(String userId, String productId, int continueType, String start, String stop)
      throws RemoteException {
    return smsClient.orderProduct(userId, productId, continueType, "", start, stop);
  }

  public Reply cancel(String userId, String productId, int continueType) throws EntityNotFoundException {
    return cancelWithUpper(userId, productId, continueType, true);
  }

  private OperateResult memCancel(String userId, String productId, int continueType) throws RemoteException {
    return smsClient.cancelOrderProduct(userId, productId, continueType, "");
  }

  private boolean delLocalSubscription(int continueType, Abonent abonent, Product product) {
    Subscription subscription = findSubscription(abonent, product);
    if (subscription == null) {
      return false;
    }

    if (continueType == 0) {
      abonent.getSubList().remove(subscription);
      entityManager.remove(subscription);
    }
    else {
      subscription.setProlongation(EProlongation.NONE);
    }
    return true;
  }

  private Subscription findSubscription(Abonent abonent, Product product) {
    List<AVPair> avPairs = new ArrayList<AVPair>(1);
    avPairs.add(new AVPair("abonent", abonent));
    avPairs.add(new AVPair("product", product));
    return PersistenceUtil.selectFirst(Subscription.class, avPairs, entityManager);
  }


  @WebMethod (operationName = "orderProduct")
  public OperateResult subscribe(@WebParam (name = "userID")String userId,
      @WebParam (name = "productID")String productId,
      @WebParam (name = "continueType")int continueType,
      @WebParam (name = "otherInfos")String detailParam,
      @WebParam (name = "serStartTime")String startTime,
      @WebParam (name = "serEndTime")String stopTime) throws EntityNotFoundException {
    String DEBUG_HEADER = "subscribe: ";
    debugger.debug(DEBUG_HEADER + "start");
    Reply ret = orderWithLower(userId, productId, continueType, startTime, stopTime, false);
    //Reply ret=new Reply(Errors.OPERATION_NOT_ALLOWED,"subscribe");
    debugger.debug(DEBUG_HEADER + "stop " + ret);
    return new OperateResult(ret.getMessage(), ret.getErr().getCode());
  }

  @WebMethod (operationName = "cancleOrderProduct")
  public OperateResult cancel(@WebParam (name = "userID")String userId,
      @WebParam (name = "productID")String productId,
      @WebParam (name = "continueType")int continueType,
      @WebParam (name = "otherInfos")String detailParam) throws EntityNotFoundException {
    String DEBUG_HEADER = "cancel: ";
    debugger.debug(DEBUG_HEADER + "start");
    Reply ret;
    //ret = cancelWithUpper(userId, productId, continueType, false);
    ret=new Reply(Errors.OPERATION_NOT_ALLOWED,"cancel");
    debugger.debug(DEBUG_HEADER + "stop " + ret);
    return new OperateResult(ret.getMessage(), ret.getErr().getCode());
  }

  @WebMethod (operationName = "changePassword")
  public OperateResult changePassword(@WebParam (name = "userID")String userId,
      @WebParam (name = "oldPassword")String oldPassword,
      @WebParam (name = "newPassword1")String newPassword,
      @WebParam (name = "newPassword2")String newPassword2) throws EntityNotFoundException {
    String DEBUG_HEADER = "changePassword: ";
    debugger.debug(DEBUG_HEADER + "start");
    SystemError err;
    OperateResult ret;


    Abonent abonent = getEntity(Abonent.class, userId);
    debugger.debug(DEBUG_HEADER + "abonent was got");

    try {
      if (oldPassword.equals(abonent.getPassword()) && newPassword.equals(newPassword2)) {

        abonent.setPassword(newPassword);
        ret = new OperateResult("OK", 0);
      }
      else {
        err = Errors.PASSWORD_MISMATCH;
        ret = new OperateResult(err.getMsg(), err.getCode());
      }
    } catch (Exception e) {
      debugger.error(e, e);
      err = Errors.COMMON_ERROR;
      ret = new OperateResult(err.getMsg(), err.getCode());
    }
    debugger.debug(DEBUG_HEADER + "stop " + ret);
    return ret;
  }

  private <T extends AMemEntity> T getEntity(Class<T> c, String id) throws EntityNotFoundException {
    String DEBUG_HEADER = "getEntity: ";
    debugger.debug(DEBUG_HEADER + "start ");
    debugger.debug(DEBUG_HEADER + "class " + c);
    debugger.debug(DEBUG_HEADER + "id " + id);
    T ret = PersistenceUtil.selectByMemId(c, id, entityManager);
    if (ret == null) {
      debugger.debug(DEBUG_HEADER + "not found");
      throw new EntityNotFoundException(id, c);
    }
    debugger.debug(DEBUG_HEADER + "stop " + ret);
    return ret;
  }

  private Reply orderWithLower(String userId, String productId, int continueType, String start, String stop, boolean connectMem
  )
      throws EntityNotFoundException {
    String DEBUG_HEADER = "orderWithLower: ";
    debugger.debug(DEBUG_HEADER + "start (userId productId)" + userId + " " + productId);
    Abonent abonent = getEntity(Abonent.class, userId);

    Product product = getEntity(Product.class, productId);

    if (!checkProductAvailable(abonent, product)) {
      return new Reply(Errors.OPERATION_NOT_ALLOWED,"cancel");
    }

    try {
      return orderWithLower(abonent, product, continueType, start, stop, connectMem);
    } catch (Exception e) {
      debugger.error(e, e);
      return new Reply(Errors.COMMON_ERROR);
    }
  }

  private Reply orderWithLower(Abonent abonent, Product product, int continueType, String start, String stop, boolean connectMem)
      throws ParseException, RemoteException {
    Product lower = product.getLower();
    if (lower != null) {
      orderWithLower(abonent, lower, continueType, start, stop, true);
    }
    return order(abonent, product, continueType, start, stop, connectMem);
  }


  private Reply order(Abonent abonent, Product product, int continueType, String start, String stop, boolean connectMem)
      throws RemoteException, ParseException {
    String DEBUG_HEADER = "order: ";
    debugger.debug(DEBUG_HEADER + "start");
    debugger.debug(DEBUG_HEADER + "abonent " + abonent);
    debugger.debug(DEBUG_HEADER + "product " + product);
    OperateResult operateResult = new OperateResult("OK", 0);
    if (connectMem) {
      debugger.debug(DEBUG_HEADER + "send to mem");
      operateResult = memOrder(abonent.getMemId(), product.getMemId(), continueType, start, stop);
      debugger.debug(DEBUG_HEADER + "done " + operateResult);
      if (operateResult.getReturnCode() != 0) {
        return new Reply(Errors.MEM_ERROR, operateResult.toString());
      }
    }
    addLocalSubscription(continueType, start, stop, abonent, product);
    debugger.debug(DEBUG_HEADER + "stop");
    return new Reply(SystemError.OK, operateResult.toString());
  }

  /**
   * @param userId       идентификатор абонента
   * @param productId    идентификатор продукта
   * @param continueType 0 - удалить подписку, 1 - отменить автоматическое продление
   * @param connectMem   выполнять соответствуюющую команду на MEM или нет
   * @return статус выполнения команды
   * @throws EntityNotFoundException в случае отсутствия нужного объекта в системе (нет продукта, нет абонента, etc)
   */
  private Reply cancelWithUpper(String userId, String productId, int continueType, boolean connectMem) throws EntityNotFoundException {
    String DEBUG_HEADER = "cancelWithUpper: ";
    debugger.debug(DEBUG_HEADER + "start");
    Abonent abonent = getEntity(Abonent.class, userId);

    Product product = getEntity(Product.class, productId);

    try {
      return cancelWithUpper(abonent, product, continueType, connectMem);
    } catch (Exception e) {
      debugger.error(e, e);
      return new Reply(Errors.COMMON_ERROR);
    }
  }

  private Reply cancelWithUpper(Abonent abonent, Product product, int continueType, boolean connectMem) throws RemoteException {
    Product upper = product.getUpper();
    if (upper != null) {
      cancelWithUpper(abonent, upper, continueType, true);
    }
    return cancel(abonent, product, continueType, connectMem);
  }

  private Reply cancel(Abonent abonent, Product product, int continueType, boolean connectMem)
      throws RemoteException {
    String DEBUG_HEADER = "cancel: ";
    debugger.debug(DEBUG_HEADER + "start");
    debugger.debug(DEBUG_HEADER + "abonent " + abonent);
    debugger.debug(DEBUG_HEADER + "product " + product);
    if (product.isRequered()) {
      return new Reply(Errors.CANCEL_REQUERED_PRODUCT);
    }

    try {
      OperateResult operateResult = new OperateResult("OK", 0);
      if (connectMem) {
        operateResult = memCancel(abonent.getMemId(), product.getMemId(), continueType);
        if (operateResult.getReturnCode() != 0) {
          return new Reply(Errors.MEM_ERROR, operateResult.toString());
        }
      }

      if (!delLocalSubscription(continueType, abonent, product)) {
        return new Reply(Errors.SUBSCRIPTION_NOT_FOUND);
      }
      else {
        return new Reply(SystemError.OK, operateResult.toString());
      }
    } finally {
      debugger.debug(DEBUG_HEADER + "stop");
    }
  }


  private boolean checkProductAvailable(Abonent abonent,Product product){
    return checker.check(abonent, product, entityManager);
  }
}


Автор: poltora 14.9.2007, 16:07
рабочий пример - это хорошо.
не подскажешь алгоритм прикрутки веб сервисов под JBoss ?

на данный момент готово - 
- SLSB (EJB 2.1) с EndPoint интерфейсом (JSR-109 EJB EndPoint), 
- сгенерированы .wsdl утилитой wstools (java-wsdl), 
- сгенерированы интерфейсы и классы из .wsdl (wsdl-java), jax-rpc-mapping.xml

а что дальше?

смотрю http://localhost:8080/jbossws/services на наличие веб-сервисов - ничего не нахожу.

Нужно запустить это дело именно под этой конфигурацией - JBoss 4.2.1 GA, JBossWS 1.2.1 GA, EJB 2.1, JSR-109

(Понимаю, что есть JSR-181, EJB3, но...)

Автор: sandello 15.9.2007, 08:03
Дык, рабочий пример - вот и весь алгоритм. Для поднятия своего ws я не делал больне ничего. WSDL руками не генерил smile Просто смотрел, что генерится автоматом  и правил код, если надо было. Все.
Я не знаю, что такое  http://localhost:8080/jbossws/services, но в моем примере сервис подымается где-то на http://localhost:8080/billing
В любом случае - смотри логи. Там все написано. Если ты используешь linux/unix, то хороший способ посмотреть то, что произошло при деплое:
1. открываешь консоль, делаешь буфер побольше
2. cd $JBOSS_SERVER/log
3. tail -f server.log
4. несколько раз нажимешь ввод, что бы текст на экране уполз вверх
5. средствами консоли, если возможно, чистишь буфер (или историю, называют по разному)
6. деплоиш свою софтину
7. прокруткой назад находишь начало вывода и внимательно читаешь

Автор: RWIII 5.11.2012, 20:05
Цитата(sandello @ 3.9.2007,  06:42)
Рабочий пример WS на JBoss 4.2.0 (ес-но, немного покоцаный  :biggrin )
...
getPmsClientInstance();
...



звучит у ж как-то нехорошо smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)