Java 类com.intellij.openapi.vfs.CharsetToolkit 实例源码

项目:educational-plugin    文件:StudyProjectGenerator.java   
@Nullable
public static Course getCourse(String zipFilePath) {
  try {
    final JBZipFile zipFile = new JBZipFile(zipFilePath);
    final JBZipEntry entry = zipFile.getEntry(EduNames.COURSE_META_FILE);
    if (entry == null) {
      return null;
    }
    byte[] bytes = entry.getData();
    final String jsonText = new String(bytes, CharsetToolkit.UTF8_CHARSET);
    Gson gson = new GsonBuilder()
      .registerTypeAdapter(Task.class, new StudySerializationUtils.Json.TaskAdapter())
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
    return gson.fromJson(jsonText, Course.class);
  }
  catch (IOException e) {
    LOG.error("Failed to unzip course archive");
    LOG.error(e);
  }
  return null;
}
项目:intellij-ce-playground    文件:ArtifactBuilderOverwriteTest.java   
private String createArchive(String relativeArchivePath, String fileNameInArchive, String text) {
  try {
    File file = new File(getOrCreateProjectDir(), relativeArchivePath);
    ZipOutputStream output = new ZipOutputStream(new FileOutputStream(file));
    try {
      output.putNextEntry(new ZipEntry(fileNameInArchive));
      output.write(text.getBytes(CharsetToolkit.UTF8));
      output.closeEntry();
    }
    finally {
      output.close();
    }
    return FileUtil.toSystemIndependentName(file.getAbsolutePath());
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:LossyEncodingTest.java   
public void testText() throws Exception {
  doTest("Text.txt");
  Charset ascii = CharsetToolkit.forName("US-ASCII");
  VirtualFile myVFile = myFile.getVirtualFile();
  FileDocumentManager.getInstance().saveAllDocuments();
  EncodingManager.getInstance().setEncoding(myVFile, ascii);
  UIUtil.dispatchAllInvocationEvents(); // wait for reload requests to bubble up
  assertEquals(ascii, myVFile.getCharset());
  int start = myEditor.getCaretModel().getOffset();
  type((char)0x445);
  type((char)0x438);
  int end = myEditor.getCaretModel().getOffset();

  Collection<HighlightInfo> infos = doHighlighting();
  HighlightInfo info = assertOneElement(infos);
  assertEquals("Unsupported characters for the charset 'US-ASCII'", info.getDescription());
  assertEquals(start, info.startOffset);
  assertEquals(end, info.endOffset);

  backspace();
  backspace();

  doDoTest(true, false);
}
项目:intellij-ce-playground    文件:LocalArchivedTemplate.java   
@Nullable
String readEntry(@NotNull final String endsWith) {
  try {
    return processStream(new StreamProcessor<String>() {
      @Override
      public String consume(@NotNull ZipInputStream stream) throws IOException {
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
          if (entry.getName().endsWith(endsWith)) {
            return StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET);
          }
        }
        return null;
      }
    });
  }
  catch (IOException ignored) {
    return null;
  }
}
项目:intellij-ce-playground    文件:BuildManager.java   
@Nullable
private static Pair<Date, File> readUsageFile(File usageFile) {
  try {
    final List<String> lines = FileUtil.loadLines(usageFile, CharsetToolkit.UTF8_CHARSET.name());
    if (!lines.isEmpty()) {
      final String dateString = lines.get(0);
      final Date date;
      synchronized (USAGE_STAMP_DATE_FORMAT) {
        date = USAGE_STAMP_DATE_FORMAT.parse(dateString);
      }
      final File projectFile = lines.size() > 1? new File(lines.get(1)) : null;
      return Pair.create(date, projectFile);
    }
  }
  catch (Throwable e) {
    LOG.info(e);
  }
  return null;
}
项目:intellij-ce-playground    文件:StreamLoader.java   
@Override
public void load(@NotNull Consumer<String> consumer) {
  try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream, CharsetToolkit.UTF8_CHARSET));
    try {
      String line;
      while ((line = br.readLine()) != null) {
        consumer.consume(line);
      }
    }
    finally {
      br.close();
    }
  }
  catch (Exception e) {
    Logger.getInstance(StreamLoader.class).error(e);
  }
}
项目:intellij-ce-playground    文件:SplitterTest.java   
private static String convertStreamToString(InputStream is) {
  if (is != null) {
    StringBuilder sb = new StringBuilder();

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, CharsetToolkit.UTF8_CHARSET));
      try {
        String line;
        while ((line = reader.readLine()) != null) {
          sb.append(line).append('\n');
        }
      }
      finally {
        reader.close();
      }
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }

    return sb.toString();
  }
  else {
    return "";
  }
}
项目:intellij-ce-playground    文件:BinaryContent.java   
@Override
@Nullable
public Document getDocument() {
  if (myDocument == null) {
    if (isBinary()) return null;

    String text = null;
    try {
      Charset charset = ObjectUtils.notNull(myCharset, EncodingProjectManager.getInstance(myProject).getDefaultCharset());
      text = CharsetToolkit.bytesToString(myBytes, charset);
    }
    catch (IllegalCharsetNameException ignored) { }

    //  Still NULL? only if not supported or an exception was thrown.
    //  Decode a string using the truly default encoding.
    if (text == null) text = new String(myBytes);
    text = LineTokenizer.correctLineSeparators(text);

    myDocument = EditorFactory.getInstance().createDocument(text);
    myDocument.setReadOnly(true);
  }

  return myDocument;
}
项目:intellij-ce-playground    文件:ExecUtil.java   
@NotNull
public static String loadTemplate(@NotNull ClassLoader loader, @NotNull String templateName, @Nullable Map<String, String> variables) throws IOException {
  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") InputStream stream = loader.getResourceAsStream(templateName);
  if (stream == null) {
    throw new IOException("Template '" + templateName + "' not found by " + loader);
  }

  String template = FileUtil.loadTextAndClose(new InputStreamReader(stream, CharsetToolkit.UTF8));
  if (variables == null || variables.size() == 0) {
    return template;
  }

  StringBuilder buffer = new StringBuilder(template);
  for (Map.Entry<String, String> var : variables.entrySet()) {
    String name = var.getKey();
    int pos = buffer.indexOf(name);
    if (pos >= 0) {
      buffer.replace(pos, pos + name.length(), var.getValue());
    }
  }
  return buffer.toString();
}
项目:intellij-ce-playground    文件:GenericRepository.java   
private String executeMethod(HttpMethod method) throws Exception {
  String responseBody;
  getHttpClient().executeMethod(method);
  Header contentType = method.getResponseHeader("Content-Type");
  if (contentType != null && contentType.getValue().contains("charset")) {
    // ISO-8859-1 if charset wasn't specified in response
    responseBody = StringUtil.notNullize(method.getResponseBodyAsString());
  }
  else {
    InputStream stream = method.getResponseBodyAsStream();
    responseBody = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET);
  }
  if (method.getStatusCode() != HttpStatus.SC_OK) {
    throw new Exception("Request failed with HTTP error: " + method.getStatusText());
  }
  return responseBody;
}
项目:intellij-ce-playground    文件:LightPlatformCodeInsightTestCase.java   
@NotNull
private static Document setupFileEditorAndDocument(@NotNull String fileName, @NotNull String fileText) throws IOException {
  EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
  deleteVFile();
  myVFile = getSourceRoot().createChildData(null, fileName);
  VfsUtil.saveText(myVFile, fileText);
  final FileDocumentManager manager = FileDocumentManager.getInstance();
  final Document document = manager.getDocument(myVFile);
  assertNotNull("Can't create document for '" + fileName + "'", document);
  manager.reloadFromDisk(document);
  document.insertString(0, " ");
  document.deleteString(0, 1);
  myFile = getPsiManager().findFile(myVFile);
  assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
  assertTrue(myFile.isPhysical());
  myEditor = createEditor(myVFile);
  myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  return document;
}
项目:intellij-ce-playground    文件:DiffContentRevision.java   
@Nullable
public String getContent() throws VcsException {
  if (myContents == null) {
    BufferExposingByteArrayOutputStream bos = new BufferExposingByteArrayOutputStream(2048);
    try {
      myRepository.getFile(myPath, -1, null, bos);
      myRepository.closeSession();
    } catch (SVNException e) {
      throw new VcsException(e);
    }
    final byte[] bytes = bos.toByteArray();
    final Charset charset = myFilePath.getCharset();
    myContents = CharsetToolkit.bytesToString(bytes, charset);
  }
  return myContents;
}
项目:intellij-ce-playground    文件:WorkingContextManager.java   
private synchronized void saveContext(@Nullable String entryName, String zipPostfix, @Nullable String comment) {
  JBZipFile archive = null;
  try {
    archive = getTasksArchive(zipPostfix);
    if (entryName == null) {
      int i = archive.getEntries().size();
      do {
        entryName = "context" + i++;
      } while (archive.getEntry("/" + entryName) != null);
    }
    JBZipEntry entry = archive.getOrCreateEntry("/" + entryName);
    if (comment != null) {
      entry.setComment(comment);
    }
    Element element = new Element("context");
    saveContext(element);
    String s = new XMLOutputter().outputString(element);
    entry.setData(s.getBytes(CharsetToolkit.UTF8_CHARSET));
  }
  catch (IOException e) {
    LOG.error(e);
  }
  finally {
    closeArchive(archive);
  }
}
项目:intellij-ce-playground    文件:FileDocumentManagerImplTest.java   
public void testSaveDocument_DocumentWasChanged() throws Exception {
  final VirtualFile file = createFile();
  final long stamp = file.getModificationStamp();
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "xxx ");
    }
  });


  myDocumentManager.saveDocument(document);
  assertTrue(stamp != file.getModificationStamp());
  assertEquals(document.getModificationStamp(), file.getModificationStamp());
  assertEquals("xxx test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET));
}
项目:intellij-ce-playground    文件:FileDocumentManagerImplTest.java   
public void testSaveAllDocuments_DocumentWasChanged() throws Exception {
  final VirtualFile file = createFile();
  final long stamp = file.getModificationStamp();
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "xxx ");
    }
  });

  myDocumentManager.saveAllDocuments();
  assertNotEquals(stamp, file.getModificationStamp());
  assertEquals("xxx test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET));
}
项目:intellij-ce-playground    文件:PersistenceStressTest.java   
@Override
protected void setUp() throws Exception {
  super.setUp();
  Random random = new Random();
  for (int i = 0; i < 1000; i++) {
    byte[] bytes = new byte[1000];
    random.nextBytes(bytes);
    String key = new String(bytes, CharsetToolkit.UTF8_CHARSET);
    myKeys.add(key);
  }
  for (int i = 0; i < 10; i++) {
    PersistentHashMap<String, Record> map = createMap(FileUtil.createTempFile("persistent", "map" + i));
    myMaps.add(map);
  }
  PagedFileStorage.StorageLockContext storageLockContext = new PagedFileStorage.StorageLockContext(false);
  myEnumerator = new PersistentStringEnumerator(FileUtil.createTempFile("persistent", "enum"), storageLockContext);

  myThreadPool = Executors.newFixedThreadPool(myMaps.size() + 1);
}
项目:intellij-ce-playground    文件:JDOMUtil.java   
@NotNull
public static XMLOutputter createOutputter(String lineSeparator) {
  XMLOutputter xmlOutputter = new MyXMLOutputter();
  Format format = Format.getCompactFormat().
    setIndent("  ").
    setTextMode(Format.TextMode.TRIM).
    setEncoding(CharsetToolkit.UTF8).
    setOmitEncoding(false).
    setOmitDeclaration(false).
    setLineSeparator(lineSeparator);
  xmlOutputter.setFormat(format);
  return xmlOutputter;
}
项目:intellij-ce-playground    文件:ShelveChangesManager.java   
private static void writePatchesToFile(final Project project,
                                       final String path,
                                       final List<FilePatch> remainingPatches,
                                       CommitContext commitContext) {
  try {
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8_CHARSET);
    try {
      UnifiedDiffWriter.write(project, remainingPatches, writer, "\n", commitContext);
    }
    finally {
      writer.close();
    }
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:LoadTextUtil.java   
@NotNull
private static Pair.NonNull<Charset, byte[]> charsetForWriting(@Nullable Project project,
                                                       @NotNull VirtualFile virtualFile,
                                                       @NotNull String text,
                                                       @NotNull Charset existing) {
  Charset specified = extractCharsetFromFileContent(project, virtualFile, text);
  Pair.NonNull<Charset, byte[]> chosen = chooseMostlyHarmlessCharset(existing, specified, text);
  Charset charset = chosen.first;

  // in case of "UTF-16", OutputStreamWriter sometimes adds BOM on it's own.
  // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6800103
  byte[] bom = virtualFile.getBOM();
  Charset fromBom = bom == null ? null : CharsetToolkit.guessFromBOM(bom);
  if (fromBom != null && !fromBom.equals(charset)) {
    chosen = Pair.createNonNull(fromBom, toBytes(text, fromBom));
  }
  return chosen;
}
项目:intellij-ce-playground    文件:JavaTestFrameworkRunnableState.java   
protected void writeClassesPerModule(String packageName, JavaParameters javaParameters, Map<Module, List<String>> perModule)
  throws FileNotFoundException, UnsupportedEncodingException, CantRunException {
  if (perModule != null && perModule.size() > 1) {
    final String classpath = getScope() == TestSearchScope.WHOLE_PROJECT
                             ? null : javaParameters.getClassPath().getPathsString();

    final PrintWriter wWriter = new PrintWriter(myWorkingDirsFile, CharsetToolkit.UTF8);
    try {
      wWriter.println(packageName);
      for (Module module : perModule.keySet()) {
        wWriter.println(PathMacroUtil.getModuleDir(module.getModuleFilePath()));
        wWriter.println(module.getName());

        if (classpath == null) {
          final JavaParameters parameters = new JavaParameters();
          parameters.getClassPath().add(JavaSdkUtil.getIdeaRtJarPath());
          configureRTClasspath(parameters);
          JavaParametersUtil.configureModule(module, parameters, JavaParameters.JDK_AND_CLASSES_AND_TESTS,
                                             getConfiguration().isAlternativeJrePathEnabled() ? getConfiguration()
                                               .getAlternativeJrePath() : null);
          wWriter.println(parameters.getClassPath().getPathsString());
        }
        else {
          wWriter.println(classpath);
        }

        final List<String> classNames = perModule.get(module);
        wWriter.println(classNames.size());
        for (String className : classNames) {
          wWriter.println(className);
        }
      }
    }
    finally {
      wWriter.close();
    }
  }
}
项目:intellij-ce-playground    文件:CvsApplicationLevelConfiguration.java   
@NotNull public static String getCharset() {
  String value = getInstance().ENCODING;
  if (DEFAULT.equals(value)) {
    return CharsetToolkit.getDefaultSystemCharset().name();
  } else {
    return value;
  }

}
项目:intellij-ce-playground    文件:LossyEncodingTest.java   
public void testDetectWrongEncoding() throws Exception {
  VirtualFile virtualFile = getVirtualFile(BASE_PATH + "/" + "Win1251.txt");
  virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
  configureByExistingFile(virtualFile);
  final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);

  assertFalse(FileDocumentManager.getInstance().isDocumentUnsaved(document));
  assertEquals(CharsetToolkit.UTF8_CHARSET, virtualFile.getCharset());

  doHighlighting();
  List<HighlightInfo> infos = DaemonCodeAnalyzerEx.getInstanceEx(getProject()).getFileLevelHighlights(getProject(), getFile());
  HighlightInfo info = assertOneElement(infos);
  assertEquals("File was loaded in the wrong encoding: 'UTF-8'", info.getDescription());
}
项目:intellij-ce-playground    文件:NavigateFromSourceTest.java   
private static void changeClassTextAndTryToNavigate(final String newClassString,
                                                    PsiJavaFile psiFile,
                                                    final AbstractProjectViewPSIPane pane,
                                                    final String expected) throws IOException, InterruptedException {
  PsiClass psiClass = psiFile.getClasses()[0];
  final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
  final JTree tree = pane.getTree();
  setBinaryContent(virtualFile, newClassString.getBytes(CharsetToolkit.UTF8_CHARSET));

  PlatformTestUtil.waitForAlarm(600);

  psiClass = psiFile.getClasses()[0];
  pane.select(psiClass, virtualFile, true);
  PlatformTestUtil.assertTreeEqual(tree, expected, true);
}
项目:intellij-ce-playground    文件:AbstractJavaFormatterTest.java   
@NotNull
public static String shiftIndentInside(@NotNull String initial, final int i, boolean shiftEmptyLines) {
  StringBuilder result = new StringBuilder(initial.length());
  List<byte[]> lines;
  try {
    LineReader reader = new LineReader(new ByteArrayInputStream(initial.getBytes(CharsetToolkit.UTF8_CHARSET)));
    lines = reader.readLines();
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }

  boolean first = true;
  for (byte[] line : lines) {
    try {
      if (!first) result.append('\n');
      if (line.length > 0 || shiftEmptyLines) {
        StringUtil.repeatSymbol(result, ' ', i);
      }
      result.append(new String(line));
    }
    finally {
      first = false;
    }
  }

  return result.toString();
}
项目:intellij-ce-playground    文件:Executor.java   
@NotNull
protected static String run(@NotNull File workingDir, @NotNull List<String> params, boolean ignoreNonZeroExitCode)
  throws ExecutionException
{
  final ProcessBuilder builder = new ProcessBuilder().command(params);
  builder.directory(workingDir);
  builder.redirectErrorStream(true);
  Process clientProcess;
  try {
    clientProcess = builder.start();
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }

  CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset());
  ProcessOutput result = handler.runProcess(30 * 1000);
  if (result.isTimeout()) {
    throw new RuntimeException("Timeout waiting for the command execution. Command: " + StringUtil.join(params, " "));
  }

  String stdout = result.getStdout().trim();
  if (result.getExitCode() != 0) {
    if (ignoreNonZeroExitCode) {
      debug("{" + result.getExitCode() + "}");
    }
    debug(stdout);
    if (!ignoreNonZeroExitCode) {
      throw new ExecutionException(result.getExitCode(), stdout);
    }
  }
  else {
    debug(stdout);
  }
  return stdout;
}
项目:intellij-ce-playground    文件:CommonSourceRootDetectionUtil.java   
private static char[] loadFileTextSkippingBom(File file) throws IOException {
  //noinspection IOResourceOpenedButNotSafelyClosed
  InputStream stream = CharsetToolkit.inputStreamSkippingBOM(new BufferedInputStream(new FileInputStream(file)));
  Reader reader = new InputStreamReader(stream);
  try {
    return FileUtilRt.loadText(reader, (int)file.length());
  }
  finally {
    reader.close();
  }
}
项目:intellij-ce-playground    文件:ExecUtil.java   
@NotNull
public static File createTempExecutableScript(@NotNull String prefix, @NotNull String suffix, @NotNull String content) throws IOException, ExecutionException {
  File tempDir = new File(PathManager.getTempPath());
  File tempFile = FileUtil.createTempFile(tempDir, prefix, suffix, true, true);
  FileUtil.writeToFile(tempFile, content.getBytes(CharsetToolkit.UTF8));
  if (!tempFile.setExecutable(true, true)) {
    throw new ExecutionException("Failed to make temp file executable: " + tempFile);
  }
  return tempFile;
}
项目:intellij-ce-playground    文件:HttpRequests.java   
@NotNull
static Charset getCharset(@NotNull Request request) throws IOException {
  String contentEncoding = request.getConnection().getContentEncoding();
  if (contentEncoding != null) {
    try {
      return Charset.forName(contentEncoding);
    }
    catch (Exception ignored) {
    }
  }
  return CharsetToolkit.UTF8_CHARSET;
}
项目:intellij-ce-playground    文件:ExportToHTMLManager.java   
@SuppressWarnings({"HardCodedStringLiteral"})
private static void generateIndexHtml(final PsiDirectory psiDirectory, final boolean recursive, final String outputDirectoryName)
  throws FileNotFoundException {
  String indexHtmlName = constructOutputDirectory(psiDirectory, outputDirectoryName) + File.separator + "index.html";
  OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(indexHtmlName), CharsetToolkit.UTF8_CHARSET);
  final String title = PsiDirectoryFactory.getInstance(psiDirectory.getProject()).getQualifiedName(psiDirectory, true);
  try {
    writer.write("<html><head><title>" + title + "</title></head><body>");
    if (recursive) {
      PsiDirectory[] directories = psiDirectory.getSubdirectories();
      for(PsiDirectory directory: directories) {
        writer.write("<a href=\"" + directory.getName() + "/index.html\"><b>" + directory.getName() + "</b></a><br />");
      }
    }
    PsiFile[] files = psiDirectory.getFiles();
    for(PsiFile file: files) {
      if (!(file instanceof PsiBinaryFile)) {
        writer.write("<a href=\"" + getHTMLFileName(file) + "\">" + file.getVirtualFile().getName() + "</a><br />");
      }
    }
    writer.write("</body></html>");
    writer.close();
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:ImportedToGeneralTestEventsConverter.java   
private void parseTestResults() {
  try {
    parseTestResults(new InputStreamReader(new FileInputStream(myFile), CharsetToolkit.UTF8_CHARSET), getProcessor());
  }
  catch (IOException e) {
    final String message = e.getMessage();
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        Messages.showErrorDialog(myConsoleProperties.getProject(), message, "Failed to Parse " + myFile.getName());
      }
    });
  }
}
项目:intellij-ce-playground    文件:ShelveChangesManager.java   
private static List<TextFilePatch> loadPatches(Project project,
                                               final String patchPath,
                                               CommitContext commitContext,
                                               boolean loadContent) throws IOException, PatchSyntaxException {
  char[] text = FileUtil.loadFileText(new File(patchPath), CharsetToolkit.UTF8);
  PatchReader reader = new PatchReader(new CharArrayCharSequence(text), loadContent);
  final List<TextFilePatch> textFilePatches = reader.readAllPatches();
  final TransparentlyFailedValueI<Map<String, Map<String, CharSequence>>, PatchSyntaxException> additionalInfo = reader.getAdditionalInfo(
    null);
  ApplyPatchDefaultExecutor.applyAdditionalInfoBefore(project, additionalInfo, commitContext);
  return textFilePatches;
}
项目:intellij-ce-playground    文件:CompoundShelfFileProcessor.java   
public void savePathFile(@NotNull ContentProvider contentProvider,
                         @NotNull final File patchPath,
                         @NotNull CommitContext commitContext)
  throws IOException {
  OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(patchPath), CharsetToolkit.UTF8_CHARSET);
  try {
    contentProvider.writeContentTo(writer, commitContext);
  }
  finally {
    writer.close();
  }
}
项目:intellij-ce-playground    文件:EclipseXMLOutputter.java   
/**
 * This will print the <code>Document</code> to the given Writer.
 *
 * <p>
 * Warning: using your own Writer may cause the outputter's
 * preferred character encoding to be ignored.  If you use
 * encodings other than UTF-8, we recommend using the method that
 * takes an OutputStream instead.
 * </p>
 *
 * @param doc <code>Document</code> to format.
 * @param out <code>Writer</code> to use.
 * @throws IOException - if there's any problem writing.
 */
