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

The following examples show how to use org.openide.filesystems.FileObject#getMIMEType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 2
Source File: CSSUpdater.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Updates css in browser using webKit.
 * @param snapshot 
 */
synchronized void update(FileObject fileObject, String content) {
    if (webKit == null) {
        return;
    }
    Project owner = FileOwnerQuery.getOwner(fileObject);
    if (owner == null) {
        return;
    }
    URL serverUrl = ServerURLMapping.toServer(owner, fileObject);
    if (serverUrl == null) {
        return;
    }
    String mimeType = fileObject.getMIMEType();
    if (mimeType.equals("text/html")) { // Should we be more strict, i.e., !mimeType.equals("text/css")? // NOI18N
        return; // Issue 225630
    }
    StyleSheetHeader header = sheetsMap.get(serverUrl.toString());
    if (header == null) {
        header = fobToSheetMap.get(fileObject);
    }
    if (header != null) {
        webKit.getCSS().setStyleSheetText(header.getStyleSheetId(), content);
    }
}
 
Example 3
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 4
Source File: WebReplaceTokenProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(String action, Lookup lookup) {
    if (ActionProvider.COMMAND_RUN_SINGLE.equals(action) ||
        ActionProvider.COMMAND_DEBUG_SINGLE.equals(action) || 
        ActionProvider.COMMAND_PROFILE_SINGLE.equals(action)) {

        FileObject[] fos = extractFileObjectsfromLookup(lookup);
        if (fos.length > 0) {
            FileObject fo = fos[0];
            String mimeType = fo.getMIMEType();
            if ("text/x-java".equals(mimeType)) { //NOI18N
                return convertJavaAction(action, fo);
            }
            if ("text/x-jsp".equals(mimeType) || "text/html".equals(mimeType) || "text/xhtml".equals(mimeType)) { // NOI18N
                return action + ".deploy"; //NOI18N
            }
        }
    }
    return null;
}
 
Example 5
Source File: DefaultMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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 6
Source File: NbinstURLStreamHandler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 7
Source File: CakePHPExternalDropHandler.java    From cakephp3-netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isAvailableMimeType(FileObject fileObject) {
    String mimeType = fileObject.getMIMEType();
    switch (mimeType) {
        case "text/css": // NOI18N
        case "text/javascript": // NOI18N
        case "image/png": // NOI18N
        case "image/jpeg": // NOI18N
        case "image/gif": // NOI18N
        case "text/x-php5": // NOI18N
            return true;
        default:
            return false;
    }
}
 
Example 8
Source File: ErrorCheckingSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String getMimeType(Parser.Result result) {
    SyntaxAnalyzerResult syntax = getSyntaxAnalyzerResult(result);
    if (syntax != null) {
        return Utils.getWebPageMimeType(syntax);
    }
    FileObject fo = result.getSnapshot().getSource().getFileObject();
    if (fo != null) {
        return fo.getMIMEType();
    } else {
        // no fileobject?
        return result.getSnapshot().getMimeType();
    }
}
 
Example 9
Source File: PageFlowController.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the file type in known.
 * @param file the fileobject type to check. If null, throws NPE.
 * @return if it is of type jsp, jspf, or html it will return true.
 */
public final boolean isKnownFile(FileObject file) {
    String[] knownMimeTypes = {"text/x-jsp", "text/html", "text/xhtml"}; //NOI18N
    String mimeType = file.getMIMEType(knownMimeTypes);
    if (mimeType.equals("text/x-jsp") && !file.getExt().equals("jspf")) { //NOI18N
        return true;
    } else if (mimeType.equals("text/html") || mimeType.equals("text/xhtml")) { //NOI18N
        return true;
    }
    return false;
}
 
Example 10
Source File: HistoryDiffView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getMimeType(FileObject file) {
    FileObject fo = file;
    if(fo != null) {
        return fo.getMIMEType();   
    } else {
        return "content/unknown"; // NOI18N
    }                
}
 
