Java Code Examples for org.openide.filesystems.FileObject.getMIMEType()

The following are Jave code examples for showing how to use getMIMEType() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: CPActionsImplementationProvider.java   View Source Code Vote up 6 votes
private static boolean canRefactor(Lookup lookup) {
    Collection<? extends Node> nodes = lookup.lookupAll(Node.class);
    if (nodes.size() != 1) {
        return false;
    }
    Node node = nodes.iterator().next();

    //can refactor only in less/sass files
    FileObject file = getFileObjectFromNode(node);
    if (file != null) {
        String mimeType = file.getMIMEType();
        if (LessLanguage.getLanguageInstance().mimeType().equals(mimeType) || ScssLanguage.getLanguageInstance().mimeType().equals(mimeType)) {
            return isRefactorableEditorElement(node);
        }
    }
    return false;
}
 
Example 2
Project: incubator-netbeans   File: GitUtils.java   View Source Code Vote up 6 votes
/**
 * Uses content analysis to return the mime type for files.
 *
 * @param file file to examine
 * @return String mime type of the file (or best guess)
 */
public static String getMimeType(File file) {
    FileObject fo = FileUtil.toFileObject(file);
    String foMime;
    boolean hasMime = false;
    if (fo == null) {
        foMime = "content/unknown"; // NOI18N
    } else {
        foMime = fo.getMIMEType();
        if ("content/unknown".equals(foMime)) { // NOI18N
            foMime = "text/plain"; // NOI18N
        } else {
            hasMime = true;
        }
    }
    if (!hasMime) {
        return isFileContentBinary(file) ? "application/octet-stream" : foMime; // NOI18N
    } else {
        return foMime;
    }
}
 
Example 3
Project: incubator-netbeans   File: GsfDataLoader.java   View Source Code Vote up 6 votes
/**
 * In addition to mimetype list, checks base mime type if the mime is compound.
 * This is a workaround for loaders implementation do not currently support compound MIME types.
 * See defect #
 * 
 * @param fo file object to recognize 
 * @return primary file / null
 */
@Override
protected FileObject findPrimaryFile(FileObject fo) {
    FileObject pf = super.findPrimaryFile(fo);
    if (pf != null) {
        return pf;
    }
    String mime = fo.getMIMEType();
    int slash = -1;
    int l = mime.length();
    for (int i = 0; i < l; i++) {
        char c = mime.charAt(i);
        if (c == '/') { // NOI18N
            slash = i;
        } else if (c == '+') { // NOI18N
            if (slash == -1) {
                return null;
            }
            String baseMime = mime.substring(0, slash + 1) + mime.substring(i + 1);
            if (registeredMimes.contains(baseMime)) {
                return fo;
            }
        }
    }
    return null;
}
 
Example 4
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 6 votes
public static String getWebPageMimeType(SyntaxAnalyzerResult result) {
    InstanceContent ic = new InstanceContent();
    ic.add(result);
    WebPageMetadata wpmeta = WebPageMetadata.getMetadata(new AbstractLookup(ic));

    if (wpmeta != null) {
        //get an artificial mimetype for the web page, this doesn't have to be equal
        //to the fileObjects mimetype.
        String mimeType = (String) wpmeta.value(WebPageMetadata.MIMETYPE);
        if (mimeType != null) {
            return mimeType;
        }
    }

    FileObject fo = result.getSource().getSourceFileObject();
    if(fo != null) {
        return fo.getMIMEType();
    } else {
        //no fileobject?
        return result.getSource().getSnapshot().getMimeType();
    }

}
 