public void output(Document doc, Writer out) throws IOException {

    printDeclaration(out, doc, CharsetToolkit.UTF8);

    // Print out root element, as well as any root level
    // comments and processing instructions,
    // starting with no indentation
    List content = doc.getContent();
    int size = content.size();
    for (int i = 0; i < size; i++) {
        Object obj = content.get(i);

        if (obj instanceof Element) {
            printElement(out, doc.getRootElement(), 0,
                         createNamespaceStack());
        }
        else if (obj instanceof Comment) {
            printComment(out, (Comment) obj);
        }
        else if (obj instanceof ProcessingInstruction) {
            printProcessingInstruction(out, (ProcessingInstruction) obj);
        }
        else if (obj instanceof DocType) {
            printDocType(out, doc.getDocType());
            // Always print line separator after declaration, helps the
            // output look better and is semantically inconsequential
            out.write(lineSeparator);
        }
        else {
            // XXX if we get here then we have a illegal content, for
            //     now we'll just ignore it
        }

        newline(out);
        indent(out, 0);
    }

    out.flush();
}
项目:intellij-ce-playground    文件:FTManager.java   
private void addTemplateFromFile(String fileName, File file) {
  Pair<String,String> nameExt = decodeFileName(fileName);
  final String extension = nameExt.second;
  final String templateQName = nameExt.first;
  if (templateQName.length() == 0) {
    return;
  }
  try {
    final String text = FileUtil.loadFile(file, CharsetToolkit.UTF8_CHARSET);
    addTemplate(templateQName, extension).setText(text);
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:PythonFileType.java   
@Override
public String getCharset(@NotNull VirtualFile file, @NotNull byte[] content) {
  if (CharsetToolkit.hasUTF8Bom(content)) {
    return CharsetToolkit.UTF8;
  }
  ByteBuffer bytes = ByteBuffer.wrap(content, 0, Math.min(256, content.length));
  String decoded = CharsetToolkit.UTF8_CHARSET.decode(bytes).toString();
  return getCharsetFromEncodingDeclaration(StringUtil.convertLineSeparators(decoded));
}
项目:intellij-ce-playground    文件:PropertiesFileType.java   
@Override
public String getCharset(@NotNull VirtualFile file, @NotNull final byte[] content) {
  Charset charset = EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(file);
  if (charset == null) {
    charset = CharsetToolkit.getDefaultSystemCharset();
  }
  return charset.name();
}
项目:intellij-ce-playground    文件:EncodingReference.java   
@Override
@NotNull
public Object[] getVariants() {
  Charset[] charsets = CharsetToolkit.getAvailableCharsets();
  List<LookupElement> suggestions = new ArrayList<LookupElement>(charsets.length);
  for (Charset charset : charsets) {
    suggestions.add(LookupElementBuilder.create(charset.name()).withCaseSensitivity(false));
  }
  return suggestions.toArray(new LookupElement[suggestions.size()]);
}
项目:intellij-ce-playground    文件:NewBaseRepositoryImpl.java   
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
  final CredentialsProvider provider = (CredentialsProvider)context.getAttribute(HttpClientContext.CREDS_PROVIDER);
  final Credentials credentials = provider.getCredentials(BASIC_AUTH_SCOPE);
  if (credentials != null) {
    request.addHeader(new BasicScheme(CharsetToolkit.UTF8_CHARSET).authenticate(credentials, request, context));
  }
  final HttpHost proxyHost = ((HttpRoute)context.getAttribute(HttpClientContext.HTTP_ROUTE)).getProxyHost();
  if (proxyHost != null) {
    final Credentials proxyCredentials = provider.getCredentials(new AuthScope(proxyHost));
    if (proxyCredentials != null) {
      request.addHeader(BasicScheme.authenticate(proxyCredentials, CharsetToolkit.UTF8, true));
    }
  }
}
项目:intellij-ce-playground    文件:ApplyPatchSaveToFileExecutor.java   
@Override
public void apply(MultiMap<VirtualFile, TextFilePatchInProgress> patchGroups,
                  LocalChangeList localList,
                  String fileName,
                  TransparentlyFailedValueI<Map<String, Map<String, CharSequence>>, PatchSyntaxException> additionalInfo) {
  final FileSaverDialog dialog = FileChooserFactory.getInstance().createSaveFileDialog(
    new FileSaverDescriptor("Save Patch to", ""), myProject);
  final VirtualFile baseDir = myProject.getBaseDir();
  final VirtualFileWrapper save = dialog.save(baseDir, "TheirsChanges.patch");
  if (save != null) {
    final CommitContext commitContext = new CommitContext();

    final VirtualFile baseForPatch = myBaseForPatch == null ? baseDir : myBaseForPatch;
    try {
      final List<FilePatch> textPatches = patchGroupsToOneGroup(patchGroups, baseForPatch);
      commitContext.putUserData(BaseRevisionTextPatchEP.ourPutBaseRevisionTextKey, false);
      PatchWriter.writePatches(myProject, save.getFile().getPath(), textPatches, commitContext, CharsetToolkit.UTF8_CHARSET);
    }
    catch (final IOException e) {
      LOG.info(e);
      WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() {
        @Override
        public void run() {
          Messages.showErrorDialog(myProject, VcsBundle.message("create.patch.error.title", e.getMessage()), CommonBundle.getErrorTitle());
        }
      }, null, myProject);
    }
  }
}
项目:intellij-ce-playground    文件:StatisticsUploadAssistant.java   
public static <T extends UsageDescriptor> String getDataString(@NotNull Map<GroupDescriptor, Set<T>> usages, int maxSize) {
  if (usages.isEmpty()) {
    return "";
  }

  String dataStr = ConvertUsagesUtil.convertUsages(usages);
  return maxSize > 0 && dataStr.getBytes(CharsetToolkit.UTF8_CHARSET).length > maxSize ? ConvertUsagesUtil.cutDataString(dataStr, maxSize) : dataStr;
}