Example 11
Source File: ProxyBinaryIndexerFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
private Map<String,? extends Iterable<? extends FileObject>> supports(
        @NonNull final Context ctx) {
    final FileObject root = ctx.getRoot();
    if (root == null) {
        return null;
    }
    if (Boolean.TRUE == SPIAccessor.getInstance().getProperty(ctx, PROP_CHECKED)) {
        return (Map<String,? extends Iterable<? extends FileObject>>) SPIAccessor.getInstance().getProperty(ctx, PROP_MATCHED_FILES);
    }
    final Map<String,Queue<FileObject>> matchedFiles = new HashMap<String, Queue<FileObject>>();

    String s = (String) params.get(ATTR_REQUIRED_RES);
    final String[] requiredResources = s == null ? null : s.split(","); //NOI18N
    s = (String) params.get(ATTR_REQUIRED_MIME);
    final String[] mimeTypes = s == null ? null : s.split(",");         //NOI18N
    s = (String) params.get(ATTR_NAME_PATTERN);
    final Pattern pattern = s == null ? null : Pattern.compile(s);
    try {
        if (isUpToDate(ctx)) {
            return null;
        }
        if (requiredResources != null) {
            boolean found = false;
            for (String r : requiredResources) {
                if (root.getFileObject(r) != null) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return null;
            }
        }
        if (mimeTypes != null || pattern != null) {
            final Enumeration<? extends FileObject> fos = root.getChildren(true);
            final Set<String> mimeTypesSet = mimeTypes == null ?
                    null :
                    new HashSet<String>(Arrays.asList(mimeTypes));
            while (fos.hasMoreElements()) {
                final FileObject f = fos.nextElement();
                if (pattern != null) {
                    final String name = f.getNameExt();
                    if (!pattern.matcher(name).matches()) {
                        continue;
                    }
                }
                String mt = MIME_UNKNOWN;
                if (mimeTypes != null) {
                    mt = f.getMIMEType(mimeTypes);
                    if (!mimeTypesSet.contains(mt)) {
                        continue;
                    }
                }
                Queue<FileObject> q = matchedFiles.get(mt);
                if (q == null) {
                    q = new ArrayDeque<FileObject>();
                    matchedFiles.put(mt, q);
                }
                q.offer(f);
            }
            if (matchedFiles.isEmpty()) {
                return null;
            }
        }
        final Map<String, ? extends Iterable<? extends FileObject>> res = Collections.unmodifiableMap(matchedFiles);
        SPIAccessor.getInstance().putProperty(ctx, PROP_MATCHED_FILES, res);
        return res;
    } finally {
        SPIAccessor.getInstance().putProperty(ctx, PROP_CHECKED, Boolean.TRUE);
    }
}
 
Example 12
Source File: JSBreakpointsInfoImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAnnotatable(FileObject fo) {
    String mimeType = fo.getMIMEType();
    return JSUtils.JS_MIME_TYPE.equals(mimeType);
}
 
Example 13
Source File: IndentationPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public TextPreview(Preferences prefs, FileObject previewFile) throws IOException {
    this(prefs, previewFile.getMIMEType(), loadPreviewText(previewFile.getInputStream()));
}
 
Example 14
Source File: CssExternalDropHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 15
Source File: JspUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static boolean isJSPOrTagFile(FileObject fo) {
    String mimeType = fo.getMIMEType();
    return JspKit.JSP_MIME_TYPE.equals(mimeType) || JspKit.TAG_MIME_TYPE.equals(mimeType);
}
 
