Exemplo n.º 1
0
  public static TCDocumentObject create(TCReferencedInstance ref) throws Exception {

    Instance instance =
        ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
            .findInstanceByUID(ref.getInstanceUID());

    if (instance == null) {
      return null;
    }

    DicomObject attrs = instance.getAttributes(false);

    MimeType mimeType = null;
    String mimeTypeStr = attrs.getString(Tag.MIMETypeOfEncapsulatedDocument);
    if (mimeTypeStr != null) {
      mimeType = MimeType.get(mimeTypeStr);
    }
    if (mimeType == null) {
      mimeType = getDocumentMimeTypeFromLabel(attrs.getString(Tag.ContentLabel));
    }

    if (mimeType != null) {
      DocumentType docType = mimeType.getDocumentType();

      if (TCImageDocument.DOC_TYPES.contains(docType)) {
        return TCImageDocument.create(ref);
      } else if (TCEncapsulatedDocument.DOC_TYPES.contains(docType)) {
        return TCEncapsulatedDocument.create(ref);
      }
    }

    throw new Exception(
        "Unable to create TC encapsulated object: Mime type not supported (" + mimeTypeStr + ")");
  }
Exemplo n.º 2
0
 public static MimeType guessFromFileExtension(String fileExtension) {
   for (MimeType type : values()) {
     if (type.isFileExtensionSupported(fileExtension)) {
       return type;
     }
   }
   return null;
 }
Exemplo n.º 3
0
 public static MimeType get(String mimeType) {
   for (MimeType type : values()) {
     if (type.getMimeTypeString().startsWith(mimeType)) {
       return type;
     }
   }
   return null;
 }
Exemplo n.º 4
0
  public MediaType process(HeaderValue headerValue) {
    MimeType mediaType = MimeType.getMatchingMimeType(headerValue.getValue());

    if (MimeType.UNKNOWN.equals(mediaType)) {
      mediaType = MimeType.guessMediaTypeFromString(headerValue.getValue());
    }

    return new MediaType(headerValue.getValue(), mediaType, headerValue.getParameters());
  }
Exemplo n.º 5
0
 /**
  * Return a string representation of the given list of {@code MimeType} objects.
  *
  * @param mimeTypes the string to parse
  * @return the list of mime types
  * @throws IllegalArgumentException if the String cannot be parsed
  */
 public static String toString(Collection<? extends MimeType> mimeTypes) {
   StringBuilder builder = new StringBuilder();
   for (Iterator<? extends MimeType> iterator = mimeTypes.iterator(); iterator.hasNext(); ) {
     MimeType mimeType = iterator.next();
     mimeType.appendTo(builder);
     if (iterator.hasNext()) {
       builder.append(", ");
     }
   }
   return builder.toString();
 }
Exemplo n.º 6
0
 /**
  * Check to see if this mime type is one of the types seen during initialisation or has been added
  * at some later stage using addKnownMimeType(...)
  *
  * @param mimeType
  * @return true if the mimeType is in the list else false is returned
  * @see #addKnownMimeType(String mimetype)
  */
 public static boolean isMimeTypeKnown(final MimeType mimeType) {
   try {
     Set s = (Set) mimeTypes.get(mimeType.getMediaType());
     if (s == null) {
       return false;
     }
     return s.contains(mimeType.getSubType());
   } catch (MimeException e) {
     return false;
   }
 }
Exemplo n.º 7
0
 /**
  * Get the most specific match of the Collection of mime types passed in. The Collection
  *
  * @param mimeTypes this should be the Collection of mime types returned from a getMimeTypes(...)
  *     call.
  * @return the most specific MimeType. If more than one of the mime types in the Collection have
  *     the same value then the first one found with this value in the Collection is returned.
  */
 public static MimeType getMostSpecificMimeType(final Collection mimeTypes) {
   MimeType mimeType = null;
   int specificity = 0;
   for (Iterator it = mimeTypes.iterator(); it.hasNext(); ) {
     MimeType mt = (MimeType) it.next();
     if (mt.getSpecificity() > specificity) {
       mimeType = mt;
       specificity = mimeType.getSpecificity();
     }
   }
   return mimeType;
 }
