com.intellij.openapi.util.io.StreamUtil Java Examples
The following examples show how to use
com.intellij.openapi.util.io.StreamUtil.
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: RefCountingStorage.java From consulo with Apache License 2.0 | 6 votes |
private BufferExposingByteArrayOutputStream internalReadStream(int record) throws IOException { waitForPendingWriteForRecord(record); byte[] result; synchronized (myLock) { result = super.readBytes(record); } InflaterInputStream in = new CustomInflaterInputStream(result); try { final BufferExposingByteArrayOutputStream outputStream = new BufferExposingByteArrayOutputStream(); StreamUtil.copyStreamContent(in, outputStream); return outputStream; } finally { in.close(); } }
Example #2
Source File: DataCompressor.java From consulo with Apache License 2.0 | 6 votes |
/** * @return pair bytes and modification count */ public static Pair<byte[], Integer> uncompress(@Nonnull InputStream stream) throws IOException { try (DataInputStream inputStream = new DataInputStream(stream)) { byte version = inputStream.readByte(); int modCount = inputStream.readInt(); int length = inputStream.readUnsignedShort(); switch (version) { case SNAPPY_V1: { byte[] compressedData = new byte[length]; int read = inputStream.read(compressedData); if (read != length) { throw new IllegalArgumentException("Can't read full byte array"); } try (SnappyInputStream snappyInputStream = new SnappyInputStream(new UnsyncByteArrayInputStream(compressedData))) { return Pair.create(StreamUtil.loadFromStream(snappyInputStream), modCount); } } default: throw new UnsupportedOperationException("Unknown version " + version); } } }
Example #3
Source File: DnDNativeTarget.java From consulo with Apache License 2.0 | 6 votes |
@Nullable public String getTextForFlavor(DataFlavor flavor) { if (myTexts.containsKey(flavor)) { return myTexts.get(flavor); } try { String text = StreamUtil.readTextFrom(flavor.getReaderForText(myTransferable)); myTexts.put(flavor, text); return text; } catch (Exception e) { myTexts.put(flavor, null); return null; } }
Example #4
Source File: RoutingRemoteFileStorage.java From idea-php-symfony2-plugin with MIT License | 6 votes |
@Override public void build(@NotNull Project project, @NotNull Collection<FileObject> fileObjects) { Map<String, Route> routeMap = new HashMap<>(); for (FileObject file : fileObjects) { String content; try { content = StreamUtil.readText(file.getContent().getInputStream(), "UTF-8"); } catch (IOException e) { continue; } if(StringUtils.isBlank(content)) { continue; } routeMap.putAll(RouteHelper.getRoutesInsideUrlGeneratorFile( PhpPsiElementFactory.createPsiFileFromText(project, content) )); } this.routeMap = routeMap; }
Example #5
Source File: PluginErrorReportSubmitter.java From BashSupport with Apache License 2.0 | 6 votes |
@Nullable private String readUrlContent(String urlString) { HttpConfigurable httpConfigurable = HttpConfigurable.getInstance(); HttpURLConnection connection = null; try { connection = httpConfigurable.openHttpConnection(urlString); String text = StreamUtil.readText(connection.getInputStream(), "UTF-8"); return text.trim(); } catch (IOException e) { //ignored } finally { if (connection != null) { connection.disconnect(); } } return null; }
Example #6
Source File: ClasspathDocSource.java From BashSupport with Apache License 2.0 | 6 votes |
/** * Reads documenation from a url, mostly this is a file source. * * @param path The prefix path to use. * @param command The command name, e.g. "echo" * @return The documentation content or null. */ private String readFromClasspath(String path, String command) { if (StringUtil.isEmpty(path) || StringUtil.isEmpty(command)) { return null; } final String fullPath = path + "/" + command + ".html"; try { URL url = getClass().getResource(fullPath); if (url == null) { return null; } final InputStream inputStream = new BufferedInputStream(url.openStream()); return StreamUtil.readText(inputStream, "UTF-8"); } catch (IOException e) { log.debug("Failed to read documentation.", e); } return null; }
Example #7
Source File: HttpRequests.java From leetcode-editor with Apache License 2.0 | 5 votes |
@Override public void close() { StreamUtil.closeStream(myInputStream); StreamUtil.closeStream(myReader); if (myConnection instanceof HttpURLConnection) { ((HttpURLConnection)myConnection).disconnect(); } }
Example #8
Source File: StubSerializationHelper.java From consulo with Apache License 2.0 | 5 votes |
void reSerializeStub(@Nonnull DataInputStream inStub, @Nonnull DataOutputStream outStub, @Nonnull StubSerializationHelper newSerializationHelper) throws IOException { IntEnumerator currentSerializerEnumerator = IntEnumerator.read(inStub); currentSerializerEnumerator.dump(outStub, id -> { String name = myIdToName.get(id); return name == null ? 0 : newSerializationHelper.myNameToId.get(name); }); StreamUtil.copyStreamContent(inStub, outStub); }
Example #9
Source File: Restarter.java From consulo with Apache License 2.0 | 5 votes |
@Override public void run() { try { StreamUtil.copyStreamContent(myIn, myOut); } catch (IOException ignore) { } }
Example #10
Source File: HttpRequests.java From consulo with Apache License 2.0 | 5 votes |
@Override public void close() { StreamUtil.closeStream(myInputStream); StreamUtil.closeStream(myReader); if (myConnection instanceof HttpURLConnection) { ((HttpURLConnection)myConnection).disconnect(); } }
Example #11
Source File: ConfirmingTrustManager.java From consulo with Apache License 2.0 | 5 votes |
private void flushKeyStore() throws Exception { FileOutputStream stream = new FileOutputStream(myPath); try { myKeyStore.store(stream, myPassword.toCharArray()); } finally { StreamUtil.closeStream(stream); } }
Example #12
Source File: PhpBundleFileFactory.java From idea-php-symfony2-plugin with MIT License | 5 votes |
@Nullable private static String getFileTemplateContent(@NotNull String filename) { try { // replace on windows, just for secure reasons return StreamUtil.readText(PhpBundleFileFactory.class.getResourceAsStream(filename), "UTF-8").replace("\r\n", "\n"); } catch (IOException e) { return null; } }
Example #13
Source File: TranslationPsiParser.java From idea-php-symfony2-plugin with MIT License | 5 votes |
public void parse(File file) { VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true); if(virtualFile == null) { Symfony2ProjectComponent.getLogger().info("VfsUtil missing translation: " + file.getPath()); return; } PsiFile psiFile; try { psiFile = PhpPsiElementFactory.createPsiFileFromText(this.project, StreamUtil.readText(virtualFile.getInputStream(), "UTF-8")); } catch (IOException e) { return; } if(psiFile == null) { return; } Symfony2ProjectComponent.getLogger().info("update translations: " + file.getPath()); Collection<NewExpression> messageCatalogues = PsiTreeUtil.collectElementsOfType(psiFile, NewExpression.class); for(NewExpression newExpression: messageCatalogues) { ClassReference classReference = newExpression.getClassReference(); if(classReference != null) { PsiElement constructorMethod = classReference.resolve(); if(constructorMethod instanceof Method) { PhpClass phpClass = ((Method) constructorMethod).getContainingClass(); if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Translation\\MessageCatalogueInterface")) { this.getTranslationMessages(newExpression); } } } } }
Example #14
Source File: JsonParseUtilTest.java From idea-php-toolbox with MIT License | 5 votes |
@Test public void testConfigDeserialize() { JsonConfigFile elements = null; try { File file = FileUtil.findFirstThatExist("src/test/java/de/espend/idea/php/toolbox/tests/utils/fixtures/ide-toolbox.metadata.json"); elements = JsonParseUtil.getDeserializeConfig(StreamUtil.readText(new FileInputStream(file), Charset.defaultCharset())); } catch (IOException e) { e.printStackTrace(); } List<JsonProvider> registrar = new ArrayList<>(elements.getProviders()); assertEquals("date_format", registrar.get(0).getName()); Collection<JsonRawLookupElement> dateFromatProvider = registrar.get(0).getItems(); JsonRawLookupElement item = ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("d")); assertNotNull(item); assertEquals(item.hashCode(), ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("d")).hashCode()); assertNotNull(ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("car"))); assertNotNull(ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("apple"))); assertEquals("source_1", registrar.get(1).getName()); assertEquals("return", registrar.get(1).getSource().getContributor()); assertEquals("\\Twig_Environment::getExtension", registrar.get(1).getSource().getParameter()); assertEquals("source_2", registrar.get(2).getName()); assertTrue(registrar.get(2).getItems().size() > 0); }
Example #15
Source File: ProjectProviderPostHttpAction.java From idea-php-toolbox with MIT License | 5 votes |
@Override protected Response handle(@NotNull Project project, @NotNull RequestMatcher requestMatcher) { String providerName = requestMatcher.getVar("provider"); if(providerName == null) { return new Response("invalid request"); } ProviderInterface provider = RemoteUtil.getProvider(providerName); if(provider == null) { return new JsonResponse(ErrorDic.create("provider not found: " + providerName)); } String content; try { content = StreamUtil.readText(requestMatcher.getHttpExchange().getRequestBody(), "UTF-8"); } catch (IOException ignored) { return new JsonResponse("error"); } RemoteStorage instance = RemoteStorage.getInstance(project); try { instance.set(provider, content); } catch (Exception e) { return new JsonResponse(ErrorDic.create(e.getMessage()), 400); } return new JsonResponse(SuccessDic.create("items added")); }
Example #16
Source File: ExtensionProviderUtil.java From idea-php-toolbox with MIT License | 5 votes |
@NotNull private static Collection<JsonConfigFile> getResourceFiles() { synchronized (STREAM_RESOURCES_LOCK) { if(RESOURCE_FILES != null) { return RESOURCE_FILES; } Collection<JsonConfigFile> files = new ArrayList<>(); for (JsonStreamResource resource : STREAM_RESOURCES.getExtensions()) { for (InputStream stream : resource.getInputStreams()) { String contents; try { contents = StreamUtil.readText(stream, "UTF-8"); } catch (IOException e) { continue; } JsonConfigFile config = JsonParseUtil.getDeserializeConfig(contents); if(config != null) { files.add(config); } } } return RESOURCE_FILES = files; } }
Example #17
Source File: JsonParseUtilTest.java From idea-php-toolbox with MIT License | 5 votes |
@Test public void testConfigDeserialize() { JsonConfigFile elements = null; try { File file = FileUtil.findFirstThatExist("src/test/java/de/espend/idea/php/toolbox/tests/utils/fixtures/ide-toolbox.metadata.json"); elements = JsonParseUtil.getDeserializeConfig(StreamUtil.readText(new FileInputStream(file), Charset.defaultCharset())); } catch (IOException e) { e.printStackTrace(); } List<JsonProvider> registrar = new ArrayList<>(elements.getProviders()); assertEquals("date_format", registrar.get(0).getName()); Collection<JsonRawLookupElement> dateFromatProvider = registrar.get(0).getItems(); JsonRawLookupElement item = ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("d")); assertNotNull(item); assertEquals(item.hashCode(), ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("d")).hashCode()); assertNotNull(ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("car"))); assertNotNull(ContainerUtil.find(dateFromatProvider, new MyJsonRawLookupElementStringCondition("apple"))); assertEquals("source_1", registrar.get(1).getName()); assertEquals("return", registrar.get(1).getSource().getContributor()); assertEquals("\\Twig_Environment::getExtension", registrar.get(1).getSource().getParameter()); assertEquals("source_2", registrar.get(2).getName()); assertTrue(registrar.get(2).getItems().size() > 0); }
Example #18
Source File: ExtensionFileGenerationUtil.java From idea-php-typo3-plugin with MIT License | 5 votes |
@Nullable private static String getFileTemplateContent(@NotNull String filename) { try { return StreamUtil .readText(ExtensionFileGenerationUtil.class.getResourceAsStream(filename), "UTF-8") .replace("\r\n", "\n"); } catch (IOException e) { return null; } }
Example #19
Source File: SoyLanguageCodeStyleSettingsProvider.java From bamboo-soy with Apache License 2.0 | 5 votes |
private String loadSample(String name) { try { return StreamUtil .readText(getClass().getClassLoader().getResourceAsStream("codeSamples/" + name + ".soy"), "UTF-8"); } catch (IOException e) { return ""; } }
Example #20
Source File: HttpUtils.java From AndroidStringsOneTabTranslation with Apache License 2.0 | 5 votes |
public static String doHttpGet(String url) { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse resp = httpClient.execute(httpGet); return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #21
Source File: HttpUtils.java From AndroidStringsOneTabTranslation with Apache License 2.0 | 5 votes |
public static String doHttpGet(String url, Header[] headers) { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.setHeaders(headers); HttpResponse resp = httpClient.execute(httpGet); return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #22
Source File: HttpUtils.java From AndroidStringsOneTabTranslation with Apache License 2.0 | 5 votes |
public static String doHttpPost(String url, List<NameValuePair> params) { try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse resp = httpClient.execute(httpPost); return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #23
Source File: HttpUtils.java From AndroidStringsOneTabTranslation with Apache License 2.0 | 5 votes |
public static String doHttpPost(String url, String xmlBody, Header[] headers) { try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setHeaders(headers); httpPost.setEntity(new StringEntity(xmlBody, "UTF-8")); HttpResponse resp = httpClient.execute(httpPost); return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
Example #24
Source File: GitIntegration.java From DarkyenusTimeTracker with The Unlicense | 5 votes |
private static String prepareCommitMessageHookContent (Path timeTrackerFile, Path gitHooksDirectory) throws IOException { String content = GitIntegration.prepareCommitMessageHookContent_cache; if (content == null) { content = GitIntegration.prepareCommitMessageHookContent_cache = StreamUtil.readText(GitIntegration.class.getResourceAsStream( "/hooks/"+ PREPARE_COMMIT_MESSAGE_HOOK_NAME), StandardCharsets.UTF_8); } return content.replace(DTT_TIME_RELATIVE_PATH_PLACEHOLDER, gitHooksDirectory.relativize(timeTrackerFile).toString()); }
Example #25
Source File: DialogContentMerger.java From azure-devops-intellij with MIT License | 5 votes |
public boolean mergeContent(final ContentTriplet contentTriplet, final Project project, final VirtualFile localFile, final VcsRevisionNumber serverVersion) { ArgumentHelper.checkIfFileWriteable(new File(localFile.getPath())); final MergeDialogCustomizer c = new MergeDialogCustomizer(); final MergeRequest request = DiffRequestFactory.getInstance().createMergeRequest(StreamUtil.convertSeparators(contentTriplet.localContent), StreamUtil.convertSeparators(contentTriplet.serverContent), StreamUtil.convertSeparators(contentTriplet.baseContent), localFile, project, ActionButtonPresentation.APPLY, ActionButtonPresentation.CANCEL_WITH_PROMPT); request.setWindowTitle(c.getMergeWindowTitle(localFile)); request.setVersionTitles(new String[]{ c.getLeftPanelTitle(localFile), c.getCenterPanelTitle(localFile), c.getRightPanelTitle(localFile, serverVersion) }); // TODO (JetBrains) call canShow() first DiffManager.getInstance().getDiffTool().show(request); if (request.getResult() == DialogWrapper.OK_EXIT_CODE) { return true; } else { request.restoreOriginalContent(); // TODO (JetBrains) maybe MergeVersion.MergeDocumentVersion.restoreOriginalContent() should save document itself? ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final Document document = FileDocumentManager.getInstance().getDocument(localFile); if (document != null) { FileDocumentManager.getInstance().saveDocument(document); } } }); return false; } }
Example #26
Source File: ExtensionProviderUtil.java From idea-php-toolbox with MIT License | 5 votes |
@NotNull private static Collection<JsonConfigFile> getResourceFiles() { synchronized (STREAM_RESOURCES_LOCK) { if(RESOURCE_FILES != null) { return RESOURCE_FILES; } Collection<JsonConfigFile> files = new ArrayList<>(); for (JsonStreamResource resource : STREAM_RESOURCES.getExtensions()) { for (InputStream stream : resource.getInputStreams()) { String contents; try { contents = StreamUtil.readText(stream, "UTF-8"); } catch (IOException e) { continue; } JsonConfigFile config = JsonParseUtil.getDeserializeConfig(contents); if(config != null) { files.add(config); } } } return RESOURCE_FILES = files; } }
Example #27
Source File: ProjectProviderPostHttpAction.java From idea-php-toolbox with MIT License | 5 votes |
@Override protected Response handle(@NotNull Project project, @NotNull RequestMatcher requestMatcher) { String providerName = requestMatcher.getVar("provider"); if(providerName == null) { return new Response("invalid request"); } ProviderInterface provider = RemoteUtil.getProvider(providerName); if(provider == null) { return new JsonResponse(ErrorDic.create("provider not found: " + providerName)); } String content; try { content = StreamUtil.readText(requestMatcher.getHttpExchange().getRequestBody(), "UTF-8"); } catch (IOException ignored) { return new JsonResponse("error"); } RemoteStorage instance = RemoteStorage.getInstance(project); try { instance.set(provider, content); } catch (Exception e) { return new JsonResponse(ErrorDic.create(e.getMessage()), 400); } return new JsonResponse(SuccessDic.create("items added")); }
Example #28
Source File: BashColorsAndFontsPage.java From BashSupport with Apache License 2.0 | 5 votes |
@NonNls @NotNull public String getDemoText() { InputStream resource = getClass().getClassLoader().getResourceAsStream("/highlighterDemoText.sh"); String demoText; try { demoText = StreamUtil.readText(resource, "UTF-8"); } catch (IOException e) { throw new RuntimeException("BashSupport could not load the syntax highlighter demo text.", e); } return demoText; }
Example #29
Source File: ServiceActionUtil.java From idea-php-symfony2-plugin with MIT License | 4 votes |
public static void buildFile(AnActionEvent event, final Project project, String templatePath) { String extension = (templatePath.endsWith(".yml") || templatePath.endsWith(".yaml")) ? "yml" : "xml" ; String fileName = Messages.showInputDialog(project, "File name (without extension)", String.format("Create %s Service", extension), Symfony2Icons.SYMFONY); if(fileName == null || StringUtils.isBlank(fileName)) { return; } FileType fileType = (templatePath.endsWith(".yml") || templatePath.endsWith(".yaml")) ? YAMLFileType.YML : XmlFileType.INSTANCE ; if(!fileName.endsWith("." + extension)) { fileName = fileName.concat("." + extension); } DataContext dataContext = event.getDataContext(); IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); if (view == null) { return; } PsiDirectory[] directories = view.getDirectories(); if(directories.length == 0) { return; } final PsiDirectory initialBaseDir = directories[0]; if (initialBaseDir == null) { return; } if(initialBaseDir.findFile(fileName) != null) { Messages.showInfoMessage("File exists", "Error"); return; } String content; try { content = StreamUtil.readText(ServiceActionUtil.class.getResourceAsStream(templatePath), "UTF-8").replace("\r\n", "\n"); } catch (IOException e) { e.printStackTrace(); return; } final PsiFileFactory factory = PsiFileFactory.getInstance(project); String bundleName = "Acme\\DemoBundle"; SymfonyBundleUtil symfonyBundleUtil = new SymfonyBundleUtil(project); SymfonyBundle symfonyBundle = symfonyBundleUtil.getContainingBundle(initialBaseDir); if(symfonyBundle != null) { bundleName = StringUtils.strip(symfonyBundle.getNamespaceName(), "\\"); } String underscoreBundle = bundleName.replace("\\", ".").toLowerCase(); if(underscoreBundle.endsWith("bundle")) { underscoreBundle = underscoreBundle.substring(0, underscoreBundle.length() - 6); } content = content.replace("{{ BundleName }}", bundleName).replace("{{ BundleNameUnderscore }}", underscoreBundle); final PsiFile file = factory.createFileFromText(fileName, fileType, content); ApplicationManager.getApplication().runWriteAction(() -> { CodeStyleManager.getInstance(project).reformat(file); initialBaseDir.add(file); }); PsiFile psiFile = initialBaseDir.findFile(fileName); if(psiFile != null) { view.selectElement(psiFile); } }
Example #30
Source File: CargoBuildProcessAdapterTest.java From teamcity-deployer-plugin with Apache License 2.0 | 4 votes |
private void assertUrlReturns(URL url, String expected2) throws IOException { final InputStream stream2 = url.openStream(); final String text2 = StreamUtil.readText(stream2); assertTrue(text2.contains(expected2)); }