Search in sources :

Example 1 with MimeTypeInfo

use of com.helger.xml.util.mime.MimeTypeInfo in project ph-web by phax.

the class MainCreateMimeTypesFileNameMapForJavaxActivation method main.

/**
 * Create the mime.types file that is read by javax.activation. See class
 * javax.annotation.MimetypesFileTypeMap
 *
 * @param args
 *        ignore
 * @throws Exception
 *         if anything goes wrong
 */
public static void main(final String[] args) throws Exception {
    final String sDestPath = "src/main/resources/META-INF/mime.types";
    Writer w = null;
    try {
        // build map from MimeType to list of extensions
        final ICommonsMap<String, ICommonsOrderedSet<String>> aMap = new CommonsHashMap<>();
        for (final MimeTypeInfo aInfo : MimeTypeInfoManager.getDefaultInstance().getAllMimeTypeInfos()) for (final String sExt : aInfo.getAllExtensions()) {
            // Skip the one empty extension!
            if (sExt.length() > 0)
                for (final String sMimeType : aInfo.getAllMimeTypeStrings()) aMap.computeIfAbsent(sMimeType, k -> new CommonsLinkedHashSet<>()).add(sExt);
        }
        // write file in format iso-8859-1!
        w = new PrintWriter(new File(sDestPath), StandardCharsets.ISO_8859_1.name());
        // write header
        for (final String sLine : VendorInfo.getFileHeaderLines()) w.write("# " + sLine + '\n');
        w.write("#\n");
        w.write("# Created on: " + ZonedDateTime.now(Clock.systemUTC()).toString() + "\n");
        w.write("# Created by: " + MainCreateMimeTypesFileNameMapForJavaxActivation.class.getName() + "\n");
        w.write("#\n");
        // write MIME type mapping
        for (final Map.Entry<String, ICommonsOrderedSet<String>> aEntry : aMap.getSortedByKey(Comparator.naturalOrder()).entrySet()) w.write("type=" + aEntry.getKey() + " exts=" + StringHelper.getImploded(',', aEntry.getValue()) + "\n");
        // done
        w.flush();
        w.close();
        LOGGER.info("Done creating " + sDestPath);
    } finally {
        StreamHelper.close(w);
    }
}
Also used : CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsOrderedSet(com.helger.commons.collection.impl.ICommonsOrderedSet) MimeTypeInfo(com.helger.xml.util.mime.MimeTypeInfo) File(java.io.File) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) Map(java.util.Map) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 2 with MimeTypeInfo

use of com.helger.xml.util.mime.MimeTypeInfo in project ph-commons by phax.

the class MainReadSharedMimeInfo method main.