Exemplo n.º 8
0
 /**
  * Use the MimeType class to extract the MIME type/subtype, ignoring the parameters. The type is
  * cached.
  */
 private synchronized String getBaseType() {
   if (shortType == null) {
     String ct = getContentType();
     try {
       MimeType mt = new MimeType(ct);
       shortType = mt.getBaseType();
     } catch (MimeTypeParseException e) {
       shortType = ct;
     }
   }
   return shortType;
 }
 /** Initialise this resource, and return it. */
 public Resource init() throws ResourceInstantiationException {
   // Register plain text mime type
   MimeType mime = new MimeType("text", "plain");
   // Register the class handler for this mime type
   mimeString2ClassHandlerMap.put(mime.getType() + "/" + mime.getSubtype(), this);
   // Register the mime type with mine string
   mimeString2mimeTypeMap.put(mime.getType() + "/" + mime.getSubtype(), mime);
   // Register file sufixes for this mime type
   suffixes2mimeTypeMap.put("txt", mime);
   suffixes2mimeTypeMap.put("text", mime);
   // Set the mimeType for this language resource
   setMimeType(mime);
   return this;
 } // init()
Exemplo n.º 10
0
  protected void writeCssTo(Writer writer, Output output) throws IOException {
    Object[] results;
    Mapper mapper;
    Node node;

    if (output.getMuted()) {
      throw new IllegalArgumentException();
    }
    mapper = SSASS.newInstance();
    mapper.setErrorHandler(new ExceptionErrorHandler());
    for (int i = 0; i < nodes.size(); i++) {
      node = nodes.get(i);
      if (i > 0) {
        writer.write(LF);
      }
      if (!overallMinimize) {
        writer.write(type.comment(location(node)));
      }
      results = mapper.run(node);
      if (results == null) {
        throw new IOException(node.toString() + ": css/sass error");
      }
      output.setMuted(declarationsOnly.get(i));
      try {
        ((Stylesheet) results[0]).toCss(output);
      } catch (GenericException e) {
        throw new IOException(node.toString() + ": css generation failed: " + e.getMessage(), e);
      }
      if (output.getMuted() != declarationsOnly.get(i)) {
        throw new IllegalStateException();
      }
    }
  }
Exemplo n.º 11
0
    public static TCEncapsulatedDocument create(TCReferencedInstance ref) throws Exception {
      Instance instance =
          ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
              .findInstanceByUID(ref.getInstanceUID());

      List<org.dcm4chee.archive.entity.File> files = instance.getFiles();
      DicomObject attrs = instance.getAttributes(false);

      attrs.remove(Tag.EncapsulatedDocument);

      MimeType mimeType = null;
      String mimeTypeStr = attrs.getString(Tag.MIMETypeOfEncapsulatedDocument);
      if (mimeTypeStr != null) {
        mimeType = MimeType.get(mimeTypeStr);
      }
      if (mimeType == null) {
        mimeType = getDocumentMimeTypeFromLabel(attrs.getString(Tag.ContentLabel));
      }

      String fsId = files.get(0).getFileSystem().getDirectoryPath();
      String fileId = files.get(0).getFilePath();
      File file =
          fsId.startsWith("tar:")
              ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId)
              : FileUtils.resolve(new File(fsId, fileId));

      return new TCEncapsulatedDocument(mimeType, ref, attrs, file);
    }
Exemplo n.º 12
0
 private static MimeType getDocumentMimeTypeFromLabel(String label) {
   if (label != null) {
     int index = label != null ? label.lastIndexOf("(") : -1; // $NON-NLS-1$
     String filename = index > 0 ? label.substring(0, index - 1) : label;
     return MimeType.guessFromFileExtension(getFileExtension(filename));
   }
   return null;
 }
