Esempio n. 1
0
  /**
   * Checks if a domain should be filtered or not: returns true if the target domain ends with the
   * comparison domain and if supplied, target path begins with the comparison path
   *
   * @param target URL to check
   * @param strings The URLs to check against
   * @return If the target is covered by any strings
   * @throws MalformedURLException
   */
  public static boolean isDomain(String target, String[] strings) throws MalformedURLException {
    URL domain = new URL(target);
    for (String s : strings) {
      if (!s.contains("/")) {
        if (ContentType.hostContains(domain.getHost(), s)) {
          return true;
        } else {
          continue;
        }
      }

      if (!s.contains("://")) {
        s = "http://" + s;
      }

      try {
        URL comparison = new URL(s.toLowerCase());

        if (ContentType.hostContains(domain.getHost(), comparison.getHost())
            && domain.getPath().startsWith(comparison.getPath())) {
          return true;
        }
      } catch (MalformedURLException ignored) {
      }
    }
    return false;
  }
  @Test
  public void shouldReturnDefaultGivenOneHeaderThatIsNotContentType() {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Something-Else", "application/json"));

    assertEquals(ContentType.typeFor("default"), ContentType.parse(headers));
  }
  public SIPHeader parse() throws ParseException {

    ContentType contentType = new ContentType();
    if (debug) dbg_enter("ContentTypeParser.parse");

    try {
      this.headerName(TokenTypes.CONTENT_TYPE);

      // The type:
      lexer.match(TokenTypes.ID);
      Token type = lexer.getNextToken();
      this.lexer.SPorHT();
      contentType.setContentType(type.getTokenValue());

      // The sub-type:
      lexer.match('/');
      lexer.match(TokenTypes.ID);
      Token subType = lexer.getNextToken();
      this.lexer.SPorHT();
      contentType.setContentSubType(subType.getTokenValue());
      super.parse(contentType);
      this.lexer.match('\n');
    } finally {
      if (debug) dbg_leave("ContentTypeParser.parse");
    }
    return contentType;
  }
Esempio n. 4
0
  public void init() {

    this.resource =
        remoteClient.getResourceManager().getResource(remoteClient.getSubject(), resourceId);

    // Lazy init children, not here
    initMeasurements();
    initOperations();
    initConfigDefs();
    initContent();

    List<PackageType> packageTypes = new ArrayList<PackageType>();
    for (ContentType ct : contentTypes.values()) {
      packageTypes.add(ct.getPackageType());
    }

    fingerprint =
        new ResourceTypeFingerprint(
            resource.getResourceType(),
            measurementDefinitions,
            operationDefinitions,
            packageTypes,
            pluginConfigurationDefinition,
            resourceConfigurationDefinition);
  }
  @Test
  public void shouldReturnDefaultGivenAnythingElse() {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Content-Type", "blah/blah"));

    assertEquals(ContentType.typeFor("default"), ContentType.parse(headers));
  }
Esempio n. 6
0
 /**
  * Returns the filename associated with this body part.
  *
  * <p>This method returns the value of the "filename" parameter from the Content-Disposition
  * header field. If the latter is not available, it returns the value of the "name" parameter from
  * the Content-Type header field.
  */
 public String getFileName() throws MessagingException {
   String filename = null;
   String header = getHeader(CONTENT_DISPOSITION_NAME, null);
   if (header != null) {
     ContentDisposition cd = new ContentDisposition(header);
     filename = cd.getParameter("filename");
   }
   if (filename == null) {
     header = getHeader(CONTENT_TYPE_NAME, null);
     if (header != null) {
       try {
         ContentType contentType = new ContentType(header);
         filename = contentType.getParameter("name");
       } catch (ParseException e) {
       }
     }
   }
   PrivilegedAction a = new GetSystemPropertyAction("mail.mime.decodefilename");
   if ("true".equals(AccessController.doPrivileged(a))) {
     try {
       filename = MimeUtility.decodeText(filename);
     } catch (UnsupportedEncodingException e) {
       throw new MessagingException(e.getMessage(), e);
     }
   }
   return filename;
 }