Example 5
Project: incubator-netbeans   File: TestUtil.java   View Source Code Vote up 6 votes
private static  Document getDocument(FileObject fo){
    Document result = null;
    if (result != null) return result;
    try {
        
        File file = FileUtil.toFile(fo);
        FileInputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[fis.available()];
        result = new org.netbeans.editor.BaseDocument(true, fo.getMIMEType());
        result.remove(0, result.getLength());
        fis.read(buffer);
        fis.close();
        String str = new String(buffer);
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    return result;
}
 
Example 6
Project: incubator-netbeans   File: CatalogModelTest.java   View Source Code Vote up 6 votes
private Document getDocument(FileObject fo){
    Document result = null;
    try {
        DataObject dObject = DataObject.find(fo);
        EditorCookie ec = (EditorCookie)dObject.getCookie(EditorCookie.class);
        Document doc = ec.openDocument();
        if(doc instanceof BaseDocument)
            return doc;
        result = new org.netbeans.editor.BaseDocument(true, fo.getMIMEType());
        String str = doc.getText(0, doc.getLength());
        result.insertString(0,str,null);
        
    } catch (Exception dObjEx) {
        return null;
    }
    return result;
}
 
Example 7
Project: incubator-netbeans   File: Mercurial.java   View Source Code Vote up 6 votes
/**
 * Uses content analysis to return the mime type for files.
 *
 * @param file file to examine
 * @return String mime type of the file (or best guess)
 */
public String getMimeType(File file) {
    FileObject fo = FileUtil.toFileObject(file);
    String foMime;
    if (fo == null) {
        foMime = "content/unknown"; // NOI18N
    } else {
        foMime = fo.getMIMEType();
        if ("content/unknown".equals(foMime)) { // NOI18N
            foMime = "text/plain"; // NOI18N
        }
    }
    if ((fileStatusCache.getStatus(file).getStatus() & FileInformation.STATUS_VERSIONED) == 0) {
        return HgUtils.isFileContentBinary(file) ? "application/octet-stream" : foMime; // NOI18N
    } else {
        return foMime;
    }
}
 
Example 8
Project: incubator-netbeans   File: DefaultMatcher.java   View Source Code Vote up 5 votes
/**
 * Checks whether the given file is a text file. The current implementation
 * does the check by the file's MIME-type.
 *
 * @param fileObj file to be checked
 * @return {@code true} if the file is a text file; {@code false} if it is a
 * binary file
 */
private static boolean isTextFile(FileObject fileObj) {
    String mimeType = fileObj.getMIMEType();

    if (mimeType.equals("content/unknown")) {                       //NOI18N
        if (searchableExtensions.contains(fileObj.getExt().toLowerCase())) {
            return true;
        } else {
            return fileObj.getSize() <= MAX_UNRECOGNIZED_FILE_SIZE ||
                    hasTextContent(fileObj);
        }
    }

    if (mimeType.startsWith("text/")) {                             //NOI18N
        return true;
    }

    if (mimeType.startsWith("application/")) {                      //NOI18N
        final String subtype = mimeType.substring(12);
        return subtype.equals("rtf") //NOI18N
                || subtype.equals("sgml") //NOI18N
                || subtype.startsWith("xml-") //NOI18N
                || subtype.endsWith("+xml") //NOI18N
                || isApplicationXSource(subtype, fileObj);
    }

    return mimeType.endsWith("+xml");                               //NOI18N
}
 
Example 9
Project: incubator-netbeans   File: LanguagesDataLoader.java   View Source Code Vote up 5 votes
protected MultiDataObject createMultiObject (FileObject primaryFile) 
throws DataObjectExistsException, IOException {
    String mimeType = primaryFile.getMIMEType ();
    if (LanguagesManager.getDefault ().createDataObjectFor (mimeType))
        return new LanguagesDataObject (primaryFile, this);
    return null;
}
 
Example 10
Project: incubator-netbeans   File: HgUtils.java   View Source Code Vote up 5 votes
/**
 * Uses content analysis for unversioned files.
 *
 * @param file file to examine
 * @return String mime type of the file (or best guess)
 */
public static String getMimeType(File file) {
    FileObject fo = FileUtil.toFileObject(file);
    String foMime;
    if (fo == null) {
        foMime = "content/unknown";
    } else {
        foMime = fo.getMIMEType();
    }
    if(foMime.startsWith("text")) {
        return foMime;
    }
    return Utils.isFileContentText(file) ? "text/plain" : "application/octet-stream";
}
 
Example 11
Project: incubator-netbeans   File: NbinstURLStreamHandler.java   View Source Code Vote up 5 votes
public String getHeaderField (String name) {
    if ("content-type".equals(name)) {                  //NOI18N
        try {
            this.connect();
            FileObject fo = FileUtil.toFileObject(f);
            if (fo != null) {
                return fo.getMIMEType();
            }
        } catch (IOException ioe) {
            Exceptions.printStackTrace(ioe);
        }
    }
    return super.getHeaderField(name);
}
 
Example 12
Project: incubator-netbeans   File: SvnUtils.java   View Source Code Vote up 5 votes
/**
 * Reads the svn:mime-type property or uses content analysis for unversioned files.
 *
 * @param file file to examine
 * @return String mime type of the file (or best guess)
 */
public static String getMimeType(File file) {
    FileObject fo = FileUtil.toFileObject(file);
    String foMime;
    if (fo == null) {
        foMime = "content/unknown";
    } else {
        foMime = fo.getMIMEType();
    }
    FileStatusCache cache = Subversion.getInstance().getStatusCache();
    if ((cache.getStatus(file).getStatus() & FileInformation.STATUS_VERSIONED) == 0) {
        if(foMime.startsWith("text/")) {
            return foMime;
        }
        return Utils.isFileContentText(file) ? "text/plain" : "application/octet-stream";
    } else {
        PropertiesClient client = new PropertiesClient(file);
        try {
            byte [] mimeProperty = client.getProperties().get("svn:mime-type");
            if (mimeProperty != null) {
                String mimePath = new String(mimeProperty);
                int pos = mimePath.indexOf('/');
                if (pos > 0) {
                    while (pos < mimePath.length()) {
                        try {
                            return MimePath.parse(mimePath).getPath();
                        } catch (IllegalArgumentException ex) {
                            // for paths in the form of text/plain;charset=UTF-8
                            mimePath = mimePath.substring(0, mimePath.length() - 1);
                        }
                    }
                }
            }
            return Utils.isFileContentText(file) ? foMime : "application/octet-stream";
        } catch (IOException e) {
            return foMime;
        }
    }
}
 
Example 13
Project: incubator-netbeans   File: HistoryDiffView.java   View Source Code Vote up 5 votes
private String getMimeType(FileObject file) {
    FileObject fo = file;
    if(fo != null) {
        return fo.getMIMEType();   
    } else {
        return "content/unknown"; // NOI18N
    }                
}
 
Example 14
Project: incubator-netbeans   File: SyntaxAnalyzerResult.java   View Source Code Vote up 4 votes
public boolean mayBeXhtml() {
    FileObject fo = getSource().getSourceFileObject();
    String mimeType = fo != null ? fo.getMIMEType() : null;
    return getHtmlTagDefaultNamespace() != null || "text/xhtml".equals(mimeType);
}
 
Example 15
Project: incubator-netbeans   File: IndentationPanel.java   View Source Code Vote up 4 votes
public TextPreview(Preferences prefs, FileObject previewFile) throws IOException {
    this(prefs, previewFile.getMIMEType(), loadPreviewText(previewFile.getInputStream()));
}
 
Example 16
Project: incubator-netbeans   File: LanguagesDataLoader.java   View Source Code Vote up 4 votes
protected FileObject findPrimaryFile (FileObject fo) {
    String mimeType = fo.getMIMEType ();
    if (LanguagesManager.getDefault ().createDataObjectFor (mimeType))
        return fo;
    return null;
}
 
Example 17
Project: incubator-netbeans   File: JSBreakpointsInfoImpl.java   View Source Code Vote up 4 votes
@Override
public boolean isAnnotatable(FileObject fo) {
    String mimeType = fo.getMIMEType();
    return JSUtils.JS_MIME_TYPE.equals(mimeType);
}
 
Example 18
Project: incubator-netbeans   File: CPUtils.java   View Source Code Vote up 4 votes
public static boolean isCPFile(FileObject file) {
    String mt = file.getMIMEType();
    return SCSS_FILE_MIMETYPE.equals(mt) || LESS_FILE_MIMETYPE.equals(mt);
}
 
Example 19
Project: incubator-netbeans   File: CssParser.java   View Source Code Vote up 4 votes
@Override
public void parse(Snapshot snapshot, Task task, SourceModificationEvent event) throws ParseException {
    cancelled.set(false);
    if (snapshot == null) {
        return;
    }
    
    this.snapshot = snapshot;
    FileObject fo = snapshot.getSource().getFileObject();
    String fileName = fo == null ? "no file" : fo.getPath(); //NOI18N
    String mimeType = topLevelSnapshotMimetype != null ? topLevelSnapshotMimetype : (fo == null ? null : fo.getMIMEType());
    LOG.log(Level.FINE, "Parsing {0} ", fileName); //NOI18N
    long start = System.currentTimeMillis();
    try {
        boolean tooLargeSnapshot = snapshot.getText().length() > MAX_SNAPSHOT_SIZE;
        
        //parse just an empty string in case of an oversize snapshot
        CharSequence source = tooLargeSnapshot ? "" : snapshot.getText();
        
        ExtCss3Lexer lexer = new ExtCss3Lexer(source, mimeType);
        TokenStream tokenstream = new CommonTokenStream(lexer);
        NbParseTreeBuilder builder = new NbParseTreeBuilder(source);
        ExtCss3Parser parser = new ExtCss3Parser(tokenstream, builder, mimeType);

        if (cancelled.get()) {
            return;
        }
        parser.styleSheet();

        if (cancelled.get()) {
            return;
        }

        AbstractParseTreeNode tree_local = builder.getTree();
        List<ProblemDescription> problems_local = new ArrayList<>();
        //add lexer issues
        problems_local.addAll(lexer.getProblems());
        //add parser issues
        problems_local.addAll(builder.getProblems());

        filterProblemsInVirtualCode(snapshot, problems_local);
        filterTemplatingProblems(snapshot, problems_local);

        if(tooLargeSnapshot) {
            //add a problem description informing the user there's something 'wrong' with the file
            problems_local.add(new ProblemDescription(0, 0, 
                    Bundle.too_large_snapshot(), ProblemDescription.Keys.PARSING.name(), ProblemDescription.Type.WARNING ));
        }
        
        if (cancelled.get()) {
            return;
        }

        this.tree = tree_local;
        this.problems = problems_local;

    } catch (RecognitionException ex) {
        throw new ParseException(String.format("Error parsing %s snapshot.", snapshot), ex); //NOI18N
    } finally {
        long end = System.currentTimeMillis();
        LOG.log(Level.FINE, "Parsing of {0} took {1} ms.", new Object[]{fileName, (end - start)}); //NOI18N
    }

}
 
Example 20
Project: incubator-netbeans   File: CssExternalDropHandler.java   View Source Code Vote up 4 votes
@Override
public boolean handleDrop(DropTargetDropEvent e) {
    Transferable t = e.getTransferable();
    if (null == t) {
        return false;
    }
    List<File> fileList = getFileList(t);
    if ((fileList == null) || fileList.isEmpty()) {
        return false;
    }

    //handle just the first file
    File file = fileList.get(0);
    FileObject target = FileUtil.toFileObject(file);
    if (file.isDirectory()) {
        return true; //as we previously claimed we canDrop() it so we need to say we've handled it even if did nothing.
    }

    JEditorPane pane = findPane(e.getDropTargetContext().getComponent());
    if (pane == null) {
        return false;
    }

    final BaseDocument document = (BaseDocument) pane.getDocument();
    FileObject current = DataLoadersBridge.getDefault().getFileObject(document);
    String relativePath = WebUtils.getRelativePath(current, target);

    final StringBuilder sb = new StringBuilder();

    //hardcoded support for common file types
    String mimeType = target.getMIMEType();
    switch (mimeType) { //NOI18N -- whole switch content
        case "text/css":
        case "text/less":
        case "text/scss":
            sb.append("@import \"").append(relativePath).append("\";");
            break;
        default:
            LOG.log(Level.INFO, "Dropping of files with mimetype {0} is not supported -  what would you like to generate? Let me know in the issue 219985 please. Thank you!", mimeType);
            return true;
    }

    //check if the line is white, and if not, insert a new line before the text
    final int offset = getLineEndOffset(pane, e.getLocation());

    final Indent indent = Indent.get(document);
    indent.lock();
    try {

        document.runAtomic(new Runnable() {

            @Override
            public void run() {
                try {
                    int ofs = offset;
                    if (!Utilities.isRowWhite(document, ofs)) {
                        document.insertString(ofs, "\n", null);
                        ofs++;
                    }
                    document.insertString(ofs, sb.toString(), null);

                    //reformat the line
                    final int from = Utilities.getRowStart(document, ofs);
                    final int to = Utilities.getRowEnd(document, ofs);

                    indent.reindent(from, to);

                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

        });

    } finally {
        indent.unlock();
    }

    return true;
}