Java Code Examples for org.netbeans.api.queries.FileEncodingQuery#getEncoding()

The following examples show how to use org.netbeans.api.queries.FileEncodingQuery#getEncoding() . 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: FileUtil.java    From jeddict with Apache License 2.0 6 votes vote down vote up
public static void expandTemplate(InputStream template, FileObject toFile, Map<String, Object> values) throws IOException {
    Charset targetEncoding = FileEncodingQuery.getEncoding(toFile);
    if (toFile.isLocked()) {
        LOG.log(Level.SEVERE, "File {0} is locked", new Object[]{toFile.getName()});
        return;
    }
    FileLock lock = toFile.lock();
    try (Writer writer = new OutputStreamWriter(toFile.getOutputStream(lock), targetEncoding)) {
        expandTemplate(new InputStreamReader(template), writer, values, targetEncoding);
    } finally {
        lock.releaseLock();
    }
    DataObject dob = DataObject.find(toFile);
    if (dob != null) {
        reformat(dob);
    }
}
 
Example 2
Source File: MatchingObjectTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testRead() throws IOException {

        MockServices.setServices(Utf8FileEncodingQueryImpl.class);

        FileObject dir = FileUtil.toFileObject(getDataDir());
        assertNotNull(dir);
        FileObject file = dir.getFileObject(
                "textFiles/utf8file.txt");
        Charset c = FileEncodingQuery.getEncoding(file);
        MatchingObject mo = new MatchingObject(new ResultModel(
                new BasicSearchCriteria(), "", null), file, c, null);
        StringBuilder text = mo.text(true);
        String textStr = text.toString();
        int lineBreakSize = textStr.charAt(textStr.length() - 1) == '\n'
                && textStr.charAt(textStr.length() - 2) == '\r' ? 2 : 1;
        assertEquals('.', textStr.charAt(textStr.length() - lineBreakSize - 1));
    }
 
Example 3
Source File: MultiLineMappedMatcherBig.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected Def checkMeasuredInternal(FileObject file,
        SearchListener listener) {

    Charset charset = FileEncodingQuery.getEncoding(file);

    LongCharSequence longSequence = null;
    try {
        File f = FileUtil.toFile(file);
        longSequence = new LongCharSequence(f, charset);
        List<TextDetail> textDetails = matchWholeFile(longSequence, file);
        if (textDetails == null) {
            return null;
        } else {
            Def def = new Def(file, charset, textDetails);
            return def;
        }
    } catch (Exception ex) {
        listener.generalError(ex);
        return null;
    } finally {
        if (longSequence != null) {
            longSequence.close();
        }
    }
}
 
Example 4
Source File: ResolveConflictsExecutor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MergeResultWriterInfo(File tempf1, File tempf2, File tempf3,
                             File outputFile, String mimeType,
                             String leftFileRevision, String rightFileRevision,
                             FileObject fo, FileLock lock, Charset encoding,
                             String newLineString) {
    this.tempf1 = tempf1;
    this.tempf2 = tempf2;
    this.tempf3 = tempf3;
    this.outputFile = outputFile;
    this.mimeType = mimeType;
    this.leftFileRevision = leftFileRevision;
    this.rightFileRevision = rightFileRevision;
    this.fo = fo;
    this.lock = lock;
    this.newLineString = newLineString;
    if (encoding == null) {
        encoding = FileEncodingQuery.getEncoding(FileUtil.toFileObject(tempf1));
    }
    this.encoding = encoding;
}
 
Example 5
Source File: GuardedBlockTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit) throws IOException, BadLocationException {
    if (guardedEditor == null) {
        guardedEditor = new FormGEditor();
        GuardedSectionsFactory gFactory = GuardedSectionsFactory.find("text/x-java");
        if (gFactory != null) {
            guardedProvider = gFactory.create(guardedEditor);
        }
    }

    if (guardedProvider != null) {
        guardedEditor.doc = doc;
        Charset c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile());
        Reader reader = guardedProvider.createGuardedReader(stream, c);
        try {
            kit.read(reader, doc, 0);
        } finally {
            reader.close();
        }
    } else {
        super.loadFromStreamToKit(doc, stream, kit);
    }
}
 
