База ответов ИНТУИТ

Построение распределенных систем на Java

<<- Назад к вопросам

В строке 32 , в классе BillingServiceServer:
1  // BillingServiceServer.java2  package com.asw.corba.ex1;3   4  // пакеты OMG CORBA5  import org.omg.CosNaming.*;6  import org.omg.CORBA.*;7  import org.omg.PortableServer.*;8  import org.omg.PortableServer.POA;9  import com.asw.corba.ex1.BillingServiceModule.*;10   11  public class BillingServiceServer {12  public static void main(String args[]) {13  try{14  // create and initialize the ORB15  ORB orb = ORB.init(args, null);16   17  // get reference to rootpoa & activate the POAManager18  POA rootpoa =19  POAHelper.narrow(orb.resolve_initial_references("RootPOA"));20  rootpoa.the_POAManager().activate();21   22  // create servant and register it with the ORB23  BillingServiceImpl BSImpl = new BillingServiceImpl();24  BSImpl.setORB(orb);25   26  // get object reference from the servant27  org.omg.CORBA.Object ref = rootpoa.servant_to_reference(BSImpl);28  BillingService href = BillingServiceHelper.narrow(ref);29   30  // get the root naming context31  // NameService invokes the name service32  org.omg.CORBA.Object objRef =33  orb.resolve_initial_references("NameService");34  // Use NamingContextExt which is part of the Interoperable35  // Naming Service (INS) specification.36  NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);37   38  // bind the Object Reference in Naming39  String name = "BillingService";40  NameComponent path[] = ncRef.to_name( name );41  ncRef.rebind(path, href);42   43  System.out.println("BillingServiceServer ready and waiting ...");44   45  // wait for invocations from clients46  orb.run();47  }48   49  catch (Exception e) {50  System.err.println("ERROR: " + e);51  e.printStackTrace(System.out);52  }53  System.out.println("BillingServer Exiting ...");54  }55  }

(Отметьте один правильный вариант ответа.)