Exemplo n.º 13
0
 public final void set(byte[] bytes, String filename, MimeType mimeType) {
   // Hibernate braucht den Aufruf der set-Methoden, um ein Update (Dirty-Flag!) zu erkennen
   setBytes(bytes);
   setFilename(filename);
   setMimeType(mimeType);
   setMultimediaType(mimeType.getMultimediaType());
   LOGGER.tracef("File aktualisiert: %s", this.toString());
 }
Exemplo n.º 14
0
 public JsonObject toJsonObject() {
   return new JsonObject()
       .put("id", fileId.toString())
       .put("name", name)
       .put("mime_type", mimeType.toString())
       .put("content_length", contentLength)
       .put("generated", generated);
 }
Exemplo n.º 15
0
  @Override
  public String toString() {

    final StringWriter stringWriter = new StringWriter();
    final MimeType mimeType = getMimeType();
    final String name = getName();
    if (name != null) {

      stringWriter.append("Name: ").append(name).append(" / ");
    }
    if (mimeType != null) {

      stringWriter.append(mimeType.name()).append(" / ");
    }
    stringWriter.append(getAbsolutePath());
    final String string = stringWriter.toString();
    return string;
  }
Exemplo n.º 16
0
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    final PrintStream logger = listener.getLogger();
    final EnvVars envVars = build.getEnvironment(listener);
    final VariableResolver<String> buildVariableResolver = build.getBuildVariableResolver();

    String evaluatedUrl = evaluate(url, buildVariableResolver, envVars);
    String evaluatedBody = evaluate(requestBody, buildVariableResolver, envVars);

    final List<HttpRequestNameValuePair> params = createParameters(build, logger, envVars);
    final List<HttpRequestNameValuePair> headers = new ArrayList<>();

    if (contentType != MimeType.NOT_SET) {
      headers.add(
          new HttpRequestNameValuePair("Content-type", contentType.getContentType().toString()));
    }
    if (acceptType != MimeType.NOT_SET) {
      headers.add(new HttpRequestNameValuePair("Accept", acceptType.getValue()));
    }
    for (HttpRequestNameValuePair header : customHeaders) {
      String headerName = evaluate(header.getName(), buildVariableResolver, envVars);
      String headerValue = evaluate(header.getValue(), buildVariableResolver, envVars);

      headers.add(new HttpRequestNameValuePair(headerName, headerValue));
    }

    RequestAction requestAction =
        new RequestAction(
            new URL(evaluatedUrl),
            httpMode,
            evaluatedBody,
            params,
            headers,
            contentType.getContentType());

    ResponseContentSupplier responseContentSupplier = performHttpRequest(listener, requestAction);

    logResponseToFile(build.getWorkspace(), logger, responseContentSupplier);
    return true;
  }
Exemplo n.º 17
0
 /** core method */
 public void writeTo(Writer writer) throws IOException {
   switch (type) {
     case CSS:
       writeCssTo(writer);
       break;
     case JS:
       writeJsTo(writer);
       break;
     default:
       throw new IllegalStateException(type.toString());
   }
 }
Exemplo n.º 18
0
  public ResponseContentSupplier performHttpRequest(TaskListener listener)
      throws InterruptedException, IOException {
    List<HttpRequestNameValuePair> params = Collections.emptyList();
    List<HttpRequestNameValuePair> headers = new ArrayList<>();
    if (contentType != MimeType.NOT_SET) {
      headers.add(
          new HttpRequestNameValuePair("Content-type", contentType.getContentType().toString()));
    }
    if (acceptType != MimeType.NOT_SET) {
      headers.add(new HttpRequestNameValuePair("Accept", acceptType.getValue()));
    }
    for (HttpRequestNameValuePair header : customHeaders) {
      headers.add(new HttpRequestNameValuePair(header.getName(), header.getValue()));
    }

    RequestAction requestAction =
        new RequestAction(
            new URL(url), httpMode, requestBody, params, headers, contentType.getContentType());

    return performHttpRequest(listener, requestAction);
  }
