Esempio n. 1
0
  protected Representation formatJSON(JSON json, Variant variant) {
    Representation r = null;
    // TODO: Firefox 2 seems to not send the specified application/json header
    //       (especially after a redirect)
    //       so we will send application/json always for now
    //       (as we don't support this API any other way right now)
    if (true /* TODO:  This is a hack */) {
      r = new StringRepresentation(json.toString(), MediaType.APPLICATION_JSON);
    } else if (MediaType.APPLICATION_JSON.equals(variant.getMediaType())
        || MediaType.APPLICATION_JAVASCRIPT.equals(variant.getMediaType())
        || MediaType.TEXT_JAVASCRIPT.equals(variant.getMediaType())) {
      r = new StringRepresentation(json.toString(), variant.getMediaType());
      // TODO: make this output streaming! (this library does not support it, which is fairly
      // crazy!)
    } else if (MediaType.APPLICATION_XML.equals(variant.getMediaType())
        || MediaType.TEXT_XML.equals(variant.getMediaType())) {
      r = new StringRepresentation(new XMLSerializer().write(json), variant.getMediaType());
    } else if (MediaType.TEXT_PLAIN.equals(variant.getMediaType())
        || MediaType.TEXT_HTML.equals(variant.getMediaType())) {
      r = new StringRepresentation(json.toString(4), variant.getMediaType());
    } else {
      getResponse().setStatus(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
    }

    r.setCharacterSet(CharacterSet.UTF_8);
    return r;
  }
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    IntParameterInfo parameterInfo;
    OpenAcdAgent agent;
    OpenAcdAgentRestInfoFull agentRestInfo;

    // if have id then get a single item
    parameterInfo = RestUtilities.getIntFromAttribute(getRequest(), REQUEST_ATTRIBUTE_ID);
    if (parameterInfo.getExists()) {
      if (!parameterInfo.getValid()) {
        return RestUtilities.getResponseError(
            getResponse(), ERROR_ID_INVALID, parameterInfo.getValueString());
      }

      try {
        agent = m_openAcdContext.getAgentById(parameterInfo.getValue());
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(), ERROR_OBJECT_NOT_FOUND, parameterInfo.getValue());
      }

      try {
        agentRestInfo = createAgentRestInfo(agent);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(),
            ERROR_READ_FAILED,
            parameterInfo.getValue(),
            exception.getLocalizedMessage());
      }

      return new OpenAcdAgentRepresentation(variant.getMediaType(), agentRestInfo);
    }

    // if not single, process request for list
    List<OpenAcdAgent> agents = m_openAcdContext.getAgents();
    List<OpenAcdAgentRestInfoFull> agentsRestInfo = new ArrayList<OpenAcdAgentRestInfoFull>();
    MetadataRestInfo metadataRestInfo;

    // sort if specified
    sortAgents(agents);

    // set requested agents groups and get resulting metadata
    metadataRestInfo = addAgents(agentsRestInfo, agents);

    // create final restinfo
    OpenAcdAgentsBundleRestInfo agentsBundleRestInfo =
        new OpenAcdAgentsBundleRestInfo(agentsRestInfo, metadataRestInfo);

    return new OpenAcdAgentsRepresentation(variant.getMediaType(), agentsBundleRestInfo);
  }
Esempio n. 3
0
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    IntParameterInfo parameterInfo;
    Branch branch;
    BranchRestInfoFull branchRestInfo;

    // if have id then get a single item
    parameterInfo = RestUtilities.getIntFromAttribute(getRequest(), REQUEST_ATTRIBUTE_ID);
    if (parameterInfo.getExists()) {
      if (!parameterInfo.getValid()) {
        return RestUtilities.getResponseError(
            getResponse(), ERROR_ID_INVALID, parameterInfo.getValueString());
      }

      try {
        branch = m_branchManager.retrieveBranch(parameterInfo.getValue());
        if (branch == null) {
          return RestUtilities.getResponseError(
              getResponse(), ERROR_OBJECT_NOT_FOUND, parameterInfo.getValue());
        }

        branchRestInfo = createBranchRestInfo(branch);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(),
            ERROR_READ_FAILED,
            parameterInfo.getValue(),
            exception.getLocalizedMessage());
      }

      return new BranchRepresentation(variant.getMediaType(), branchRestInfo);
    }

    // if not single, process request for list
    List<Branch> branches = m_branchManager.getBranches();
    List<BranchRestInfoFull> branchesRestInfo = new ArrayList<BranchRestInfoFull>();
    MetadataRestInfo metadataRestInfo;

    // sort if specified
    sortBranches(branches);

    // set requested agents groups and get resulting metadata
    metadataRestInfo = addBranches(branchesRestInfo, branches);

    // create final restinfo
    BranchesBundleRestInfo branchesBundleRestInfo =
        new BranchesBundleRestInfo(branchesRestInfo, metadataRestInfo);

    return new BranchesRepresentation(variant.getMediaType(), branchesBundleRestInfo);
  }
