@VisibleForTesting static File toFile(URL url) { checkArgument(url.getProtocol().equals("file")); try { return new File(url.toURI()); // Accepts escaped characters like %20. } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars. return new File(url.getPath()); // Accepts non-escaped chars like space. } } }
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
public static void checkJarFile(URL jar) throws IOException { File jarFile; try { jarFile = new File(jar.toURI()); } catch (URISyntaxException e) { throw new IOException("JAR file path is invalid '" + jar + "'"); } if (!jarFile.exists()) { throw new IOException("JAR file does not exist '" + jarFile.getAbsolutePath() + "'"); } if (!jarFile.canRead()) { throw new IOException("JAR file can't be read '" + jarFile.getAbsolutePath() + "'"); } // TODO: Check if proper JAR file }
@Test public void testUTF8FileWindowsBreaks() throws URISyntaxException, IOException { final File testFileIso = new File(this.getClass().getResource("/test-file-utf8-win-linebr.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, testParamBlockSize, UTF_8); assertFileWithShrinkingTestLines(reversedLinesFileReader); }
@Test public void verify() throws Exception { URL u = NoAnonymousInnerClassesTest.class.getResource("/"); File f = new File(u.toURI()); String prefix = f.getAbsolutePath(); int count = 0; while (!queue.isEmpty()) { for (String s : parts) { if (Character.isDigit(s.charAt(0))) { String n = f.getAbsolutePath().substring(prefix.length()).replace('\\', '.').replace('/', '.'); if (n.startsWith(".")) { n = n.substring(1);
/** * Create all required directories in path for a file */ public static void assertDirExists(URL targetFile) { File parent = null; try { parent = new File(targetFile.toURI()).getParentFile(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } if(!parent.exists() && !parent.mkdirs()){ throw new IllegalStateException("Couldn't create dir: " + parent); } } }
private String filePath(String filename) { URL fileUrl = getClass().getClassLoader().getResource(filename); try { return new File(fileUrl.toURI()).getAbsolutePath(); } catch (URISyntaxException e) { return fileUrl.getPath(); } }
@Test public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException { final File testFileIso = new File(this.getClass().getResource("/" + fileName).toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, buffSize, encoding); final Stack<String> lineStack = new Stack<>(); bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso), encoding)); String line = null; // read all lines in normal order while ((line = bufferedReader.readLine()) != null) { lineStack.push(line); } // read in reverse order and compare with lines from stack while ((line = reversedLinesFileReader.readLine()) != null) { final String lineFromBufferedReader = lineStack.pop(); assertEquals(lineFromBufferedReader, line); } }
@Test public void testFileSystemResourceWithFilePath() throws Exception { Path filePath = Paths.get(getClass().getResource("Resource.class").toURI()); Resource resource = new FileSystemResource(filePath); doTestResource(resource); assertEquals(new FileSystemResource(filePath), resource); }
private static String getUnmigrationCommandLine(File jenkinsHome) { StringBuilder cp = new StringBuilder(); for (Class<?> c : new Class<?>[] {RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */Charsets.class, WriterOutputStream.class, BuildException.class, FastDateFormat.class}) { URL location = c.getProtectionDomain().getCodeSource().getLocation(); String locationS = location.toString(); if (location.getProtocol().equals("file")) { try { locationS = new File(location.toURI()).getAbsolutePath(); } catch (URISyntaxException x) { // never mind } } if (cp.length() > 0) { cp.append(File.pathSeparator); } cp.append(locationS); } return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome); }
@Test public void testURL() throws Exception { URL url = new URL("http://www.cheese.com/asiago"); Properties props = new Properties(); props.put(DefaultConfigurationResolver.DEFAULT_CONFIG_PROPERTY_NAME, url); URI resolved = DefaultConfigurationResolver.resolveConfigURI(props); assertEquals(url.toURI(), resolved); }
private Optional<? extends FileCustomizableResponseType> matchFile(String path) { Optional<URL> optionalUrl = staticResourceResolver.resolve(path); if (optionalUrl.isPresent()) { try { URL url = optionalUrl.get(); if (url.getProtocol().equals("file")) { File file = Paths.get(url.toURI()).toFile(); if (file.exists() && !file.isDirectory() && file.canRead()) { return Optional.of(new NettySystemFileCustomizableResponseType(file)); } } return Optional.of(new NettyStreamedFileCustomizableResponseType(url)); } catch (URISyntaxException e) { //no-op } } return Optional.empty(); }
@Test public void testFileSystemResourceWithImport() throws URISyntaxException { String file = getClass().getResource(RESOURCE_CONTEXT.getPath()).toURI().getPath(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new FileSystemResource(file)); // comes from "resourceImport.xml" xbf.getBean("resource1", ResourceTestBean.class); // comes from "resource.xml" xbf.getBean("resource2", ResourceTestBean.class); }
@Override public Path getFilePath() { if (url.getProtocol().equals("file")) { try { return Paths.get(url.toURI()); } catch (URISyntaxException e) { return null; } } return null; }
public static File getFile(String classPathLocation) throws IOException, URISyntaxException { URL resource = PropertyFileConfigurationSource.class.getClassLoader().getResource(classPathLocation); if (resource == null) { resource = new URL("file://" + classPathLocation); } if (!"file".equals(resource.getProtocol())) { throw new IOException("Saving to property files inside a war, ear or jar is not possible."); } return new File(resource.toURI()); } }
@Override public String toString() { final URL location = klass.getProtectionDomain().getCodeSource().getLocation(); try { final String jar = new File(location.toURI()).getName(); if (jar.endsWith(".jar")) { return jar; } return "project.jar"; } catch (Exception ignored) { return "project.jar"; } } }
@Test public void testUTF16LEFile() throws URISyntaxException, IOException { final File testFileUTF16LE = new File(this.getClass().getResource("/test-file-utf16le.bin").toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileUTF16LE, testParamBlockSize, "UTF-16LE"); assertFileWithShrinkingTestLines(reversedLinesFileReader); }
@Test public void binary_file_with_unmappable_character() throws Exception { File woff = new File(this.getClass().getResource("glyphicons-halflings-regular.woff").toURI()); Metadata metadata = new FileMetadata().readMetadata(new FileInputStream(woff), StandardCharsets.UTF_8, woff.getAbsolutePath()); assertThat(metadata.lines()).isEqualTo(135); assertThat(metadata.nonBlankLines()).isEqualTo(133); assertThat(metadata.hash()).isNotEmpty(); assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains("Invalid character encountered in file"); assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains( "glyphicons-halflings-regular.woff at line 1 for encoding UTF-8. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'."); }
/**try to get {@link java.io.File} from url*/ public static @Nullable java.io.File getFile(URL url) { java.io.File file; String path; try { path = url.toURI().getSchemeSpecificPart(); if ((file = new java.io.File(path)).exists()) return file; } catch (URISyntaxException e) { } try { path = URLDecoder.decode(url.getPath(), "UTF-8"); if (path.contains(".jar!")) path = path.substring(0, path.lastIndexOf(".jar!") + ".jar".length()); if ((file = new java.io.File(path)).exists()) return file; } catch (UnsupportedEncodingException e) { } try { path = url.toExternalForm(); if (path.startsWith("jar:")) path = path.substring("jar:".length()); if (path.startsWith("wsjar:")) path = path.substring("wsjar:".length()); if (path.startsWith("file:")) path = path.substring("file:".length()); if (path.contains(".jar!")) path = path.substring(0, path.indexOf(".jar!") + ".jar".length()); if (path.contains(".war!")) path = path.substring(0, path.indexOf(".war!") + ".war".length()); if ((file = new java.io.File(path)).exists()) return file; path = path.replace("%20", " "); if ((file = new java.io.File(path)).exists()) return file; } catch (Exception e) { } return null; }