public static void main(final String[] args) throws MimeTypeParserException {
    LOGGER.info("Reading shared-mime-info/freedesktop.org.xml");
    final IMicroDocument aDoc = MicroReader.readMicroXML(new File("src/test/resources/shared-mime-info/freedesktop.org.xml.in"));
    if (aDoc == null)
        throw new IllegalStateException("Failed to read mime type info file!");
    final MimeTypeInfoManager aMgr = new MimeTypeInfoManager();
    for (final IMicroElement eSrcMimeType : aDoc.getDocumentElement().getAllChildElements(NS, "mime-type")) {
        final String sMIMEType = eSrcMimeType.getAttributeValue("type");
        final ICommonsOrderedSet<MimeTypeWithSource> aLocalNames = new CommonsLinkedHashSet<>();
        // Names
        aLocalNames.add(new MimeTypeWithSource(sMIMEType));
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "alias")) {
            final String sAlias = eSrcChild.getAttributeValue("type");
            aLocalNames.add(new MimeTypeWithSource(sAlias));
        }
        // Description
        String sComment = null;
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "comment")) if (!eSrcChild.hasAttribute("xml:lang")) {
            sComment = eSrcChild.getTextContentTrimmed();
            break;
        }
        // Sub class of
        final ICommonsOrderedSet<String> aSubClassOf = new CommonsLinkedHashSet<>();
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "sub-class-of")) {
            final String s = eSrcChild.getAttributeValue("type");
            aSubClassOf.add(s);
        }
        boolean bHasAnyGlob = false;
        final ICommonsOrderedSet<String> aGlobs = new CommonsLinkedHashSet<>();
        final ICommonsOrderedSet<ExtensionWithSource> aExts = new CommonsLinkedHashSet<>();
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "glob")) {
            final String sPattern = eSrcChild.getAttributeValue("pattern");
            if (RegExHelper.stringMatchesPattern("\\*\\.[0-9a-zA-Z]+", sPattern)) {
                final String sExt = sPattern.substring(2);
                aExts.add(new ExtensionWithSource(sExt));
            } else
                aGlobs.add(sPattern);
            bHasAnyGlob = true;
        }
        if (bHasAnyGlob) {
            // Append only if at least on filename pattern is present
            aMgr.registerMimeType(new MimeTypeInfo(aLocalNames, sComment, aSubClassOf, aGlobs, aExts, "shared-mime-info"));
        }
    }
    LOGGER.info("Read " + aMgr.getAllMimeTypeInfos().size() + " mime type infos");
    // Maps file extension to MIME type
    LOGGER.info("Reading shared-mime-info/fileext-mimetype-mapping-local.xml");
    final Map<String, String> FileExtMap = new HashMap<>();
    if (XMLMapHandler.readMap(new FileSystemResource("src/test/resources/shared-mime-info/fileext-mimetype-mapping-local.xml"), FileExtMap).isFailure())
        throw new InitializationException("Failed to init file extension to mimetype mapping file");
    LOGGER.info("Read " + FileExtMap.size() + " entries");
    // Check old data
    for (final Map.Entry<String, String> aEntry : CollectionHelper.getSortedByKey(FileExtMap).entrySet()) {
        final String sOldExt = aEntry.getKey();
        final String sOldMimeType = aEntry.getValue();
        final MimeType aOldMimeType = MimeTypeParser.parseMimeType(sOldMimeType);
        ICommonsList<MimeTypeInfo> aNew;
        // First check for Mime Type, as they are unique
        aNew = aMgr.getAllInfosOfMimeType(aOldMimeType);
        if (aNew != null) {
            // Mime type is present - check if extension is also present
            boolean bFound = false;
            for (final MimeTypeInfo aInfo : aNew) if (aInfo.containsExtension(sOldExt)) {
                bFound = true;
                break;
            }
            if (!bFound) {
                if (aNew.size() == 1) {
                    aMgr.addExtension(aNew.get(0), new ExtensionWithSource(sOldExt, "old"));
                    if (false)
                        LOGGER.info("Added extension '" + sOldExt + "' to " + sOldMimeType + "!");
                } else
                    LOGGER.error(sOldMimeType + ": '" + sOldExt + "' not found in " + aNew + "!");
            }
        } else {
            // no such mime type present - Check other direction: ext 2 mimetype
            aNew = aMgr.getAllInfosOfExtension(sOldExt);
            if (aNew != null) {
                // Found extension - check if MIME type matches that type
                boolean bFound = false;
                for (final MimeTypeInfo aInfo : aNew) if (aInfo.containsMimeType(sOldMimeType)) {
                    bFound = true;
                    break;
                }
                if (!bFound) {
                    if (aNew.size() == 1) {
                        aMgr.addMimeType(aNew.get(0), new MimeTypeWithSource(aOldMimeType, "old"));
                        if (false)
                            LOGGER.info("'" + sOldExt + "': " + sOldMimeType + " not found in " + aNew.get(0) + "!");
                    } else
                        LOGGER.error("'" + sOldExt + "': " + sOldMimeType + " not found in any of " + aNew + "!");
                }
            } else {
                // No such mapping from ext to mime type
                // Create a new entry
                aMgr.registerMimeType(new MimeTypeInfo(CollectionHelper.newOrderedSet(new MimeTypeWithSource(sOldMimeType)), null, new CommonsLinkedHashSet<>(), new CommonsLinkedHashSet<>(), CollectionHelper.newOrderedSet(new ExtensionWithSource(sOldExt)), "old"));
                if (false)
                    LOGGER.info("Creating new: " + sOldMimeType + " = '" + sOldExt + "'");
            }
        }
    }
    LOGGER.info("Finally having " + aMgr.getAllMimeTypeInfos().size() + " mime type infos");
    if (MicroWriter.writeToFile(aMgr.getAsDocument(), new File("src/main/resources/codelists/mime-type-info.xml")).isSuccess())
        LOGGER.info("done - run mvn license:format !!");
    else
        LOGGER.error("Error writing file");
}
Also used : MimeTypeWithSource(com.helger.xml.util.mime.MimeTypeInfo.MimeTypeWithSource) HashMap(java.util.HashMap) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) InitializationException(com.helger.commons.exception.InitializationException) MimeTypeInfoManager(com.helger.xml.util.mime.MimeTypeInfoManager) MimeType(com.helger.commons.mime.MimeType) ExtensionWithSource(com.helger.xml.util.mime.MimeTypeInfo.ExtensionWithSource) IMicroElement(com.helger.xml.microdom.IMicroElement) MimeTypeInfo(com.helger.xml.util.mime.MimeTypeInfo) IMicroDocument(com.helger.xml.microdom.IMicroDocument) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

MimeTypeInfo (com.helger.xml.util.mime.MimeTypeInfo)2 File (java.io.File)2 Map (java.util.Map)2 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)1 CommonsLinkedHashSet (com.helger.commons.collection.impl.CommonsLinkedHashSet)1 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)1 ICommonsOrderedSet (com.helger.commons.collection.impl.ICommonsOrderedSet)1 InitializationException (com.helger.commons.exception.InitializationException)1 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 MimeType (com.helger.commons.mime.MimeType)1 IMicroDocument (com.helger.xml.microdom.IMicroDocument)1 IMicroElement (com.helger.xml.microdom.IMicroElement)1 ExtensionWithSource (com.helger.xml.util.mime.MimeTypeInfo.ExtensionWithSource)1 MimeTypeWithSource (com.helger.xml.util.mime.MimeTypeInfo.MimeTypeWithSource)1 MimeTypeInfoManager (com.helger.xml.util.mime.MimeTypeInfoManager)1 PrintWriter (java.io.PrintWriter)1 Writer (java.io.Writer)1 HashMap (java.util.HashMap)1