Exemplo n.º 19
0
 @Override
 public int hashCode() {
   Long result = id;
   result = 31 * result + version;
   result = 31 * result + (fromAddress != null ? fromAddress.hashCode() : 0);
   result = 31 * result + (toAddress != null ? toAddress.hashCode() : 0);
   result = 31 * result + (subject != null ? subject.hashCode() : 0);
   result = 31 * result + (body != null ? body.hashCode() : 0);
   result = 31 * result + (mimeType != null ? mimeType.hashCode() : 0);
   result = 31 * result + (sentDate != null ? sentDate.hashCode() : 0);
   result = 31 * result + (sentSuccessfully ? 1 : 0);
   return result.intValue();
 }
Exemplo n.º 20
0
  /**
   * Create a FileDocument
   *
   * @param file {@code File}
   */
  public FileDocument(final File file) {

    if (file == null) {

      throw new NullPointerException();
    }
    if (!file.exists()) {

      throw new DSSException("File Not Found: " + file.getAbsolutePath());
    }
    this.file = file;
    this.mimeType = MimeType.fromFileName(file.getName());
  }
Exemplo n.º 21
0
  /** core method */
  private void writeJsTo(Writer writer) throws IOException {
    Compiler compiler;
    CompilerOptions options;
    List<SourceFile> externals;
    List<SourceFile> sources;
    Result result;
    boolean first;
    int i;
    Node node;

    compiler = new Compiler(new LoggerErrorManager());
    options = new CompilerOptions();
    options.setOutputCharset(Engine.ENCODING);
    sources = new ArrayList<>();
    externals = new ArrayList<>();
    for (i = 0; i < nodes.size(); i++) {
      node = nodes.get(i);
      sources.add(
          SourceFile.fromCode(
              location(node) + /* to get unique names, which is checked by the compiler: */ "_" + i,
              readString(node)));
    }
    result = compiler.compile(externals, sources, options);
    if (!result.success) {
      if (result.errors.length < 1) {
        throw new IllegalStateException();
      }
      throw new IOException(
          result.errors[0].sourceName
              + ":"
              + result.errors[0].lineNumber
              + ":"
              + result.errors[0].description);
    }
    if (overallMinimize) {
      writer.write(compiler.toSource());
    } else {
      first = true;
      for (SourceFile source : sources) {
        if (first) {
          first = false;
        } else {
          writer.write(LF);
        }
        if (!overallMinimize) {
          writer.write(type.comment(source.getName()));
        }
        writer.write(source.getCode());
      }
    }
  }
Exemplo n.º 22
0
    public static TCEncapsulatedDocument create(
        TCObject tc, MimeType mimeType, String filename, InputStream in, String description)
        throws Exception {

      if (mimeType == null || !DOC_TYPES.contains(mimeType.getDocumentType())) {
        throw new Exception("Mime-Type is not supported (" + mimeType + ")");
      }

      TCReferencedInstance ref = createReferencedInstance(tc, UID.EncapsulatedPDFStorage, MODALITY);

      DicomObject metaData =
          TCDocumentObject.createDicomMetaData(
              mimeType,
              filename,
              description,
              ref,
              tc.getPatientId(),
              tc.getPatientIdIssuer(),
              tc.getPatientName(),
              MODALITY);
      metaData.putString(Tag.TransferSyntaxUID, VR.UI, UID.ExplicitVRLittleEndian);
      metaData.putString(
          Tag.DocumentTitle,
          VR.ST,
          description != null && !description.isEmpty() ? description : getFileName(filename));
      metaData.putString(Tag.MIMETypeOfEncapsulatedDocument, VR.LO, mimeType.getMimeTypeString());
      metaData.putString(Tag.BurnedInAnnotation, VR.CS, "NO"); // $NON-NLS-1$
      metaData.putSequence(Tag.ConceptNameCodeSequence, 0);

      try {
        return new TCEncapsulatedDocument(mimeType, ref, metaData, IOUtils.toByteArray(in));
      } finally {
        if (in != null) {
          in.close();
        }
      }
    }
