List of usage examples for java.net URL toURI
public URI toURI() throws URISyntaxException
From source file:gumga.framework.application.service.GumgaFreemarkerTemplateEngineService.java
@Override public void init() throws TemplateEngineException { if (cfg == null) { try {//from w w w. j a v a2 s . co m //Creates the template folder if it doesn't exists... checkFolder(this.templateFolder); //...then copies default templates in there URL resourceUrl = getClass().getResource("/templates"); Path resourcePath = Paths.get(resourceUrl.toURI()); for (File file : resourcePath.toFile().listFiles()) { File destination = new File(this.templateFolder + File.separator + file.getName()); if (!destination.exists()) { Files.copy(file, destination); } } initStatic(); cfg.setDirectoryForTemplateLoading(new File(this.templateFolder)); cfg.setDefaultEncoding(this.defaultEncoding); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } catch (IOException ex) { throw new TemplateEngineException("An error occurred while initializating the template engine", ex); } catch (URISyntaxException e) { throw new TemplateEngineException("An error occurred while initializating the template engine", e); } catch (java.nio.file.FileSystemNotFoundException ex) { System.out.println("------->Templates no encontrados." + ex); } } }
From source file:com.netflix.nicobar.core.archive.JarScriptArchiveTest.java
@Test public void testLoadWithModuleSpec() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_MODULE_SPEC_JAR.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); // if the module spec isn't provided, it should be discovered in the jar JarScriptArchive scriptArchive = new JarScriptArchive.Builder(rootPath).build(); ScriptModuleSpec moduleSpec = scriptArchive.getModuleSpec(); assertEquals(moduleSpec.getModuleId(), TEST_MODULE_SPEC_JAR.getModuleId()); assertEquals(moduleSpec.getModuleDependencies(), Collections.emptySet()); Map<String, String> expectedMetadata = new HashMap<String, String>(); expectedMetadata.put("metadataName1", "metadataValue1"); expectedMetadata.put("metadataName2", "metadataValue2"); }
From source file:com.agileapes.couteau.maven.sample.task.CompileCodeTask.java
/** * This method will determine the classpath argument passed to the JavaC compiler used by this * implementation/* ww w .ja va 2 s .c o m*/ * @return the classpath * @throws org.apache.maven.artifact.DependencyResolutionRequiredException if the resolution of classpath requires a prior * resolution of dependencies for the target project */ private String getClassPath(SampleExecutor executor) throws DependencyResolutionRequiredException { //Adding compile time dependencies for the project final List elements = executor.getProject().getCompileClasspathElements(); final Set<File> classPathElements = new HashSet<File>(); //noinspection unchecked classPathElements.addAll(elements); //Adding runtime dependencies available to the target project final ClassLoader loader = executor.getProjectClassLoader(); URL[] urls = new URL[0]; if (loader instanceof URLClassLoader) { urls = ((URLClassLoader) loader).getURLs(); } else if (loader instanceof ConfigurableClassLoader) { urls = ((ConfigurableClassLoader) loader).getUrls(); } for (URL url : urls) { try { final File file = new File(url.toURI()); if (file.exists()) { classPathElements.add(file); } } catch (Throwable ignored) { } } //Adding dependency artifacts for the target project for (Object dependencyArtifact : executor.getProject().getDependencyArtifacts()) { if (!(dependencyArtifact instanceof DefaultArtifact)) { continue; } DefaultArtifact artifact = (DefaultArtifact) dependencyArtifact; if (artifact.getFile() != null) { classPathElements.add(artifact.getFile()); } } return StringUtils.collectionToDelimitedString(classPathElements, File.pathSeparator); }
From source file:la.alsocan.symbiot.access.DriverDao.java
public DriverDao(ObjectMapper om) { // open drivers folder String jarFolder;// ww w .jav a2s. c o m try { URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); File jarFile = new File(url.toURI()); jarFolder = jarFile.getParentFile().getPath(); } catch (URISyntaxException ex) { jarFolder = "<unable to resolve>"; } String driverFolderPath = jarFolder + File.separatorChar + DRIVER_FOLDER_NAME; File folder = new File(driverFolderPath); if (!folder.exists() || !folder.isDirectory()) { throw new IllegalStateException("Could not find folder '" + driverFolderPath + "'"); } // load drivers in memory drivers = new LinkedHashMap<>(); for (File file : folder.listFiles((File dir, String name) -> { return name.endsWith(".json"); })) { DriverTo to; try { to = om.readValue(file, DriverTo.class); if (!drivers.containsKey(to.getId())) { drivers.put(to.getId(), to); } else { LOG.warn("The driver file '" + file.getName() + "' uses a conflicting ID '" + to.getId() + "'"); LOG.info("Check driver with name '" + drivers.get(to.getId()).getName() + "' to resolve conflict"); LOG.info("Driver file '" + file.getName() + "' will not be loaded"); } } catch (IOException ex) { LOG.warn("Malformed driver '" + file.getName() + "': " + ex.getMessage()); LOG.info("Driver '" + file.getName() + "' will not be loaded"); } } }
From source file:juzu.impl.plugin.amd.AmdMaxAgeTestCase.java
@Test @RunAsClient//from w ww . jav a 2 s. c om public void test() throws Exception { URL applicationURL = applicationURL(); driver.get(applicationURL.toString()); WebElement elt = driver.findElement(By.id("Foo")); URL url = new URL(applicationURL.getProtocol(), applicationURL.getHost(), applicationURL.getPort(), elt.getText()); HttpGet get = new HttpGet(url.toURI()); HttpResponse response = HttpClientBuilder.create().build().execute(get); Header[] cacheControl = response.getHeaders("Cache-Control"); assertEquals(1, cacheControl.length); assertEquals("max-age=1000", cacheControl[0].getValue()); }
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
/** * Get data from HTTP POST method./* w ww . ja v a 2s . c o m*/ * * This method uses * <ul> * <li>Connection timeout = 300000 (5 minutes)</li> * <li>Socket/Read timeout = 300000 (5 minutes)</li> * <li>Socket Read Buffer = 10485760 (10MB) to provide more space to read</li> * </ul> * -- in case the site is slow * * @return * @throws MalformedURLException * @throws URISyntaxException * @throws UnsupportedEncodingException * @throws IOException * @throws ClientProtocolException * @throws Exception */ public static String getPostData(String sourceUrl, String postString) throws MalformedURLException, URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException, Exception { String result = ""; URL targetUrl = new URL(sourceUrl); /* * Create http parameter to set Connection timeout = 300000 Socket/Read * timeout = 300000 Socket Read Buffer = 10485760 */ HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 300000); HttpConnectionParams.setSocketBufferSize(httpParams, 10485760); HttpConnectionParams.setSoTimeout(httpParams, 300000); // set the http param to the DefaultHttpClient HttpClient httpClient = new DefaultHttpClient(httpParams); // create POST method and set the URL and POST data HttpPost post = new HttpPost(targetUrl.toURI()); StringEntity entity = new StringEntity(postString, "UTF-8"); post.setEntity(entity); logger.info("Execute the POST request with all input data"); // Execute the POST request on the http client to get the response HttpResponse response = httpClient.execute(post, new BasicHttpContext()); if (null != response && response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); if (null != httpEntity) { long contentLength = httpEntity.getContentLength(); logger.info("Content length: " + contentLength); // no data, if the content length is insufficient if (contentLength <= 0) { return ""; } // read the response to String InputStream responseStream = httpEntity.getContent(); if (null != responseStream) { BufferedReader reader = null; StringWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(responseStream)); writer = new StringWriter(); int count = 0; int size = 1024 * 1024; char[] chBuff = new char[size]; while ((count = reader.read(chBuff, 0, size)) >= 0) { writer.write(chBuff, 0, count); } result = writer.getBuffer().toString(); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { IOUtils.closeQuietly(responseStream); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } } } logger.info("data read complete"); return result; }
From source file:com.netflix.nicobar.core.archive.PathScriptArchiveTest.java
@Test public void testLoadTextPath() throws Exception { URL rootPathUrl = getClass().getClassLoader().getResource(TEST_TEXT_PATH.getResourcePath()); Path rootPath = Paths.get(rootPathUrl.toURI()).toAbsolutePath(); ModuleId moduleId = ModuleId.create("testModuleId"); PathScriptArchive scriptArchive = new PathScriptArchive.Builder(rootPath) .setModuleSpec(new ScriptModuleSpec.Builder(moduleId).build()).build(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), moduleId); Set<String> archiveEntryNames = scriptArchive.getArchiveEntryNames(); assertEquals(archiveEntryNames, normalizeFilenames(TEST_TEXT_PATH.getContentPaths())); for (String entryName : archiveEntryNames) { URL entryUrl = scriptArchive.getEntry(entryName); assertNotNull(entryUrl);//from w ww.j a v a2 s . c o m InputStream inputStream = entryUrl.openStream(); String content = IOUtils.toString(inputStream, Charsets.UTF_8); assertNotNull(content); } }
From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTest.java
public void givenAndroidManifestThenTargetPackageIsFound() throws MalformedURLException, URISyntaxException, MojoExecutionException { final URL url = this.getClass().getResource("AndroidManifest.xml"); final URI uri = url.toURI(); final File file = new File(uri); final String foundTargetPackage = androidMojo.extractPackageNameFromAndroidManifest(file); Assert.assertEquals("com.example.android.apis.tests", foundTargetPackage); }
From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTest.java
public void givenAndroidManifestThenInstrumentationRunnerIsFound() throws MalformedURLException, URISyntaxException, MojoExecutionException { final URL url = this.getClass().getResource("AndroidManifest.xml"); final URI uri = url.toURI(); final File file = new File(uri); final String foundInstrumentationRunner = androidMojo.extractInstrumentationRunnerFromAndroidManifest(file); Assert.assertEquals("android.test.InstrumentationTestRunner", foundInstrumentationRunner); }
From source file:org.yamj.api.common.http.DefaultPoolingHttpClient.java
@Override public HttpEntity requestResource(URL url) throws IOException { URI uri;//w ww. j a v a 2 s . c om try { uri = url.toURI(); } catch (URISyntaxException ex) { throw new IllegalArgumentException(INVALID_URL + url, ex); } return requestResource(uri); }