コード例 #1
0
  @Get("xml")
  public Representation toXml() {
    try {
      DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML);
      // Generate a DOM document representing the item.
      Document d = representation.getDocument();

      Element eltItem = d.createElement("item");
      d.appendChild(eltItem);
      Element eltName = d.createElement("name");
      eltName.appendChild(d.createTextNode(item.getName()));
      eltItem.appendChild(eltName);

      Element eltDescription = d.createElement("description");
      eltDescription.appendChild(d.createTextNode(item.getDescription()));
      eltItem.appendChild(eltDescription);

      d.normalizeDocument();

      // Returns the XML representation of this document.
      return representation;
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
コード例 #2
0
  @Get
  public Representation toXml() throws IOException {
    // Create a new DOM representation
    DomRepresentation result = new DomRepresentation();

    // Ensure pretty printing
    result.setIndenting(true);

    // Retrieve the DOM document to populate
    Document doc = result.getDocument();

    // Append the root node
    Node mailElt = doc.createElement("mail");
    doc.appendChild(mailElt);

    // Append the child nodes and set their text content
    Node statusElt = doc.createElement("status");
    statusElt.setTextContent("received");
    mailElt.appendChild(statusElt);

    Node subjectElt = doc.createElement("subject");
    subjectElt.setTextContent("Message to self");
    mailElt.appendChild(subjectElt);

    Node contentElt = doc.createElement("content");
    contentElt.setTextContent("Doh!");
    mailElt.appendChild(contentElt);

    Node accountRefElt = doc.createElement("accountRef");
    accountRefElt.setTextContent(new Reference(getReference(), "..").getTargetRef().toString());
    mailElt.appendChild(accountRefElt);
    return result;
  }
コード例 #3
0
  /**
   * Returns the list of identifiers for the mails in the inbox
   *
   * @return The list of identifiers.
   * @throws ResourceException
   */
  protected List<String> getMailIdentifiers() throws ResourceException {
    final List<String> result = new ArrayList<String>();

    // 1 - Get to mailbox content
    final Request request = new Request(Method.GET, getMailboxUri());
    if (getMailboxChallengeScheme() != null) {
      final ChallengeResponse challengeResponse =
          new ChallengeResponse(
              getMailboxChallengeScheme(), getMailboxLogin(), getMailboxPassword());
      request.setChallengeResponse(challengeResponse);
    }
    final Response response = getContext().getClientDispatcher().handle(request);

    if (!response.getStatus().isSuccess()) {
      throw new ResourceException(response.getStatus(), "Cannot get the mail iddentifiers.");
    }

    // 2 - Parse the list of mails
    if (response.isEntityAvailable()) {
      final DomRepresentation rep = new DomRepresentation(response.getEntity());
      for (final Node node : rep.getNodes("/emails/email/@href")) {
        final String href = node.getNodeValue();
        if (href.startsWith("/")) {
          result.add(href.substring(1));
        } else {
          result.add(href);
        }
      }
    }

    return result;
  }
コード例 #4
0
  @Post("xml")
  public Representation testDoctor(Representation entity) {

    DomRepresentation representation = null;
    try {
      DomRepresentation input = new DomRepresentation(entity);
      // input
      Document doc = input.getDocument();
      Element rootEl = doc.getDocumentElement();
      String username = XMLUtils.getTextValue(rootEl, "username");
      String firstName = XMLUtils.getTextValue(rootEl, "firstname");
      String lastName = XMLUtils.getTextValue(rootEl, "lastname");

      // output
      representation = new DomRepresentation(MediaType.TEXT_XML);

      String res = "OK " + username;

      Map<String, String> map = new HashMap<String, String>();
      map.put("result", res);
      Document d = representation.getDocument();
      d = XMLUtils.createXMLResult("doctorTestOutput", map, d);

    } catch (IOException e) {
      representation = XMLUtils.createXMLError("login error", "" + e.getMessage());
    }

    // Returns the XML representation of this document.
    return representation;
  }
コード例 #5
0
  /**
   * Tests that we can GET a value from the system and verify that it is within acceptable range.
   *
   * @throws Exception if GET fails
   */
  @Test
  public void testGet() throws Exception {
    PhotovoltaicsData.modifySystemState();

    // Set up the GET client
    // String getUrl = "http://localhost:7001/photovoltaic/state";
    String getUrl = "http://localhost:7001/cgi-bin/egauge?tot";
    ClientResource getClient = new ClientResource(getUrl);

    // Get the XML representation.
    DomRepresentation domRep = new DomRepresentation(getClient.get());
    Document domDoc = domRep.getDocument();

    // Grabs tags from XML.
    NodeList meterList = domDoc.getElementsByTagName("meter");
    NodeList energyList = domDoc.getElementsByTagName("energy");
    NodeList powerList = domDoc.getElementsByTagName("power");

    // Grabs attributes from tags.
    String title = ((Element) meterList.item(1)).getAttribute("title");

    // Grabs value from tags.
    String energy = ((Element) energyList.item(1)).getTextContent();
    String power = ((Element) powerList.item(1)).getTextContent();

    // Check that we are returning the correct title.
    assertEquals("Checking that title is \"Solar\"", title, "Solar");

    // Check that the returned value is within a delta of our value.
    assertEquals(1500, Double.parseDouble(energy), 1750);
    assertEquals(700, Double.parseDouble(power), 700);
  }
コード例 #6
0
  @Post("xml")
  public Representation acceptItem(Representation entity) {

    DomRepresentation result = null;
    Document d = null;
    try {

      DomRepresentation input = new DomRepresentation(entity);
      Document doc = input.getDocument();
      // handle input document
      Element rootEl = doc.getDocumentElement();
      String usernameDoctor = XMLUtils.getTextValue(rootEl, "username");
      // output
      result = new DomRepresentation(MediaType.TEXT_XML);
      d = result.getDocument();

      try {
        ObjectifyService.register(Patient.class);
        ObjectifyService.register(Relative.class);
      } catch (Exception e) {
      }

      Key<Relative> doctor = new Key<Relative>(Relative.class, usernameDoctor);

      Objectify ofy = ObjectifyService.begin();

      List<Patient> listRU = ofy.query(Patient.class).filter("doctor", doctor).list();

      Element root = d.createElement("getUsers");
      d.appendChild(root);

      Element eltName4 = d.createElement("getUsersList");

      for (Patient us : listRU) {

        Element user = d.createElement("user");

        user.setAttribute("firstname", "" + us.getFirstName());
        user.setAttribute("lastname", "" + us.getLastName());
        user.setAttribute("username", "" + us.getUsername());
        user.setAttribute("password", "" + us.getPassword());
        user.appendChild(d.createTextNode(us.getUsername()));
        eltName4.appendChild(user);
      }
      root.appendChild(eltName4);

      d.normalizeDocument();

    } catch (Exception e) {
      result = XMLUtils.createXMLError("get doctors list error", "" + e.getMessage());
    }

    return result;
  }
コード例 #7
0
ファイル: UsersResource.java プロジェクト: flacro/photowall
  @Post
  public Representation update(Representation entity) {
    DomRepresentation r = null;
    try {
      int userid = Integer.parseInt((String) getRequest().getAttributes().get("userid"));
      Users u = userservice.getUsers(userid);
      String fname = u.getLogo();
      // upload picture
      ResourceBundle rb = ResourceBundle.getBundle("config");
      String path = rb.getString("albumpath");
      String fileName = "";
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // Configure the factory here, if desired.
      ServletFileUpload upload = new ServletFileUpload(factory);
      // Configure the uploader here, if desired.
      List fileItems = upload.parseRequest(ServletUtils.getRequest(getRequest()));
      Iterator iter = fileItems.iterator();
      for (; iter.hasNext(); ) {
        FileItem fileItem = (FileItem) iter.next();
        if (fileItem.isFormField()) { // 当前是一个表单项
          System.out.println(
              "form field : " + fileItem.getFieldName() + ", " + fileItem.getString());
        } else {
          // 当前是一个上传的文件
          fileName = fileItem.getName();
          String extension = fileName.substring(fileName.lastIndexOf("."));
          if (fname == null || fname.equals("")) {
            Random random = new Random(10);
            int n = random.nextInt(10000);
            fileName = new Date().getTime() + "-" + n + extension;
          } else fileName = fname;
          fileItem.write(new File(path + fileName));
        }
        // 只处理第一张图片
        break;
      }

      // 生成XML表示
      r = new DomRepresentation(MediaType.TEXT_XML);
      Document doc = r.getDocument();
      Element root = doc.createElement("varkrs");
      root.setAttribute("id", "" + u.getId());
      root.setAttribute("name", u.getUsername());
      root.setAttribute("gender", "" + u.getGender());
      root.setAttribute("grade", "" + u.getGrade());
      root.setAttribute("logo", u.getLogo());
      doc.appendChild(root);
      return r;
    } catch (Exception e) {
      LogDetail.logexception(e);
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return null;
    }
  }
コード例 #8
0
  /**
   * Handle HTTP GET Metod / xml
   *
   * @return an XML list of contacts.
   */
  @Get("xml")
  public Representation toXML() {
    // System.out.println("Request Original Ref " + getOriginalRef());
    // System.out.println("Request Entity " + getRequest().getEntityAsText()
    // +
    // " entity mediaType " + getRequest().getEntity().getMediaType());

    Reference ref = getRequest().getResourceRef();
    final String baseURL = ref.getHierarchicalPart();
    Form formQuery = ref.getQueryAsForm();

    try {
      DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML);

      Document d = representation.getDocument();
      Element elContacts = d.createElement(CONTACTS);
      d.appendChild(elContacts);

      Iterator<Contact> it =
          getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator();
      while (it.hasNext()) {
        Contact contact = it.next();

        Element el = d.createElement(CONTACT);

        Element id = d.createElement(ID);
        id.appendChild(d.createTextNode(String.format("%s", contact.getId())));
        el.appendChild(id);

        Element firstname = d.createElement(FIRST_NAME);
        firstname.appendChild(d.createTextNode(contact.getFirstName()));
        el.appendChild(firstname);

        Element lastname = d.createElement(LAST_NAME);
        lastname.appendChild(d.createTextNode(contact.getLastName()));
        el.appendChild(lastname);

        Element url = d.createElement(URL);
        url.appendChild(d.createTextNode(String.format("%s/%s", baseURL, contact.getId())));
        el.appendChild(url);

        elContacts.appendChild(el);
      }

      d.normalizeDocument();
      return representation;
    } catch (Exception e) {
      setStatus(Status.SERVER_ERROR_INTERNAL);
      return null;
    }
  }