Exemplo n.º 23
0
    private static MimeType checkMimeType(MimeType mimeType) throws Exception {
      if (mimeType == null || !DOC_TYPES.contains(mimeType.getDocumentType())) {
        throw new Exception("Mime-Type is not supported (" + mimeType + ")");
      }

      // if there's an ImageIO Dicom reader plugin available, we are able
      // to read/restore all mime types (jpeg, png, gif, bmp). If not,
      // we need to use the WADO service to convert dicom->image. However
      // the WADO service just supports dicom->jpeg and in newer version
      // dicom->png conversions.
      if (!dicomReaderAvailable) {
        if (!MimeType.ImagePNG.equals(mimeType)) {
          mimeType = MimeType.ImageJPEG;
        }
      }
      return mimeType;
    }
Exemplo n.º 24
0
  public static TCDocumentObject create(
      TCObject tc, MimeType mimeType, String filename, InputStream in, String description)
      throws Exception {
    if (mimeType != null) {
      DocumentType docType = mimeType.getDocumentType();

      if (TCImageDocument.DOC_TYPES.contains(docType)) {
        return TCImageDocument.create(tc, mimeType, filename, in, description);
      } else if (TCEncapsulatedDocument.DOC_TYPES.contains(docType)) {
        return TCEncapsulatedDocument.create(tc, mimeType, filename, in, description);
      }
    }

    throw new Exception(
        "Unable to create TC encapsulated object: MimeType not supported ("
            + mimeType
            + ")"); //$NON-NLS-1$ //$NON-NLS-2$
  }
Exemplo n.º 25
0
    private URL createWadoURL(MimeType mimeType, int size) {
      StringBuilder sbuilder = new StringBuilder();
      sbuilder.append(WADODelegate.getInstance().getWadoBaseUrl());
      sbuilder.append("&studyUID=").append(getStudyInstanceUID());
      sbuilder.append("&seriesUID=").append(getSeriesInstanceUID());
      sbuilder.append("&objectUID=").append(getSOPInstanceUID());
      if (mimeType != null && MimeType.ImagePNG.equals(mimeType)) {
        sbuilder.append("&contentType=").append(mimeType.getMimeTypeString());
      }
      if (size > 0) {
        sbuilder.append("&rows=").append(size);
      }

      try {
        return new URL(sbuilder.toString());
      } catch (Exception e) {
        log.error("Malformed WADO URL!", e);
        return null;
      }
    }
Exemplo n.º 26
0
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Email that = (Email) o;

    if (id != that.id) return false;
    if (sentSuccessfully != that.sentSuccessfully) return false;
    if (version != that.version) return false;
    if (body != null ? !body.equals(that.body) : that.body != null) return false;
    if (mimeType != null ? !mimeType.equals(that.mimeType) : that.mimeType != null) return false;
    if (fromAddress != null ? !fromAddress.equals(that.fromAddress) : that.fromAddress != null)
      return false;
    if (sentDate != null ? !sentDate.equals(that.sentDate) : that.sentDate != null) return false;
    if (subject != null ? !subject.equals(that.subject) : that.subject != null) return false;
    if (toAddress != null ? !toAddress.equals(that.toAddress) : that.toAddress != null)
      return false;

    return true;
  }
