private void sendHtmlResponse(@NotNull HttpRequest request, @NotNull ChannelHandlerContext context, String pagePath) throws IOException { BufferExposingByteArrayOutputStream byteOut = new BufferExposingByteArrayOutputStream(); InputStream pageTemplateStream = getClass().getResourceAsStream(pagePath); String pageTemplate = StreamUtil.readText(pageTemplateStream, Charset.forName("UTF-8")); try { String pageWithProductName = pageTemplate.replaceAll("%IDE_NAME", ApplicationNamesInfo.getInstance().getFullProductName()); byteOut.write(StreamUtil.loadFromStream(new ByteArrayInputStream(pageWithProductName.getBytes(Charset.forName("UTF-8"))))); HttpResponse response = Responses.response("text/html", Unpooled.wrappedBuffer(byteOut.getInternalBuffer(), 0, byteOut.size())); Responses.addNoCache(response); response.headers().set("X-Frame-Options", "Deny"); Responses.send(response, context.channel(), request); } finally { byteOut.close(); pageTemplateStream.close(); } }
@Override public void run() { try { logger.info("Attempting to read template main sketch file."); InputStream templateFileStream = this.getClass().getResourceAsStream("SketchTemplate.java.template"); byte[] templateContent = StreamUtil.loadFromStream(templateFileStream); logger.info("Read a total of " + templateContent.length + " bytes from template sketch file stream."); VirtualFile sketchFile = sourceDirPointer.createChildData(this, "Sketch.java"); logger.info("Attempting to create template sketch file '" + sketchFile + "' as a child of '" + sourceDirPointer.getPath() + "'."); try (OutputStream sketchFileStream = sketchFile.getOutputStream(ApplicationManager.getApplication())) { sketchFileStream.write(templateContent); } } catch (IOException ex) { logger.error(ex); } }
@Nullable private String readClasspathResource(String name) { try { String classpath = System.getProperty("java.class.path"); LOGGER.debug("Reading " + name + " from classpath=" + classpath); ClassLoader classLoader = OptionReference.class.getClassLoader(); if (classLoader == null) { throw new IllegalStateException("Can not obtain classloader instance"); } InputStream resource = classLoader.getResourceAsStream(name); if (resource == null) { LOGGER.debug("Could not find " + name); return null; } return StreamUtil.readText(resource, StandardCharsets.UTF_8); } catch (Exception e) { LOGGER.error("Could not read " + name, e); } return null; }
/** * * @param path String * @return String */ private String readFile(String path) { String content = ""; try { content = StreamUtil.readText( PhpClassRenderer.class.getResourceAsStream(path), "UTF-8" ); } catch (IOException e) { e.printStackTrace(); } return content; }
@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; } }
@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; } }
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(); } }
private static void copyWithFiltering(File file, Ref<File> outputFileRef, List<ResourceRootFilter> filters, CompileContext context) throws IOException { final FileInputStream originalInputStream = new FileInputStream(file); try { final InputStream inputStream = transform(filters, originalInputStream, outputFileRef, context); FileUtil.createIfDoesntExist(outputFileRef.get()); FileOutputStream outputStream = new FileOutputStream(outputFileRef.get()); try { FileUtil.copy(inputStream, outputStream); } finally { StreamUtil.closeStream(inputStream); StreamUtil.closeStream(outputStream); } } finally { StreamUtil.closeStream(originalInputStream); } }
public void save(@NotNull ExternalProject externalProject) { Output output = null; try { final File externalProjectDir = externalProject.getProjectDir(); final File configurationFile = getProjectConfigurationFile(new ProjectSystemId(externalProject.getExternalSystemId()), externalProjectDir); if (!FileUtil.createParentDirs(configurationFile)) return; output = new Output(new FileOutputStream(configurationFile)); myKryo.writeObject(output, externalProject); LOG.debug("Data saved for imported project from: " + externalProjectDir.getPath()); } catch (FileNotFoundException e) { LOG.error(e); } finally { StreamUtil.closeStream(output); } }
@Nullable public ExternalProject load(@NotNull ProjectSystemId externalSystemId, File externalProjectPath) { LOG.debug("Attempt to load project data from: " + externalProjectPath); ExternalProject externalProject = null; Input input = null; try { final File configurationFile = getProjectConfigurationFile(externalSystemId, externalProjectPath); if (configurationFile.isFile()) { input = new Input(new FileInputStream(configurationFile)); externalProject = myKryo.readObject(input, DefaultExternalProject.class); } } catch (Exception e) { LOG.error(e); } finally { StreamUtil.closeStream(input); } if (externalProject != null) { LOG.debug("Loaded project: " + externalProject.getProjectDir()); } return externalProject; }
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; }
public static String getResponseContentAsString(@NotNull HttpMethod response) throws IOException { // Sometimes servers don't specify encoding and HttpMethod#getResponseBodyAsString // by default decodes from Latin-1, so we got to read byte stream and decode it from UTF-8 // manually //if (!response.hasBeenUsed()) { // return ""; //} org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE); if (header != null && header.getValue().contains("charset")) { // ISO-8859-1 if charset wasn't specified in response return StringUtil.notNullize(response.getResponseBodyAsString()); } else { InputStream stream = response.getResponseBodyAsStream(); return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET); } }
private static String[] splitLines(String string) { string = StreamUtil.convertSeparators(string); boolean spaceAdded = false; if (string.endsWith("\n")) { string += " "; spaceAdded = true; } final String[] temp = string.split("\n"); if (spaceAdded) { final String[] result = new String[temp.length - 1]; System.arraycopy(temp, 0, result, 0, result.length); return result; } else { return temp; } }
@Nullable String readEntry(Condition<ZipEntry> condition) { ZipInputStream stream = null; try { stream = getStream(); ZipEntry entry; while ((entry = stream.getNextEntry()) != null) { if (condition.value(entry)) { return StreamUtil.readText(stream, TemplateModuleBuilder.UTF_8); } } } catch (IOException e) { return null; } finally { StreamUtil.closeStream(stream); } return null; }
private static MultiMap<String, ArchivedProjectTemplate> getTemplates() { InputStream stream = null; HttpURLConnection connection = null; String code = ApplicationInfo.getInstance().getBuild().getProductCode(); try { connection = getConnection(code + "_templates.xml"); stream = connection.getInputStream(); String text = StreamUtil.readText(stream, TemplateModuleBuilder.UTF_8); return createFromText(text); } catch (IOException ex) { // timeouts, lost connection etc LOG.info(ex); return MultiMap.emptyInstance(); } catch (Exception e) { LOG.error(e); return MultiMap.emptyInstance(); } finally { StreamUtil.closeStream(stream); if (connection != null) { connection.disconnect(); } } }
private BufferExposingByteArrayOutputStream internalReadStream(int record) throws IOException { waitForPendingWriteForRecord(record); synchronized (myLock) { byte[] result = super.readBytes(record); InflaterInputStream in = new CustomInflaterInputStream(result); try { final BufferExposingByteArrayOutputStream outputStream = new BufferExposingByteArrayOutputStream(); StreamUtil.copyStreamContent(in, outputStream); return outputStream; } finally { in.close(); } } }
/** * Make GET request to specified URL and return HTTP entity of result as Reader object */ private String makeRequest(String url) throws IOException { HttpClient client = getHttpClient(); HttpMethod method = new GetMethod(url); configureHttpMethod(method); String entityContent; try { client.executeMethod(method); // Can't use HttpMethod#getResponseBodyAsString because Trello doesn't specify encoding // in Content-Type header and by default this method decodes from Latin-1 entityContent = StreamUtil.readText(method.getResponseBodyAsStream(), "utf-8"); } finally { method.releaseConnection(); } LOG.debug(entityContent); //return new InputStreamReader(method.getResponseBodyAsStream(), "utf-8"); return entityContent; }
@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; }
@Nullable public static String createEntityRepositoryContent(Map<String, String> templateVars) { String content; try { content = StreamUtil.readText(CreateEntityRepositoryIntentionAction.class.getResourceAsStream("template/EntityRepository.php"), "UTF-8"); } catch (IOException e) { return null; } for(Map.Entry<String, String> templateVar: templateVars.entrySet()) { content = content.replace("{{" + templateVar.getKey() +"}}", templateVar.getValue()); } return content; }
private static boolean runManagerCommand(final String managerUrl) { try { URL url = new URL(managerUrl); long time = System.currentTimeMillis(); while (System.currentTimeMillis() - time < TIMEOUT) { LOG.debug("Running server command: " + managerUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(false); String encoded = Base64.getEncoder().encodeToString(AUTHORIZATION_STRING.getBytes(StandardCharsets.UTF_8)); urlConnection.setRequestProperty(AUTHORIZATION_PROPERTY, BASIC_AUTHORIZATION_METHOD + encoded); urlConnection.connect(); String msg = StreamUtil.readText(urlConnection.getInputStream()); LOG.debug("Server returned: " + msg); if (msg != null) { return !msg.startsWith(FAIL_MESSAGE_PREFIX); } } return false; } catch (IOException e) { LOG.debug(e); return false; } }
public static String getResponseContentAsString(@NotNull HttpMethod response) throws IOException { // Sometimes servers don't specify encoding and HttpMethod#getResponseBodyAsString // by default decodes from Latin-1, so we got to read byte stream and decode it from UTF-8 // manually //if (!response.hasBeenUsed()) { // return ""; //} org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE); if(header != null && header.getValue().contains("charset")) { // ISO-8859-1 if charset wasn't specified in response return StringUtil.notNullize(response.getResponseBodyAsString()); } else { InputStream stream = response.getResponseBodyAsStream(); return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET); } }
private KeyStore loadKeyStore(String path, String password) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File cacertsFile = new File(path); if (cacertsFile.exists()) { FileInputStream stream = null; try { stream = new FileInputStream(path); keyStore.load(stream, password.toCharArray()); } finally { StreamUtil.closeStream(stream); } } else { FileUtil.createParentDirs(cacertsFile); keyStore.load(null, password.toCharArray()); } } catch (Exception e) { LOG.error(e); broken = true; } return keyStore; }
public boolean addCertificate(X509Certificate certificate) { if (broken) { return false; } String alias = certificate.getIssuerX500Principal().getName(); FileOutputStream stream = null; try { myKeyStore.setCertificateEntry(alias, certificate); stream = new FileOutputStream(myPath); myKeyStore.store(stream, myPassword.toCharArray()); // trust manager should be updated each time its key store was modified myTrustManager = initFactoryAndGetManager(); return true; } catch (Exception e) { LOG.error(e); return false; } finally { StreamUtil.closeStream(stream); } }
protected byte[] download(final String urlString) throws IOException { final HttpMethod getMethod = new GetMethod(urlString); InputStream in = null; try { myHttpClient.executeMethod(getMethod); if (getMethod.getStatusCode() != HttpStatus.SC_OK) { throw new IOException(String.format("Problem [%d] while downloading %s: %s", getMethod.getStatusCode(), urlString, getMethod.getStatusText())); } in = getMethod.getResponseBodyAsStream(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); StreamUtil.copyStreamContent(in, bOut); return bOut.toByteArray(); } finally { FileUtil.close(in); getMethod.releaseConnection(); } }
@Nullable public static String computeNamespace(@NotNull VirtualFile file) { InputStream stream = null; try { stream = file.getInputStream(); return XsdNamespaceBuilder.computeNamespace(stream); } catch(IOException e) { return null; } finally { StreamUtil.closeStream(stream); } }
@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; } }
private String loadSample(String name) { try { return StreamUtil .readText(getClass().getClassLoader().getResourceAsStream("codeSamples/" + name + ".soy"), "UTF-8"); } catch (IOException e) { return ""; } }
/** * Get 请求 * * @param uri * @return * @throws Exception */ public static String syncGet(String uri) throws Exception { URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); String result = new String(StreamUtil.loadFromStream(inStream)); return result; }
public static Map<Version, String> getAvailableArtifactVersions(String groupId, String artifactId, Collection<URL> repositories) throws IOException { Map<Version, String> availableVersions = new TreeMap<>(Version.descendingOrderComparator()); final String relativePathToArtifact = groupId.replace(".", "/") + "/" + artifactId.replace(".", "/"); String artifactLocation; for (final URL repository : repositories) { artifactLocation = repository.toExternalForm() + "/" + relativePathToArtifact; HttpURLConnection artifactRootConnection = HttpConfigurable.getInstance().openHttpConnection(artifactLocation); String artifactRootPage = StreamUtil.readText(artifactRootConnection.getInputStream(), StandardCharsets.UTF_8); Matcher artifactVersionMatcher = ARTIFACT_ROOT_VERSION_PATTERN.matcher(artifactRootPage); while (artifactVersionMatcher.find()) { String matchedVersion = artifactVersionMatcher.group(1); Version parsedVersion = Version.parseString(matchedVersion); if (parsedVersion != Version.INVALID) { String versionUrl = repository.toExternalForm() + "/" + relativePathToArtifact + "/" + parsedVersion.toString(); availableVersions.put(parsedVersion, versionUrl); } } artifactRootConnection.disconnect(); if (! availableVersions.isEmpty()) { break; } } return availableVersions; }
static <T> T consumeZipStream(@NotNull StreamProcessor<T> consumer, @NotNull ZipInputStream stream) throws IOException { try { return consumer.consume(stream); } finally { StreamUtil.closeStream(stream); } }
private static KeyStore createKeyStore(@NotNull String path, @NotNull String password) { KeyStore keyStore; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File cacertsFile = new File(path); if (cacertsFile.exists()) { FileInputStream stream = null; try { stream = new FileInputStream(path); keyStore.load(stream, password.toCharArray()); } finally { StreamUtil.closeStream(stream); } } else { if (!FileUtil.createParentDirs(cacertsFile)) { LOG.error("Cannot create directories: " + cacertsFile.getParent()); return null; } keyStore.load(null, password.toCharArray()); } } catch (Exception e) { LOG.error(e); return null; } return keyStore; }
private void flushKeyStore() throws Exception { FileOutputStream stream = new FileOutputStream(myPath); try { myKeyStore.store(stream, myPassword.toCharArray()); } finally { StreamUtil.closeStream(stream); } }
/** * Get direct from file because IDEA cache files(see #IDEA-81067) */ public static String getText(VirtualFile file) throws IOException { FileInputStream inputStream = new FileInputStream(file.getPath()); try { return StreamUtil.readText(inputStream); } finally { inputStream.close(); } }
@NotNull private static MultiMap<String, String> getBrokenPluginVersions() { if (ourBrokenPluginVersions == null) { ourBrokenPluginVersions = MultiMap.createSet(); if (System.getProperty("idea.ignore.disabled.plugins") == null && !isUnitTestMode()) { BufferedReader br = new BufferedReader(new InputStreamReader(PluginManagerCore.class.getResourceAsStream("/brokenPlugins.txt"))); try { String s; while ((s = br.readLine()) != null) { s = s.trim(); if (s.startsWith("//")) continue; List<String> tokens = ParametersListUtil.parse(s); if (tokens.isEmpty()) continue; if (tokens.size() == 1) { throw new RuntimeException("brokenPlugins.txt is broken. The line contains plugin name, but does not contains version: " + s); } String pluginId = tokens.get(0); List<String> versions = tokens.subList(1, tokens.size()); ourBrokenPluginVersions.putValues(pluginId, versions); } } catch (IOException e) { throw new RuntimeException("Failed to read /brokenPlugins.txt", e); } finally { StreamUtil.closeStream(br); } } } return ourBrokenPluginVersions; }
@Test public void testLinks() throws java.io.IOException { final String s = StreamUtil.readText(PyTestTracebackParserTest.class.getResource("linksDataTest.txt").openStream(), Charset.defaultCharset()); final Set<String> requiredStrings = new HashSet<String>(); requiredStrings.add("file:///c:/windows/system32/file.txt - 42"); requiredStrings.add("file:///c:/windows/system32/file_spam.txt - 42"); requiredStrings.add("c:\\documents and settings\\foo.txt - 43"); requiredStrings.add("file:///c:/windows/system32/file.txt - 42"); requiredStrings.add("/file.py - 42"); requiredStrings.add("c:\\folder55\\file.py - 12"); requiredStrings.add("C:\\temp\\untitled55\\test_sample.py - 5"); requiredStrings.add("C:\\temp\\untitled55\\test_sample.py - 6"); requiredStrings.add("C:\\temp\\untitled55\\test_sample.py - 7"); requiredStrings.add("C:\\temp\\untitled55\\test_sample.py - 89999"); requiredStrings.add("C:\\temp\\untitled55\\test_sample.py - 99999"); requiredStrings.add("../../../files/files.py - 100"); requiredStrings.add("/Users/Mac Hipster/Applications/PyCharm 4.0 .app/helpers/lala.py - 12"); requiredStrings.add("C:\\Users\\ilya.kazakevich\\virtenvs\\spammy\\lib\\site-packages\\django_cron\\models.py - 4"); final Logger logger = Logger.getInstance(PyTestTracebackParserTest.class); final String[] strings = s.split("\n"); logger.warn(String.format("Got lines %s", strings)); for (final String line : strings) { logger.warn(String.format("Starting with string %s", line)); final LinkInTrace trace = new PyTestTracebackParser().findLinkInTrace(line); logger.warn(String.format("Got %s", trace)); if (trace != null) { final boolean removeResult = requiredStrings.remove(trace.getFileName() + " - " + trace.getLineNumber()); Assert.assertTrue(String.format("Unexpected file found %s line %s", trace.getFileName(), trace.getLineNumber()), removeResult); } } Assert.assertThat("Some lines were not found", requiredStrings, Matchers.empty()); }
@Nullable public static String computeNamespace(@NotNull VirtualFile file) { InputStream stream = null; try { stream = file.getInputStream(); return XsdNamespaceBuilder.computeNamespace(stream); } catch (IOException e) { return null; } finally { StreamUtil.closeStream(stream); } }