Beispiel #1
0
  @Test
  public void testGetCompute() {
    Compute compute = null;
    try {
      compute = new Compute(Architecture.x64, 2, "TestCase", 200, 20, State.active, null);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (NamingException e) {
      e.printStackTrace();
    }
    // test if compute ist not null
    Assert.assertNotNull(compute);
    // connect to api
    clientResource.setReference(
        OcciConfig.getInstance().config.getString("occi.server.location")
            + "compute/"
            + compute.getId());
    clientResource.setHostRef(
        OcciConfig.getInstance().config.getString("occi.server.location")
            + "compute/"
            + compute.getId());
    // create new representation
    Representation representation = null;
    try {
      // send post request
      representation = clientResource.get();
    } catch (Exception ex) {
      System.out.println("Failed to execute GET request: " + ex.getMessage());
    }
    Assert.assertNotNull(representation);
    // get request and print it in debugger
    Request request = Request.getCurrent();
    System.out.println(request.toString() + "\n\n");
    System.out.println("--------------------------------");
    // get current response
    Response response = Response.getCurrent();
    Assert.assertNotNull(response);
    System.out.println("Response: " + response.toString());

    try {
      representation.write(System.out);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    System.out.println("\n--------------------------------");
  }
Beispiel #2
0
  /**
   * Add Mixin definition.
   *
   * @param representation
   * @return added mixin definition and status
   */
  @Put
  public String putOCCIRequest() {
    // set occi version info
    getServerInfo().setAgent(OcciConfig.getInstance().config.getString("occi.version"));

    LOGGER.debug("Analyzing header information");

    StringBuffer buffer = new StringBuffer();

    Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
    LOGGER.info("Request header: " + requestHeaders);

    String categoryCase = OcciCheck.checkCaseSensitivity(requestHeaders.toString()).get("category");
    String[] header;
    // if there is no category in header, its a bad request
    if (requestHeaders.getFirstValue(categoryCase) != null) {
      header = requestHeaders.getFirstValue(categoryCase).split(";");
    } else {
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, buffer.toString());
      return " ";
    }
    String scheme = "";
    for (int i = 0; i < header.length; i++) {
      header[i] = header[i].trim();
      if (header[i].contains("scheme=")) {
        if (header[i].contains("\"")) {
          scheme = header[i].substring(8, header[i].length() - 1);
        } else {
          scheme = header[i].substring(7, header[i].length());
        }
        LOGGER.info("scheme: " + scheme);
      }
    }
    Set<Mixin> related = new HashSet<Mixin>();
    try {
      // iterate through all mixins to find the related
      for (Mixin mixin : Mixin.getMixins()) {
        if (mixin.getScheme().toString() == requestHeaders.getFirstValue("rel")) {
          related.add(mixin);
        }
      }
      String term = header[0];
      String title = header[0];
      LOGGER.debug("term: " + term);
      LOGGER.debug("title: " + title);
      // create new mixin instance
      new Mixin(related, term, title, scheme, null);
      LOGGER.debug("Created mixin");
    } catch (Exception e) {
      getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE, buffer.toString());
      return "Exception caught " + e.getMessage();
    }
    // access the request headers and get the Accept attribute
    Representation representation =
        OcciCheck.checkContentType(requestHeaders, buffer.append(" "), getResponse());
    getResponse().setEntity(representation);
    // getResponse().setStatus(Status.SUCCESS_OK);
    return " ";
  }
Beispiel #3
0
  public Compute(
      Architecture architecture,
      int cores,
      String hostname,
      float speed,
      float memory,
      State state,
      Set<String> attributes)
      throws URISyntaxException, NumberFormatException, IllegalArgumentException, NamingException {
    super("Compute", links, attributes);
    this.architecture = architecture;
    this.cores = cores;
    this.hostname = hostname;
    this.speed = speed;
    this.memory = memory;
    this.state = state;

    generateActionNames();

    // check if all attributes are correct
    if ((cores < 1)) {
      throw new NumberFormatException("Number of cores is negative!");
    } else if (speed <= 1) {
      throw new NumberFormatException("Number of speed is negative!");
    } else if (memory <= 1) {
      throw new NumberFormatException("Number of memory is negative!");
    }
    // check if there is a hostname
    if (hostname.length() == 0) {
      throw new NamingException("Name of the Compute resource can not be null");
    }
    /*
     * set Category
     */
    setKind(
        new Kind(
            actionSet,
            null,
            null,
            null,
            "compute",
            "Compute",
            OcciConfig.getInstance().config.getString("occi.scheme") + "/infrastructure#",
            attributes));
    getKind().setActionNames(actionNames);
    // set uuid for the resource
    uuid = UUID.randomUUID();
    setId(new URI(uuid.toString()));
    // put resource into compute list
    computeList.put(uuid, this);

    // Generate attribute list
    generateAttributeList();
  }