Exemplo n.º 27
0
 /**
  * While MimeType(s) are being loaded by the MimeDetector(s) they should be added to the list of
  * known MIME types. It is not mandatory for MimeDetector(s) to do so but they should where
  * possible so that the list is as complete as possible. You can add other MIME types to this list
  * using this method. You can then use the isMimeTypeKnown(...) utility methods to see if a MIME
  * type you have matches one that the utility has already seen.
  *
  * <p>This can be used to limit the mime types you work with i.e. if its not been loaded then
  * don't bother using it as it won't match. This is no guarantee that a match will not be found as
  * it is possible that a particular MimeDetector does not have an initialisation phase that loads
  * all of the MIME types it will match.
  *
  * <p>For instance if you had a MIME type of abc/xyz and passed this to isMimeTypeKnown(...) it
  * would return false unless you specifically add this to the know MIME types using this method.
  *
  * @param mimeType a MIME type you want to add to the known MIME types. Duplicates are ignored.
  * @see #isMimeTypeKnown(String mimeType)
  * @see #isMimeTypeKnown(MimeType mimetType)
  */
 public static void addKnownMimeType(final MimeType mimeType) {
   addKnownMimeType(mimeType.toString());
 }
Exemplo n.º 28
0
  /**
   * Copied code from java.util.Properties. Parsing the data ourselves is the only way to handle
   * duplicate keys and values.
   */
  private void parseAndStoreReader(BufferedReader in) throws IOException {
    while (true) {
      // Get next line
      String line = in.readLine();
      if (line == null) {
        return;
      }

      if (line.length() > 0) {
        // Continue lines that end in slashes if they are not comments
        char firstChar = line.charAt(0);
        if (firstChar != '#' && firstChar != '!') {
          while (continueLine(line)) {
            String nextLine = in.readLine();
            if (nextLine == null) {
              nextLine = new String("");
            }
            String loppedLine = line.substring(0, line.length() - 1);
            // Advance beyond whitespace on new line
            int startIndex = 0;
            for (; startIndex < nextLine.length(); startIndex++) {
              if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1) {
                break;
              }
            }
            nextLine = nextLine.substring(startIndex, nextLine.length());
            line = new String(loppedLine + nextLine);
          }

          // Find start of key
          int len = line.length();
          int keyStart = 0;
          for (; keyStart < len; keyStart++) {
            if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1) {
              break;
            }
          }

          // Blank lines are ignored
          if (keyStart == len) {
            continue;
          }

          // Find separation between key and value
          int separatorIndex = keyStart;
          for (; separatorIndex < len; separatorIndex++) {
            char currentChar = line.charAt(separatorIndex);
            if (currentChar == '\\') {
              separatorIndex++;
            } else if (keyValueSeparators.indexOf(currentChar) != -1) {
              break;
            }
          }

          // Skip over whitespace after key if any
          int valueIndex = separatorIndex;
          for (; valueIndex < len; valueIndex++) {
            if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
              break;
            }
          }

          // Skip over one non whitespace key value separators if any
          if (valueIndex < len) {
            if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1) {
              valueIndex++;
            }
          }

          // Skip over white space after other separators if any
          while (valueIndex < len) {
            if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
              break;
            }
            valueIndex++;
          }

          String key = line.substring(keyStart, separatorIndex);
          String value = (separatorIndex < len) ? line.substring(valueIndex, len) : "";

          // Convert then store key and value
          key = loadConvert(key);
          value = loadConvert(value);

          try {
            MimeType mime = new MimeType(value);
            if ("text".equals(mime.getPrimaryType())) {
              String charset = mime.getParameter("charset");
              if (DataTransferer.doesSubtypeSupportCharset(mime.getSubType(), charset)) {
                // We need to store the charset and eoln
                // parameters, if any, so that the
                // DataTransferer will have this information
                // for conversion into the native format.
                DataTransferer transferer = DataTransferer.getInstance();
                if (transferer != null) {
                  transferer.registerTextFlavorProperties(
                      key, charset, mime.getParameter("eoln"), mime.getParameter("terminators"));
                }
              }

              // But don't store any of these parameters in the
              // DataFlavor itself for any text natives (even
              // non-charset ones). The SystemFlavorMap will
              // synthesize the appropriate mappings later.
              mime.removeParameter("charset");
              mime.removeParameter("class");
              mime.removeParameter("eoln");
              mime.removeParameter("terminators");
              value = mime.toString();
            }
          } catch (MimeTypeParseException e) {
            e.printStackTrace();
            continue;
          }

          DataFlavor flavor;
          try {
            flavor = new DataFlavor(value);
          } catch (Exception e) {
            try {
              flavor = new DataFlavor(value, (String) null);
            } catch (Exception ee) {
              ee.printStackTrace();
              continue;
            }
          }

          // For text/* flavors, store mappings in separate maps to
          // enable dynamic mapping generation at a run-time.
          if ("text".equals(flavor.getPrimaryType())) {
            store(value, key, getFlavorToNative());
            store(key, value, getNativeToFlavor());
          } else {
            store(flavor, key, getFlavorToNative());
            store(key, flavor, getNativeToFlavor());
          }
        }
      }
    }
  }