コード例 #9
0
  @Put
  public void store(DomRepresentation mailRep) {
    // Retrieve the XML element using XPath expressions
    String status = mailRep.getText("/mail/status");
    String subject = mailRep.getText("/mail/subject");
    String content = mailRep.getText("/mail/content");
    String accountRef = mailRep.getText("/mail/accountRef");

    // Output the XML element values
    System.out.println("Status: " + status);
    System.out.println("Subject: " + subject);
    System.out.println("Content: " + content);
    System.out.println("Account URI: " + accountRef);
  }
コード例 #10
0
  @Post("xml")
  public Representation acceptItem(Representation entity) {

    DomRepresentation representation = null;
    try {
      DomRepresentation input = new DomRepresentation(entity);
      // input
      Document doc = input.getDocument();
      Element rootEl = doc.getDocumentElement();
      String username = XMLUtils.getTextValue(rootEl, "username");

      // output
      representation = new DomRepresentation(MediaType.TEXT_XML);

      // Generate a DOM document representing the list of
      // items.

      String res = "";
      try {
        ObjectifyService.register(Patient.class);
      } catch (Exception e) {
      }

      Objectify ofy = ObjectifyService.begin();
      Patient us = ofy.query(Patient.class).filter("username", username).get();
      if (us == null) {
        res = "user not found.";
      } else {

        ofy.delete(us);
        res = "OK, " + us.getUsername() + " deleted.";
      }
      getLogger().info("res: " + res);
      Map<String, String> map = new HashMap<String, String>();
      map.put("result", res);
      Document d = representation.getDocument();
      d = XMLUtils.createXMLResult("rehabDeleteUserOutput", map, d);

    } catch (IOException e) {
      representation = XMLUtils.createXMLError("user delete error", "" + e.getMessage());
    }

    // Returns the XML representation of this document.
    return representation;
  }