Example 6
Source File: ResolveConflictsExecutor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MergeResultWriterInfo(File tempf1, File tempf2, File tempf3,
                             File outputFile, String mimeType,
                             String leftFileRevision, String rightFileRevision,
                             FileObject fo, FileLock lock, Charset encoding,
                             String newLineString) {
    this.tempf1 = tempf1;
    this.tempf2 = tempf2;
    this.tempf3 = tempf3;
    this.outputFile = outputFile;
    this.mimeType = mimeType;
    this.leftFileRevision = leftFileRevision;
    this.rightFileRevision = rightFileRevision;
    this.fo = fo;
    this.lock = lock;
    this.newLineString = newLineString;
    if (encoding == null) {
        encoding = FileEncodingQuery.getEncoding(FileUtil.toFileObject(tempf1));
    }
    this.encoding = encoding;
}
 
Example 7
Source File: FolderArchive.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Charset encoding() {
    Charset e = encoding;
    if (e == null) {
        FileObject file = FileUtil.toFileObject(root);
        if (file != null) {
            e = FileEncodingQuery.getEncoding(file);
        } else {
            // avoid further checks
            e = UNKNOWN_CHARSET;
        }
        encoding = e;
    }
    return e != UNKNOWN_CHARSET ? e : null;
}
 
Example 8
Source File: XMLResultItem.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public String getText() {
    if (content == null) {
        return null;
    }
    FileObject f = URLMapper.findFileObject(content);
    if (f != null) {
        try {
            return new String(f.asBytes(), FileEncodingQuery.getEncoding(f));
        } catch (IOException x) {
            LOG.log(Level.INFO, "Could not load " + content, x);
        }
    }
    return null;
}
 
Example 9
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the Charset for the referenceFile and associates it weakly with
 * the given file. A following getAssociatedEncoding() call for
 * the file will then return the referenceFile-s Charset.
 *
 * @param referenceFile the file which charset has to be used when encoding file
 * @param file file to be encoded with the referenceFile-s charset
 *
 */
public static void associateEncoding(FileObject refFo, FileObject fo) {
    if(refFo == null || refFo.isFolder()) {
        return;
    }
    if(fo == null || fo.isFolder()) {
        return;
    }
    Charset c = FileEncodingQuery.getEncoding(refFo);
    associateEncoding(fo, c);
}
 
Example 10
Source File: BaseActionProviderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject createBuildScript(@NonNull final Project p) throws IOException {
    final FileObject bs = FileUtil.createData(p.getProjectDirectory(), "build.xml");    //NOI18N
    try (PrintWriter out = new PrintWriter(new OutputStreamWriter(bs.getOutputStream(), FileEncodingQuery.getEncoding(bs)))) {
        out.println("<project name='test' default='clean'>");   //NOI18N
        out.println("<target name='clean'/>");  //NOI18N
        out.println("</project>");  //NOI18N
    }
    return bs;
}
 
Example 11
Source File: DiffSidebar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the original content of the working copy. This method is typically only called after the OriginalContent
 * object is created and once for every property change event. 
 * 
 * @param oc current OriginalContent
 * @return Reader original content of the working copy or null if the original content is not available
 */ 
private String getText(VersioningSystem vs) {
    if (vs == null) {
        return null;
    }

    Collection<FileObject> filesToCheckout = getFiles(fileObject);
    if (filesToCheckout.isEmpty()) {
        return null;
    }

    File tempFolder = getTempFolder();
    FileObject tempFileObj = null;

    try {            
        Collection<File> originalFiles = checkoutOriginalFiles(filesToCheckout, tempFolder, vs);

        Charset encoding = FileEncodingQuery.getEncoding(fileObject);
        for (File f : originalFiles) {
            org.netbeans.modules.versioning.util.Utils.associateEncoding(f, encoding);
        }
        File tempFile = new File(tempFolder, fileObject.getNameExt());
        tempFileObj = FileUtil.toFileObject(tempFile);     //can be null
        return getText(tempFile, tempFileObj, encoding);
    } catch (Exception e) {
        // let providers raise errors when they feel appropriate
        return null;
    } finally {
        deleteTempFolder(tempFolder, tempFileObj);
    }
}
 