Exemplo n.º 29
0
  /**
   * Returns a <code>List</code> of <code>DataFlavor</code>s to which the specified <code>String
   * </code> native can be translated by the data transfer subsystem. The <code>List</code> will be
   * sorted from best <code>DataFlavor</code> to worst. That is, the first <code>DataFlavor</code>
   * will best reflect data in the specified native to a Java application.
   *
   * <p>If the specified native is previously unknown to the data transfer subsystem, and that
   * native has been properly encoded, then invoking this method will establish a mapping in both
   * directions between the specified native and a <code>DataFlavor</code> whose MIME type is a
   * decoded version of the native.
   *
   * <p>If the specified native is not a properly encoded native and the mappings for this native
   * have not been altered with <code>setFlavorsForNative</code>, then the contents of the <code>
   * List</code> is platform dependent, but <code>null</code> cannot be returned.
   *
   * @param nat the native whose corresponding <code>DataFlavor</code>s should be returned. If
   *     <code>null</code> is specified, all <code>DataFlavor</code>s currently known to the data
   *     transfer subsystem are returned in a non-deterministic order.
   * @return a <code>java.util.List</code> of <code>DataFlavor</code> objects into which
   *     platform-specific data in the specified, platform-specific native can be translated
   * @see #encodeJavaMIMEType
   * @since 1.4
   */
  public synchronized List<DataFlavor> getFlavorsForNative(String nat) {

    // Check cache, even for null nat
    SoftReference ref = (SoftReference) getFlavorsForNativeCache.get(nat);
    if (ref != null) {
      ArrayList retval = (ArrayList) ref.get();
      if (retval != null) {
        return (List) retval.clone();
      }
    }

    LinkedList retval = new LinkedList();

    if (nat == null) {
      List natives = getNativesForFlavor(null);
      HashSet dups = new HashSet(natives.size());

      for (Iterator natives_iter = natives.iterator(); natives_iter.hasNext(); ) {
        List flavors = getFlavorsForNative((String) natives_iter.next());
        for (Iterator flavors_iter = flavors.iterator(); flavors_iter.hasNext(); ) {
          Object flavor = flavors_iter.next();
          if (dups.add(flavor)) {
            retval.add(flavor);
          }
        }
      }
    } else {
      List flavors = nativeToFlavorLookup(nat);

      if (disabledMappingGenerationKeys.contains(nat)) {
        return flavors;
      }

      HashSet dups = new HashSet(flavors.size());

      List flavorsAndbaseTypes = nativeToFlavorLookup(nat);

      for (Iterator flavorsAndbaseTypes_iter = flavorsAndbaseTypes.iterator();
          flavorsAndbaseTypes_iter.hasNext(); ) {
        Object value = flavorsAndbaseTypes_iter.next();
        if (value instanceof String) {
          String baseType = (String) value;
          String subType = null;
          try {
            MimeType mimeType = new MimeType(baseType);
            subType = mimeType.getSubType();
          } catch (MimeTypeParseException mtpe) {
            // Cannot happen, since we checked all mappings
            // on load from flavormap.properties.
            assert (false);
          }
          if (DataTransferer.doesSubtypeSupportCharset(subType, null)) {
            if (TEXT_PLAIN_BASE_TYPE.equals(baseType) && dups.add(DataFlavor.stringFlavor)) {
              retval.add(DataFlavor.stringFlavor);
            }

            for (int i = 0; i < UNICODE_TEXT_CLASSES.length; i++) {
              DataFlavor toAdd = null;
              try {
                toAdd =
                    new DataFlavor(baseType + ";charset=Unicode;class=" + UNICODE_TEXT_CLASSES[i]);
              } catch (ClassNotFoundException cannotHappen) {
              }
              if (dups.add(toAdd)) {
                retval.add(toAdd);
              }
            }

            for (Iterator charset_iter = DataTransferer.standardEncodings();
                charset_iter.hasNext(); ) {
              String charset = (String) charset_iter.next();

              for (int i = 0; i < ENCODED_TEXT_CLASSES.length; i++) {
                DataFlavor toAdd = null;
                try {
                  toAdd =
                      new DataFlavor(
                          baseType + ";charset=" + charset + ";class=" + ENCODED_TEXT_CLASSES[i]);
                } catch (ClassNotFoundException cannotHappen) {
                }

                // Check for equality to plainTextFlavor so
                // that we can ensure that the exact charset of
                // plainTextFlavor, not the canonical charset
                // or another equivalent charset with a
                // different name, is used.
                if (toAdd.equals(DataFlavor.plainTextFlavor)) {
                  toAdd = DataFlavor.plainTextFlavor;
                }

                if (dups.add(toAdd)) {
                  retval.add(toAdd);
                }
              }
            }

            if (TEXT_PLAIN_BASE_TYPE.equals(baseType) && dups.add(DataFlavor.plainTextFlavor)) {
              retval.add(DataFlavor.plainTextFlavor);
            }
          } else {
            // Non-charset text natives should be treated as
            // opaque, 8-bit data in any of its various
            // representations.
            for (int i = 0; i < ENCODED_TEXT_CLASSES.length; i++) {
              DataFlavor toAdd = null;
              try {
                toAdd = new DataFlavor(baseType + ";class=" + ENCODED_TEXT_CLASSES[i]);
              } catch (ClassNotFoundException cannotHappen) {
              }

              if (dups.add(toAdd)) {
                retval.add(toAdd);
              }
            }
          }
        } else {
          DataFlavor flavor = (DataFlavor) value;
          if (dups.add(flavor)) {
            retval.add(flavor);
          }
        }
      }
    }

    ArrayList arrayList = new ArrayList(retval);
    getFlavorsForNativeCache.put(nat, new SoftReference(arrayList));
    return (List) arrayList.clone();
  }