コード例 #11
0
  /**
   * @param subPath
   * @throws IOException
   * @throws DOMException
   */
  private void getAndCheckJaxb(String subPath) throws Exception {
    Response response = get(subPath);
    assertEquals(Status.SUCCESS_OK, response.getStatus());

    DomRepresentation entity = new DomRepresentation(response.getEntity());
    Node xml = entity.getDocument().getFirstChild();
    System.out.println(subPath + ": " + entity.getText());
    assertEquals("person", xml.getNodeName());

    NodeList nodeList = xml.getChildNodes();
    Node node = nodeList.item(0);
    assertEquals("firstname", node.getNodeName());
    assertEquals("Angela", node.getFirstChild().getNodeValue());

    node = nodeList.item(1);
    assertEquals("lastname", node.getNodeName());
    assertEquals("Merkel", node.getFirstChild().getNodeValue());
    assertEquals(2, nodeList.getLength());
  }
コード例 #12
0
ファイル: UsersResource.java プロジェクト: flacro/photowall
  @Get
  public Representation get() {
    try {
      int id = Integer.parseInt(getRequest().getAttributes().get("userid").toString());
      Users u = userservice.getUsers(id);

      // 生成XML表示
      DomRepresentation r = new DomRepresentation(MediaType.TEXT_XML);
      Document doc = r.getDocument();
      Element root = doc.createElement("varkrs");
      root.setAttribute("id", "" + u.getId());
      root.setAttribute("name", u.getUsername());
      root.setAttribute("gender", "" + u.getGender());
      root.setAttribute("grade", "" + u.getGrade());
      root.setAttribute("logo", u.getLogo());
      doc.appendChild(root);
      return r;
    } catch (Exception e) {
      LogDetail.logexception(e);
      getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
      return null;
    }
  }
