List of usage examples for java.net URI toURL
public URL toURL() throws MalformedURLException
From source file:io.specto.hoverfly.junit.HoverflyRule.java
private Path extractBinary(final String binaryName) throws IOException, URISyntaxException { final URI sourceHoverflyUrl = findResourceOnClasspath(binaryName); final Path temporaryHoverflyPath = Files.createTempFile(binaryName, ""); LOGGER.info("Storing binary in temporary directory " + temporaryHoverflyPath); final File temporaryHoverflyFile = temporaryHoverflyPath.toFile(); FileUtils.copyURLToFile(sourceHoverflyUrl.toURL(), temporaryHoverflyFile); if (SystemUtils.IS_OS_WINDOWS) { temporaryHoverflyFile.setExecutable(true); temporaryHoverflyFile.setReadable(true); temporaryHoverflyFile.setWritable(true); } else {//from www. ja v a 2s . co m Files.setPosixFilePermissions(temporaryHoverflyPath, new HashSet<>(asList(OWNER_EXECUTE, OWNER_READ))); } return temporaryHoverflyPath; }
From source file:ddf.catalog.transformer.OverlayActionProvider.java
@Override public <T> Action getAction(T subject) { if (canHandle(subject)) { final Metacard metacard = (Metacard) subject; try {//from w ww . jav a2 s . c o m final String sourceId = URLEncoder.encode(metacard.getSourceId(), UTF_8); final String metacardId = URLEncoder.encode(metacard.getId(), UTF_8); final String encodedTransformerId = URLEncoder.encode(transformerId, UTF_8); final URI uri = new URI(SystemBaseUrl.EXTERNAL.constructUrl( "/catalog/sources/" + sourceId + "/" + metacardId + "?transform=" + encodedTransformerId, true)); final String overlayName = transformerId.substring(OVERLAY_PREFIX.length()); return new ActionImpl(ID + transformerId, TITLE + overlayName + " overlay", DESCRIPTION + overlayName + " overlay transformer", uri.toURL()); } catch (URISyntaxException | MalformedURLException | UnsupportedEncodingException e) { LOGGER.debug("Error constructing URL", e); } } else { LOGGER.debug("Cannot handle the input [{}]", subject); } return null; }
From source file:org.apache.ws.scout.transport.AxisTransport.java
public Element send(Element request, URI endpointURL) throws TransportException { Service service = null;/* w ww .j av a 2s .c o m*/ Call call = null; Element response = null; if (log.isDebugEnabled()) { log.debug("\nRequest message:\n" + XMLUtils.ElementToString(request)); log.debug(endpointURL.toString()); } try { service = new Service(); call = (Call) service.createCall(); call.setTargetEndpointAddress(endpointURL.toURL()); String requestString = XMLUtils.ElementToString(request); SOAPBodyElement body = new SOAPBodyElement(new ByteArrayInputStream(requestString.getBytes("UTF-8"))); Object[] soapBodies = new Object[] { body }; Vector result = (Vector) call.invoke(soapBodies); if (result.size() > 0) { response = ((SOAPBodyElement) result.elementAt(0)).getAsDOM(); } } catch (AxisFault fault) { try { Message msg = call.getResponseMessage(); response = msg.getSOAPEnvelope().getFirstBody().getAsDOM(); } catch (Exception ex) { throw new TransportException(ex); } } catch (Exception ex) { throw new TransportException(ex); } if (log.isDebugEnabled()) { log.debug("\nResponse message:\n" + XMLUtils.ElementToString(response)); } return response; }
From source file:org.biopax.psidev.ontology_manager.impl.OntologyManagerImpl.java
protected OntologyAccess fetchOntology(String ontologyID, String format, URI uri) throws OntologyLoaderException { OntologyAccess oa = null;/*from www.j a v a2s . c om*/ // check the format if ("OBO".equals(format)) { if (uri == null) { throw new IllegalArgumentException("The given CvSource doesn't have a URL"); } else { URL url; try { url = uri.toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException("The given CvSource doesn't have a valid URL: " + uri); } // parse the URL and load the ontology OboLoader loader = new OboLoader(); try { log.debug("Parsing ontology at URL: " + url); oa = loader.parseOboFile(url, ontologyID); oa.setName(ontologyID); } catch (Exception e) { throw new OntologyLoaderException("OboFile parser failed with Exception: ", e); } } } else { throw new OntologyLoaderException("Unsupported ontology format: " + format); } log.info("Successfully created OntologyAccessImpl from values: ontology=" + ontologyID + " format=" + format + " location=" + uri); return oa; }
From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java
public void xsltWrite(File transformationSource, URI xsltMainFileUri, File transformationTarget) { try {/*from w w w . j av a2 s.c om*/ // Set up input and output files InputStream stream = null; if (xsltMainFileUri.getScheme().startsWith("http")) { URL url = xsltMainFileUri.toURL(); URLConnection urlConnection = url.openConnection(); stream = urlConnection.getInputStream(); } else { File xsl = new File(xsltMainFileUri); // FeatureCatalogue.java already checked that file exists stream = new FileInputStream(xsl); } Source xsltSource = new StreamSource(stream); xsltSource.setSystemId(xsltMainFileUri.toString()); Source xmlSource = new StreamSource(transformationSource); Result res = new StreamResult(transformationTarget); // create an instance of TransformerFactory if (xslTransformerFactory != null) { // use TransformerFactory specified in configuration System.setProperty("javax.xml.transform.TransformerFactory", xslTransformerFactory); } else { // use TransformerFactory determined by system } TransformerFactory transFact = TransformerFactory.newInstance(); /* * Set URI resolver for transformation, configured with standard * mappings (e.g. for the localization files) and possibly other * mappings. */ transFact.setURIResolver(new XsltUriResolver(hrefMappings)); Transformer trans = transFact.newTransformer(xsltSource); /* * Specify any standard transformation parameters (e.g. for * localization). */ for (String key : transformationParameters.keySet()) { trans.setParameter(key, transformationParameters.get(key)); } /* Execute the transformation. */ trans.transform(xmlSource, res); } catch (Exception e) { String m = e.getMessage(); if (m != null) { if (result != null) { result.addError(m); } else { System.err.println(m); } } else { String msg = "Exception occurred while processing the XSL transformation."; if (result != null) { result.addError(msg); } else { System.err.println(msg); } } } }
From source file:org.opendatakit.aggregate.odktables.impl.api.InstanceFileServiceImpl.java
@Override public Response getManifest(@Context HttpHeaders httpHeaders, @QueryParam(PARAM_AS_ATTACHMENT) String asAttachment) throws IOException { UriBuilder ub = info.getBaseUriBuilder(); ub.path(OdkTables.class, "getTablesService"); UriBuilder full = ub.clone().path(TableService.class, "getRealizedTable") .path(RealizedTableService.class, "getInstanceFiles") .path(InstanceFileService.class, "getManifest"); URI self = full.build(appId, tableId, schemaETag, rowId); String manifestUrl = self.toURL().toExternalForm(); // retrieve the incoming if-none-match eTag... List<String> eTags = httpHeaders.getRequestHeader(HttpHeaders.IF_NONE_MATCH); String eTag = (eTags == null || eTags.isEmpty()) ? null : eTags.get(0); DbTableInstanceManifestETagEntity eTagEntity = null; try {/*from w w w . j a va 2 s . c o m*/ try { eTagEntity = DbTableInstanceManifestETags.getRowIdEntry(tableId, rowId, cc); } catch (ODKEntityNotFoundException e) { // ignore... } if (eTag != null && eTagEntity != null && eTag.equals(eTagEntity.getManifestETag())) { return Response.status(Status.NOT_MODIFIED).header(HttpHeaders.ETAG, eTag) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Credentials", "true").build(); } userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW); ArrayList<OdkTablesFileManifestEntry> manifestEntries = new ArrayList<OdkTablesFileManifestEntry>(); DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc); BlobEntitySet instance = blobStore.getBlobEntitySet(rowId, cc); int count = instance.getAttachmentCount(cc); for (int i = 1; i <= count; ++i) { OdkTablesFileManifestEntry entry = new OdkTablesFileManifestEntry(); entry.filename = instance.getUnrootedFilename(i, cc); entry.contentLength = instance.getContentLength(i, cc); entry.contentType = instance.getContentType(i, cc); entry.md5hash = instance.getContentHash(i, cc); URI getFile = ub.clone().path(TableService.class, "getRealizedTable") .path(RealizedTableService.class, "getInstanceFiles") .path(InstanceFileService.class, "getFile") .build(appId, tableId, schemaETag, rowId, entry.filename); String locationUrl = getFile.toURL().toExternalForm(); entry.downloadUrl = locationUrl; manifestEntries.add(entry); } OdkTablesFileManifest manifest = new OdkTablesFileManifest(manifestEntries); String newETag = Integer.toHexString(manifest.hashCode()); // create a new eTagEntity if there isn't one already... if (eTagEntity == null) { eTagEntity = DbTableInstanceManifestETags.createNewEntity(tableId, rowId, cc); eTagEntity.setManifestETag(newETag); eTagEntity.put(cc); } else if (!newETag.equals(eTagEntity.getManifestETag())) { Log log = LogFactory.getLog(FileManifestServiceImpl.class); log.error("TableInstance (" + tableId + "," + rowId + ") Manifest ETag does not match computed value!"); eTagEntity.setManifestETag(newETag); eTagEntity.put(cc); } // and whatever the eTag is in that entity is the eTag we should return... eTag = eTagEntity.getManifestETag(); ResponseBuilder rBuild = Response.ok(manifest).header(HttpHeaders.ETAG, eTag) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true"); if (asAttachment != null && !"".equals(asAttachment)) { // Set the filename we're downloading to the disk. rBuild.header(HtmlConsts.CONTENT_DISPOSITION, "attachment; " + "filename=\"" + "manifest.json" + "\""); } return rBuild.build(); } catch (ODKDatastoreException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Unable to retrieve manifest of attachments for: " + manifestUrl) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true") .build(); } catch (PermissionDeniedException e) { String msg = e.getMessage(); if (msg == null) { msg = e.toString(); } LOGGER.error(("ODKTables file upload permissions error: " + msg)); return Response.status(Status.FORBIDDEN).entity(new Error(ErrorType.PERMISSION_DENIED, msg)) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true") .build(); } }
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
/** Send command */ private void servletGetWithParam(String param) throws IOException, URISyntaxException { /* Only localhost is allowed as sender, so no fancy external target used here final URI uriWithParam = new URI(/* w w w . j av a2s. c o m*/ this.baseURI.getScheme(), this.baseURI.getUserInfo(), this.baseURI.getHost(), this.baseURI.getPort(), this.baseURI.getPath(), param, this.baseURI.getFragment()); */ final URI uriWithParam = new URI(this.baseURI.getScheme(), this.baseURI.getUserInfo(), "127.0.0.1", 8080, this.baseURI.getPath(), param, this.baseURI.getFragment()); final URL url = uriWithParam.toURL(); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); log.debug("Connection to " + url.toExternalForm() + " resulted in HTTP " + con.getResponseCode()); assertEquals("Response code", HttpURLConnection.HTTP_OK, con.getResponseCode()); con.disconnect(); }
From source file:org.codehaus.mojo.jspc.CompilationMojoSupport.java
/** * Figure out where the tools.jar file lives. *///w w w . j a v a2s.c o m private URL findToolsJar() throws MojoExecutionException { final File javaHome = FileUtils.resolveFile(new File(File.pathSeparator), System.getProperty("java.home")); final List<File> toolsPaths = new ArrayList<File>(); File file = null; if (SystemUtils.IS_OS_MAC_OSX) { file = FileUtils.resolveFile(javaHome, "../Classes/classes.jar"); toolsPaths.add(file); } if (file == null || !file.exists()) { file = FileUtils.resolveFile(javaHome, "../lib/tools.jar"); toolsPaths.add(file); } if (!file.exists()) { throw new MojoExecutionException( "Could not find tools.jar at " + toolsPaths + " under java.home: " + javaHome); } getLog().debug("Using tools.jar: " + file); final URI fileUri = file.toURI(); try { return fileUri.toURL(); } catch (MalformedURLException e) { throw new MojoExecutionException("Could not generate URL from URI: " + fileUri, e); } }
From source file:com.microsoft.tfs.client.common.ui.teamexplorer.pages.TeamExplorerHomePage.java
private void createProtocolHandlerUI(final FormToolkit toolkit, final Composite parent, final TeamExplorerContext context) { if (!ProtocolHandler.getInstance().hasProtocolHandlerRequest() || !context.isConnectedToCollection()) { return;//ww w. ja v a 2 s .c om } final Composite composite = toolkit.createComposite(parent); composite.setBackground(TeamExplorerHelpers.getDropCompositeBackground(parent)); SWTUtil.gridLayout(composite, 1, false, 3, 3); GridDataBuilder.newInstance().hAlignFill().hGrab().vIndent(5).applyTo(composite); final Composite innerComposite = toolkit.createComposite(composite); innerComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); innerComposite.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); SWTUtil.gridLayout(innerComposite, 2, false, 5, 5); GridDataBuilder.newInstance().hAlignFill().hGrab().applyTo(innerComposite); final TeamExplorerNavigationLinkConfig[] navHomPageLinks = configuration.getNavigationLinks(HOME_PAGE_ID); for (final TeamExplorerNavigationLinkConfig item : navHomPageLinks) { final ITeamExplorerNavigationLink navLink = item.createInstance(); if (navLink.isVisible(context)) { final Composite itemComposite = toolkit.createComposite(innerComposite); itemComposite.setBackground(innerComposite.getBackground()); SWTUtil.gridLayout(itemComposite, 1, false, 5, 5); GridDataBuilder.newInstance().hAlignFill().hGrab().applyTo(itemComposite); final String branchText = MessageFormat.format("<span color=\"linkcolor\">{0}</span>", //$NON-NLS-1$ ProtocolHandler.getInstance().getProtocolHandlerBranchForHtml()); final String repositoryLink = MessageFormat.format("<a href=\"{0}\">{1}</a>", //$NON-NLS-1$ WebAccessHelper.getGitRepoURL(context, ProtocolHandler.getInstance().getProtocolHandlerProject(), ProtocolHandler.getInstance().getProtocolHandlerRepository(), ProtocolHandler.getInstance().getProtocolHandlerBranch()), ProtocolHandler.getInstance().getProtocolHandlerRepositoryForHtml()); final String localizedMessageText = MessageFormat.format( Messages.getString("TeamExplorerHomePage.ImportRepoMessageFormat"), //$NON-NLS-1$ branchText, repositoryLink); final String messageText = MessageFormat.format("<form><p>{0}</p></form>", localizedMessageText); //$NON-NLS-1$ final FormText formText = toolkit.createFormText(itemComposite, false); formText.setBackground(innerComposite.getBackground()); formText.setForeground(innerComposite.getForeground()); formText.setText(messageText, true, false); formText.setColor("linkcolor", formText.getHyperlinkSettings().getForeground()); //$NON-NLS-1$ formText.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { try { final URI repoUri = new URI((String) e.getHref()); PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser() .openURL(repoUri.toURL()); } catch (final Exception ex) { log.error("Error opening browser:", ex); //$NON-NLS-1$ } } }); GridDataBuilder.newInstance().hAlignFill().hGrab().wHint(200).applyTo(formText); final String cloneText = Messages.getString("TeamExplorerHomePage.CloneButtonText"); //$NON-NLS-1$ final Button cloneButton = toolkit.createButton(itemComposite, cloneText, SWT.PUSH); cloneButton.setBackground(TeamExplorerHelpers.getDropCompositeBackground(parent)); cloneButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { navLink.clicked(parent.getShell(), context, navigator, null); TeamExplorerHelpers.toggleCompositeVisibility(composite); TeamExplorerHelpers.relayoutContainingScrolledComposite(parent); ProtocolHandler.getInstance().removeProtocolHandlerArguments(); } @Override public void widgetDefaultSelected(final SelectionEvent e) { navLink.clicked(parent.getShell(), context, navigator, null); TeamExplorerHelpers.toggleCompositeVisibility(composite); TeamExplorerHelpers.relayoutContainingScrolledComposite(parent); ProtocolHandler.getInstance().removeProtocolHandlerArguments(); } }); GridDataBuilder.newInstance().hAlignLeft().hGrab().applyTo(cloneButton); } } final ImageHyperlink closeButton = toolkit.createImageHyperlink(innerComposite, SWT.PUSH); final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); final Image image = imageHelper.getImage("/images/common/close_button.png"); //$NON-NLS-1$ closeButton.setImage(image); closeButton.setText(""); //$NON-NLS-1$ closeButton.setBackground(innerComposite.getBackground()); GridDataBuilder.newInstance().vAlignTop().hAlignRight().applyTo(closeButton); closeButton.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(final HyperlinkEvent e) { TeamExplorerHelpers.toggleCompositeVisibility(composite); TeamExplorerHelpers.relayoutContainingScrolledComposite(parent); ProtocolHandler.getInstance().removeProtocolHandlerArguments(); } }); composite.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(final DisposeEvent e) { imageHelper.dispose(); image.dispose(); } }); }
From source file:com.asakusafw.runtime.stage.launcher.LauncherOptionsParser.java
private List<URL> processLibraries(List<Path> libraryPaths, String applicationClassName) throws IOException, InterruptedException { if (libraryPaths.isEmpty()) { return Collections.emptyList(); }// w ww . ja v a 2s. c om Map<Path, Path> resolved = processLibraryCache(libraryPaths); List<URL> localUrls = new ArrayList<>(); List<Path> remotePaths = new ArrayList<>(); for (Path path : libraryPaths) { URI uri = path.toUri(); assert uri.getScheme() != null; if (uri.getScheme().equals("file")) { //$NON-NLS-1$ localUrls.add(uri.toURL()); } Path remote = resolved.get(path); if (remote == null) { remotePaths.add(path); } else { remotePaths.add(remote); } } if (configuration.getBoolean(KEY_CACHE_JOBJAR, DEFAULT_CACHE_JOBJAR)) { configureJobJar(libraryPaths, applicationClassName, resolved); } String libjars = buildLibjars(remotePaths); if (libjars.isEmpty() == false) { configuration.set(KEY_CONF_LIBRARIES, libjars); } return localUrls; }