List of usage examples for java.net URI toURL
public URL toURL() throws MalformedURLException
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
public void test() throws Exception { List<List<String>> commands = new ArrayList<List<String>>(); // CLI uses groovy to parse the path which requires either a double backslash or a single slash String applicationAbsolutePath = applicationFile.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/"); List<String> boostrapApplicationCommand = Arrays.asList("azure:bootstrap-app", "--verbose", "-timeout", String.valueOf(TIMEOUT_IN_MINUTES), "-progress", String.valueOf(POLLING_INTERVAL_IN_MINUTES), "-azure-svc", AZURE_HOSTED_SERVICE, "-azure-pwd", RDP_PFX_FILE_PASSWORD, "-azure-location", "'" + AZURE_REGION + "'", applicationAbsolutePath); commands.add(boostrapApplicationCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear();//from w w w . j a v a2s .co m String deploymentUrl = deployment.getUrl(); final URL restAdminMachinesUrl = getMachinesUrl(deploymentUrl); log("Getting number of running machines"); repetativeAssert("Number of machines", new RepetativeConditionProvider() { @Override public boolean getCondition() { try { int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl); logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins=" + EXPECTED_NUMBER_OF_MACHINES); return EXPECTED_NUMBER_OF_MACHINES == numberOfMachines; } catch (Exception e) { logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e); return false; } } }); List<String> connectCommand = Arrays.asList("azure:connect-app", "--verbose", "-timeout 5", "-azure-svc", AZURE_HOSTED_SERVICE); List<String> installApplicationCommand = Arrays.asList("install-application", "--verbose", applicationAbsolutePath); commands.add(connectCommand); commands.add(installApplicationCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear(); final URI travelApplicationUrl = getTravelApplicationUrl(deploymentUrl).toURI(); RepetativeConditionProvider applicationInstalledCondition = new RepetativeConditionProvider() { @Override public boolean getCondition() { try { URL url = travelApplicationUrl.toURL(); return isUrlAvailable(url); } catch (Exception e) { logger.log(Level.WARNING, "Exception while checking if " + travelApplicationUrl.toString() + " is available", e); return false; } } }; repetativeAssert("Failed waiting for travel application", applicationInstalledCondition); List<String> setInstancesScaleOutCommand = Arrays.asList("azure:set-instances", "--verbose", "-azure-svc", AZURE_HOSTED_SERVICE, TOMCAT_SERVICE, NUMBER_OF_INSTANCES_FOR_TOMCAT_SERVICE); commands.add(connectCommand); commands.add(setInstancesScaleOutCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear(); repetativeAssert("Failed waiting for scale out", new RepetativeConditionProvider() { @Override public boolean getCondition() { try { int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl); logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins=" + (EXPECTED_NUMBER_OF_MACHINES + 1)); return numberOfMachines == EXPECTED_NUMBER_OF_MACHINES + 1; } catch (Exception e) { logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e); return false; } } }); List<String> uninstallApplicationCommand = Arrays.asList("uninstall-application", "--verbose", "-timeout", String.valueOf(TIMEOUT_IN_MINUTES), APPLICATION_NAME); commands.add(connectCommand); commands.add(uninstallApplicationCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear(); Assert.assertFalse("Travel application should not be running", isUrlAvailable(travelApplicationUrl.toURL())); List<String> setInstancesScaleInCommand = Arrays.asList("azure:set-instances", "--verbose", "-azure-svc", AZURE_HOSTED_SERVICE, TOMCAT_SERVICE, INITIAL_NUMBER_OF_INSTANCES_FOR_TOMCAT_SERVICE); commands.add(connectCommand); commands.add(setInstancesScaleInCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear(); repetativeAssert("Failed waiting for scale in", new RepetativeConditionProvider() { @Override public boolean getCondition() { try { int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl); logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins=" + EXPECTED_NUMBER_OF_MACHINES); return EXPECTED_NUMBER_OF_MACHINES == numberOfMachines; } catch (Exception e) { logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e); return false; } } }); commands.add(connectCommand); commands.add(installApplicationCommand); runCliCommands(cliExecutablePath, commands, isDebugMode); commands.clear(); repetativeAssert("Failed waiting for travel application", applicationInstalledCondition); }
From source file:org.deegree.ogcwebservices.wass.wss.operation.DoServiceHandler.java
private void setNewOnlineResource(org.deegree.owscommon_new.Operation op, URI facadeURI) { if (op.getDCP() != null) { for (DCP dcp : op.getDCP()) { // assuming HTTP here, SOAP won't work! org.deegree.owscommon_new.HTTP http = (org.deegree.owscommon_new.HTTP) dcp; try { if (http.getGetOnlineResources().size() > 0) { List<URL> urls = http.getGetOnlineResources(); List<URL> urlsnew = new ArrayList<URL>(urls.size()); for (int i = 0; i < urls.size(); ++i) { urlsnew.add(facadeURI.toURL()); }//from ww w .j ava 2 s . co m http.setGetOnlineResources(urlsnew); } if (http.getPostOnlineResources().size() > 0) { List<URL> urls = http.getPostOnlineResources(); List<URL> urlsnew = new ArrayList<URL>(urls.size()); for (int i = 0; i < urls.size(); ++i) { urlsnew.add(facadeURI.toURL()); } http.setPostOnlineResources(urls); } } catch (MalformedURLException e1) { e1.printStackTrace(); } } } }
From source file:com.w20e.socrates.servlet.WebsurveyServlet.java
/** * Initialize the runner for a given questionnaire. The runner, if * successfully created, is stored in the 'runnerCtx' attribute * of the session. /*from w w w. j a v a 2 s .c om*/ * * @param req HTTP request * @param res HTTP response * @param session HTTP session * @param options any specific creation options */ private boolean initializeRunner(HttpServletRequest req, HttpServletResponse res, HttpSession session, Map<String, String> options) { String id = req.getParameter("id"); LOGGER.finest("Parameter id is " + id); URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, id); /** * Get global config. */ Configuration cfg = null; try { cfg = ConfigurationResource.getInstance().getConfiguration(qUri.toURL()); } catch (Exception e1) { return false; } LOGGER.fine("Using config URI " + qUri.toString()); try { RunnerContextImpl ctx = this.runnerFactory.createContext(qUri, options); // Check whether the instance has a variable locale set. If so, this becomes the default. // Locale locale = null; try { locale = LocaleUtility.getLocale(ctx.getInstance().getNode("locale").getValue().toString(), true); LOGGER.fine("Using default locale set in model instance: " + locale); } catch (Exception e) { locale = LocaleUtility.DEFAULT_LOCALE; LOGGER.warning( "Not using default locale set in model instance due to errors, fall back: " + locale); } LOGGER.fine("Using default locale " + locale); // Now see if we need to take the locale from the request // parameters or the user agent headers. locale = ServletHelper.getLocale(req, locale); LOGGER.fine("Using locale " + locale); ctx.setLocale(locale); ctx.setQuestionnaireId(qUri); /* * We may need to reread an existing data set. We do this if the * request didn't explicitly forbid it, and we do have either an * existing session or a stored instance file. */ if ("true".equals(cfg.getString("enablelongsessions", "true"))) { LOGGER.info("Has long session? " + this.sessionMgr.hasLongSession(req, id)); if (this.sessionMgr.hasLongSession(req, id) && !"true".equals(options.get("disable_reload"))) { Instance inst = this.sessionMgr.salvageInstance(id, req, ctx); if (inst != null) { ctx.setInstance(inst); LOGGER.fine("Setting state to " + (String) inst.getMetaData().get("stateId")); ctx.getStateManager().setStateById((String) inst.getMetaData().get("stateId")); } else { LOGGER.warning("Unable to restore instance"); } } } else if (req.getParameter("regkey") != null) { Instance inst = this.sessionMgr.salvageInstanceFromRegkey(req.getParameter("regkey"), req, ctx); if (inst != null) { ctx.setInstance(inst); LOGGER.fine("Setting state to " + (String) inst.getMetaData().get("stateId")); ctx.getStateManager().setStateById((String) inst.getMetaData().get("stateId")); } else { LOGGER.warning("Unable to restore instance"); } } Map<String, Object> meta = ctx.getInstance().getMetaData(); meta.put("qId", id); meta.put("qLocale", locale); ServletHelper.setMetaData(req, meta); // Store runner context in session // session.setAttribute("runnerCtx", new WebsurveyContext(ctx, id, locale)); // Output filename. If unset, default to overwritable file. // if (!meta.containsKey("filename") || meta.get("filename") == null) { meta.put("filename", id + (ctx.getModel().getMetaData().containsKey("Version") ? "-" + ctx.getModel().getMetaData().get("Version") : "") + "_" + locale + "_" + WebsurveyServlet.FORMATTER.format(Calendar.getInstance().getTime()) + "_" + meta.get("key")); } if ("true".equals(cfg.getString("enablelongsessions", "true"))) { // Finally, add cookie that holds info on user data, if we // don't // already have it, and set output // file name. // if (!this.sessionMgr.hasLongSession(req, id)) { this.sessionMgr.createLongLivedSession(id, meta.get("filename").toString() + "||" + session.getId(), res); } } } catch (UnsupportedMediumException e) { this.sessionMgr.invalidateSession(req); LOGGER.log(Level.SEVERE, "Error in creating runner context", e); return false; } return true; }
From source file:com.piusvelte.webcaster.MainActivity.java
@Override public void openMedium(int parent, int child) { Medium m = getMediaAt(parent).get(child); final ContentMetadata contentMetadata = new ContentMetadata(); contentMetadata.setTitle(m.getFile().substring(m.getFile().lastIndexOf(File.separator) + 1)); if (mediaProtocolMessageStream != null) { String urlStr = String.format("http://%s/%s", mediaHost, m.getFile()); try {/*ww w . j av a2 s . c om*/ URL url = new URL(urlStr); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); MediaProtocolCommand cmd = mediaProtocolMessageStream.loadMedia(url.toString(), contentMetadata, true); cmd.setListener(new MediaProtocolCommand.Listener() { @Override public void onCompleted(MediaProtocolCommand mPCommand) { btnPlay.setText(getString(R.string.pause) + " " + contentMetadata.getTitle()); onSetVolume(0.5); } @Override public void onCancelled(MediaProtocolCommand mPCommand) { btnPlay.setText(getString(R.string.play) + " " + contentMetadata.getTitle()); } }); } catch (IllegalStateException e) { Log.e(TAG, "Problem occurred with MediaProtocolCommand during loading", e); } catch (IOException e) { Log.e(TAG, "Problem opening MediaProtocolCommand during loading", e); } catch (URISyntaxException e) { Log.e(TAG, "Problem encoding URI: " + urlStr, e); } } else { Toast.makeText(this, "No message stream", Toast.LENGTH_SHORT).show(); } }
From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java
/** * Gets the XML content from url./*from w w w. java 2 s.com*/ * * @param url the url * @param context the context * @return the rdf content from url * @throws URISyntaxException the URI syntax exception * @throws IOException Signals that an I/O exception has occurred. * @throws MalformedURLException the malformed URL exception */ private Path getXMLContentFromUrl(String url, ServiceContext context) throws URISyntaxException, IOException, MalformedURLException { Path rdfFile; URI uri = new URI(url); rdfFile = Files.createTempFile("thesaurus", ".rdf"); XmlRequest httpReq = context.getBean(GeonetHttpRequestFactory.class).createXmlRequest(uri.toURL()); httpReq.setAddress(uri.getPath()); Lib.net.setupProxy(context, httpReq); httpReq.executeLarge(rdfFile); return rdfFile; }
From source file:edu.mayo.informatics.lexgrid.convert.utility.ManifestUtil.java
/** * This method validates the manifest file * //from w w w . java 2 s .co m * @param uri * @return boolean if the URI indicates valid file. */ private boolean isValidFile(URI uri) { boolean isValid = false; try { if (uri != null) { if (uri.getScheme().equals("file")) { new FileReader(new File(uri)); } else { new InputStreamReader(uri.toURL().openConnection().getInputStream()); } isValid = true; } } catch (Exception e) { messages_.fatal("Validation Error" + ":" + e.getMessage()); } return isValid; }
From source file:org.sickbeard.SickBeard.java
private <T> JsonResponse<T> commandResponse(String command, Type type) throws Exception { URI uri = this.getServerUri(command); // URI uri = new URI( serverUri.toString() + URLEncoder.encode(command) ); HttpURLConnection server = (HttpURLConnection) uri.toURL().openConnection(); server.setConnectTimeout(30000);//from w w w .ja va 2s . co m BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream())); // TypeToken cannot figure out T so instead it must be supplied //Type type = new TypeToken< JSONResponse<T> >() {}.getType(); GsonBuilder build = new GsonBuilder(); StringBuilder sBuild = new StringBuilder(); String input; while ((input = reader.readLine()) != null) sBuild.append(input); reader.close(); input = sBuild.toString(); build.registerTypeAdapter(JsonBoolean.class, new JsonBooleanDeserializer()); JsonResponse<T> response = null; try { response = build.create().fromJson(input, type); tryExtractError(response); return response; } catch (Exception e) { // well something messed up // if this part messes up then something REALLY bad happened response = build.create().fromJson(input, new TypeToken<JsonResponse<Object>>() { }.getType()); tryExtractError(response); // DO NOT RETURN AN ACTUAL OBJECT!!!!! // this makes the code in the UI confused return null; } }
From source file:hudson.ClassicPluginStrategy.java
@Override public PluginWrapper createPluginWrapper(File archive) throws IOException { final Manifest manifest; URL baseResourceURL = null;// www . j a va2 s . c om File expandDir = null; // if .hpi, this is the directory where war is expanded boolean isLinked = isLinked(archive); if (isLinked) { manifest = loadLinkedManifest(archive); } else { if (archive.isDirectory()) {// already expanded expandDir = archive; } else { expandDir = new File(archive.getParentFile(), getBaseName(archive.getName())); explode(archive, expandDir); } File manifestFile = new File(expandDir, PluginWrapper.MANIFEST_FILENAME); if (!manifestFile.exists()) { throw new IOException("Plugin installation failed. No manifest at " + manifestFile); } FileInputStream fin = new FileInputStream(manifestFile); try { manifest = new Manifest(fin); } finally { fin.close(); } } final Attributes atts = manifest.getMainAttributes(); // TODO: define a mechanism to hide classes // String export = manifest.getMainAttributes().getValue("Export"); List<File> paths = new ArrayList<File>(); if (isLinked) { parseClassPath(manifest, archive, paths, "Libraries", ","); parseClassPath(manifest, archive, paths, "Class-Path", " +"); // backward compatibility baseResourceURL = resolve(archive, atts.getValue("Resource-Path")).toURI().toURL(); } else { File classes = new File(expandDir, "WEB-INF/classes"); if (classes.exists()) paths.add(classes); File lib = new File(expandDir, "WEB-INF/lib"); File[] libs = lib.listFiles(JAR_FILTER); if (libs != null) paths.addAll(Arrays.asList(libs)); try { Class pathJDK7 = Class.forName("java.nio.file.Path"); Object toPath = File.class.getMethod("toPath").invoke(expandDir); URI uri = (URI) pathJDK7.getMethod("toUri").invoke(toPath); baseResourceURL = uri.toURL(); } catch (NoSuchMethodException e) { throw new Error(e); } catch (ClassNotFoundException e) { baseResourceURL = expandDir.toURI().toURL(); } catch (InvocationTargetException e) { throw new Error(e); } catch (IllegalAccessException e) { throw new Error(e); } } File disableFile = new File(archive.getPath() + ".disabled"); if (disableFile.exists()) { LOGGER.info("Plugin " + archive.getName() + " is disabled"); } // compute dependencies List<PluginWrapper.Dependency> dependencies = new ArrayList<PluginWrapper.Dependency>(); List<PluginWrapper.Dependency> optionalDependencies = new ArrayList<PluginWrapper.Dependency>(); String v = atts.getValue("Plugin-Dependencies"); if (v != null) { for (String s : v.split(",")) { PluginWrapper.Dependency d = new PluginWrapper.Dependency(s); if (d.optional) { optionalDependencies.add(d); } else { dependencies.add(d); } } } for (DetachedPlugin detached : DETACHED_LIST) detached.fix(atts, optionalDependencies); // Register global classpath mask. This is useful for hiding JavaEE APIs that you might see from the container, // such as database plugin for JPA support. The Mask-Classes attribute is insufficient because those classes // also need to be masked by all the other plugins that depend on the database plugin. String masked = atts.getValue("Global-Mask-Classes"); if (masked != null) { for (String pkg : masked.trim().split("[ \t\r\n]+")) coreClassLoader.add(pkg); } ClassLoader dependencyLoader = new DependencyClassLoader(coreClassLoader, archive, Util.join(dependencies, optionalDependencies)); dependencyLoader = getBaseClassLoader(atts, dependencyLoader); return new PluginWrapper(pluginManager, archive, manifest, baseResourceURL, createClassLoader(paths, dependencyLoader, atts), disableFile, dependencies, optionalDependencies); }