Esempio n. 7
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) {
    }
  }
  @Test
  public void shouldReturnDefaultGivenMoreThanOneHeaders() {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Content-Type", "application/json"));
    headers.add(new RestData.Header("Content-Type", "application/json"));

    assertEquals(ContentType.typeFor("default"), ContentType.parse(headers));
  }
 @Test
 public void shouldUseSpecifieDefaultCharsetProperty() {
   List<Header> headers = new ArrayList<Header>();
   headers.add(new RestData.Header("Content-Type", "application/json"));
   Config c = Config.getConfig();
   c.add("restfixture.content.handlers.map", confMap());
   c.add("restfixture.content.default.charset", "MY-CHARSET");
   ContentType.config(c);
   assertEquals(ContentType.parseCharset(headers), "MY-CHARSET");
 }
 @Test
 public void shouldSetupInternalStateFromConfig() {
   StringBuffer configEntry = new StringBuffer();
   configEntry.append("application/x-html=xml<br/>\n");
   Config c = Config.getConfig();
   c.add("restfixture.content.handlers.map", configEntry.toString());
   ContentType.config(c);
   assertEquals(ContentType.XML, ContentType.typeFor("application/x-html"));
   assertEquals(ContentType.XML, ContentType.typeFor("default"));
 }
 /**
  * convert an integral value to its corresponding content type enum.
  *
  * @return the ContentType enum corresponding to the integral value.
  * @param contentType integral value to be converted to an ContentType enum.
  * @throws IllegalArgumentException if the integral value does not correspond to a valid
  *     ContentType.
  */
 public static ContentType getContentType(byte contentType) throws IllegalArgumentException {
   for (ContentType c : ContentType.values()) if (contentType == c.ordinal()) return c;
   throw new IllegalArgumentException(
       "Invalid synchronized lyric content type "
           + contentType
           + ".  It must be between "
           + OTHER.ordinal()
           + " and "
           + INFORMATION.ordinal()
           + ".");
 }
 @Test
 public void
     shouldUseDefaultSystemCharsetIfCharsetNotParseableAndDefaultNotSpecifiedViaProperty() {
   List<Header> headers = new ArrayList<Header>();
   headers.add(new RestData.Header("Content-Type", "application/json"));
   Config c = Config.getConfig();
   c.add("restfixture.content.handlers.map", confMap());
   c.add("restfixture.content.default.charset", null);
   ContentType.config(c);
   assertEquals(ContentType.parseCharset(headers), Charset.defaultCharset().name());
 }
Esempio n. 13
0
  /**
   * Match with the specified ContentType object. This method compares <strong>only the <code>
   * primaryType</code> and <code>subType</code> </strong>. The parameters of both operands are
   * ignored.
   *
   * <p>For example, this method will return <code>true</code> when comparing the ContentTypes for
   * <strong>"text/plain"</strong> and <strong>"text/plain; charset=foobar"</strong>.
   *
   * <p>If the <code>subType</code> of either operand is the special character '*', then the subtype
   * is ignored during the match. For example, this method will return <code>true</code> when
   * comparing the ContentTypes for <strong>"text/plain"</strong> and <strong>"text/*" </strong>
   *
   * @param cType to compare this against
   */
  public boolean match(ContentType cType) {
    // Match primaryType
    if (!primaryType.equalsIgnoreCase(cType.getPrimaryType())) return false;

    String sType = cType.getSubType();

    // If either one of the subTypes is wildcarded, return true
    if ((subType.charAt(0) == '*') || (sType.charAt(0) == '*')) return true;

    // Match subType
    if (!subType.equalsIgnoreCase(sType)) return false;

    return true;
  }