Beispiel #4
0
  // TODO Die Parameter beim Request werden nicht korrekt übergeben. Keine
  // Ahnung woran es liegt.
  @Test(enabled = false)
  public void testPostCompute() {
    // connect to api
    clientResource.setReference(
        OcciConfig.getInstance().config.getString("occi.server.location") + "compute");
    // Tests if client resource is connected to api
    Assert.assertNotNull(clientResource);
    // try to create a compute resource
    String architecture = "x86";
    String cores = "20";
    String hostname = "Ubuntu";
    String speed = "2000000";
    String memory = "1024";
    String category = "compute";
    // create new request and add all attributes
    Form form = new Form();
    form.add("occi.compute.architecture", architecture);
    form.add("occi.compute.cores", cores);
    form.add("occi.compute.hostname", hostname);
    form.add("occi.compute.speed", speed);
    form.add("occi.compute.memory", memory);
    form.add("category", category);
    System.out.println("\n FORM " + form.toString());
    // create new representation
    Representation representation = null;
    try {
      // send post request
      representation = clientResource.post(form.toString(), MediaType.TEXT_PLAIN);
    } catch (Exception ex) {
      System.out.println("Failed to execute POST request " + ex.getMessage());
    }
    Assert.assertNotNull(representation);
    // get request and print it in debugger
    Request request = Request.getCurrent();
    System.out.println(request.toString() + "\n\n" + form.getMatrixString());
    System.out.println("--------------------------------");
    // get current response
    Response response = Response.getCurrent();
    Assert.assertNotNull(response);
    System.out.println("Response: " + response.toString());

    try {
      representation.write(System.out);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    System.out.println("\n--------------------------------");
  }
Beispiel #5
0
 /** Generate list with action names. */
 public static final HashSet<String> generateActionNames() {
   if (actionNames.isEmpty()) {
     for (int i = 0; i < beanFactory.getBeanDefinitionNames().length; i++) {
       if (beanFactory
           .getBean(beanFactory.getBeanDefinitionNames()[i])
           .toString()
           .contains("compute")) {
         actionNames.add(
             OcciConfig.getInstance().config.getString("occi.scheme")
                 + "/infrastructure/compute/action#"
                 + beanFactory.getBeanDefinitionNames()[i]);
       }
     }
   }
   return actionNames;
 }
Beispiel #6
0
/**
 * Class to test the compute interface. The test class starts the occi api and connects to it via
 * client resource.
 *
 * <p>Test cases are: HTTP POST HTTP GET HTTP DELETE HTTP PUT
 *
 * @author Sebastian Laag
 * @author Sebastian Heckmann
 */
public class TestRestCompute {
  private ClientResource clientResource =
      new ClientResource(OcciConfig.getInstance().config.getString("occi.server.location"));

  @BeforeTest
  public void setUp() {
    try {
      // start occi api
      occiApi.main(null);
    } catch (Exception ex) {
      System.out.println("Failed to start occiApi: " + ex.getMessage());
    }
  }

  @Test
  public void testGetCompute() {
    Compute compute = null;
    try {
      compute = new Compute(Architecture.x64, 2, "TestCase", 200, 20, State.active, null);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (NamingException e) {
      e.printStackTrace();
    }
    // test if compute ist not null
    Assert.assertNotNull(compute);
    // connect to api
    clientResource.setReference(
        OcciConfig.getInstance().config.getString("occi.server.location")
            + "compute/"
            + compute.getId());
    clientResource.setHostRef(
        OcciConfig.getInstance().config.getString("occi.server.location")
            + "compute/"
            + compute.getId());
    // create new representation
    Representation representation = null;
    try {
      // send post request
      representation = clientResource.get();
    } catch (Exception ex) {
      System.out.println("Failed to execute GET request: " + ex.getMessage());
    }
    Assert.assertNotNull(representation);
    // get request and print it in debugger
    Request request = Request.getCurrent();
    System.out.println(request.toString() + "\n\n");
    System.out.println("--------------------------------");
    // get current response
    Response response = Response.getCurrent();
    Assert.assertNotNull(response);
    System.out.println("Response: " + response.toString());

    try {
      representation.write(System.out);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    System.out.println("\n--------------------------------");
  }

  // TODO Die Parameter beim Request werden nicht korrekt übergeben. Keine
  // Ahnung woran es liegt.
  @Test(enabled = false)
  public void testPostCompute() {
    // connect to api
    clientResource.setReference(
        OcciConfig.getInstance().config.getString("occi.server.location") + "compute");
    // Tests if client resource is connected to api
    Assert.assertNotNull(clientResource);
    // try to create a compute resource
    String architecture = "x86";
    String cores = "20";
    String hostname = "Ubuntu";
    String speed = "2000000";
    String memory = "1024";
    String category = "compute";
    // create new request and add all attributes
    Form form = new Form();
    form.add("occi.compute.architecture", architecture);
    form.add("occi.compute.cores", cores);
    form.add("occi.compute.hostname", hostname);
    form.add("occi.compute.speed", speed);
    form.add("occi.compute.memory", memory);
    form.add("category", category);
    System.out.println("\n FORM " + form.toString());
    // create new representation
    Representation representation = null;
    try {
      // send post request
      representation = clientResource.post(form.toString(), MediaType.TEXT_PLAIN);
    } catch (Exception ex) {
      System.out.println("Failed to execute POST request " + ex.getMessage());
    }
    Assert.assertNotNull(representation);
    // get request and print it in debugger
    Request request = Request.getCurrent();
    System.out.println(request.toString() + "\n\n" + form.getMatrixString());
    System.out.println("--------------------------------");
    // get current response
    Response response = Response.getCurrent();
    Assert.assertNotNull(response);
    System.out.println("Response: " + response.toString());

    try {
      representation.write(System.out);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    System.out.println("\n--------------------------------");
  }

  @AfterTest
  public void tearDown() {
    clientResource = null;
    System.gc();
  }
}
Beispiel #7
0
  /**
   * Returns all available resources.
   *
   * @return ComputeResource String
   */
  @Get
  public String getOCCIRequest() {
    // set occi version
    getServerInfo().setAgent(OcciConfig.getInstance().config.getString("occi.version"));
    LOGGER.debug("getReference().getLastSegment(): " + getReference().getLastSegment());

    // if there is something behind -, set bad request
    if (!getReference().getLastSegment().equals("-")) {
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return "There are no resources at the query interface.";
    }

    createQueryKinds();
    createQueryLinks();
    createQueryMixins();

    StringBuffer buffer = new StringBuffer();
    /*
     * Print all properties of the kind instance
     */
    for (Kind kind : queryKinds) {
      if (kind != null) {
        buffer.append("Category: " + kind.getTerm() + ";");
        buffer.append(" scheme=\"" + kind.getScheme() + "\";");
        // buffer.append("\r\n");
        buffer.append(" class=\"kind\"");
        buffer.append("\r\n");
        // append related scheme to buffer, if kind has a related kind
        if (kind.getRelated() != null) {
          for (Kind related : kind.getRelated()) {
            if (related != null) {
              buffer.append("\t\t rel=").append(related.getScheme()).append(";\n");
            }
          }
        }
        buffer.append("\t\t attributes=\"");
        if (kind.getAttributes() != null) {
          for (String attribute : kind.getAttributes()) {
            if (attribute != null) {
              buffer.append(attribute).append(" ");
            }
          }
        }
        buffer.append("\";\n");
        buffer.append("\t\t actions=");
        for (String actionName : kind.getActionNames()) {
          if (actionName != null) {
            buffer.append(actionName).append(" ");
          }
        }
        buffer.append(";");
        buffer.append("\r\n");
        buffer.append("\t\t location=/").append(kind.getTerm()).append("/;");
        buffer.append("\r\n");
      }
    }

    /*
     * Print all link properties.
     */
    for (Link link : queryLinks) {
      if (link != null) {
        buffer.append("Category: ").append(link.getKind().getTerm()).append(";");
        buffer.append("\t\t scheme=\"").append(link.getKind().getScheme()).append("\";");
        buffer.append("\r\n");
        buffer.append("\t\t class=\"link\";");
        buffer.append("\r\n");
        // append related scheme to buffer, if kind has a related kind
        if (link.getKind().getRelated() != null) {
          for (Kind related : link.getKind().getRelated()) {
            if (related != null) {
              buffer.append("\t\t rel=").append(related.getScheme()).append(";\n");
            }
          }
        }
        buffer.append("\t\t attributes=\"");
        if (link.getKind().getAttributes() != null) {
          for (String attribute : link.getKind().getAttributes()) {
            if (attribute != null) {
              buffer.append(attribute + " ");
            }
          }
        }
        buffer.append("\";\n");
        buffer.append("\t\t actions=");
        for (String actionName : link.getKind().getActionNames()) {
          if (actionName != null) {
            buffer.append(actionName).append(" ");
          }
        }
        buffer.append(";");
        buffer.append("\r\n");
        buffer.append("\t\t location=/").append(link.getKind().getTerm()).append("/;");
        buffer.append("\r\n");
      }
    }

    /*
     * Print all properties of the mixin instance
     */

    if (ipNetworkInterface != null) {
      buffer.append("Category: ").append(ipNetworkInterface.getTitle()).append(";");
      buffer.append("\t\t scheme=\"").append(ipNetworkInterface.getScheme()).append("\";");
      buffer.append("\r\n");
      buffer.append("\t\t class=\"mixin\"");
      buffer.append("\r\n");
      // append related scheme to buffer, if kind has a related
      // kind
      if (ipNetworkInterface.getRelated() != null) {
        for (Mixin related : ipNetworkInterface.getRelated()) {
          if (related != null) {
            buffer.append("\t\t rel=").append(related.getScheme()).append(";\n");
          }
        }
      }
      buffer.append("\t\t attributes=\"");
      if (ipNetworkInterface.getAttributes() != null) {
        for (String attribute : ipNetworkInterface.getAttributes()) {
          if (attribute != null) {
            buffer.append(attribute).append(" ");
          }
        }
      }
      buffer.append("\";\n");
      buffer.append("\t\t location=/").append(ipNetworkInterface.getTerm()).append("/;");
      buffer.append("\r\n");
    }

    /*
     * Print all properties of the mixin instance
     */
    for (Mixin mixin : Mixin.getMixins()) {
      if (mixin != null && !mixin.getTerm().equals("ipnetwork")) {
        buffer.append("Category: " + mixin.getTitle()).append(";");

        buffer.append("\r\n");
        buffer.append("\t\t class=\"mixin\"");
        buffer.append("\r\n");
        // append related scheme to buffer, if kind has a related
        // kind
        if (mixin.getRelated() != null) {
          for (Mixin related : mixin.getRelated()) {
            if (related != null) {
              buffer.append("\t\t rel=").append(related.getScheme()).append(";\n");
            }
          }
        }
        buffer.append("\t\t scheme=").append(mixin.getScheme()).append(";");
        buffer.append("\r\n");
        buffer.append("\t\t location=/").append(mixin.getTerm()).append("/;");
        buffer.append("\r\n");
      }
    }
    buffer.append("\r\n");

    // Generate all action names list
    Network.generateActionNames();
    Storage.generateActionNames();
    Compute.generateActionNames();

    /*
     * Print all action names.
     */
    for (String computeAction : Compute.getActionNames()) {
      if (computeAction.contains("#")) {
        buffer
            .append("Category: " + computeAction.substring(computeAction.lastIndexOf("#") + 1))
            .append(";");
      } else {
        buffer.append("Cagegory: action;");
      }
      buffer
          .append(" scheme=\"" + computeAction.substring(0, computeAction.lastIndexOf("#") + 1))
          .append("\"\n");

      if (computeAction.contains("#start")) {
        // buffer.append(" attributes: ");
      } else if (computeAction.contains("#stop")) {
        // buffer.append(" attributes: "
        // + StopAction.getStopAttributesAsString() + " ");
      } else if (computeAction.contains("#restart")) {
        // buffer.append(" attributes: "
        // + RestartAction.getRestartAttributesAsString()
        // + " ");
      } else if (computeAction.contains("#suspend")) {
        // buffer.append(" attributes: "
        // + SuspendAction.getSuspendAttributesAsString()
        // + " ");
      }
    }

    for (String storageAction : Storage.getActionNames()) {
      if (storageAction.contains("#")) {
        buffer
            .append("Category: ")
            .append(storageAction.substring(storageAction.lastIndexOf("#") + 1))
            .append(";");
      } else {
        buffer.append("Cagegory: action;");
      }
      buffer
          .append("\t\t scheme=\"")
          .append(storageAction.substring(0, storageAction.lastIndexOf("#") + 1))
          .append("\"\n");
    }

    for (String networkAction : Network.getActionNames()) {
      if (networkAction.contains("#")) {
        buffer
            .append("Category: " + networkAction.substring(networkAction.lastIndexOf("#") + 1))
            .append(";");
      } else {
        buffer.append("Cagegory: action;");
      }
      buffer
          .append("\t\t scheme=\"" + networkAction.substring(0, networkAction.lastIndexOf("#") + 1))
          .append("\"\n");
    }

    // access the request headers and get the Accept attribute of the
    // Content-Type
    Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
    Representation representation =
        OcciCheck.checkContentType(requestHeaders, buffer, getResponse());
    LOGGER.debug("Raw Request headers: " + requestHeaders.toString());

    /*
     * if content type equals text/occi, render query information in the
     * header and NOT in the body
     */
    if (representation.getMediaType().toString().equals("text/occi")) {
      // Generate the header rendering if media-type equals text/occi
      OcciCheck occiCheck = new OcciCheck();
      occiCheck.setHeaderRendering((LinkedList<Kind>) queryKinds);
      getResponse().setEntity(representation);
      return " ";
    }
    // add content type and status to client response
    getResponse().setEntity(representation);
    return " ";
  }
Beispiel #8
0
  /**
   * Delete a existing mixin definition. If it does not exist 404 Not Found Exception.
   *
   * @param representation
   * @return removed mixin defintion and status
   */
  @Delete
  public String deleteOCCIRequest(Representation representation) {
    // set occi version info
    getServerInfo().setAgent(OcciConfig.getInstance().config.getString("occi.version"));

    StringBuffer buffer = new StringBuffer();
    // save header information
    Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");

    String requestCategory = "";
    String categoryCase = OcciCheck.checkCaseSensitivity(requestHeaders.toString()).get("category");
    // match category and Category

    if (requestHeaders.getFirstValue(categoryCase) != null) {
      // get header values
      requestCategory = requestHeaders.getFirstValue(categoryCase);
    } else {
      // set status code bad request
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return " ";
    }
    requestCategory = OcciCheck.addWhitespaceAfterSemicolonAndTrim(requestCategory);

    // print header information
    LOGGER.debug("Request Header: " + requestCategory);
    StringTokenizer categoryList = new StringTokenizer(requestCategory);
    HashMap<String, Object> categoryMap = new HashMap<String, Object>();
    // fill category map with header information
    while (categoryList.hasMoreTokens()) {
      // store header information in seperate array fields
      String[] temp = categoryList.nextToken().split("\\=");
      LOGGER.debug("Category List: " + temp[0]);
      if (temp.length > 1) {
        LOGGER.debug("Category List: " + temp[0] + "\t" + temp[1]);
        if (temp[0] != null && temp[1] != null) {
          // remove leading, trailing whitespaces and add whitespaces
          // between semicolons
          temp[0] = OcciCheck.addWhitespaceAfterSemicolonAndTrim(temp[0]);
          temp[1] = OcciCheck.addWhitespaceAfterSemicolonAndTrim(temp[1]);
          categoryMap.put(temp[0], temp[1]);
        }
      } else {
        if (temp[0].contains(";")) {
          temp[0] = temp[0].replace(";", "");
        }
        categoryMap.put(categoryCase, temp[0]);
      }
    }
    // iterate through all mixin instances
    for (Mixin mixin : Mixin.getMixins()) {
      // if the request parameter match a existing mixin definition,
      // delete the definition
      LOGGER.info(
          "Category Map: " + categoryMap.get(categoryCase) + "\t mixin title: " + mixin.getTitle());
      if (mixin.getTitle().equals(categoryMap.get(categoryCase))) {
        Mixin.getMixins().remove(mixin);
        mixin = null;
        // access the request headers and get the Accept attribute
        representation =
            OcciCheck.checkContentType(requestHeaders, buffer.append(" "), getResponse());
        // set representation
        getResponse().setEntity(representation);
        // getResponse().setStatus(Status.SUCCESS_OK,
        // buffer.toString());
        return " ";
      }
    }
    buffer.append("Mixin definition not found");
    getResponse().setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED, buffer.toString());
    return buffer.toString();
  }