/**
   * Assert if the FileOrdered have been copied It gets the list of files from the order, and gets
   * the file described in the list of files
   *
   * @param order the order to assert
   * @param nbFileCopied the expected number of files to be copied
   */
  private void assertFileOrderedExists(Order order, int nbFileCopied) {
    assertNotNull(order);
    assertNotNull(order.getResourceCollection());

    assertEquals(1, order.getResourceCollection().size());
    Representation result = null;
    try {

      String res = order.getResourceCollection().get(0);

      ClientResource cr = new ClientResource(res);

      ChallengeResponse chal =
          new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password);

      cr.setChallengeResponse(chal);

      result = cr.get(getMediaTest());

      assertNotNull(result);
      assertTrue(cr.getStatus().isSuccess());

      try {
        // get the list of files
        String text = result.getText();
        String[] contents = text.split("\r\n");
        assertNotNull(contents);
        assertEquals(nbFileCopied, contents.length);
        Reference content = new Reference(contents[0]);
        // asserts
        assertNotNull(content);
        assertNotSame("", content.toString());
        // get the file corresponding to the first url, check that this file
        // exists
        cr = new ClientResource(content);

        chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password);

        cr.setChallengeResponse(chal);

        result = cr.get(getMediaTest());
        assertNotNull(result);
        assertTrue(cr.getStatus().isSuccess());

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } finally {
        RIAPUtils.exhaust(result);
      }

    } finally {
      RIAPUtils.exhaust(result);
    }
  }
  /**
   * Invoke PUT
   *
   * @param uri String
   * @param params String
   * @param object Representation
   * @param parameters Map<String, String>
   * @param uriTemplate String
   */
  public void putDocAPI(
      String uri,
      String params,
      Representation object,
      Map<String, String> parameters,
      String uriTemplate) {
    ClientResource cr = new ClientResource(uri);
    System.out.println("URI: " + uriTemplate);

    docAPI.appendSection("Format");
    // url type
    // request
    ClientResource crLocal = new ClientResource(uriTemplate);
    docAPI.appendRequest(Method.PUT, crLocal);
    // parameters
    docAPI.appendParameters(parameters);
    docAPI.appendSection("Example");
    docAPI.appendRequest(Method.PUT, cr, object);

    // response
    Representation result = cr.put(object, docAPI.getMediaTest());
    docAPI.appendResponse(result);

    RIAPUtils.exhaust(result);
  }
  /**
   * Invoke GET
   *
   * @param uri String
   * @param params String
   * @param parameters Map<String, String>
   * @param uriTemplate String
   */
  public void retrieveDocAPI(
      String uri,
      String params,
      Map<String, String> parameters,
      String uriTemplate,
      ChallengeResponse challengeResponse) {
    ClientResource cr = new ClientResource(uri);
    cr.setChallengeResponse(challengeResponse);

    System.out.println("URI: " + uriTemplate);
    Representation result = cr.get(docAPI.getMediaTest());
    docAPI.appendSection("Format");
    // url type
    // request
    ClientResource crLocal = new ClientResource(uri);
    docAPI.appendRequest(Method.GET, crLocal);
    // parameters
    docAPI.appendParameters(parameters);
    docAPI.appendSection("Example");
    docAPI.appendRequest(Method.GET, cr);
    // response
    docAPI.appendResponse(result);

    RIAPUtils.exhaust(result);
  }
  /**
   * Invoke POST
   *
   * @param item DataSet
   */
  public void create(DataSet item) {
    Representation rep =
        GetRepresentationUtils.getRepresentationDataset(item, MediaType.APPLICATION_JSON);
    ClientResource cr = new ClientResource(getBaseUrl());
    Representation result = cr.post(rep, MediaType.APPLICATION_JSON);
    assertTrue(cr.getStatus().isSuccess());
    assertNotNull(result);

    Response response = getResponse(MediaType.APPLICATION_JSON, result, DataSet.class);
    assertTrue(response.getSuccess());
    assertNotNull(response.getItem());

    DataSet rs = (DataSet) response.getItem();
    assertEquals(rs, item);
    RIAPUtils.exhaust(result);
    cr.release();
  }
  /**
   * Invoke PUT
   *
   * @param uri String
   * @param params String
   * @param parameters Map<String, String>
   * @param uriTemplate String
   */
  public void deleteDocAPI(
      String uri, String params, Map<String, String> parameters, String uriTemplate) {
    ClientResource cr = new ClientResource(uri);
    Representation result = cr.delete(docAPI.getMediaTest());
    docAPI.appendSection("Format");
    // url type
    // request
    ClientResource crLocal = new ClientResource(uriTemplate);
    docAPI.appendRequest(Method.DELETE, crLocal);
    // parameters
    docAPI.appendParameters(parameters);
    docAPI.appendSection("Example");
    docAPI.appendRequest(Method.DELETE, cr);
    // response
    docAPI.appendResponse(result);

    RIAPUtils.exhaust(result);
  }
  /**
   * Invoke an order and return the status returned
   *
   * @param urlAttach2 the url attachment of the resource
   * @return the TaskModel returned representing the status of the Task resource
   */
  protected TaskModel invokeOrder(String urlAttach2, String parameters) {
    String url = getHostUrl() + PROJECT_URL + urlAttach2 + parameters;
    Representation result = null;
    try {
      ClientResource cr = new ClientResource(url);
      ChallengeResponse chal =
          new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password);
      cr.setChallengeResponse(chal);
      result = cr.post(null, getMediaTest());
      assertNotNull(result);
      assertTrue(cr.getStatus().isSuccess());
      Response response = getResponse(getMediaTest(), result, TaskModel.class);
      assertTrue(response.getSuccess());

      return (TaskModel) response.getItem();
    } finally {
      RIAPUtils.exhaust(result);
    }
  }
  /** Post some JSON to the user userstorage */
  private void postJSON() {
    // http://localhost:8182/sitools/userstorage/admin?filepath=%2Ftmp&filename=SvaRecordDefinitionFile.json
    StringRepresentation repr =
        new StringRepresentation(urlFileContent, MediaType.APPLICATION_JSON);

    Reference reference =
        new Reference(
            getBaseUrl()
                + settings
                    .getString(Consts.APP_USERSTORAGE_USER_URL)
                    .replace("{identifier}", userLogin)
                + "/files");
    reference.addQueryParameter("filename", cartFileName);
    reference.addQueryParameter("filepath", cartFilePath);

    ClientResource cr = new ClientResource(reference);
    ChallengeResponse challenge =
        new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password);
    cr.setChallengeResponse(challenge);
    Representation result = cr.post(repr, MediaType.APPLICATION_JSON);
    assertNotNull(result);
    RIAPUtils.exhaust(result);
  }
  private String getServicesDescription(String parentApplicationUrl) {
    String url = parentApplicationUrl + "/services";
    System.out.println(url);
    Representation result = null;
    try {
      ClientResource cr = new ClientResource(url);
      result = cr.get(getMediaTest());
      assertNotNull(result);
      assertTrue(cr.getStatus().isSuccess());
      Response response = getResponse(getMediaTest(), result, ResourceModelDTO.class, true);
      assertTrue(response.getSuccess());
      assertNotNull(response.getData());
      assertEquals(1, response.getData().size());

      ResourceModelDTO resDTO = (ResourceModelDTO) response.getData().get(0);
      List<ResourceParameter> parameters = resDTO.getParameters();
      boolean found = false;
      String fileName = null;
      for (ResourceParameter resourceParameter : parameters) {
        if (resourceParameter.getName().equals("fileName")) {
          found = true;
          assertEquals("xs:template", resourceParameter.getValueType());
          String value = resourceParameter.getValue();
          assertFalse(value.contains("${date:"));
          fileName = resourceParameter.getValue();
          break;
        }
      }
      if (!found) {
        fail("Parameter fileName not found");
      }
      return fileName;
    } finally {
      RIAPUtils.exhaust(result);
    }
  }
  /**
   * Invoke an order and assert that the it is successful, that the {@link MediaType} of the result
   * is expectedMediaType and that its name if expectedFileName
   *
   * @param urlAttach2 the url attachment of the resource
   * @param parameters the parameters to add to the request
   * @param expectedMediaType the expected {@link MediaType} in return
   * @param expectedFileName the expected file name in return
   */
  protected void invokeOrderGet(
      String urlAttach2, String parameters, MediaType expectedMediaType, String expectedFileName) {
    String url = getHostUrl() + PROJECT_URL + urlAttach2 + parameters;
    Representation result = null;
    try {
      ClientResource cr = new ClientResource(url);
      ChallengeResponse chal =
          new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password);
      cr.setChallengeResponse(chal);
      result = cr.get();
      assertNotNull(result);
      assertTrue(cr.getStatus().isSuccess());

      assertEquals(expectedMediaType, result.getMediaType());

      assertNotNull(result.getDisposition());
      String fileName = result.getDisposition().getFilename();
      assertNotNull(fileName);
      assertEquals(expectedFileName, fileName);

    } finally {
      RIAPUtils.exhaust(result);
    }
  }
  /**
   * REST API Response Representation wrapper for single or multiple items expexted
   *
   * @param media MediaType expected
   * @param representation service response representation
   * @param dataClass class expected for items of the Response object
   * @param isArray if true wrap the data property else wrap the item property
   * @return Response
   */
  public static Response getResponseOrderandUserstorage(
      MediaType media, Representation representation, Class<?> dataClass, boolean isArray) {
    try {
      if (!media.isCompatible(MediaType.APPLICATION_JSON)
          && !media.isCompatible(MediaType.APPLICATION_XML)) {
        Engine.getLogger(AbstractSitoolsTestCase.class.getName())
            .warning("Only JSON or XML supported in tests");
        return null;
      }

      XStream xstream = XStreamFactory.getInstance().getXStreamReader(media);
      xstream.autodetectAnnotations(false);
      xstream.alias("response", Response.class);

      // for order
      xstream.alias("order", Order.class);

      // for userstorage
      xstream.alias("userstorage", UserStorage.class);
      xstream.alias("diskStorage", DiskStorage.class);

      if (isArray) {
        xstream.alias("item", dataClass);
        xstream.alias("item", Object.class, dataClass);
        // xstream.omitField(Response.class, "data");
        if (media.isCompatible(MediaType.APPLICATION_JSON)) {
          xstream.addImplicitCollection(Response.class, "data", dataClass);
          xstream.addImplicitCollection(Order.class, "events", Event.class);
          xstream.addImplicitCollection(Order.class, "resourceCollection", String.class);
        }

      } else {
        xstream.alias("item", dataClass);
        xstream.alias("item", Object.class, dataClass);

        if (dataClass == Order.class) {
          xstream.aliasField("order", Response.class, "item");
          if (media.isCompatible(MediaType.APPLICATION_JSON)) {
            xstream.addImplicitCollection(Order.class, "events", Event.class);
            xstream.addImplicitCollection(Order.class, "resourceCollection", String.class);
          }
        }
        if (dataClass == UserStorage.class) {
          xstream.aliasField("userstorage", Response.class, "item");
        }
      }
      xstream.aliasField("data", Response.class, "data");

      SitoolsXStreamRepresentation<Response> rep =
          new SitoolsXStreamRepresentation<Response>(representation);
      rep.setXstream(xstream);

      if (media.isCompatible(getMediaTest())) {
        Response response = rep.getObject("response");

        return response;
      } else {
        Engine.getLogger(AbstractSitoolsTestCase.class.getName())
            .warning("Only JSON or XML supported in tests");
        return null; // TODO complete test with ObjectRepresentation
      }
    } finally {
      RIAPUtils.exhaust(representation);
    }
  }