Esempio n. 4
0
 protected Representation doRepresent(Object payload, Variant variant) throws ResourceException {
   if (Representation.class.isAssignableFrom(payload.getClass())) {
     // representation
     return (Representation) payload;
   } else if (InputStream.class.isAssignableFrom(payload.getClass())) {
     // inputStream
     return new InputStreamRepresentation(variant.getMediaType(), (InputStream) payload);
   } else if (String.class.isAssignableFrom(payload.getClass())) {
     // inputStream
     return new StringRepresentation((String) payload, variant.getMediaType());
   } else {
     // object, make it a representation
     return serialize(variant, payload);
   }
 }
 /**
  * Returns a full representation for a given variant.
  *
  * @param variant the requested variant of this representation
  * @return the representation of this resource
  * @throws ResourceException when the requested resource cannot be represented as requested.
  */
 @Override
 public Representation represent(Variant variant) throws ResourceException {
   String xmlString;
   // If credentials are provided, they need to be valid
   if (!isAnonymous() && !validateCredentials()) {
     return null;
   }
   // First check if source in URI exists
   if (validateKnownSource()) {
     Source source = dbManager.getSource(uriSource);
     // If source is private, check if current user is allowed to view
     if ((!source.isPublic()) && (!validateSourceOwnerOrAdmin())) {
       return null;
     }
     // If we make it here, we're all clear to send the XML: either source is public or source is
     // private but user is authorized to GET.
     if (variant.getMediaType().equals(MediaType.TEXT_XML)) {
       try {
         xmlString = getSourceSummary();
       } catch (JAXBException e) {
         setStatusInternalError(e);
         return null;
       }
       return getStringRepresentation(xmlString);
     }
     // Some MediaType other than text/xml requested
     else {
       return null;
     }
   } else {
     // unknown source
     return null;
   }
 }