Example 16
Source File: ColorModel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String [] loadPreviewExample(String mimeType) {
    FileObject exampleFile = null;
    String exampleMimeType = null;
    
    if (mimeType == null || mimeType.length() == 0) {
        FileObject f = FileUtil.getConfigFile("OptionsDialog/PreviewExamples"); //NOI18N
        if (f != null && f.isFolder()) {
            FileObject [] ff = f.getChildren();
            for(int i = 0 ; i < ff.length; i++) {
                if (ff[i].isData()) {
                    exampleFile = ff[i];
                    break;
                }
            }
        }
        if (exampleFile != null) {
            if (exampleFile.getMIMEType().equals("content/unknown")) { //NOI18N
                exampleMimeType = "text/x-all-languages"; //NOI18N
            } else {
                exampleMimeType = exampleFile.getMIMEType();
            }
        }
    } else {
        exampleFile = FileUtil.getConfigFile("OptionsDialog/PreviewExamples/" + mimeType); //NOI18N
        exampleMimeType = mimeType;
    }
    
    if (exampleFile != null && exampleFile.isValid() && exampleFile.getSize() > 0) {
        StringBuilder sb;
        if (exampleFile.getSize() < (long) Integer.MAX_VALUE) {
            sb = new StringBuilder((int)exampleFile.getSize());
        } else {
            sb = new StringBuilder(Integer.MAX_VALUE);
        }
            
        
        try {
            InputStreamReader is = new InputStreamReader(exampleFile.getInputStream());
            char [] buffer = new char[1024];
            int size;
            try {
                while(0 < (size = is.read(buffer, 0, buffer.length))) {
                    sb.append(buffer, 0, size);
                }
            } finally {
                is.close();
            }
        } catch (IOException ioe) {
            LOG.log(Level.WARNING, "Can't read font & colors preview example", ioe); //NOI18N
        }
        
        return new String [] { sb.toString(), exampleMimeType };
    } else {
        if(exampleFile != null && !exampleFile.isValid()) {
            LOG.log(Level.WARNING, "Font & colors preview example is invalid " + exampleFile); //NOI18N
        }
        return new String [] { "", "text/plain" }; //NOI18N
    }            
}
 
Example 17
Source File: V8BreakpointsActiveService.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAnnotatable(FileObject fo) {
    String mimeType = fo.getMIMEType();
    return JS_MIME_TYPE.equals(mimeType);
}
 
Example 18
Source File: WebBreakpointsActiveService.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAnnotatable(FileObject fo) {
    String mimeType = fo.getMIMEType();
    return MiscEditorUtil.isJSOrWrapperMIMEType(mimeType);
}
 
Example 19
Source File: LanguagesDataLoader.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected FileObject findPrimaryFile (FileObject fo) {
    String mimeType = fo.getMIMEType ();
    if (LanguagesManager.getDefault ().createDataObjectFor (mimeType))
        return fo;
    return null;
}
 
Example 20
Source File: TextFetcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    if (EventQueue.isDispatchThread()) {
        if (cancelled) {
            return;
        }
        
        FileObject fob = source.matchingObj.getFileObject(); 
        String mimeType = fob.getMIMEType();
        //We don't want the swing html editor kit, and even if we 
        //do get it, it will frequently throw a random NPE 
        //in StyleSheet.removeHTMLTags that appears to be a swing bug
        if ("text/html".equals(mimeType)) {                         //NOI18N
            mimeType = "text/plain";                                //NOI18N
        }
        textDisplayer.setText(text,
                              mimeType,
                              getLocation());
        done = true;
    }  else {
        
        /* called from the request processor's thread */
        
        if (Thread.interrupted()) {
            return;
        }
        
        String invalidityDescription
                = source.matchingObj.getInvalidityDescription();
        if (invalidityDescription != null) {
            text = invalidityDescription;
        } else {
            try {
                text = source.matchingObj.getText();
            } catch (ClosedByInterruptException cbie) {
                cancelled = true;
                return;
            } catch (IOException ioe) {
                text = ioe.getLocalizedMessage();
                
//                cancel();
            }
        }
        
        if (Thread.interrupted()) {
            return;
        }
        
        EventQueue.invokeLater(this);
    }
}