Exemplo n.º 30
0
 static {
   ALL = MimeType.valueOf(ALL_VALUE);
   APPLICATION_ATOM_XML = MimeType.valueOf(APPLICATION_ATOM_XML_VALUE);
   APPLICATION_FORM_URLENCODED = MimeType.valueOf(APPLICATION_FORM_URLENCODED_VALUE);
   APPLICATION_JSON = MimeType.valueOf(APPLICATION_JSON_VALUE);
   APPLICATION_OCTET_STREAM = MimeType.valueOf(APPLICATION_OCTET_STREAM_VALUE);
   APPLICATION_XHTML_XML = MimeType.valueOf(APPLICATION_XHTML_XML_VALUE);
   APPLICATION_XML = MimeType.valueOf(APPLICATION_XML_VALUE);
   IMAGE_GIF = MimeType.valueOf(IMAGE_GIF_VALUE);
   IMAGE_JPEG = MimeType.valueOf(IMAGE_JPEG_VALUE);
   IMAGE_PNG = MimeType.valueOf(IMAGE_PNG_VALUE);
   MULTIPART_FORM_DATA = MimeType.valueOf(MULTIPART_FORM_DATA_VALUE);
   TEXT_HTML = MimeType.valueOf(TEXT_HTML_VALUE);
   TEXT_PLAIN = MimeType.valueOf(TEXT_PLAIN_VALUE);
   TEXT_XML = MimeType.valueOf(TEXT_XML_VALUE);
 }