Esempio n. 6
0
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    // process request for single
    int idInt;
    BranchRestInfoFull branchRestInfo = null;
    String idString = (String) getRequest().getAttributes().get("id");

    if (idString != null) {
      try {
        idInt = RestUtilities.getIntFromAttribute(idString);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(),
            RestUtilities.ResponseCode.ERROR_BAD_INPUT,
            "ID " + idString + " not found.");
      }

      try {
        branchRestInfo = createBranchRestInfo(idInt);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(),
            RestUtilities.ResponseCode.ERROR_READ_FAILED,
            "Read Skills failed",
            exception.getLocalizedMessage());
      }

      return new BranchRepresentation(variant.getMediaType(), branchRestInfo);
    }

    // if not single, process request for all
    List<Branch> branches = m_branchManager.getBranches();
    List<BranchRestInfoFull> branchesRestInfo = new ArrayList<BranchRestInfoFull>();
    MetadataRestInfo metadataRestInfo;

    // sort if specified
    sortBranches(branches);

    // set requested agents groups and get resulting metadata
    metadataRestInfo = addBranches(branchesRestInfo, branches);

    // create final restinfo
    BranchesBundleRestInfo branchesBundleRestInfo =
        new BranchesBundleRestInfo(branchesRestInfo, metadataRestInfo);

    return new BranchesRepresentation(variant.getMediaType(), branchesBundleRestInfo);
  }
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    // process request for single
    int idInt;
    OpenAcdQueueGroupRestInfoFull queueGroupRestInfo = null;
    String idString = (String) getRequest().getAttributes().get("id");

    if (idString != null) {
      try {
        idInt = RestUtilities.getIntFromAttribute(idString);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(), ResponseCode.ERROR_BAD_INPUT, "ID " + idString + " not found.");
      }

      try {
        queueGroupRestInfo = createQueueGroupRestInfo(idInt);
      } catch (Exception exception) {
        return RestUtilities.getResponseError(
            getResponse(),
            ResponseCode.ERROR_READ_FAILED,
            "Read Queue Group failed",
            exception.getLocalizedMessage());
      }

      return new OpenAcdQueueGroupRepresentation(variant.getMediaType(), queueGroupRestInfo);
    }

    // if not single, process request for all
    List<OpenAcdQueueGroup> queueGroups = m_openAcdContext.getQueueGroups();
    List<OpenAcdQueueGroupRestInfoFull> queueGroupsRestInfo =
        new ArrayList<OpenAcdQueueGroupRestInfoFull>();
    MetadataRestInfo metadataRestInfo;

    // sort if specified
    sortQueueGroups(queueGroups);

    // set requested based on pagination and get resulting metadata
    metadataRestInfo = addQueueGroups(queueGroupsRestInfo, queueGroups);

    // create final restinfo
    OpenAcdQueueGroupsBundleRestInfo queueGroupsBundleRestInfo =
        new OpenAcdQueueGroupsBundleRestInfo(queueGroupsRestInfo, metadataRestInfo);

    return new OpenAcdQueueGroupsRepresentation(variant.getMediaType(), queueGroupsBundleRestInfo);
  }
  /**
   * Returns an UnitTestDailyProjectData instance.
   *
   * @param variant The representational variant requested.
   * @return The representation.
   */
  @Override
  public Representation represent(Variant variant) {
    Logger logger = this.server.getLogger();
    logger.fine("UnitTest DPD: Starting");
    if (variant.getMediaType().equals(MediaType.TEXT_XML)) {
      try {
        // [1] get the SensorBaseClient for the user making this request.
        SensorBaseClient client = super.getSensorBaseClient();
        // [2] Check the front side cache and return if the DPD is found and is OK to access.
        String cachedDpd = this.server.getFrontSideCache().get(uriUser, project, uriString);
        if ((cachedDpd != null) && client.inProject(uriUser, project)) {
          return super.getStringRepresentation(cachedDpd);
        }
        // [2] get a SensorDataIndex of UnitTest sensor data for this Project on the requested day.
        XMLGregorianCalendar startTime = Tstamp.makeTimestamp(this.timestamp);
        XMLGregorianCalendar endTime = Tstamp.incrementDays(startTime, 1);
        logger.fine("UnitTest DPD: Requesting index: " + uriUser + " " + project);
        SensorDataIndex index =
            client.getProjectSensorData(uriUser, project, startTime, endTime, "UnitTest");
        // [3] Update the counter with this data.
        logger.fine("UnitTest DPD: Got index.  " + index.getSensorDataRef().size() + " instances");
        UnitTestCounter counter = new UnitTestCounter();
        for (SensorDataRef ref : index.getSensorDataRef()) {
          counter.add(client.getSensorData(ref));
        }
        logger.fine("UnitTest DPD: Finished retrieving instances. ");

        // return resulting data
        UnitTestDailyProjectData unitTestDPD = new UnitTestDailyProjectData();
        // create the individual MemberData elements.
        String sensorBaseHost = this.server.getServerProperties().get(SENSORBASE_FULLHOST_KEY);
        for (String member : counter.getMembers()) {
          MemberData memberData = new MemberData();
          memberData.setMemberUri(sensorBaseHost + "users/" + member);
          memberData.setSuccess(counter.getPassCount(member));
          memberData.setFailure(counter.getFailCount(member));
          unitTestDPD.getMemberData().add(memberData);
        }

        unitTestDPD.setOwner(uriUser);
        unitTestDPD.setProject(project);
        unitTestDPD.setStartTime(startTime);
        unitTestDPD.setUriPattern("**"); // we don't support UriPatterns yet.

        String xmlData = makeUnitTestDPD(unitTestDPD);
        if (!Tstamp.isTodayOrLater(startTime)) {
          this.server.getFrontSideCache().put(uriUser, project, uriString, xmlData);
        }
        logRequest("UnitTest");
        return super.getStringRepresentation(xmlData);

      } catch (Exception e) {
        setStatusError("Error creating UnitTest DPD.", e);
        return null;
      }
    }
    return null;
  }
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    final MediaType mediaType = variant.getMediaType();
    if (mediaType.equals(MediaType.TEXT_XML)) {
      return new StringRepresentation("<a>b</a>", mediaType);
    } else if (mediaType.equals(MediaType.TEXT_HTML)) {
      return new StringRepresentation("<html><body>a</body></html>", mediaType);
    }

    return null;
  }