Example 12
Source File: FormEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream stream) throws IOException, BadLocationException {
    if (guardedProvider != null) {
        Charset c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile());
        Writer writer = guardedProvider.createGuardedWriter(stream, c);
        try {
            kit.write(writer, doc, 0, doc.getLength());
        } finally {
            writer.close();
        }
    } else {
        super.saveFromKitToStream(doc, kit, stream);
    }
}
 
Example 13
Source File: ContextualPatch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Charset getEncoding(File file) {
    try {
        return FileEncodingQuery.getEncoding(FileUtil.toFileObject(file));
    } catch (Throwable e) { // TODO: workaround for #108850
        // return default
    }
    return Charset.defaultCharset();
}
 
Example 14
Source File: FastMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Def checkBig(FileObject fileObject, File file,
        SearchListener listener) {

    Charset charset = FileEncodingQuery.getEncoding(fileObject);
    CharsetDecoder decoder = prepareDecoder(charset);

    LongCharSequence longSequence = null;
    try {
        longSequence = new LongCharSequence(file, charset);
        List<TextDetail> textDetails = multiline
                ? matchWholeFile(longSequence, fileObject)
                : matchLines(longSequence, fileObject);
        if (textDetails == null) {
            return null;
        } else {
            Def def = new Def(fileObject, decoder.charset(), textDetails);
            return def;
        }
    } catch (Exception ex) {
        listener.generalError(ex);
        return null;
    } finally {
        if (longSequence != null) {
            longSequence.close();
        }
    }
}
 
Example 15
Source File: PropertiesEditorSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Charset getCharset() {
    if (charset == null) {
        charset = FileEncodingQuery.getEncoding(myEntry.getDataObject().getPrimaryFile());
    }
    return charset;
}
 
Example 16
Source File: ResolveConflictsExecutor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean handleMergeFor(final File file, FileObject fo, FileLock lock,
                            final MergeVisualizer merge) throws IOException {
    String mimeType = (fo == null) ? "text/plain" : fo.getMIMEType(); // NOI18N
    String ext = (fo == null) ? "" : "." + fo.getExt();             //NOI18N
    File f1 = FileUtil.normalizeFile(File.createTempFile(TMP_PREFIX, ext));
    File f2 = FileUtil.normalizeFile(File.createTempFile(TMP_PREFIX, ext));
    File f3 = FileUtil.normalizeFile(File.createTempFile(TMP_PREFIX, ext));
    f1.deleteOnExit();
    f2.deleteOnExit();
    f3.deleteOnExit();
    
    newLineString = Utils.getLineEnding(fo, lock);

    Charset encoding = FileEncodingQuery.getEncoding(fo);
    final Difference[] diffs = copyParts(true, file, f1, true, encoding);
    if (diffs.length == 0) {
        ConflictResolvedAction.resolved(file);  // remove conflict status
        return false;
    }

    copyParts(false, file, f2, false, encoding);
    //GraphicalMergeVisualizer merge = new GraphicalMergeVisualizer();
    String originalLeftFileRevision = leftFileRevision;
    String originalRightFileRevision = rightFileRevision;
    if (leftFileRevision != null) leftFileRevision = leftFileRevision.trim();
    if (rightFileRevision != null) rightFileRevision = rightFileRevision.trim();
    List<HgLogMessage> parentRevisions = null;
    if (leftFileRevision.equals(LOCAL)) {
        try {
            parentRevisions = HgCommand.getParents(Mercurial.getInstance().getRepositoryRoot(file), file, null);
        } catch (HgException ex) {
            Mercurial.LOG.log(Level.INFO, null, ex);
        }
        if (parentRevisions != null && parentRevisions.size() > 1) {
            leftFileRevision = formatRevision(parentRevisions.get(0));
            rightFileRevision = formatRevision(parentRevisions.get(1));
        }
    }
    if (leftFileRevision == null || leftFileRevision.equals(file.getAbsolutePath() + ORIG_SUFFIX)
            || leftFileRevision.equals(LOCAL)){
        leftFileRevision = org.openide.util.NbBundle.getMessage(ResolveConflictsExecutor.class, "Diff.titleWorkingFile"); // NOI18N
    }
    if (rightFileRevision == null || rightFileRevision.equals(file.getAbsolutePath() + ORIG_SUFFIX)) {
        rightFileRevision = org.openide.util.NbBundle.getMessage(ResolveConflictsExecutor.class, "Diff.titleWorkingFile"); // NOI18N
    }
    
    final StreamSource s1;
    final StreamSource s2;
    Utils.associateEncoding(file, f1);
    Utils.associateEncoding(file, f2);
    s1 = StreamSource.createSource(file.getName(), leftFileRevision, mimeType, f1);
    s2 = StreamSource.createSource(file.getName(), rightFileRevision, mimeType, f2);
    final StreamSource result = new MergeResultWriterInfo(f1, f2, f3, file, mimeType,
                                                          originalLeftFileRevision,
                                                          originalRightFileRevision,
                                                          fo, lock, encoding, newLineString);
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Component c = merge.createView(diffs, s1, s2, result);
                if (c instanceof TopComponent) {
                    ((TopComponent) c).putClientProperty(ResolveConflictsExecutor.class.getName(), Boolean.TRUE);
                }
            } catch (IOException ioex) {
                org.openide.ErrorManager.getDefault().notify(ioex);
            }
        }
    });
    return true;
}
 
