List of usage examples for java.net URL getPath
public String getPath()
From source file:msi.gama.gui.swt.WorkspaceModelsManager.java
public static void linkSampleModelsToWorkspace() { final IWorkspace workspace = ResourcesPlugin.getWorkspace(); URL urlRep = null; try {/*from w w w. j a va 2 s.c o m*/ urlRep = FileLocator.toFileURL(new URL("platform:/plugin/msi.gama.models/models/")); } catch (IOException e) { e.printStackTrace(); return; } File modelsRep = new File(urlRep.getPath()); // FileBean gFile = new FileBean(modelsRep); File[] projects = modelsRep.listFiles(noHiddenFiles); for (final File project : projects) { File dotFile = null; /* parcours des fils pour trouver le dot file et creer le lien vers le projet */ File[] children = project.listFiles(); for (int i = 0; i < children.length; i++) { if (children[i].getName().equals(".project")) { dotFile = new File(children[i].getPath()); break; } } IProjectDescription tempDescription = null; /* If the '.project' doesn't exists we create one */ if (dotFile == null) { /* Initialize file content */ tempDescription = setProjectDescription(project); } else { final IPath location = new Path(dotFile.getAbsolutePath()); try { tempDescription = workspace.loadProjectDescription(location); } catch (CoreException e) { e.printStackTrace(); } } final IProjectDescription description = tempDescription; WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override protected void execute(final IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { IProject proj = workspace.getRoot().getProject(project.getName()); if (!proj.exists()) { proj.create(description, monitor); } else { // project exists but is not accessible if (!proj.isAccessible()) { proj.delete(true, null); proj = workspace.getRoot().getProject(project.getName()); proj.create(description, monitor); } } proj.open(IResource.NONE, monitor); setValuesProjectDescription(proj, true); } }; try { operation.run(null); stampWorkspaceFromModels(); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java
private static URL waitForDependency(URL url, String serviceName, String key, String value, String username, String password) throws InterruptedException { boolean isFoundRunningService = false; ObjectMapper mapper = new ObjectMapper(); int counter = 0; URL endpoint = null;/* www . ja v a 2s. c o m*/ while (!isFoundRunningService) { endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort())); if (endpoint != null) { String isLive = null; try { URL statusURL = new URL(endpoint.toExternalForm() + url.getPath()); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH, CLIENT_KEYSTORE_PASSWORD_PATH); KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo); final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kms, tms, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier()); httpsConnection.setSSLSocketFactory(socketFactory); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } if (Utils.isNotNullOrEmpty(username)) { String encoded = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes("UTF-8")); log.info(username + ":******"); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); } isLive = IOUtils.toString(urlConnection.getInputStream()); Map<String, Object> esResponse = mapper.readValue(isLive, new TypeReference<Map<String, Object>>() { }); if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) { isFoundRunningService = true; } else { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")" + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")" + e.getMessage()); } } else { if (counter % 10 == 0) log.info("Could not find " + serviceName + " in namespace, waiting.."); } counter++; Thread.sleep(1000l); } return endpoint; }
From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java
/** * Normalization code courtesy of 'Mike Houston' http://stackoverflow.com/questions/2993649/how-to-normalize-a-url-in-java *//*from ww w .jav a 2 s . c o m*/ public static String NormalizeURL(final String taintedURL) throws MalformedURLException { final URL url; try { url = new URI(taintedURL).normalize().toURL(); } catch (URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } final String path = url.getPath().replace("/$", ""); final SortedMap<String, String> params = CreateParameterMap(url.getQuery()); final int port = url.getPort(); final String queryString; if (params != null) { // Some params are only relevant for user tracking, so remove the most commons ones. for (Iterator<String> i = params.keySet().iterator(); i.hasNext();) { final String key = i.next(); if (key.startsWith("utm_") || key.contains("session")) i.remove(); } queryString = "?" + Canonicalize(params); } else queryString = ""; return url.getProtocol() + "://" + url.getHost() + (port != -1 && port != 80 ? ":" + port : "") + path + queryString; }
From source file:it.baeyens.arduino.managers.Manager.java
private static void loadLibraryIndex(boolean download) { try {/* w w w.jav a 2 s . c o m*/ URL librariesUrl = new URL(Defaults.LIBRARIES_URL); String localFileName = Paths.get(librariesUrl.getPath()).getFileName().toString(); Path librariesPath = Paths .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString()); File librariesFile = librariesPath.toFile(); if (!librariesFile.exists() || download) { librariesPath.getParent().toFile().mkdirs(); Files.copy(librariesUrl.openStream(), librariesPath, StandardCopyOption.REPLACE_EXISTING); } if (librariesFile.exists()) { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(librariesFile), Charset.forName("UTF8"))) { //$NON-NLS-1$ libraryIndex = new Gson().fromJson(reader, LibraryIndex.class); libraryIndex.resolve(); } } } catch (IOException e) { Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to load library index", e)); //$NON-NLS-1$ } }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java
/** * Make the given URL available as an executable file. A temporary file is created and deleted * upon a regular shutdown of the JVM. If the parameter {@code aCache} is {@code true}, the * temporary file is remembered in a cache and if a file is requested for the same URL at a * later time, the same file is returned again. If the previously created file has been deleted * meanwhile, it is recreated from the URL. * * @param aUrl/*w w w . j ava2 s . c o m*/ * the URL. * @param aCache * use the cache or not. * @return an executable file created from the given URL. * @throws IOException * if the file has permissions issues. */ public static synchronized File getUrlAsExecutable(URL aUrl, boolean aCache) throws IOException { File file; synchronized (urlFileCache) { file = urlFileCache.get(aUrl.toString()); if (!aCache || (file == null) || !file.exists()) { String name = FilenameUtils.getBaseName(aUrl.getPath()); file = File.createTempFile(name, ".temp"); file.setExecutable(true); if (!file.canExecute()) { StringBuilder errorMessage = new StringBuilder(128); errorMessage.append("Tried to use temporary folder, but seems it is not " + "executable. Please check the permissions rights from your " + "temporary folder.\n"); if (isEnvironmentVariableDefined(XDG_RUNTIME_DIR_ENV_VAR, errorMessage) && checkFolderPermissions(errorMessage, System.getenv(XDG_RUNTIME_DIR_ENV_VAR))) { file = getFileAsExecutable(aUrl, System.getenv(XDG_RUNTIME_DIR_ENV_VAR)); } else if (isEnvironmentVariableDefined(DKPRO_HOME_ENV_VAR, errorMessage) && checkFolderPermissions(errorMessage, System.getenv(DKPRO_HOME_ENV_VAR) + File.separator + "temp")) { file = getFileAsExecutable(aUrl, System.getenv(DKPRO_HOME_ENV_VAR) + File.separator + "temp"); } else { if (!isUserHomeDefined(errorMessage) || !checkFolderPermissions(errorMessage, System.getProperty("user.home") + File.separator + ".dkpro" + File.separator + "temp")) { throw new IOException(errorMessage.toString()); } file = getFileAsExecutable(aUrl, System.getProperty("user.home") + File.separator + ".dkpro" + File.separator + "temp"); } } file.deleteOnExit(); InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = aUrl.openStream(); outputStream = new FileOutputStream(file); copy(inputStream, outputStream); } finally { closeQuietly(inputStream); closeQuietly(outputStream); } if (aCache) { urlFileCache.put(aUrl.toString(), file); } } } return file; }
From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java
/** * Generates download manifest based on bundle manifest and puts in into * system owned bucket/*w w w.j a v a2s .c o m*/ * * @param baseManifest * the base manifest * @param keyToUse * public key that used for encryption * @param manifestName * name for generated manifest file * @param expirationHours * expiration policy in hours for pre-signed URLs * @param urlForNc * indicates if urs are constructed for NC use * @return pre-signed URL that can be used to download generated manifest * @throws DownloadManifestException */ public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse, final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException { EucaS3Client s3Client = null; try { try { s3Client = s3ClientsPool.borrowObject(); } catch (Exception ex) { throw new DownloadManifestException("Can't borrow s3Client from the pool"); } // prepare to do pre-signed urls if (!urlForNc) s3Client.refreshEndpoint(true); else s3Client.refreshEndpoint(); Date expiration = new Date(); long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours; expiration.setTime(msec); // check if download-manifest already exists if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' is already created and has not expired. Skipping creation"); URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } else { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist"); } UrlValidator urlValidator = new UrlValidator(); final String manifest = baseManifest.getManifest(); if (manifest == null) { throw new DownloadManifestException("Can't generate download manifest from null base manifest"); } final Document inputSource; final XPath xpath; Function<String, String> xpathHelper; DocumentBuilder builder = XMLParser.getDocBuilder(); inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes())); if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) { LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false)); throw new InvalidBaseManifestException("Base manifest does not have manifest element"); } StringBuilder signatureSrc = new StringBuilder(); Document manifestDoc = builder.newDocument(); Element root = (Element) manifestDoc.createElement("manifest"); manifestDoc.appendChild(root); Element el = manifestDoc.createElement("version"); el.appendChild(manifestDoc.createTextNode("2014-01-14")); signatureSrc.append(nodeToString(el, false)); root.appendChild(el); el = manifestDoc.createElement("file-format"); el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString())); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); xpath = XPathFactory.newInstance().newXPath(); xpathHelper = new Function<String, String>() { @Override public String apply(String input) { try { return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING); } catch (XPathExpressionException ex) { return null; } } }; // extract keys // TODO: move this? if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) { String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key"); String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv"); String size = xpathHelper.apply("/manifest/image/size"); EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse); el = manifestDoc.createElement("bundle"); Element key = manifestDoc.createElement("encrypted-key"); key.appendChild(manifestDoc.createTextNode(encryptKey.getKey())); Element iv = manifestDoc.createElement("encrypted-iv"); iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV())); el.appendChild(key); el.appendChild(iv); Element sizeEl = manifestDoc.createElement("unbundled-size"); sizeEl.appendChild(manifestDoc.createTextNode(size)); el.appendChild(sizeEl); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); } el = manifestDoc.createElement("image"); String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath()); if (bundleSize == null) { throw new InvalidBaseManifestException("Base manifest does not have size element"); } Element size = manifestDoc.createElement("size"); size.appendChild(manifestDoc.createTextNode(bundleSize)); el.appendChild(size); Element partsEl = manifestDoc.createElement("parts"); el.appendChild(partsEl); // parts NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource, XPathConstants.NODESET); if (parts == null) { throw new InvalidBaseManifestException("Base manifest does not have parts"); } for (int i = 0; i < parts.getLength(); i++) { Node part = parts.item(i); String partIndex = part.getAttributes().getNamedItem("index").getNodeValue(); String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part, XPathConstants.NODE)).getTextContent(); String partDownloadUrl = partKey; if (baseManifest.getManifestType().signPartUrl()) { GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest( baseManifest.getBaseBucket(), partKey, HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest); partDownloadUrl = s.toString(); } else { // validate url per EUCA-9144 if (!urlValidator.isEucalyptusUrl(partDownloadUrl)) throw new DownloadManifestException( "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:" + partDownloadUrl); } Node digestNode = null; if (baseManifest.getManifestType().getDigestElement() != null) digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part, XPathConstants.NODE)); Element aPart = manifestDoc.createElement("part"); Element getUrl = manifestDoc.createElement("get-url"); getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl)); aPart.setAttribute("index", partIndex); aPart.appendChild(getUrl); if (digestNode != null) { NamedNodeMap nm = digestNode.getAttributes(); if (nm == null) throw new DownloadManifestException( "Some parts in manifest don't have digest's verification algorithm"); Element digest = manifestDoc.createElement("digest"); digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent()); digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent())); aPart.appendChild(digest); } partsEl.appendChild(aPart); } root.appendChild(el); signatureSrc.append(nodeToString(el, false)); String signatureData = signatureSrc.toString(); Element signature = manifestDoc.createElement("signature"); signature.setAttribute("algorithm", "RSA-SHA256"); signature.appendChild(manifestDoc .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes()))); root.appendChild(signature); String downloadManifest = nodeToString(manifestDoc, true); // TODO: move this ? createManifestsBucketIfNeeded(s3Client); putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, downloadManifest, expiration); // generate pre-sign url for download manifest URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } catch (Exception ex) { LOG.error("Got an error", ex); throw new DownloadManifestException("Can't generate download manifest"); } finally { if (s3Client != null) try { s3ClientsPool.returnObject(s3Client); } catch (Exception e) { // sad, but let's not break instances run LOG.warn("Could not return s3Client to the pool"); } } }
From source file:gr.wavesoft.webng.io.web.WebStreams.java
public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException { try {//from w ww .jav a2 s . c o m // WebRequest connection ClientConnectionRequest connRequest = connectionManager.requestConnection( new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null); ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS); try { // Prepare request BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath()); // Setup headers if (headers != null) { for (String k : headers.keySet()) { request.addHeader(k, headers.get(k)); } } // Send request conn.sendRequestHeader(request); // Fetch response HttpResponse response = conn.receiveResponseHeader(); conn.receiveResponseEntity(response); HttpEntity entity = response.getEntity(); if (entity != null) { BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true); // Replace entity response.setEntity(managedEntity); } // Do something useful with the response // The connection will be released automatically // as soon as the response content has been consumed return response; } catch (IOException ex) { // Abort connection upon an I/O error. conn.abortConnection(); throw ex; } } catch (HttpException ex) { throw new IOException("HTTP Exception occured", ex); } catch (InterruptedException ex) { throw new IOException("InterruptedException", ex); } catch (ConnectionPoolTimeoutException ex) { throw new IOException("ConnectionPoolTimeoutException", ex); } }
From source file:com.twinsoft.convertigo.engine.Context.java
private static String getWebInfPath() { if (webinfPath == null) { URL engineProps = Engine.class.getResource(EnginePropertiesManager.PROPERTIES_FILE_NAME); String path = engineProps.getPath(); path = path.replaceAll("%20", " "); int start = Engine.isLinux() ? 0 : 1; int end = path.lastIndexOf(EnginePropertiesManager.PROPERTIES_FILE_NAME); webinfPath = path.substring(start, end + 1); Engine.logContext.debug("Convertigo bin path : " + webinfPath); }//ww w. j a v a 2s .c o m return webinfPath; }
From source file:co.cask.cdap.security.server.ExternalAuthenticationServerSSLTest.java
@BeforeClass public static void beforeClass() throws Exception { URL certUrl = ExternalAuthenticationServerSSLTest.class.getClassLoader().getResource("cert.jks"); Assert.assertNotNull(certUrl);//from w w w .j a v a2 s. c o m String authHandlerConfigBase = Constants.Security.AUTH_HANDLER_CONFIG_BASE; CConfiguration cConf = CConfiguration.create(); SConfiguration sConf = SConfiguration.create(); cConf.set(Constants.Security.AUTH_SERVER_BIND_ADDRESS, "127.0.0.1"); cConf.set(Constants.Security.SSL_ENABLED, "true"); cConf.set(Constants.Security.AuthenticationServer.SSL_PORT, "0"); cConf.set(authHandlerConfigBase.concat("useLdaps"), "true"); cConf.set(authHandlerConfigBase.concat("ldapsVerifyCertificate"), "false"); sConf.set(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PATH, certUrl.getPath()); configuration = cConf; sConfiguration = sConf; String keystorePassword = sConf.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PASSWORD); KeyStoreKeyManager keyManager = new KeyStoreKeyManager(certUrl.getFile(), keystorePassword.toCharArray()); SSLUtil sslUtil = new SSLUtil(keyManager, new TrustAllTrustManager()); ldapListenerConfig = InMemoryListenerConfig.createLDAPSConfig("LDAP", InetAddress.getByName("127.0.0.1"), ldapPort, sslUtil.createSSLServerSocketFactory(), sslUtil.createSSLSocketFactory()); setup(); }
From source file:grails.core.DefaultGrailsApplication.java
protected static void initialiseGroovyExtensionModules() { if (extensionMethodsInitialized) return;//from w w w . j a v a 2s .c o m extensionMethodsInitialized = true; Map<CachedClass, List<MetaMethod>> map = new HashMap<CachedClass, List<MetaMethod>>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { Enumeration<URL> resources = classLoader.getResources(ExtensionModuleScanner.MODULE_META_INF_FILE); while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.getPath().contains("groovy-all")) { // already registered continue; } Properties properties = new Properties(); InputStream inStream = null; try { inStream = url.openStream(); properties.load(inStream); ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()) .registerExtensionModuleFromProperties(properties, classLoader, map); } catch (IOException e) { throw new GroovyRuntimeException("Unable to load module META-INF descriptor", e); } finally { if (inStream != null) { inStream.close(); } } } } catch (IOException ignored) { } for (Map.Entry<CachedClass, List<MetaMethod>> moduleMethods : map.entrySet()) { CachedClass cls = moduleMethods.getKey(); cls.addNewMopMethods(moduleMethods.getValue()); } }