Варианты ответа
производится получение объектной ссылки на объект, реализующий сервис BillingService
производится получение объектной ссылки на корневой раздел имен(Верный ответ)
производится создание корневого раздела имен
Похожие вопросы
В строке 41, в классе BillingServiceServer:
1  // BillingServiceServer.java2  package com.asw.corba.ex1;3   4  // пакеты OMG CORBA5  import org.omg.CosNaming.*;6  import org.omg.CORBA.*;7  import org.omg.PortableServer.*;8  import org.omg.PortableServer.POA;9  import com.asw.corba.ex1.BillingServiceModule.*;10   11  public class BillingServiceServer {12  public static void main(String args[]) {13  try{14  // create and initialize the ORB15  ORB orb = ORB.init(args, null);16   17  // get reference to rootpoa & activate the POAManager18  POA rootpoa =19  POAHelper.narrow(orb.resolve_initial_references("RootPOA"));20  rootpoa.the_POAManager().activate();21   22  // create servant and register it with the ORB23  BillingServiceImpl BSImpl = new BillingServiceImpl();24  BSImpl.setORB(orb);25   26  // get object reference from the servant27  org.omg.CORBA.Object ref = rootpoa.servant_to_reference(BSImpl);28  BillingService href = BillingServiceHelper.narrow(ref);29   30  // get the root naming context31  // NameService invokes the name service32  org.omg.CORBA.Object objRef =33  orb.resolve_initial_references("NameService");34  // Use NamingContextExt which is part of the Interoperable35  // Naming Service (INS) specification.36  NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);37   38  // bind the Object Reference in Naming39  String name = "BillingService";40  NameComponent path[] = ncRef.to_name( name );41  ncRef.rebind(path, href);42   43  System.out.println("BillingServiceServer ready and waiting ...");44   45  // wait for invocations from clients46  orb.run();47  }48   49  catch (Exception e) {50  System.err.println("ERROR: " + e);51  e.printStackTrace(System.out);52  }53  System.out.println("BillingServer Exiting ...");54  }55  }
В строке 54, в классе BillingServiceImpl:
1  // BillingServiceImpl.java2  // BillingServiceImpl реализует удаленный интерфейс BillingService для 3  // предоставления удаленного объекта BillingService4  package com.asw.rmi.ex2;5   6  // Набор базовых пакетов Java7  import java.rmi.*;8  import java.util.*;9  import java.rmi.server.*;10   11  public class BillingServiceImpl extends UnicastRemoteObject 12  implements BillingService {13   14  private  Hashtable hash;  // хэш-таблица для хранения карт15  // инициализация сервера16  public BillingServiceImpl() throws RemoteException{17  super();18  hash = new Hashtable();19  }20   21  // реализация метода addNewCard интерфейса BillingService22  public void addNewCard(Card card) throws RemoteException {23   24  hash.put(card.cardNumber, card);25  }26   27  // реализация метода processOperations интерфейса BillingService28  public void processOperations(CardOperation[] operations) 29  throws RemoteException {30  for (int i=0;i<operations.length;i++){31  Card c = (Card)hash.get(operations[i].card);32  if (c==null) throw new NotExistsCardOperation();33  c.balance+=operations[i].amount;34  hash.put(operations[i].card,c);35  }36  }37   38  // реализация метода getCard интерфейса BillingService39  public Card getCard(String card) throws RemoteException{40  Card c = (Card)hash.get(card);41  return c;42  };43   44  // запуск удаленного объекта BillingService45  public static void main (String[] args) throws Exception {46  System.out.println("Initializing BillingService...");47   48  // создание удаленного объекта49  BillingService service = new BillingServiceImpl();50   51  //задание имени удаленного объекта52  String serviceName = "rmi://localhost/BillingService";53  // регистрация удаленного объекта BillingService в реестре rmiregistry54  Naming.rebind(serviceName, service);55  }56   57  }
В какой строке кода BillingServiceImpl осуществляется прием клиентского соединения:
1  // BillingServiceImpl.java2  package com.asw.corba.ex1;3   4  // базовые пакеты Java5  import java.util.Hashtable;6   7  import com.asw.corba.ex1.BillingServiceModule.*;8   9  // пакеты OMG CORBA10  import org.omg.CORBA.*;11   12  public class BillingServiceImpl  extends BillingServicePOA {13  private ORB orb;14  private  Hashtable hash = new Hashtable();15   16  public void setORB(ORB orb_val) {17  orb = orb_val;18  }19   20  public void addNewCard(String personName, String card) {21  hash.put(card, new Double(0.0));22  }23   24  public void addMoney(String card, double money) {25  Double d = (Double)hash.get(card);26   27  if (d!=null) hash.put(card,new Double(d.doubleValue()+money));28  }29   30  public void subMoney(String card, double money) {31  Double d = (Double)hash.get(card);32   33  if (d!=null) hash.put(card,new Double(d.doubleValue()-money));34  }35   36  public double getCardBalance(String card) {37  Double d = (Double)hash.get(card);38   39  if (d!=null) return d.doubleValue();40  else return 0;41  }42  }
Почему в коде BillingServiceImpl отсутствуют операторы чтения данных из сети?
1  // BillingServiceImpl.java2  package com.asw.corba.ex1;3   4  // базовые пакеты Java5  import java.util.Hashtable;6   7  import com.asw.corba.ex1.BillingServiceModule.*;8   9  // пакеты OMG CORBA10  import org.omg.CORBA.*;11   12  public class BillingServiceImpl  extends BillingServicePOA {13  private ORB orb;14  private  Hashtable hash = new Hashtable();15   16  public void setORB(ORB orb_val) {17  orb = orb_val;18  }19   20  public void addNewCard(String personName, String card) {21  hash.put(card, new Double(0.0));22  }23   24  public void addMoney(String card, double money) {25  Double d = (Double)hash.get(card);26   27  if (d!=null) hash.put(card,new Double(d.doubleValue()+money));28  }29   30  public void subMoney(String card, double money) {31  Double d = (Double)hash.get(card);32   33  if (d!=null) hash.put(card,new Double(d.doubleValue()-money));34  }35   36  public double getCardBalance(String card) {37  Double d = (Double)hash.get(card);38   39  if (d!=null) return d.doubleValue();40  else return 0;41  }42  }
В какой строке кода BillingServiceImpl происходит чтение из сети аргументов, передаваемых в метод addNewCard:
1  // BillingServiceImpl.java2  package com.asw.corba.ex1;3   4  // базовые пакеты Java5  import java.util.Hashtable;6   7  import com.asw.corba.ex1.BillingServiceModule.*;8   9  // пакеты OMG CORBA10  import org.omg.CORBA.*;11   12  public class BillingServiceImpl  extends BillingServicePOA {13  private ORB orb;14  private  Hashtable hash = new Hashtable();15   16  public void setORB(ORB orb_val) {17  orb = orb_val;18  }19   20  public void addNewCard(String personName, String card) {21  hash.put(card, new Double(0.0));22  }23   24  public void addMoney(String card, double money) {25  Double d = (Double)hash.get(card);26   27  if (d!=null) hash.put(card,new Double(d.doubleValue()+money));28  }29   30  public void subMoney(String card, double money) {31  Double d = (Double)hash.get(card);32   33  if (d!=null) hash.put(card,new Double(d.doubleValue()-money));34  }35   36  public double getCardBalance(String card) {37  Double d = (Double)hash.get(card);38   39  if (d!=null) return d.doubleValue();40  else return 0;41  }42  }
В строке 18, в классе BillingClient:
1  // BillingClient.java2  // BillingClient использует удаленный объект BillingService для работы 3  // с информацией на пластиковых картах4  package com.asw.rmi.ex2;5   6  // Набор базовых пакетов Java7  import java.rmi.*;8  import java.util.Date;9   10  public class BillingClient {11  // выполнение BillingClient12  public static void main(String[] args) throws Exception{ 13  // создание строки, содержащей URL удаленного объекта14  String objectName = "rmi://"+args[0]+"/BillingService";15  System.out.println("Starting...\n");16  // соединение с реестром RMI и получение удаленной ссылки17  // на удаленный объект18  BillingService bs = (BillingService)Naming.lookup(objectName);19  System.out.println("done");20   21  // проверка на наличие карт с указанными номерами 22  // в случае отсутствия карты с указанными параметрами23  // добавляем новую карту24  Card c;25  c = bs.getCard("1");26  if (c==null) {27  c = new Card("Piter",new Date(),"1",0.0);28  bs.addNewCard(c);29  }30   31  c = bs.getCard("2");32  if (c==null) {33  c = new Card("Stefan",new Date(),"2",0.0);34  bs.addNewCard(c);35  }36   37  c = bs.getCard("3");38  if (c==null) {39  c = new Card("Nataly",new Date(),"3",0.0);40  bs.addNewCard(c);41  }42   43  // определение массива операций по картам44  System.err.println("begin...\n");45  int cnt = 30000;46  CardOperation[] co = new CardOperation[cnt];47  for (int i = 0; i < cnt; i++) {48  switch (i%3){49  case 0:  co[i] = new CardOperation("1",1,new Date());break;50  case 1:  co[i] = new CardOperation("2",1,new Date());break;51  case 2:  co[i] = new CardOperation("3",1,new Date());break;52  }53  }54  // проведение указанных в массиве операций55  bs.processOperations(co);56  57  // печать текущего баланса обработанных карт58  System.out.println(bs.getCard("1"));59  System.out.println(bs.getCard("2"));60  System.out.println(bs.getCard("3"));61  }62  }
В какой строке кода BillingServiceImpl происходит чтение из сети аргументов, передаваемых в метод processOperations:
1  // BillingServiceImpl.java2  // BillingServiceImpl реализует удаленный интерфейс BillingService для 3  // предоставления удаленного объекта BillingService4  package com.asw.rmi.ex2;5   6  // Набор базовых пакетов Java7  import java.rmi.*;8  import java.util.*;9  import java.rmi.server.*;10   11  public class BillingServiceImpl extends UnicastRemoteObject 12  implements BillingService {13   14  private  Hashtable hash;  // хэш-таблица для хранения карт15  // инициализация сервера16  public BillingServiceImpl() throws RemoteException{17  super();18  hash = new Hashtable();19  }20   21  // реализация метода addNewCard интерфейса BillingService22  public void addNewCard(Card card) throws RemoteException {23   24  hash.put(card.cardNumber, card);25  }26   27  // реализация метода processOperations интерфейса BillingService28  public void processOperations(CardOperation[] operations) 29  throws RemoteException {30  for (int i=0;i<operations.length;i++){31  Card c = (Card)hash.get(operations[i].card);32  if (c==null) throw new NotExistsCardOperation();33  c.balance+=operations[i].amount;34  hash.put(operations[i].card,c);35  }36  }37   38  // реализация метода getCard интерфейса BillingService39  public Card getCard(String card) throws RemoteException{40  Card c = (Card)hash.get(card);41  return c;42  };43   44  // запуск удаленного объекта BillingService45  public static void main (String[] args) throws Exception {46  System.out.println("Initializing BillingService...");47   48  // создание удаленного объекта49  BillingService service = new BillingServiceImpl();50   51  //задание имени удаленного объекта52  String serviceName = "rmi://localhost/BillingService";53  // регистрация удаленного объекта BillingService в реестре rmiregistry54  Naming.rebind(serviceName, service);55  }56   57  }
В какой строке происходит прием соединения клиента (класс BillingService):
1  package com.asw.net.ex1;2  import java.net.*;3  import java.util.Hashtable;4  import java.io.*;5  6  public class BillingService extends Thread{7  public static final int ADD_NEW_CARD = 1;8  public static final int ADD_MONEY = 2;9  public static final int SUB_MONEY = 3;10  public static final int GET_CARD_BALANCE = 4;11  public static final int EXIT_CLIENT = 5;12  13  private int serverPort = 7896;14  private ServerSocket ss;15  private  Hashtable hash;16  17  public static void main(String[] args) {18    BillingService bs = new BillingService();19    bs.start();20  }21  22  public BillingService(){23    hash = new Hashtable();24  }25  26  public void run(){27    try {28      ss = new ServerSocket(serverPort);29      System.out.println("Server started");30      while(true){31        Socket s = ss.accept();32        System.out.println("Client accepted");33        BillingClientService bcs = new BillingClientService(this, new DataInputStream(s.getInputStream()),                new DataOutputStream(s.getOutputStream()));34        bcs.start();35      }36    } catch (IOException e) {37      e.printStackTrace();38    }39  }40  41  public void addNewCard(String personName, String card) {42    hash.put(card, new Double(0.0));43  }44  public void addMoney(String card, double money) {45    Double d = (Double)hash.get(card);46    if (d!=null) hash.put(card,new Double(d.doubleValue()+money));47  }48  public void subMoney(String card, double money) {49    Double d = (Double)hash.get(card);50    if (d!=null) hash.put(card,new Double(d.doubleValue()-money));51  }52  public double getCardBalance(String card) {53    Double d = (Double)hash.get(card);54    if (d!=null) return d.doubleValue();55    return 0;56  }57  }
Метод readObject, в строке 32 , в случае, если клиент после установки соединения не записал в поток никаких данных, приведет:
1  package com.asw.net.ex2;2  import java.io.*;3  import java.net.*;4  5  public class BillingClientService extends Thread {6  ObjectInputStream ois;7  ObjectOutputStream oos;8  BillingService bs;9  Socket s;10  11  public BillingClientService(BillingService bs,Socket s){12    System.out.println("Constructor BillingClientService\n");13    this.bs = bs;14    this.s = s;15    try {16      this.oos = new ObjectOutputStream(s.getOutputStream());17      this.ois = new ObjectInputStream(s.getInputStream());18    } catch (IOException e) {19      // TODO Auto-generated catch block20      e.printStackTrace();21    }22    23    System.out.println("Stream`s done \n socket="+s);24  }25  public void run(){26    System.out.println("ClientService thread started\n");27    boolean work = true;28    while (work) {29      int command;30      Object o;31      try {32        o = ois.readObject();              33        if (o instanceof Card[]) {34          Card[] cards = (Card[])o;35          for (int i=0;i<cards.length;i++){36            bs.addNewCard(cards[i]);37          }38        }else if (o instanceof CardOperation[]){39          CardOperation[] co = (CardOperation[])o;40          for (int i=0;i<co.length;i++){41            bs.addMoney(co[i].card,co[i].amount);42          }43        }else if (o instanceof String){44          oos.writeObject(bs.getCard((String)o)); 45        }else System.out.println("Bad operation");46        47      } catch (IOException e) {48        e.printStackTrace();49      } catch (ClassNotFoundException e) {50        e.printStackTrace();51      }52    }53  }54  }
В каком методе класса BillingService происходит создание соединений с клиентами:
1  package com.asw.net.ex1;2  import java.net.*;3  import java.util.Hashtable;4  import java.io.*;5  6  public class BillingService extends Thread{7  public static final int ADD_NEW_CARD = 1;8  public static final int ADD_MONEY = 2;9  public static final int SUB_MONEY = 3;10  public static final int GET_CARD_BALANCE = 4;11  public static final int EXIT_CLIENT = 5;12  13  private int serverPort = 7896;14  private ServerSocket ss;15  private  Hashtable hash;16  17  public static void main(String[] args) {18    BillingService bs = new BillingService();19    bs.start();20  }21  22  public BillingService(){23    hash = new Hashtable();24  }25  26  public void run(){27    try {28      ss = new ServerSocket(serverPort);29      System.out.println("Server started");30      while(true){31        Socket s = ss.accept();32        System.out.println("Client accepted");33        BillingClientService bcs = new BillingClientService(this, new DataInputStream(s.getInputStream()),               new DataOutputStream(s.getOutputStream()));34        bcs.start();35      }36    } catch (IOException e) {37      e.printStackTrace();38    }39  }40  41  public void addNewCard(String personName, String card) {42    hash.put(card, new Double(0.0));43  }44  public void addMoney(String card, double money) {45    Double d = (Double)hash.get(card);46    if (d!=null) hash.put(card,new Double(d.doubleValue()+money));47  }48  public void subMoney(String card, double money) {49    Double d = (Double)hash.get(card);50    if (d!=null) hash.put(card,new Double(d.doubleValue()-money));51  }52  public double getCardBalance(String card) {53    Double d = (Double)hash.get(card);54    if (d!=null) return d.doubleValue();55    return 0;56  }57  }