コード例 #13
0
  @Delete("xml")
  public String deleteClinicConnectionDetails(DomRepresentation rep)
      throws IOException, SAXException {
    StringWriter xml = new StringWriter();
    XmlWriter xmlWriter = new XmlWriter(xml);

    xmlWriter.startDocument();
    xmlWriter.setDataFormat(true);

    xmlWriter.startElement("response");

    Element dataNode = (Element) rep.getNode("//request/data");

    ClinicRequirements deletedInstance = null;
    try {
      if (dataNode != null) {
        xmlConverter.alias("data", ClinicRequirements.class);
        //				deletedInstance = clinicRequirementsBean
        //						.delete((ClinicRequirements) xmlConverter
        //								.unmarshal(new DomReader(dataNode)));

        xmlWriter.dataElement("status", "0");
        xmlWriter.startElement("data");
        xmlWriter.startElement("record");
        //				xmlWriter.dataElement("clinicRequireMentId", new Integer(
        //						deletedInstance.getClinicRequirementId()).toString());
        xmlWriter.endElement("record");
        xmlWriter.endElement("data");

      } else // Sending error message
      {
        xmlWriter.dataElement("status", "-1");
        xmlWriter.dataElement("data", "Unable to delete the Clinic Requirments! Please retry!");
      }
    } catch (Exception ex) {
      xmlWriter.dataElement("status", "-1");
      xmlWriter.dataElement("data", ex.getLocalizedMessage());
    }
    xmlWriter.endElement("response");
    xmlWriter.endDocument();

    return xml.toString();
  }
コード例 #14
0
  @Post("xml")
  public String addClinicConnectionDetails(DomRepresentation rep) throws IOException, SAXException {
    StringWriter xml = new StringWriter();
    XmlWriter xmlWriter = new XmlWriter(xml);

    ObjectOutputStream out;

    xmlWriter.startDocument();
    xmlWriter.setDataFormat(true);

    xmlWriter.startElement("response");

    Element dataNode = (Element) rep.getNode("//request/data");

    ClinicRequirements persistedInstance = null;
    try {
      if (dataNode != null) {
        xmlConverter.alias("data", ClinicRequirements.class);
        //				persistedInstance = clinicRequirementsBean
        //						.persist((ClinicRequirements) xmlConverter
        //								.unmarshal(new DomReader(dataNode)));

        xmlWriter.dataElement("status", "0");
        xmlConverter.alias("record", ClinicRequirements.class);
        out = xmlConverter.createObjectOutputStream(xmlWriter.getWriter(), "data");
        //				out.writeObject(persistedInstance);
        out.close();

      } else // Sending error message
      {
        xmlWriter.dataElement("status", "-1");
        xmlWriter.dataElement("data", "Unable to add the Clinic Requirments! Please retry!");
      }
    } catch (Exception ex) {
      xmlWriter.dataElement("status", "-1");
      xmlWriter.dataElement("data", ex.getLocalizedMessage());
    }
    xmlWriter.endElement("response");
    xmlWriter.endDocument();

    return xml.toString();
  }
コード例 #15
0
ファイル: ServerUtils.java プロジェクト: laiello/zend-webapi
 public static DomRepresentation readDomRepresentation(String fileName) throws IOException {
   Document doc = readXMLFile(fileName);
   DomRepresentation dom = new DomRepresentation();
   dom.setDocument(doc);
   return dom;
 }