Esempio n. 14
0
  // Request content type resolution follows similar precedence order to accept type:
  // 1. Request header
  // 2. RestLiRequestOption
  // 3. RestClient configuration
  private void addEntityAndContentTypeHeaders(
      RestRequestBuilder builder, DataMap dataMap, ContentType contentType) throws IOException {
    if (dataMap != null) {
      String header = builder.getHeader(RestConstants.HEADER_CONTENT_TYPE);

      ContentType type;
      if (header == null) {
        if (contentType != null) {
          type = contentType;
        } else if (_contentType != null) {
          type = _contentType;
        } else {
          type = DEFAULT_CONTENT_TYPE;
        }
        builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, type.getHeaderKey());
      } else {
        javax.mail.internet.ContentType headerContentType;
        try {
          headerContentType = new javax.mail.internet.ContentType(header);
        } catch (ParseException e) {
          throw new IllegalStateException("Unable to parse Content-Type: " + header);
        }

        if (headerContentType
            .getBaseType()
            .equalsIgnoreCase(RestConstants.HEADER_VALUE_APPLICATION_JSON)) {
          type = ContentType.JSON;
        } else if (headerContentType
            .getBaseType()
            .equalsIgnoreCase(RestConstants.HEADER_VALUE_APPLICATION_PSON)) {
          type = ContentType.PSON;
        } else {
          throw new IllegalStateException("Unknown Content-Type: " + headerContentType.toString());
        }
      }

      switch (type) {
        case PSON:
          builder.setEntity(PSON_DATA_CODEC.mapToBytes(dataMap));
          break;
        case JSON:
          builder.setEntity(JACKSON_DATA_CODEC.mapToBytes(dataMap));
          break;
        default:
          throw new IllegalStateException("Unknown ContentType:" + type);
      }
    }
  }
  /**
   * @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;
  }
  @Test
  public void shouldReturnCorrectTypeGivenApplicationJson() {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Content-Type", "application/json"));

    assertEquals(ContentType.JSON, ContentType.parse(headers));
  }
  @Test
  public void shouldReturnCorrectTypeGivenApplicationTextWithCharset() {
    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Content-Type", "text/plain; charset=iso-8859-1"));

    assertEquals(ContentType.TEXT, ContentType.parse(headers));
  }
Esempio n. 18
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());
   }
 }
Esempio n. 19
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());
   }
 }
  @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();
  }
Esempio n. 21
0
 @Override
 ContentType updateContentType(ContentType ctype) {
   if (ctype != null && !ctype.getContentType().equals(ContentType.MESSAGE_RFC822)) {
     throw new UnsupportedOperationException("cannot change a message to text:" + ctype);
   }
   return super.updateContentType(
       ctype == null ? new ContentType(ContentType.MESSAGE_RFC822) : ctype);
 }
Esempio n. 22
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. 23
0
 /** @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;
  }
Esempio n. 25
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. 26
0
 public static void handle_abs_file(EventLoader event_loader, String path, boolean need_cache) {
   HttpServletResponse response = event_loader.response();
   response.setContentType(ContentType.is(event_loader.postfix()));
   response.setCharacterEncoding(Controller.encode_type);
   if (need_cache) {
     Resource file = file_map.get(MyMath.encryptionWithMD5(path));
     if (file != null) {
       file.use++;
       write(file.list, event_loader);
     } else {
       read_file(event_loader, path, need_cache);
     }
   } else {
     read_file(event_loader, path, need_cache);
   }
 }
  /**
   * If the frame body's values have been modified, then resize the raw binary buffer and store the
   * new values there. When finished, the dirty flag is reset to indicate that the buffer is up to
   * date, and the frame is now ready to be saved to the .mp3 file.
   */
  @Override
  public void setBuffer() {
    if (isDirty()) {
      int numSynchronizedLyricBytes = 0;
      for (SynchronizedLyric synchronizedLyric : synchronizedLyrics)
        numSynchronizedLyricBytes +=
            stringToBytes(encoding, synchronizedLyric.getText()).length + 4;

      byte[] languageBytes = language.getCodeBytes();
      byte[] descriptionBytes = stringToBytes(encoding, description);
      byte[] synchronizedLyricBytes = new byte[numSynchronizedLyricBytes];
      byte[] textBytes = null;
      byte[] timeStampBytes = null;
      int index = 0;

      buffer =
          new byte
              [1
                  + languageBytes.length
                  + 1
                  + 1
                  + descriptionBytes.length
                  + synchronizedLyricBytes.length];

      buffer[index] = (byte) encoding.ordinal();
      index = 1;
      System.arraycopy(languageBytes, 0, buffer, index, languageBytes.length);
      index += languageBytes.length;
      buffer[index] = (byte) timeStampFormat.getValue();
      index++;
      buffer[index] = (byte) contentType.ordinal();
      index++;
      System.arraycopy(descriptionBytes, 0, buffer, index, descriptionBytes.length);
      index += descriptionBytes.length;
      for (SynchronizedLyric synchronizedLyric : synchronizedLyrics) {
        numSynchronizedLyricBytes +=
            stringToBytes(encoding, synchronizedLyric.getText()).length + 4;
        textBytes = stringToBytes(encoding, synchronizedLyric.getText());
        System.arraycopy(textBytes, 0, buffer, index, textBytes.length);
        index += textBytes.length;
        timeStampBytes = intToBytes(synchronizedLyric.getTimeStamp());
        System.arraycopy(timeStampBytes, 0, buffer, index, timeStampBytes.length);
        index += timeStampBytes.length;
      }
      dirty = false;
    }
  }
  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();
  }
  @Override
  public boolean equals(Object obj) {

    /*
     * Any major changes to this method such as adding a field check, requires changes in the
     * hashCode method. According to the Java Object Specification, "If two objects are equal
     * according to the equals(Object) method, then calling the hashCode method on each of the
     * two objects must produce the same integer result."
     */

    if (!(obj instanceof ContentType)) {
      return false;
    }

    ContentType newObject = (ContentType) obj;

    if (this.getName() == null) {
      if (newObject.getName() != null) {
        return false;
      }
    } else if (!this.getName().equals(newObject.getName())) {
      return false;
    }

    if (this.getVersion() == null) {
      if (newObject.getVersion() != null) {
        return false;
      }
    } else if (!this.getVersion().equals(newObject.getVersion())) {
      return false;
    }

    if (this.getNamespace() == null) {
      if (newObject.getNamespace() != null) {
        return false;
      }
    } else if (!this.getNamespace().equals(newObject.getNamespace())) {
      return false;
    }

    return true;
  }
  @Test
  public void shouldSetupTheContentTypeToAdaptersMapViaConfig() {

    Config c = Config.getConfig();
    c.add("restfixture.content.handlers.map", confMap());
    c.add("restfixture.content.default.charset", "MY-CHARSET");
    ContentType.config(c);

    List<Header> headers = new ArrayList<Header>();
    headers.add(new RestData.Header("Content-Type", "application/json"));
    assertEquals(ContentType.JSON, ContentType.parse(headers));
    headers.set(0, new RestData.Header("Content-Type", "application/xml; charset=iso12344"));
    assertEquals(ContentType.XML, ContentType.parse(headers));
    headers.set(0, new RestData.Header("Content-Type", "application/xhtml"));
    assertEquals(ContentType.XML, ContentType.parse(headers));
    headers.set(0, new RestData.Header("Content-Type", "application/my-app-xml"));
    assertEquals(ContentType.XML, ContentType.parse(headers));
    headers.set(0, new RestData.Header("Content-Type", "text/plain"));
    assertEquals(ContentType.JSON, ContentType.parse(headers));

    // overrides "default"
    headers.set(0, new RestData.Header("Content-Type", "unhandled"));
    assertEquals(ContentType.TEXT, ContentType.parse(headers));
  }