List of usage examples for java.net URI toURL
public URL toURL() throws MalformedURLException
From source file:de.sub.goobi.metadaten.MetadatenImagesHelper.java
/** * scale given image file to png using internal embedded content server. *///from w w w . jav a 2s . c o m public void scaleFile(URI inFileName, URI outFileName, int inSize, int intRotation) throws ImageManagerException, IOException, ImageManipulatorException { logger.trace("start scaleFile"); int tmpSize = inSize / 3; if (tmpSize < 1) { tmpSize = 1; } if (logger.isTraceEnabled()) { logger.trace("tmpSize: " + tmpSize); } if (ConfigCore.getParameter("kitodoContentServerUrl", "").equals("")) { logger.trace("api"); ImageManager im = new ImageManager(inFileName.toURL()); logger.trace("im"); RenderedImage ri = im.scaleImageByPixel(tmpSize, tmpSize, ImageManager.SCALE_BY_PERCENT, intRotation); logger.trace("ri"); JpegInterpreter pi = new JpegInterpreter(ri); logger.trace("pi"); FileOutputStream outputFileStream = (FileOutputStream) fileService.write(outFileName); logger.trace("output"); pi.writeToStream(null, outputFileStream); logger.trace("write stream"); outputFileStream.close(); logger.trace("close stream"); } else { String cs = ConfigCore.getParameter("kitodoContentServerUrl") + inFileName + "&scale=" + tmpSize + "&rotate=" + intRotation + "&format=jpg"; cs = cs.replace("\\", "/"); if (logger.isTraceEnabled()) { logger.trace("url: " + cs); } URL csUrl = new URL(cs); HttpClient httpclient = new HttpClient(); GetMethod method = new GetMethod(csUrl.toString()); logger.trace("get"); Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000); method.getParams().setParameter("http.socket.timeout", contentServerTimeOut); int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { return; } if (logger.isTraceEnabled()) { logger.trace("statusCode: " + statusCode); } InputStream inStream = method.getResponseBodyAsStream(); logger.trace("inStream"); try (BufferedInputStream bis = new BufferedInputStream(inStream); OutputStream fos = fileService.write(outFileName);) { logger.trace("BufferedInputStream"); logger.trace("FileOutputStream"); byte[] bytes = new byte[8192]; int count = bis.read(bytes); while (count != -1 && count <= 8192) { fos.write(bytes, 0, count); count = bis.read(bytes); } if (count != -1) { fos.write(bytes, 0, count); } } logger.trace("write"); } logger.trace("end scaleFile"); }
From source file:org.mitre.mpf.mvc.controller.MediaController.java
@RequestMapping(value = "/saveURL", method = RequestMethod.POST) @ResponseBody//w ww . j a v a 2 s .c o m public Map<String, String> saveMedia(@RequestParam(value = "urls", required = true) String[] urls, @RequestParam(value = "desiredpath", required = true) String desiredpath, HttpServletResponse response) throws WfmProcessingException, MpfServiceException { log.debug("URL Upload to Directory:" + desiredpath + " urls:" + urls.length); String err = "Illegal or missing desiredpath"; if (desiredpath == null) { log.error(err); throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err); } ; String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath(); //verify the desired path File desiredPath = new File(desiredpath); if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory log.error(err); throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err); } //passing in urls as a list of Strings //download the media to the server //build a map of success or failure for each file with a custom response object Map<String, String> urlResultMap = new HashMap<String, String>(); for (String enteredURL : urls) { enteredURL = enteredURL.trim(); URI uri; try { uri = new URI(enteredURL); //the check for absolute URI determines if any scheme is present, regardless of validity //(which is checked in both this and the next try block) if (!uri.isAbsolute()) { uri = new URI("http://" + uri.toASCIIString()); } } catch (URISyntaxException incorrectUriTranslation) { log.error("The string {} did not translate cleanly to a URI.", enteredURL, incorrectUriTranslation); urlResultMap.put(enteredURL, "String did not cleanly convert to URI"); continue; } File newFile = null; String localName = null; try { URL url = uri.toURL(); //caught by MalformedURLException //will throw an IOException,which is already caught HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); connection.disconnect(); String filename = url.getFile(); if (filename.isEmpty()) { String err2 = "The filename does not exist when uploading from the url '" + url + "'"; log.error(err2); urlResultMap.put(enteredURL, err2); continue; } if (!ioUtils.isApprovedFile(url)) { String contentType = ioUtils.getMimeType(url); String msg = "The media is not a supported type. Please add a whitelist." + contentType + " entry to the mediaType.properties file."; log.error(msg + " URL:" + url); urlResultMap.put(enteredURL, msg); continue; } localName = uri.getPath(); //we consider no path to be malformed for our purposes if (localName.isEmpty()) { throw new MalformedURLException(String.format("%s does not have valid path", uri)); } //use the full path name for the filename to allow for more unique filenames localName = localName.substring(1);//remove the leading '/' localName = localName.replace("/", "-");//replace the rest of the path with - //get a new unique filename incase the name currently exists newFile = ioUtils.getNewFileName(desiredpath, localName); //save the file FileUtils.copyURLToFile(url, newFile); log.info("Completed write of {} to {}", uri.getPath(), newFile.getAbsolutePath()); urlResultMap.put(enteredURL, "successful write to: " + newFile.getAbsolutePath()); } catch (MalformedURLException badUrl) { log.error("URI {} could not be converted. ", uri, badUrl); urlResultMap.put(enteredURL, "Unable to locate media at the provided address."); } catch (IOException badWrite) { log.error("Error writing media to temp file from {}.", enteredURL, badWrite); urlResultMap.put(enteredURL, "Unable to save media from this url. Please view the server logs for more information."); if (newFile != null && newFile.exists()) { newFile.delete(); } } catch (Exception failure) { //catch the remaining exceptions //this is most likely a failed connection log.error("Exception thrown while saving media from the url {}.", enteredURL, failure); urlResultMap.put(enteredURL, "Error while saving media from this url. Please view the server logs for more information."); } } return urlResultMap; }
From source file:org.LexGrid.LexBIG.gui.load.LoaderExtensionShell.java
/** * Builds the gui./*w ww .j a v a 2 s . c om*/ * * @param shell the shell * @param loader the loader */ private void buildVSGUI(final Shell shell, final Loader loader, final boolean loadingVS, final boolean loadingPL) { Group options = new Group(shell, SWT.NONE); options.setText("Load Options"); shell.setLayout(new GridLayout()); GridData gd = new GridData(GridData.FILL_HORIZONTAL); options.setLayoutData(gd); GridLayout layout = new GridLayout(1, false); options.setLayout(layout); Group groupUri = new Group(options, SWT.NONE); groupUri.setLayout(new GridLayout(3, false)); groupUri.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Label label = new Label(groupUri, SWT.NONE); label.setText("URI:"); final Text file = new Text(groupUri, SWT.BORDER); file.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL)); OptionHolder optionHolder = loader.getOptions(); if (optionHolder.isResourceUriFolder()) { Utility.getFolderChooseButton(groupUri, file); } else { Utility.getFileChooseButton(groupUri, file, optionHolder.getResourceUriAllowedFileTypes().toArray(new String[0]), optionHolder.getResourceUriAllowedFileTypes().toArray(new String[0])); } Group groupControlButtons = new Group(options, SWT.NONE); groupControlButtons.setLayout(new GridLayout(3, false)); groupControlButtons.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); final Button load = new Button(groupControlButtons, SWT.PUSH); final Button nextLoad = new Button(groupControlButtons, SWT.PUSH); final Button close = new Button(groupControlButtons, SWT.PUSH); close.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, true, 1, 1)); load.setText("Load"); load.setToolTipText("Start Load Process."); load.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { URI uri = null; // is this a local file? File theFile = new File(file.getText()); if (theFile.exists()) { uri = theFile.toURI(); } else { // is it a valid URI (like http://something) try { uri = new URI(file.getText()); uri.toURL().openConnection(); } catch (Exception e) { dialog_.showError("Path Error", "No file could be located at this location"); return; } } setLoading(true); load.setEnabled(false); close.setEnabled(false); loader.load(uri); // Create/start a new thread to update the buttons when the load completes. ButtonUpdater buttonUpdater = new ButtonUpdater(nextLoad, close, loader); Thread t = new Thread(buttonUpdater); t.setDaemon(true); t.start(); } public void widgetDefaultSelected(SelectionEvent arg0) { // } }); nextLoad.setText("Next Load"); nextLoad.setToolTipText("Start a New Load Process."); nextLoad.setEnabled(false); nextLoad.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { Loader newLoader = null; try { newLoader = lb_vd_gui_.getLbs().getServiceManager(null).getLoader(loader.getName()); } catch (LBException e) { e.printStackTrace(); } if (!isLoading()) { // close the current window and create/initialize it again with the same loader shell.dispose(); setMonitorLoader(true); initializeLBVSDGui(newLoader, loadingVS, loadingPL); } } public void widgetDefaultSelected(SelectionEvent arg0) { // } }); close.setText("Close"); close.setToolTipText("Close this Loader Window."); close.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { shell.dispose(); } public void widgetDefaultSelected(SelectionEvent arg0) { // } }); Composite status = null; if (loadingVS) status = getStatusCompositeForValueSets(shell, loader); else if (loadingPL) status = getStatusCompositeForPickList(shell, loader); gd = new GridData(GridData.FILL_BOTH); status.setLayoutData(gd); }
From source file:org.dishevelled.thumbnail.AbstractThumbnailManager.java
/** * Create and return a thumbnail image for the specified URI. * * @param uri URI for the original image, must not be null * @param modificationTime modification time for the original image * @param thumbnailDirectory thumbnail directory * @param size size//from www.j av a2 s .com * @return a thumbnail image for the specified URI * @throws IOException if an I/O error occurs */ private BufferedImage createThumbnail(final URI uri, final long modificationTime, final File thumbnailDirectory, final int size) throws IOException { if (uri == null) { throw new IllegalArgumentException("uri must not be null"); } String fileName = DigestUtils.md5Hex(uri.toString()) + ".png"; // fail fast if fail file exists File failFile = new File(failDirectory, fileName); if (failFile.exists()) { throw new IOException("cannot create a thumbnail image for " + uri); } // check if thumbnail exists File thumbnailFile = new File(thumbnailDirectory, fileName); if (thumbnailFile.exists()) { Thumbnail thumbnail = cache.getUnchecked(thumbnailFile); if (thumbnail.getModificationTime() == modificationTime) { return thumbnail.getImage(); } } // load the image and create new thumbnail URL url = uri.toURL(); BufferedImage image = null; try { image = ImageIO.read(url); } catch (IOException e) { createFailFile(failFile); throw new IOException("cannot create a thumbnail image for " + uri, e); } if (image == null) { createFailFile(failFile); throw new IOException("cannot create a thumbnail image for " + uri); } Thumbnail thumbnail = new Thumbnail(uri, modificationTime, image.getWidth(), image.getHeight(), Scalr.resize(image, size)); File tmp = File.createTempFile("tmp", ".png", thumbnailDirectory); fixPermissions(tmp); thumbnail.write(tmp); com.google.common.io.Files.move(tmp, thumbnailFile); return thumbnail.getImage(); }
From source file:ddf.catalog.resource.impl.URLResourceReader.java
/** * Retrieves a {@link ddf.catalog.resource.Resource} based on a {@link URI} and provided * arguments. A connection is made to the {@link URI} to obtain the * {@link ddf.catalog.resource.Resource}'s {@link InputStream} and build a * {@link ResourceResponse} from that. If the {@link URI}'s scheme is HTTP or HTTPS, the * {@link ddf.catalog.resource.Resource}'s name gets set to the {@link URI} passed in, * otherwise, if it is a file scheme, the name is set to the actual file name. * * @param resourceURI//from w w w.jav a2 s. c o m * A {@link URI} that defines what {@link ddf.catalog.resource.Resource} to retrieve * and how to do it. * @param properties * Any additional arguments that should be passed to the {@link ResourceReader}. * @return A {@link ResourceResponse} containing the retrieved * {@link ddf.catalog.resource.Resource}. */ @Override public ResourceResponse retrieveResource(URI resourceURI, Map<String, Serializable> properties) throws IOException, ResourceNotFoundException { String bytesToSkip = null; if (resourceURI == null) { LOGGER.warn("Resource URI was null"); throw new ResourceNotFoundException("Unable to find resource"); } if (properties.containsKey(BYTES_TO_SKIP)) { bytesToSkip = properties.get(BYTES_TO_SKIP).toString(); LOGGER.debug("bytesToSkip: {}", bytesToSkip); } if (resourceURI.getScheme().equals(URL_HTTP_SCHEME) || resourceURI.getScheme().equals(URL_HTTPS_SCHEME)) { LOGGER.debug("Resource URI is HTTP or HTTPS"); String fileAddress = resourceURI.toURL().getFile(); LOGGER.debug("resource name: {}", fileAddress); return retrieveHttpProduct(resourceURI, fileAddress, bytesToSkip, properties); } else if (resourceURI.getScheme().equals(URL_FILE_SCHEME)) { LOGGER.debug("Resource URI is a File"); File filePathName = new File(resourceURI); if (validateFilePath(filePathName)) { String fileName = filePathName.getName(); LOGGER.debug("resource name: {}", fileName); return retrieveFileProduct(resourceURI, fileName, bytesToSkip); } else { throw new ResourceNotFoundException("Error retrieving resource [" + resourceURI.toString() + "]. Invalid Resource URI of [" + resourceURI.toString() + "]. Resources must be in one of the following directories: " + this.rootResourceDirectories.toString()); } } else { ResourceNotFoundException ce = new ResourceNotFoundException( "Resource qualifier ( " + resourceURI.getScheme() + " ) not valid. " + URLResourceReader.TITLE + " requires a qualifier of " + URL_HTTP_SCHEME + " or " + URL_HTTPS_SCHEME + " or " + URL_FILE_SCHEME); throw ce; } }
From source file:org.audiveris.omr.classifier.AbstractClassifier.java
/** * Load model and norms from the most suitable classifier data files. * If user files do not exist or cannot be unmarshalled, the default files are used. * * @param fileName file name for classifier data * @return the model loaded//from w w w .j a va2 s .c o m */ protected M load(String fileName) { // First, try user data, if any, in local EVAL folder logger.debug("AbstractClassifier. Trying user data"); { final Path path = WellKnowns.TRAIN_FOLDER.resolve(fileName); if (Files.exists(path)) { try { Path root = ZipFileSystem.open(path); logger.debug("loadModel..."); M model = loadModel(root); logger.debug("loadNorms..."); norms = loadNorms(root); logger.debug("loaded."); root.getFileSystem().close(); if (!isCompatible(model, norms)) { final String msg = "Obsolete classifier user data in " + path + ", trying default data"; logger.warn(msg); } else { // Tell user we are not using the default logger.info("Classifier data loaded from local {}", path); return model; // Normal exit } } catch (Exception ex) { logger.warn("Load error {}", ex.toString(), ex); norms = null; } } } // Second, use default data (in program RES folder) logger.debug("AbstractClassifier. Trying default data"); final URI uri = UriUtil.toURI(WellKnowns.RES_URI, fileName); try { // Must be a path to a true zip *file* final Path zipPath; logger.debug("uri={}", uri); if (uri.toString().startsWith("jar:")) { // We have a .zip within a .jar // Quick fix: copy the .zip into a separate temp file // TODO: investigate a better solution! File tmpFile = File.createTempFile("AbstractClassifier-", ".tmp"); logger.debug("tmpFile={}", tmpFile); tmpFile.deleteOnExit(); try (InputStream is = uri.toURL().openStream()) { FileUtils.copyInputStreamToFile(is, tmpFile); } zipPath = tmpFile.toPath(); } else { zipPath = Paths.get(uri); } final Path root = ZipFileSystem.open(zipPath); M model = loadModel(root); norms = loadNorms(root); root.getFileSystem().close(); if (!isCompatible(model, norms)) { final String msg = "Obsolete classifier default data in " + uri + ", please retrain from scratch"; logger.warn(msg); } else { logger.info("Classifier data loaded from default uri {}", uri); return model; // Normal exit } } catch (Exception ex) { logger.warn("Load error on {} {}", uri, ex.toString(), ex); } norms = null; // No norms return null; // No model }
From source file:codemirror.eclipse.ui.utils.IOUtils.java
/** * Gets the contents at the given URI./*from ww w . j a va 2s. c o m*/ * * @param uri * The URI source. * @param encoding * The encoding name for the URL contents. * @return The contents of the URL as a String. * @throws IOException if an I/O exception occurs. * @since 2.1. */ public static String toString(URI uri, String encoding) throws IOException { return toString(uri.toURL(), encoding); }
From source file:net.pms.dlna.RootFolder.java
/** * Returns the iTunes XML file. This file has all the information of the * iTunes database. The methods used in this function depends on whether PMS * runs on Mac OS X or Windows.//from w w w. j a v a 2s .c o m * * @return (String) Absolute path to the iTunes XML file. * @throws Exception */ private String getiTunesFile() throws Exception { String line; String iTunesFile = null; if (Platform.isMac()) { // the second line should contain a quoted file URL e.g.: // "file://localhost/Users/MyUser/Music/iTunes/iTunes%20Music%20Library.xml" Process process = Runtime.getRuntime().exec("defaults read com.apple.iApps iTunesRecentDatabases"); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); // we want the 2nd line if ((line = in.readLine()) != null && (line = in.readLine()) != null) { line = line.trim(); // remove extra spaces line = line.substring(1, line.length() - 1); // remove quotes and spaces URI tURI = new URI(line); iTunesFile = URLDecoder.decode(tURI.toURL().getFile(), "UTF8"); } if (in != null) { in.close(); } } else if (Platform.isWindows()) { Process process = Runtime.getRuntime().exec( "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v \"My Music\""); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String location = null; while ((line = in.readLine()) != null) { final String LOOK_FOR = "REG_SZ"; if (line.contains(LOOK_FOR)) { location = line.substring(line.indexOf(LOOK_FOR) + LOOK_FOR.length()).trim(); } } if (in != null) { in.close(); } if (location != null) { // Add the iTunes folder to the end location = location + "\\iTunes\\iTunes Music Library.xml"; iTunesFile = location; } else { logger.info("Could not find the My Music folder"); } } return iTunesFile; }
From source file:net.pms.dlna.RootFolder.java
private VirtualFolder createApertureDlnaLibrary(String url) throws UnsupportedEncodingException, MalformedURLException, XmlParseException, IOException, URISyntaxException { VirtualFolder res = null;//from w w w . j a va 2 s .co m if (url != null) { Map<String, Object> iPhotoLib; // every project is a album, too List<?> listOfAlbums; Map<?, ?> album; Map<?, ?> photoList; URI tURI = new URI(url); iPhotoLib = Plist.load(URLDecoder.decode(tURI.toURL().getFile(), System.getProperty("file.encoding"))); // loads the (nested) properties. photoList = (Map<?, ?>) iPhotoLib.get("Master Image List"); // the list of photos final Object mediaPath = iPhotoLib.get("Archive Path"); String mediaName; if (mediaPath != null) { mediaName = mediaPath.toString(); if (mediaName != null && mediaName.lastIndexOf("/") != -1 && mediaName.lastIndexOf(".aplibrary") != -1) { mediaName = mediaName.substring(mediaName.lastIndexOf("/"), mediaName.lastIndexOf(".aplibrary")); } else { mediaName = "unknown library"; } } else { mediaName = "unknown library"; } logger.info("Going to parse aperture library: " + mediaName); res = new VirtualFolder(mediaName, null); listOfAlbums = (List<?>) iPhotoLib.get("List of Albums"); // the list of events (rolls) for (Object item : listOfAlbums) { album = (Map<?, ?>) item; if (album.get("Parent") == null) { VirtualFolder vAlbum = createApertureAlbum(photoList, album, listOfAlbums); res.addChild(vAlbum); } } } else { logger.info("No Aperture library found."); } return res; }