Java «Содержание не разрешено в прологе.» - PullRequest
0 голосов
/ 23 марта 2020

Я пишу клиент, который может зарезервировать слоты, просмотреть доступные слоты, просмотреть забронированные вами слоты и отменить зарезервированные слоты. Мой код работает для всего, кроме резервирования слотов.

Ниже приведен код для резервирования слота.

      while(hotelBooked == false && bandBooked == false)
      {
          // This works
          xmlString = XMLRequest.availability(requestID, USERNAME, PASSWORD);
          ArrayList<String> availSlots = checkAvailiabilityOrBookings(xmlString);
          for(int i = 0; i < availSlots.size(); i++)
          {
              TimeUnit.SECONDS.sleep(1);
              System.out.println("availSlots.get(" + i + "): " + Integer.parseInt(availSlots.get(i).trim()));

              // generate a unique ID based off time
              requestID = genRequestID();
              System.out.println("REQUESTID" + requestID);

              //Something goes wrong around here
              xmlString = XMLRequest.Reservation(requestID, USERNAME, PASSWORD, 134);
              // breaks in this method
              hotelBooked = reserveSlot(xmlString, hotelNum);

              if(hotelBooked == true)
              {
                  bandBooked = reserveSlot(xmlString, bandNum);
                  if(bandBooked == false)
                  {
                    requestID = genRequestID();
                    System.out.println("REQUESTID " + requestID);
                    xmlString = XMLRequest.cancel(requestID, USERNAME, PASSWORD, Integer.parseInt(availSlots.get(i).trim()));
                    cancelSlot(xmlString, hotelNum);
                  }// if
                  else
                  {
                      requestID = genRequestID();
                      System.out.println("REQUESTID" + requestID);
                          xmlString = XMLRequest.bookings(requestID, USERNAME, PASSWORD);
                        bookedSlots = checkAvailiabilityOrBookings(xmlString);
                        System.out.println("1st time - Booked slots:");
                        System.out.println(bookedSlots.toString());
                      break;
                  }
              }// if

Ниже приведен метод, который он разбивает на

// reserve a slot
public static Boolean reserveSlot(String xmlString, String hotelOrBand) {
    System.out.println("Entered reserveSlot");
    Response recMsgOutput;
    PutMethod putMethod;
    boolean booked = false;

try {

    if(hotelOrBand.equals(String.valueOf(3010)))
    {
        putMethod = putMethodHotel;
    }
    else
    {
        putMethod = putMethodBand;
    }

  /*
   * Set the request's entity (body).
   */
    System.out.println("Set the request's entity (body)");
    RequestEntity entity = new StringRequestEntity(xmlString);
    putMethod.setRequestEntity(entity);

  /*
   * Set the put method's headers
   */
    System.out.println("Set the put method's headers");
    putMethod.addRequestHeader("Content-Type", "application/xml");
    putMethod.addRequestHeader("Accept", "application/xml");

  /*
   * Create a client and the execute the put method.
   */

       System.out.println("Create a client and the execute the put method.");

       HttpClient client = new HttpClient();
       int responseCode = client.executeMethod(putMethod);

       while(responseCode != HttpStatus.SC_OK){
        client = new HttpClient();
        responseCode = client.executeMethod(putMethod);
        TimeUnit.SECONDS.sleep(1);
       }// while

      if (responseCode == HttpStatus.SC_OK) {
        System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));

        String [] message = Response.getMsgURI(putMethod.getResponseBodyAsString()).split("/");

        String msgNum = message[message.length - 1];

        String recMsgArg = "http://jewel.cs.man.ac.uk:" + hotelOrBand + "/queue/msg/" + msgNum + "?username=0ih058&password=4UhMf9";

        System.out.println("recMsgArg " + recMsgArg);

        String [] recMsgArgArray = new String[1];

        // Send requests to ClientRecMsg
        recMsgArgArray[0] = recMsgArg;
        System.out.println("recMsgArgArray " + recMsgArgArray[0]);
        recMsgOutput = ClientRecMsg.main(recMsgArgArray);

        Matcher matcher1 = Pattern.compile("\\d+").matcher(recMsgOutput.toString());
        matcher1.find();
        int responseNum = Integer.valueOf(matcher1.group());
        System.out.println("num: " + responseNum);

        if(responseNum == 200)
            booked = true;

    } else if(responseCode != HttpStatus.SC_OK) {
      System.out.println("Error code:" + responseCode);
      System.out.println("Error message:" + putMethod.getResponseBodyAsString());
    }
}//try

Выводит это

availSlots.get(4): 135
REQUESTID 1584934385
Entered reserveSlot
Set the request's entity (body)
Set the put method's headers
Create a client and the execute the put method.
[Fatal Error] :1:1: Content is not allowed in prolog.
uk.ac.manchester.cs.comp28112.lab2.ParseException
        at uk.ac.manchester.cs.comp28112.lab2.Response.getMsgURI(Response.java:179)
        at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.reserveSlot(ClientReserve.java:527)
        at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.reserveRequest(ClientReserve.java:164)
        at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.main(ClientReserve.java:77)


XML для резервирования - код ниже

    static public String Reservation(String request_id, String username,
            String password, int slot_id) throws RequestException {
        try {
            XMLRequest.createBuilder();

            Document document = documentBuilder.newDocument();
            Element reserve_element = document.createElement(RESERVE_ELEMENT);
            document.appendChild(reserve_element);

            Node id_element = document.createElement(REQUEST_ID_ELEMENT);
            id_element.appendChild(document.createTextNode(request_id));
            reserve_element.appendChild(id_element);

            Node username_element = document.createElement(USERNAME_ELEMENT);
            username_element.appendChild(document.createTextNode(username));
            reserve_element.appendChild(username_element);

            Node password_element = document.createElement(PASSWORD_ELEMENT);
            password_element.appendChild(document.createTextNode(password));
            reserve_element.appendChild(password_element);

            Node slot_id_element = document.createElement(SLOT_ID_ELEMENT);
            slot_id_element.appendChild(document.createTextNode(new Integer(
                    slot_id).toString()));
            reserve_element.appendChild(slot_id_element);

            return XMLRequest.toString(document);

        } catch (ParserConfigurationException e) {
            throw new RequestException(e);
        } catch (TransformerConfigurationException e) {
            throw new RequestException(e);
        } catch (TransformerFactoryConfigurationError e) {
            throw new RequestException(e.getException());
        } catch (TransformerException e) {
            throw new RequestException(e);
        }

Ниже приведен метод для Response.getMsgURI ()

    static public String getMsgURI(String xmlString) throws ParseException {

        try {
            Response.createBuilder();
            InputSource source = new InputSource(new StringReader(xmlString));

            Node node = (Node) msgIdXPathExpression.evaluate(source, XPathConstants.NODE);

            return node.getTextContent();

        } catch (XPathExpressionException e) {
            throw new ParseException();
        } catch (ParserConfigurationException e) {
            throw new ParseException();
        }
    }

Ниже приведен вывод для метода putMethod.getResponseBodyAsString ()

Status: 500 Internal Server Error
Content-Type: text/html

<html><body><h1>500 Internal Server Error</h1></body></html>

Я думаю, что это связано с выполнением нескольких запросов xml в одном и том же методе, потому что когда я сначала выполняю запрос на резервирование, он работает нормально, но когда я пытаюсь сделать еще один запрос xml сразу после того, как он застревает.

Приносим извинения за то, что включили так много кода, помощь будет высоко оценена, спасибо.

1 Ответ

0 голосов
/ 21 апреля 2020

Проблема заключалась в том, что я пытался повторно использовать объекты putMethod, мне нужно было создавать новый каждый раз, когда я делал запрос. Я не знаю, почему это так.

...