Esempio n. 1
0
 public InputStreamEntity(InputStream inputStream, long j, ContentType contentType) {
   this.content = (InputStream) Args.notNull(inputStream, "Source input stream");
   this.length = j;
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
Esempio n. 2
0
  /**
   * Sets the filename associated with this body part.
   *
   * @exception IllegalWriteException if the underlying implementation does not support modification
   * @exception IllegalStateException if this body part is obtained from a READ_ONLY folder
   */
  public void setFileName(String filename) throws MessagingException {
    PrivilegedAction a = new GetSystemPropertyAction("mail.mime.encodefilename");
    if ("true".equals(AccessController.doPrivileged(a))) {
      try {
        filename = MimeUtility.encodeText(filename);
      } catch (UnsupportedEncodingException e) {
        throw new MessagingException(e.getMessage(), e);
      }
    }
    String header = getHeader(CONTENT_DISPOSITION_NAME, null);
    if (header == null) {
      header = "attachment";
    }
    ContentDisposition cd = new ContentDisposition(header);
    cd.setParameter("filename", filename);
    setHeader(CONTENT_DISPOSITION_NAME, cd.toString());

    // We will also set the "name" parameter of the Content-Type field
    // to preserve compatibility with nonconformant MUAs
    header = getHeader(CONTENT_TYPE_NAME, null);
    if (header == null) {
      DataHandler dh0 = getDataHandler();
      if (dh0 != null) header = dh0.getContentType();
      else header = "text/plain";
    }
    try {
      ContentType contentType = new ContentType(header);
      contentType.setParameter("name", filename);
      setHeader(CONTENT_TYPE_NAME, contentType.toString());
    } catch (ParseException e) {
    }
  }
  /**
   * @param existing
   * @param attributeItems
   * @return
   */
  protected SwordValidationInfo validate(
      ArrayList<SwordValidationInfo> existing,
      ArrayList<SwordValidationInfo> attributeItems,
      Properties validationContext) {
    boolean validateAll = (existing == null);

    SwordValidationInfo result = new SwordValidationInfo(xmlName);
    result.setContentDescription(content);

    // item specific rules
    if (content == null) {
      result.addValidationInfo(
          new SwordValidationInfo(
              xmlName, "Missing content for element", SwordValidationInfoType.WARNING));
    }

    if (validateAll) {
      SwordValidationInfo info =
          new SwordValidationInfo(
              xmlName, new XmlName(xmlName.getPrefix(), ATTRIBUTE_TYPE, xmlName.getNamespace()));
      info.setContentDescription(type.toString());
      result.addAttributeValidationInfo(info);
    }

    result.addUnmarshallValidationInfo(existing, attributeItems);
    return result;
  }
Esempio n. 4
0
 /** @since 4.2 */
 public FileEntity(final File file, final ContentType contentType) {
   super();
   this.file = Args.notNull(file, "File");
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
 /** @since 4.2 */
 public FileEntity(final File file, final ContentType contentType) {
   super();
   if (file == null) {
     throw new IllegalArgumentException("File may not be null");
   }
   this.file = file;
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
  /**
   * Marshall the data in this object to an Element object.
   *
   * @return The data expressed in an Element.
   */
  public Element marshall() {
    Element element = new Element(getQualifiedName(), Namespaces.NS_ATOM);
    if (type != null) {
      Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type.toString());
      element.addAttribute(typeAttribute);
    }

    if (content != null) {
      element.appendChild(content);
    }
    return element;
  }
  @Override
  public void handle(HttpExchange t) throws IOException {
    OutputStream os = t.getResponseBody();
    URI uri = t.getRequestURI();

    if (!uri.toString().startsWith("/")) {
      /* suspecting path traversal attack */
      String response = "403 (Forbidden)\n";
      t.sendResponseHeaders(403, response.getBytes().length);
      os.write(response.getBytes());
      os.close();
      return;
    }

    ContentType contentType;
    if (uri.toString().equals("/")) {
      contentType = ContentType.HTML;
    } else {
      contentType = ContentType.getContentType(uri.toString());
    }
    if (contentType != ContentType.REQUEST) {
      handleFile(t, contentType);
      return;
    }

    // Presentation layer on of VCenterPluginResp
    // Accept with response code 200.
    t.sendResponseHeaders(200, 0);
    Headers h = t.getResponseHeaders();

    h.set("Content-Type", contentType.toString());
    StringBuilder s =
        new StringBuilder()
            .append("<?xml-stylesheet type=\"")
            .append(ContentType.XSL)
            .append("\" href=\"")
            .append(styleSheet)
            .append("\"?>");

    // serialize the actual response object in XML
    VCenterPluginReq req = new VCenterPluginReq(uri);
    VCenterPluginResp resp = new VCenterPluginResp(req);
    resp.writeObject(s);

    os.write(s.toString().getBytes());
    os.close();
  }
  private void handleFile(HttpExchange t, ContentType contentType)
      throws IOException, FileNotFoundException {

    OutputStream os = t.getResponseBody();

    String fileName = t.getRequestURI().toString();

    if (fileName.equals("/")) {
      fileName = "/vcenter-plugin.html";
    }
    File file = new File(VCenterHttpServer.INSTANCE.getWebRoot() + fileName).getCanonicalFile();

    if (!file.getPath().startsWith(VCenterHttpServer.INSTANCE.getWebRoot())) {
      // Suspected path traversal attack: reject with 403 error.
      String response = "403 (Forbidden)\n";
      t.sendResponseHeaders(403, response.getBytes().length);
      os.write(response.getBytes());
      os.close();
      return;
    }
    if (!file.isFile()) {
      // Object does not exist or is not a file: reject with 404 error.
      // s_logger.error(" Cannot load " + fileName);
      String response = "404 (Not Found)\n";
      t.sendResponseHeaders(404, response.length());
      os.write(response.getBytes());
      os.close();
      return;
    }

    // Object exists and is a file: accept with response code 200.
    Headers h = t.getResponseHeaders();
    h.set("Content-Type", contentType.toString());
    t.sendResponseHeaders(200, 0);

    FileInputStream fs = new FileInputStream(file);
    final byte[] buffer = new byte[0x100000];
    int count = 0;
    while ((count = fs.read(buffer)) >= 0) {
      os.write(buffer, 0, count);
    }
    fs.close();

    os.close();
  }
Esempio n. 9
0
 /**
  * Creates a StringEntityHC4 with the specified content and content type.
  *
  * @param string content to be used. Not {@code null}.
  * @param contentType content type to be used. May be {@code null}, in which case the default MIME
  *     type {@link ContentType#TEXT_PLAIN} is assumed.
  * @throws IllegalArgumentException if the string parameter is null
  * @throws UnsupportedCharsetException Thrown when the named charset is not available in this
  *     instance of the Java virtual machine
  * @since 4.2
  */
 public StringEntityHC4(final String string, final ContentType contentType)
     throws UnsupportedCharsetException {
   super();
   Args.notNull(string, "Source string");
   Charset charset = contentType != null ? contentType.getCharset() : null;
   if (charset == null) {
     charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET);
   }
   try {
     this.content = string.getBytes(charset.name());
   } catch (final UnsupportedEncodingException ex) {
     // should never happen
     throw new UnsupportedCharsetException(charset.name());
   }
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
Esempio n. 10
0
  /**
   * Updates the headers of this part, based on the content.
   *
   * @exception IllegalWriteException if the underlying implementation does not support modification
   * @exception IllegalStateException if this body part is obtained from a READ_ONLY folder
   */
  protected void updateHeaders() throws MessagingException {
    if (getDataHandler() != null) {
      try {
        String contentType = dh.getContentType();
        ContentType ct = new ContentType(contentType);
        if (ct.match("multipart/*")) {
          MimeMultipart mmp = (MimeMultipart) dh.getContent();
          mmp.updateHeaders();
        } else if (ct.match("message/rfc822")) {
        } else {
          // Update Content-Transfer-Encoding
          if (getHeader(CONTENT_TRANSFER_ENCODING_NAME) == null) {
            setHeader(CONTENT_TRANSFER_ENCODING_NAME, MimeUtility.getEncoding(dh));
          }
        }

        // Update Content-Type if nonexistent,
        // and Content-Type "name" with Content-Disposition "filename"
        // parameter(see setFilename())
        if (getHeader(CONTENT_TYPE_NAME) == null) {
          String disposition = getHeader(CONTENT_DISPOSITION_NAME, null);
          if (disposition != null) {
            ContentDisposition cd = new ContentDisposition(disposition);
            String filename = cd.getParameter("filename");
            if (filename != null) {
              ct.setParameter("name", filename);
              contentType = ct.toString();
            }
          }
          setHeader(CONTENT_TYPE_NAME, contentType);
        }
      } catch (IOException e) {
        throw new MessagingException("I/O error", e);
      }
    }
  }
Esempio n. 11
0
 /**
  * Set the {@linkplain ContentType media type} of the body, as specified by the {@code
  * Content-Type} header.
  */
 public void setContentType(ContentType contentType) {
   set(CONTENT_TYPE, contentType.toString());
 }
Esempio n. 12
0
 /**
  * Set the list of acceptable {@linkplain MediaType media types}, as specified by the {@code
  * Accept} header.
  */
 public void setAccept(List<ContentType> acceptableMediaTypes) {
   set(ACCEPT, ContentType.toString(acceptableMediaTypes));
 }
  /**
   * @param text
   * @param validate
   * @return
   * @throws org.purl.sword.base.UnmarshallException
   */
  public SwordValidationInfo unmarshall(Element text, Properties validationProperties)
      throws UnmarshallException {
    if (!isInstanceOf(text, xmlName)) {
      return handleIncorrectElement(text, validationProperties);
    }

    ArrayList<SwordValidationInfo> validationItems = new ArrayList<SwordValidationInfo>();
    ArrayList<SwordValidationInfo> attributeItems = new ArrayList<SwordValidationInfo>();

    try {
      initialise();

      // get the attributes
      int attributeCount = text.getAttributeCount();
      Attribute attribute = null;
      for (int i = 0; i < attributeCount; i++) {
        attribute = text.getAttribute(i);
        if (ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) {
          boolean success = true;
          String value = attribute.getValue();
          if (ContentType.TEXT.toString().equals(value)) {
            type = ContentType.TEXT;
          } else if (ContentType.HTML.toString().equals(value)) {
            type = ContentType.HTML;
          } else if (ContentType.XHTML.toString().equals(value)) {
            type = ContentType.XHTML;
          } else {
            log.error("Unable to parse extract type in " + getQualifiedName());
            SwordValidationInfo info =
                new SwordValidationInfo(
                    xmlName,
                    new XmlName(attribute),
                    "Invalid content type has been specified",
                    SwordValidationInfoType.ERROR);
            info.setContentDescription(value);
            attributeItems.add(info);
            success = false;
          }

          if (success) {
            SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute));
            info.setContentDescription(type.toString());
            attributeItems.add(info);
          }
        } else {
          SwordValidationInfo info =
              new SwordValidationInfo(
                  xmlName,
                  new XmlName(attribute),
                  SwordValidationInfo.UNKNOWN_ATTRIBUTE,
                  SwordValidationInfoType.INFO);
          info.setContentDescription(attribute.getValue());
          attributeItems.add(info);
        }
      }

      // retrieve all of the sub-elements
      int length = text.getChildCount();
      if (length > 0) {
        content = unmarshallString(text);
      }

    } catch (Exception ex) {
      log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage());
      throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex);
    }

    SwordValidationInfo result = null;
    if (validationProperties != null) {
      result = validate(validationItems, attributeItems, validationProperties);
    }
    return result;
  }
Esempio n. 14
0
 /** @return the mime type */
 public String getMimeType() {
   if (type == null) return APPLICATION_UNKNOW.toString();
   return type + "/" + subtype;
 }
Esempio n. 15
0
 @Override
 public String toString() {
   if (type == null) return APPLICATION_UNKNOW.toString();
   if (this.charset == null) return type + "/" + subtype;
   return type + "/" + subtype + " charset=" + charset;
 }