Example 17
Source File: IndentFileEntry.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates a new Java source from the template. Unlike the standard FileEntry.Format,
       this indents the resulting text using an indentation engine.
   */
   @Override
   public FileObject createFromTemplate (FileObject f, String name) throws IOException {
       String ext = getFile ().getExt ();

       if (name == null) {
           name = FileUtil.findFreeFileName(f, getFile ().getName (), ext);
       }
       FileObject fo = f.createData (name, ext);
       java.text.Format frm = createFormat (f, name, ext);
       InputStream is=getFile ().getInputStream ();
       Charset encoding = FileEncodingQuery.getEncoding(getFile());
       Reader reader = new InputStreamReader(is,encoding);
       BufferedReader r = new BufferedReader (reader);
       StyledDocument doc = createDocument(createEditorKit(fo.getMIMEType()));
       IndentEngine eng = (IndentEngine)indentEngine.get();
       if (eng == null) eng = IndentEngine.find(doc);
       Object attr = getFile().getAttribute(EA_PREFORMATTED);
       boolean preformatted = false;
       
       if (attr != null && attr instanceof Boolean) {
           preformatted = ((Boolean)attr).booleanValue();
       }

       try {
           FileLock lock = fo.lock ();
           try {
               encoding = FileEncodingQuery.getEncoding(fo);
               OutputStream os=fo.getOutputStream(lock);
               OutputStreamWriter w = new OutputStreamWriter(os, encoding);
               try {
                   String line = null;
                   String current;
                   int offset = 0;

                   while ((current = r.readLine ()) != null) {
                       if (line != null) {
                           // newline between lines
                           doc.insertString(offset, NEWLINE, null);
                           offset++;
                       }
                       line = frm.format (current);

                       // partial indentation used only for pre-formatted sources
                       // see #19178 etc.
                       if (!preformatted || !line.equals(current)) {
                           line = fixupGuardedBlocks(safeIndent(eng, line, doc, offset));
                       }
                       doc.insertString(offset, line, null);
                           offset += line.length();
                   }
                   doc.insertString(doc.getLength(), NEWLINE, null);
                   w.write(doc.getText(0, doc.getLength()));
               } catch (javax.swing.text.BadLocationException e) {
               } finally {
                   w.close ();
               }
           } finally {
               lock.releaseLock ();
           }
       } finally {
           r.close ();
       }
       // copy attributes
       FileUtil.copyAttributes (getFile (), fo);
// hack to overcome package-private modifier in setTemplate(fo, boolean)
       fo.setAttribute(DataObject.PROP_TEMPLATE, null);
       return fo;
   }
 
