Java Code Examples for java.net.URL#toURI()
The following examples show how to use
java.net.URL#toURI() .
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: EdgeAttributeComparatorTest.java From pdfxtk with Apache License 2.0 | 6 votes |
@Test public void complexSortCondition() throws URISyntaxException { URL url = EdgeAttributeComparatorTest.class.getClassLoader().getResource( "testComparator1.xml" ); try { File file = new File( url.toURI() ); EdgeAttributeComparator cmp = new EdgeAttributeComparator(); List col = new ArrayList( SerializationUtil.readDump( file ) ); Collections.sort( col, cmp ); assertTrue( true ); } catch ( Exception e ) { fail( "sorting failed: " + e ); } }
Example 2
Source File: CustomMybatisMapperConfigurationTest.java From activiti6-boot2 with Apache License 2.0 | 6 votes |
private AnnotationConfigApplicationContext context(Class<?>... clzz) throws Exception { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(clzz); URL propertiesUrl = this.getClass().getClassLoader().getResource("config/application.properties"); File springBootPropertiesFile = new File(propertiesUrl.toURI()); Properties springBootProperties = new Properties(); springBootProperties.load(new FileInputStream(springBootPropertiesFile)); annotationConfigApplicationContext .getEnvironment() .getPropertySources() .addFirst(new PropertiesPropertySource("testProperties", springBootProperties)); annotationConfigApplicationContext.refresh(); return annotationConfigApplicationContext; }
Example 3
Source File: AndroidResourceLoader.java From Time4A with Apache License 2.0 | 5 votes |
@Override public URI locate( String moduleName, Class<?> moduleRef, String path ) { try { if (MODULES.contains(moduleName)) { StringBuilder sb = new StringBuilder(); sb.append("net/time4j/"); sb.append(moduleName); sb.append('/'); sb.append(path); return new URI(sb.toString()); } // last try - ask the class loader URL url = moduleRef.getClassLoader().getResource(path); if (url != null) { return url.toURI(); } } catch (URISyntaxException e) { // now we give up } return null; }
Example 4
Source File: ProxyURLStreamHandlerFactoryTest.java From netbeans with Apache License 2.0 | 5 votes |
/** Tests UNC path is correctly treated. On JDK1.5 UNCFileStreamHandler should * be installed in ProxyURLStreamHandlerFactory to workaround JDK bug * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086147. */ public void testUNCFileURLStreamHandler() throws Exception { if(!Utilities.isWindows()) { return; } File uncFile = new File("\\\\computerName\\sharedFolder\\a\\b\\c\\d.txt"); URI uri = Utilities.toURI(uncFile); String expectedURI = "file://computerName/sharedFolder/a/b/c/d.txt"; assertEquals("Wrong URI from File.toURI.", expectedURI, uri.toString()); URL url = uri.toURL(); assertEquals("Wrong URL from URI.toURL", expectedURI, url.toString()); assertEquals("URL.getAuthority must is now computer name.", "computerName", url.getAuthority()); uri = url.toURI(); assertEquals("Wrong URI from URL.toURI.", expectedURI, uri.toString()); }
Example 5
Source File: TestUtils.java From yangtools with Eclipse Public License 1.0 | 5 votes |
public static SchemaContext parseYangSource(final String yangSourceFilePath) throws ReactorException, URISyntaxException, IOException, YangSyntaxErrorException { URL resourceFile = StmtTestUtils.class.getResource(yangSourceFilePath); File testSourcesFile = new File(resourceFile.toURI()); return parseYangSources(testSourcesFile); }
Example 6
Source File: PeerCertificateExtractorTest.java From okhttp-peer-certificate-extractor with Apache License 2.0 | 5 votes |
/** * Extract from pem file */ @Test public void extractPeerCertificateFromPemTest() throws URISyntaxException { URL certificateUrl = PeerCertificateExtractorTest.class.getResource("/certificate.pem"); File certificate = new File(certificateUrl.toURI()); String peerCertificate = PeerCertificateExtractor.extract(certificate); String expectedResult = "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME="; assertTrue(expectedResult.equals(peerCertificate)); }
Example 7
Source File: WebTestCase.java From htmlunit with Apache License 2.0 | 5 votes |
/** * Loads an expectation file for the specified browser search first for a browser specific resource * and falling back in a general resource. * @param resourcePrefix the start of the resource name * @param resourceSuffix the end of the resource name * @return the content of the file * @throws Exception in case of error */ protected String loadExpectation(final String resourcePrefix, final String resourceSuffix) throws Exception { final URL url = getExpectationsResource(getClass(), getBrowserVersion(), resourcePrefix, resourceSuffix); assertNotNull(url); final File file = new File(url.toURI()); String content = FileUtils.readFileToString(file, UTF_8); content = StringUtils.replace(content, "\r\n", "\n"); return content; }
Example 8
Source File: BasicHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 5 votes |
public JSONObject put(URL targetUrl, String data, String accessKey, String value) throws Exception { HttpPut httpput = new HttpPut(targetUrl.toURI()); setPutEntity(data, httpput); auth(httpput); setHeader(httpput); addHeader(httpput, accessKey, value); return parseResponse(doPut(httpput)); }
Example 9
Source File: TranslationBundleTest.java From roboconf-platform with Apache License 2.0 | 5 votes |
@Test public void testSameNumberOfPropertiesInTranslations() throws Exception { Map<String,Integer> keyToCurlyBracketsCount = new HashMap<> (); for( String lang : TranslationBundle.LANGUAGES ) { URL url = TranslationBundle.class.getResource( "/" + lang + ".json" ); File f = new File( url.toURI()); String content = Utils.readFileContent( f ); Matcher m = Pattern.compile( TranslationBundle.ROW_PATTERN ).matcher( content ); while( m.find()) { // Basic coherence among translation files String s = m.group( 2 ); int ocb = s.length() - s.replace( "{", "").length(); int ccb = s.length() - s.replace( "}", "").length(); Assert.assertEquals( "Not the same number of { and } in " + m.group( 1 ) + " (" + lang + ")", ocb, ccb ); Integer expectedValue = keyToCurlyBracketsCount.get( m.group( 1 )); if( expectedValue != null ) Assert.assertEquals( "Not the expected number of properties in " + m.group( 1 ) + " (" + lang + ")", expectedValue.intValue(), ocb ); else keyToCurlyBracketsCount.put( m.group( 1 ), ocb ); // Coherence with Java types try { ErrorCode ec = ErrorCode.valueOf( m.group( 1 )); Assert.assertEquals( "Not the right number of properties", ec.getI18nProperties().length, ocb ); } catch( IllegalArgumentException e ) { // nothing } } } }
Example 10
Source File: UIServlet.java From celos with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { URL celosURL = (URL) Util.requireNonNull(getServletContext().getAttribute(Main.CELOS_URL_ATTR)); URL hueURL = (URL) getServletContext().getAttribute(Main.HUE_URL_ATTR); File configFile = (File) getServletContext().getAttribute(Main.CONFIG_FILE_ATTR); CelosClient client = new CelosClient(celosURL.toURI()); res.setContentType("text/html;charset=utf-8"); res.setStatus(HttpServletResponse.SC_OK); ScheduledTime end = getDisplayTime(req.getParameter(TIME_PARAM)); int zoomLevelMinutes = getZoomLevel(req.getParameter(ZOOM_PARAM)); NavigableSet<ScheduledTime> tileTimes = getTileTimesSet(getFirstTileTime(end, zoomLevelMinutes), zoomLevelMinutes, MAX_MINUTES_TO_FETCH, MAX_TILES_TO_DISPLAY); ScheduledTime start = tileTimes.first(); Set<WorkflowID> workflowIDs = client.getWorkflowList(); Map<WorkflowID, WorkflowStatus> statuses = fetchStatuses(client, workflowIDs, start, end); List<WorkflowGroup> groups; if (configFile != null) { groups = getWorkflowGroups(new FileInputStream(configFile), workflowIDs); } else { groups = getDefaultGroups(workflowIDs); } UIConfiguration conf = new UIConfiguration(start, end, tileTimes, groups, statuses, hueURL); res.getWriter().append(render(conf)); } catch (Exception e) { throw new ServletException(e); } }
Example 11
Source File: FileUtil.java From w2j-cli with MIT License | 5 votes |
/** * 转URL为URI * * @param url URL * @return URI * @exception RuntimeException 包装URISyntaxException */ public static URI toURI(URL url) throws RuntimeException { if (null == url) { return null; } try { return url.toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
Example 12
Source File: WSDLSemanticValidatorTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testEmptyInlineSchemaValid() throws Exception { String fileName = "/org/netbeans/modules/xml/wsdl/validator/resources/typesTests/inlineSchemaTests/emptyInlineSchema.wsdl"; URL url = getClass().getResource(fileName); URI uri = url.toURI(); HashSet<String> expectedErrors = new HashSet<String>(); validate(uri, expectedErrors); }
Example 13
Source File: PluginLoader.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
private static URI toUri(URL url) throws PluginException { try { return url.toURI(); } catch (URISyntaxException e) { throw new PluginException("Bad uri: " + url, e); } }
Example 14
Source File: TestLasIO.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
public void testLazReader() throws Exception { // String name = "/media/hydrologis/Samsung_T3/UNIBZ/monticolo2019/Coverage_SolarTirol_05.laz"; // File lasFile = new File(name); String name = "las/1.2-with-color.laz"; URL lasUrl = this.getClass().getClassLoader().getResource(name); File lasFile = new File(lasUrl.toURI()); int expectedCount = 1065; ALasReader reader = Las.getReader(lasFile, null); reader.open(); ILasHeader libLasHeader = reader.getHeader(); if (reader.hasNextPoint()) { LasRecord nextPoint = reader.getNextPoint(); short r = nextPoint.color[0]; short g = nextPoint.color[1]; short b = nextPoint.color[2]; assertEquals(68, r); assertEquals(77, g); assertEquals(88, b); } long recordsCount = libLasHeader.getRecordsCount(); assertEquals(expectedCount, recordsCount); reader.close(); }
Example 15
Source File: WSDLInlineSchemaValidatorTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testInlineSchemaImportingAnotherSchemaUsingCatalogValid() throws Exception { //this test is to mimic wsdl importing xsd which imports another xsd from different projevt //so it uses catalog.xml at project level String fileName = "/org/netbeans/modules/xml/wsdl/validator/resources/typesTests/inlineSchemaTests/InventoryService.wsdl"; URL url = getClass().getResource(fileName); URI uri = url.toURI(); validate(uri, 0); }
Example 16
Source File: ResponseStreamTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 4 votes |
@Test public void testGetWithIncorrectQueryParameter() throws Exception { URL url = buildURL(true, true, 1); HttpGet httpget = new HttpGet(url.toURI()); readHttpResponse(getHttpClient(url).execute(httpget), 400); }
Example 17
Source File: IngestJobCompressionTest.java From hadoop-solr with Apache License 2.0 | 4 votes |
@Test public void testBzip2CompressionWithDirectory() throws Exception { Path input = new Path(tempDir, "DirectoryIngestMapper"); fs.mkdirs(input); for (int i = 0; i < 6; i++) { String compressedFileName = "dir" + File.separator + "frank_txt_" + i + ".txt.bz2"; Path currentInput = new Path(input, compressedFileName); // Copy compressed file to HDFS URL url = IngestJobCompressionTest.class.getClassLoader().getResource(compressedFileName); assertTrue(url != null); Path localPath = new Path(url.toURI()); fs.copyFromLocalFile(localPath, currentInput); } String jobName = "JobCompressionTest" + System.currentTimeMillis(); String[] args = new JobArgs().withJobName(jobName).withClassname(DirectoryIngestMapper.class.getName()) .withCollection(DEFAULT_COLLECTION).withZkString(getBaseUrl()) .withInput(input.toUri().toString() + File.separator + "dir" + File.separator + "frank_txt*.bz2") .getJobArgs(); int val = ToolRunner.run(conf, new IngestJob(), args); // Verify job assertEquals(0, val); MockRecordWriter mockRecordWriter = IngestJobMockMapRedOutFormat.writers.get(jobName); assertTrue(mockRecordWriter != null); assertEquals(6, mockRecordWriter.map.size()); // Verify document fields String id = "frank_txt_0.txt"; for (String key : mockRecordWriter.map.keySet()) { if (key.contains(id)) { id = key; } } LWDocument doc = mockRecordWriter.map.get(id).getLWDocument(); assertTrue((doc != null)); // TODO: check fields // Remove the results from this test IngestJobMockMapRedOutFormat.writers.remove(jobName); }
Example 18
Source File: BinaryForSourceImpl.java From netbeans with Apache License 2.0 | 4 votes |
@Override public Result findBinaryRoots(@NonNull final URL sourceRoot) { try { final URI key = sourceRoot.toURI(); Result res = cache.get(key); if (res == null) { URL binRoot = null; //Try project sources final FileObject srcDir = project.getSourceDirectory(); if (srcDir != null && srcDir.toURI().equals(key)) { binRoot = Utilities.toURI(project.getClassesDirectory()).toURL(); } //Try project generated sources if (binRoot == null) { final File genSrcDir = project.getGeneratedClassesDirectory(); if (genSrcDir != null && Utilities.toURI(genSrcDir).equals(key)) { binRoot = Utilities.toURI(project.getClassesDirectory()).toURL(); } } //Try unit tests if (binRoot == null) { for (final String testKind : project.supportedTestTypes()) { final FileObject testSrcDir = project.getTestSourceDirectory(testKind); if (testSrcDir != null && testSrcDir.toURI().equals(key)) { binRoot = Utilities.toURI(project.getTestClassesDirectory(testKind)).toURL(); break; } final File testGenSrcDir = project.getTestGeneratedClassesDirectory(testKind); if (testGenSrcDir != null && Utilities.toURI(testGenSrcDir).equals(key)) { binRoot = Utilities.toURI(project.getTestClassesDirectory(testKind)).toURL(); break; } } } if (binRoot != null) { res = new ResImpl(binRoot); final Result oldRes = cache.putIfAbsent(key, res); if (oldRes != null) { res = oldRes; } } } return res; } catch (MalformedURLException mue) { Exceptions.printStackTrace(mue); } catch (URISyntaxException use) { Exceptions.printStackTrace(use); } return null; }
Example 19
Source File: BulkIngestMapFileLoaderTest.java From datawave with Apache License 2.0 | 4 votes |
@Test public void testTakeOwnershipJobDirectoryFailedRenameLoadedExists() throws Exception { BulkIngestMapFileLoaderTest.logger.info("testTakeOwnershipJobDirectoryFailedRenameLoadedExists called..."); try { URL url = BulkIngestMapFileLoaderTest.class.getResource("/datawave/ingest/mapreduce/job/"); String workDir = "."; String jobDirPattern = "jobs/"; String instanceName = "localhost"; String zooKeepers = "localhost"; Credentials credentials = new Credentials("user", new PasswordToken("pass")); URI seqFileHdfs = url.toURI(); URI srcHdfs = url.toURI(); URI destHdfs = url.toURI(); String jobtracker = "localhost"; Map<String,Integer> tablePriorities = new HashMap<>(); Configuration conf = new Configuration(); BulkIngestMapFileLoader uut = new BulkIngestMapFileLoader(workDir, jobDirPattern, instanceName, zooKeepers, credentials, seqFileHdfs, srcHdfs, destHdfs, jobtracker, tablePriorities, conf, 0); Assert.assertNotNull("BulkIngestMapFileLoader constructor failed to create an instance.", uut); Map<String,Boolean> existsResults = new HashMap<>(); String filePath = String.format("%s%s", url.toString(), BulkIngestMapFileLoader.LOADING_FILE_MARKER); existsResults.put(filePath, Boolean.TRUE); BulkIngestMapFileLoaderTest.WrappedLocalFileSystem fs = new BulkIngestMapFileLoaderTest.WrappedLocalFileSystem(createMockInputStream(), new FileStatus[] {createMockFileStatus()}, false, false, false, false, existsResults, false, false); Whitebox.invokeMethod(FileSystem.class, "addFileSystemForTesting", BulkIngestMapFileLoaderTest.FILE_SYSTEM_URI, conf, fs); Path jobDirectory = new Path(url.toString()); boolean results = uut.takeOwnershipJobDirectory(jobDirectory); Assert.assertFalse("BulkIngestMapFileLoader#takeOwnershipJobDirectory failed to return false as expected.", results); List<String> uutLogEntries = retrieveUUTLogs(); List<String> calls = fs.callsLogs(); Assert.assertTrue("BulkIngestMapFileLoader#takeOwnershipJobDirectory failed generate a renamed message", processOutputContains(uutLogEntries, "Renamed")); Assert.assertTrue("BulkIngestMapFileLoader#takeOwnershipJobDirectory failed generate another process took ownership message", processOutputContains(uutLogEntries, "Another process already took ownership of ")); Assert.assertTrue("BulkIngestMapFileLoader#takeOwnershipJobDirectory failed to call FileSystem#rename", processOutputContains(calls, "FileSystem#rename(")); Assert.assertTrue("BulkIngestMapFileLoader#takeOwnershipJobDirectory failed to call FileSystem#exists", processOutputContains(calls, "FileSystem#exists(")); } finally { Whitebox.invokeMethod(FileSystem.class, "addFileSystemForTesting", BulkIngestMapFileLoaderTest.FILE_SYSTEM_URI, null, null); BulkIngestMapFileLoaderTest.logger.info("testTakeOwnershipJobDirectoryFailedRenameLoadedExists completed."); } }
Example 20
Source File: RabbitMQHttpClient.java From kkbinlog with Apache License 2.0 | 3 votes |
/** * Construct an instance with the provided url and credentials. * @param url the url e.g. "http://localhost:15672/api/". * @param username the user name. * @param password the password * @param sslConnectionSocketFactory ssl connection factory for http client * @param sslContext ssl context for http client * @throws MalformedURLException for a badly formed URL. * @throws URISyntaxException for a badly formed URL. */ private RabbitMQHttpClient(URL url, String username, String password, SSLConnectionSocketFactory sslConnectionSocketFactory, SSLContext sslContext) throws MalformedURLException, URISyntaxException { this.rootUri = url.toURI(); this.rt = new RestTemplate(getRequestFactory(url, username, password, sslConnectionSocketFactory, sslContext)); this.rt.setMessageConverters(getMessageConverters()); }