Esempio n. 10
0
  protected XStreamRepresentation createRepresentation(Variant variant) throws ResourceException {
    XStreamRepresentation representation = null;

    try {
      // check is this variant a supported one, to avoid calling getText() on potentially huge
      // representations
      if (MediaType.APPLICATION_JSON.equals(variant.getMediaType(), true)
          || MediaType.APPLICATION_XML.equals(variant.getMediaType(), true)
          || MediaType.TEXT_HTML.equals(variant.getMediaType(), true)) {
        String text =
            (variant instanceof Representation) ? ((Representation) variant).getText() : "";

        XStream xstream;
        if (MediaType.APPLICATION_JSON.equals(variant.getMediaType(), true)
            || MediaType.TEXT_HTML.equals(variant.getMediaType(), true)) {
          xstream =
              (XStream)
                  getContext().getAttributes().get(PlexusRestletApplicationBridge.JSON_XSTREAM);
        } else if (MediaType.APPLICATION_XML.equals(variant.getMediaType(), true)) {
          xstream =
              (XStream)
                  getContext().getAttributes().get(PlexusRestletApplicationBridge.XML_XSTREAM);
        } else {
          return null;
        }

        if (text != null) {
          CharacterSet charset = variant.getCharacterSet();
          if (charset == null) {
            charset = CharacterSet.ISO_8859_1;
          }
          if (!CharacterSet.UTF_8.equals(charset)) {
            // must fix text encoding NXCM-2494
            text = new String(new String(text.getBytes(), "UTF-8").getBytes(charset.getName()));
          }
        }

        representation = new XStreamRepresentation(xstream, text, variant.getMediaType());
        return representation;
      } else {
        return null;
      }
    } catch (IOException e) {
      throw new ResourceException(
          Status.SERVER_ERROR_INTERNAL, "Cannot get the representation!", e);
    }
  }
 @Override
 public Representation represent(Variant variant) throws ResourceException {
   Phonebook privatePhonebook = m_phonebookManager.getPrivatePhonebook(getUser());
   if (privatePhonebook != null) {
     Collection<PhonebookEntry> entries = privatePhonebook.getEntries();
     ArrayList<String> ids = new ArrayList<String>();
     for (PhonebookEntry entry : entries) {
       ids.add(String.valueOf(entry.getId()));
     }
     if (ids.contains(m_entryId)) {
       PhonebookEntry entry = m_phonebookManager.getPhonebookEntry(Integer.parseInt(m_entryId));
       PhonebookEntry reprEntry = (PhonebookEntry) entry.duplicate();
       return new PhonebookEntryRepresentation(variant.getMediaType(), reprEntry);
     }
   }
   return null;
 }
Esempio n. 12
0
  protected Representation serialize(Variant variant, Object payload) throws ResourceException {
    if (payload == null) {
      return null;
    }

    XStreamRepresentation result = createRepresentation(variant);

    if (result == null) {
      throw new ResourceException(
          Status.CLIENT_ERROR_NOT_ACCEPTABLE,
          "The requested mediaType='" + variant.getMediaType() + "' is unsupported!");
    }

    result.setPayload(payload);

    return result;
  }
Esempio n. 13
0
 public Representation represent(Variant variant) throws ResourceException {
   Representation representation;
   if (variant.getMediaType() == MediaType.APPLICATION_XML) {
     representation =
         new WriterRepresentation(MediaType.APPLICATION_XML) {
           public void write(Writer writer) throws IOException {
             XmlMarshaller.marshalDocument(writer, "script", makePresentableMap());
           }
         };
   } else {
     representation =
         new WriterRepresentation(MediaType.TEXT_HTML) {
           public void write(Writer writer) throws IOException {
             ScriptResource.this.writeHtml(writer);
           }
         };
   }
   // TODO: remove if not necessary in future?
   representation.setCharacterSet(CharacterSet.UTF_8);
   return representation;
 }
Esempio n. 14
0
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    Representation result = null;

    if (variant.getMediaType().equals(MediaType.TEXT_PLAIN)) {
      // Creates a text representation
      final StringBuilder sb = new StringBuilder();
      sb.append("----------------\n");
      sb.append("Bookmark details\n");
      sb.append("----------------\n\n");
      sb.append("User:     "******"URI:      ").append(this.bookmark.getUri()).append('\n');
      sb.append("Short:    ").append(this.bookmark.getShortDescription()).append('\n');
      sb.append("Long:     ").append(this.bookmark.getLongDescription()).append('\n');
      sb.append("Date:     ").append(this.bookmark.getDateTime()).append('\n');
      sb.append("Restrict: ").append(Boolean.toString(this.bookmark.isRestrict())).append('\n');
      result = new StringRepresentation(sb);
    }

    return result;
  }