Example 18
Source File: ResolveConflictsExecutor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean handleMergeFor(final File file, FileObject fo, FileLock lock, final MergeVisualizer merge) throws IOException {
    String mimeType = (fo == null) ? "text/plain" : fo.getMIMEType(); // NOI18N
    File folder = Utils.getTempFolder();
    File f1 = new File(folder, TMP_PREFIX + "ours-" + file.getName()); //NOI18N
    f1.createNewFile();
    f1.deleteOnExit();
    File f2 = new File(folder, TMP_PREFIX + "theirs-" + file.getName()); //NOI18N
    f1.createNewFile();
    f2.deleteOnExit();
    
    File f3 = new File(folder, TMP_PREFIX + "result-" + file.getName()); //NOI18N
    f3.deleteOnExit();
    
    newLineString = Utils.getLineEnding(fo, lock);

    Charset encoding = FileEncodingQuery.getEncoding(fo);
    final Difference[] diffs = copyParts(true, file, f1, true, encoding);
    if (diffs.length == 0) {
        toResolve.add(file);
        return false;
    }

    copyParts(false, file, f2, false, encoding);

    String originalLeftFileRevision = leftFileRevision;
    String originalRightFileRevision = rightFileRevision;
    if (leftFileRevision != null) leftFileRevision = leftFileRevision.trim();
    if (rightFileRevision != null) rightFileRevision = rightFileRevision.trim();
    if (leftFileRevision == null || leftFileRevision.isEmpty()) {
        leftFileRevision = org.openide.util.NbBundle.getMessage(ResolveConflictsExecutor.class, "Diff.titleWorkingFile"); // NOI18N
    } else {
        leftFileRevision = formatRevision(leftFileRevision);
    }
    if (rightFileRevision == null || rightFileRevision.isEmpty()) {
        rightFileRevision = org.openide.util.NbBundle.getMessage(ResolveConflictsExecutor.class, "Diff.titleWorkingFile"); // NOI18N
    } else {
        rightFileRevision = formatRevision(rightFileRevision);
    }
    
    final StreamSource s1;
    final StreamSource s2;
    Utils.associateEncoding(file, f1);
    Utils.associateEncoding(file, f2);
    s1 = StreamSource.createSource(file.getName(), leftFileRevision, mimeType, f1);
    s2 = StreamSource.createSource(file.getName(), rightFileRevision, mimeType, f2);
    final StreamSource result = new MergeResultWriterInfo(f1, f2, f3, file, mimeType,
                                                          originalLeftFileRevision,
                                                          originalRightFileRevision,
                                                          fo, lock, encoding, newLineString);
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                Component c = merge.createView(diffs, s1, s2, result);
                if (c instanceof TopComponent) {
                    ((TopComponent) c).putClientProperty(ResolveConflictsExecutor.class.getName(), Boolean.TRUE);
                }
            } catch (IOException ioex) {
                GitClientExceptionHandler.notifyException(ioex, true);
            }
        }
    });
    return true;
}
 
Example 19
Source File: FastMatcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Check file content using Java NIO API.
 */
private Def checkSmall(FileObject fo, File file,
        SearchListener listener) {

    MappedByteBuffer bb = null;
    FileChannel fc = null;
    try {
        // Open the file and then get a channel from the stream
        FileInputStream fis = new FileInputStream(file);
        fc = fis.getChannel();

        // Get the file's size and then map it into memory
        int sz = (int) fc.size();
        bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);

        if (asciiPattern && !matchesIgnoringEncoding(bb)) {
            return null;
        }
        // Decode the file into a char buffer
        Charset charset = FileEncodingQuery.getEncoding(fo);
        CharsetDecoder decoder = prepareDecoder(charset);
        decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
        CharBuffer cb = decoder.decode(bb);

        List<TextDetail> textDetails = multiline
                ? matchWholeFile(cb, fo)
                : matchLines(cb, fo);
        if (textDetails == null) {
            return null;
        } else {
            Def def = new Def(fo, decoder.charset(), textDetails);
            return def;
        }
    } catch (Exception e) {
        listener.generalError(e);
        return null;
    } finally {
        if (fc != null) {
            try {
                fc.close();
            } catch (IOException ex) {
                listener.generalError(ex);
            }
        }
        unmap(bb);
    }
}
 
Example 20
Source File: TestPerformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getText(FileObject file) throws IOException {
    Charset encoding = FileEncodingQuery.getEncoding(file);

    return new String(file.asBytes(), encoding);
}