@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
/** Retourne le stream associé à une URL, d'abord teste le réseau et sinon le cache */ public InputStream getWithBackup(String url) throws Exception { // Cache non accessible, on retourne directement l'appel distant if (!isAvailable()) return Util.openStream(url); Exception eBackup = null; InputStream is = null; // Tentative d'accès direct par le réseau try { is = Util.openStream(url); if (is == null) throw new Exception("cache openStream error"); } catch (Exception e) { is = null; eBackup = e; } String id = codage(url); File f = new File(dir + Util.FS + id); // Ca a marché en direct ! if (is != null) { // Devrais-je tenter de remettre à jour le cache if (!f.isFile() || outOfDate(f)) add(url); return is; } // Ca n'a pas marché en direct, peut être présent dans le cache ? if (f.isFile() && f.canRead() && f.length() > 0) { aladin.trace(3, "[" + url + "] backup from cache !"); return new FileInputStream(f); } // Bon, pas d'autre solution throw eBackup; }
/** * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_ * indexed images. Images are cached: loading an image with the same name twice will get the * cached image the second time. If you want to remove an image from the cache, use purgeImage. * Throws JGError when there was an error. */ @SuppressWarnings({"deprecation", "unchecked"}) public JGImage loadImage(String imgfile) { Image img = (Image) loadedimages.get(imgfile); if (img == null) { URL imgurl = getClass().getResource(imgfile); if (imgurl == null) { try { File imgf = new File(imgfile); if (imgf.canRead()) { imgurl = imgf.toURL(); } else { imgurl = new URL(imgfile); // throw new JGameError( // "File "+imgfile+" not found.",true); } } catch (MalformedURLException e) { // e.printStackTrace(); throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true); } } img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgfile, img); } try { ensureLoaded(img); } catch (Exception e) { // e.printStackTrace(); throw new JGameError("Error loading image " + imgfile); } return new JREImage(img); }
// Look through the http-import directory and process all // the files there, oldest first. Note that these are actual // files, not queue elements. private void processHttpImportFiles() { File importDirFile = new File(TrialConfig.basepath + TrialConfig.httpImportDir); if (!importDirFile.exists()) return; File[] files = importDirFile.listFiles(); for (int k = 0; k < files.length; k++) { File next = files[k]; if (next.canRead() && next.canWrite()) { FileObject fileObject = FileObject.getObject(next); if (preprocess(fileObject)) { process(fileObject); if (!queueForDatabase(fileObject)) Log.message(Quarantine.file(next, processorServiceName)); else Log.message(processorServiceName + ": Processing complete: " + next.getName()); } // If the file still exists, then there must be a bug // somewhere; log it and quarantine the file so we don't // fall into an infinite loop. if (next.exists()) { logger.warn( "File still in queue after processing:\n" + next + "The file will be quarantined."); Log.message(Quarantine.file(next, processorServiceName)); } Thread.currentThread().yield(); } } }
/** * Returns an input stream to the resource. * * @param resource The path leading to the resource. Can be an URL, a path leading to a class * resource or a {@link File}. * @return InputStream instance. * @throws IOException If the resource could not be found or opened. */ public static InputStream openInputStream(String resource) throws IOException { try { // See if the resource is an URL first. final URL url = new URL(resource); // success, load the resource. return url.openStream(); } catch (MalformedURLException e) { // No luck. Fallback to class loader paths. } // Try current thread's class loader first. final ClassLoader ldr = Thread.currentThread().getContextClassLoader(); InputStream is; if (ldr != null && (is = ldr.getResourceAsStream(resource)) != null) { return is; } else if ((is = ResourceUtils.class.getResourceAsStream(resource)) != null) { return is; } else if ((is = ClassLoader.getSystemResourceAsStream(resource)) != null) { return is; } // Try file path final File f = new File(resource); if (f.exists() && f.isFile() && f.canRead()) { return new FileInputStream(f); } throw new IOException("Could not locate resource: " + resource); }
/** * Creates an instance bound to url. If <code>acceptDeflate</code> is true then HTTP Request * headers will indicate to servers that this client can accept compressed documents. * * @param urlString Connect to this URL. * @param acceptCompress true if this client will accept compressed responses * @throws FileNotFoundException thrown if <code>urlString</code> is not a valid URL, or a * filename which exists on the system. */ public DConnect2(String urlString, boolean acceptCompress) throws FileNotFoundException { int ceIndex = urlString.indexOf('?'); if (ceIndex != -1) { this.urlString = urlString.substring(0, ceIndex); String expr = urlString.substring(ceIndex); int selIndex = expr.indexOf('&'); if (selIndex != -1) { this.projString = expr.substring(0, selIndex); this.selString = expr.substring(selIndex); } else { this.projString = expr; this.selString = ""; } } else { this.urlString = urlString; this.projString = this.selString = ""; } this.acceptCompress = acceptCompress; // capture encoded url this.urlStringEncoded = EscapeStrings.escapeURL(this.urlString); // Check out the URL to see if it is file:// try { URL testURL = new URL(urlString); if ("file".equals(testURL.getProtocol())) { filePath = testURL.getPath(); // See if .dds and .dods files exist File f = new File(filePath + ".dds"); if (!f.canRead()) { throw new FileNotFoundException("file not readable: " + urlString + ".dds"); } f = new File(filePath + ".dods"); if (!f.canRead()) { throw new FileNotFoundException("file not readable: " + urlString + ".dods"); } } /* Set the server version cause we won't get it from anywhere */ ver = new ServerVersion(ServerVersion.DAP2_PROTOCOL_VERSION, ServerVersion.XDAP); } catch (DAP2Exception ex) { throw new FileNotFoundException("Cannot set server version"); } catch (MalformedURLException e) { throw new FileNotFoundException("Malformed URL: " + urlString); } }
/** Loop a sound file (in .wav, .mid, or .au format) in a background thread. */ public static void loop(String filename) { URL url = null; try { File file = new File(filename); if (file.canRead()) url = file.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } // URL url = StdAudio.class.getResource(filename); if (url == null) throw new RuntimeException("audio " + filename + " not found"); AudioClip clip = Applet.newAudioClip(url); clip.loop(); }
/** * Converts a dir string to a linked dir string * * @param dir the directory string (e.g. /usr/local/httpd) * @param browserLink web-path to Browser.jsp */ public static String dir2linkdir(String dir, String browserLink, int sortMode) { File f = new File(dir); StringBuffer buf = new StringBuffer(); while (f.getParentFile() != null) { if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getName()) + File.separator + "</a>"); } else buf.insert(0, conv2Html(f.getName()) + File.separator); f = f.getParentFile(); } if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getAbsolutePath()) + "</a>"); } else buf.insert(0, f.getAbsolutePath()); return buf.toString(); }
private File getAndValidateFile(String pFile, String pWhat) throws IOException { File ret = new File(pFile); if (!ret.exists()) { throw new FileNotFoundException("No such " + pWhat + " " + pFile); } if (!ret.canRead()) { throw new IOException( pWhat.substring(0, 1).toUpperCase() + pWhat.substring(1) + " " + pFile + " is not readable"); } return ret; }
public static void startClient() { try { // Command Line connection serverSocket = new ServerSocket(PORT); commandLineSocket = serverSocket.accept(); commandLineInputScanner = new Scanner(commandLineSocket.getInputStream()); commandLinePrintWriter = new PrintWriter(commandLineSocket.getOutputStream(), true); // Creating a directory for downloaded files if (!destinationDirectory.canRead()) { destinationDirectory.mkdir(); } // Running a thread for result reading inputThread.start(); // Running a thread for commands sending outputTread.start(); System.out.println("Waiting for JCL"); } catch (IOException e) { localPrintWriter.println("Server offline."); } }
/** * Returns the DAS object from the dataset referenced by this object's URL. The DAS object is * referred to by appending `.das' to the end of a DODS URL. * * @return the DAS associated with the referenced dataset. * @throws MalformedURLException if the URL given to the constructor has an error * @throws IOException if an error connecting to the remote server * @throws ParseException if the DAS parser returned an error * @throws DASException on an error constructing the DAS * @throws DAP2Exception if an error returned by the remote server */ public DAS getDAS() throws IOException, ParseException, DAP2Exception { DASCommand command = new DASCommand(); if (filePath != null) { // url was file: File daspath = new File(filePath + ".das"); // See if the das file exists if (daspath.canRead()) { command.process(new FileInputStream(daspath)); } } else if (stream != null) { command.process(stream); } else { // assume url is remote try { openConnection(urlStringEncoded + ".das" + projString + selString, command); } catch (DAP2Exception de) { // if(de.getErrorCode() != DAP2Exception.NO_SUCH_FILE) // throw de; // rethrow } } return command.das; }
/** * Returns the `Data object' from the dataset referenced by this object's URL given the constraint * expression CE. Note that the Data object is really just a DDS object with data bound to the * variables. The DDS will probably contain fewer variables (and those might have different types) * than in the DDS returned by getDDS() because that method returns the entire DDS (but without * any data) while this method returns only those variables listed in the projection part of the * constraint expression. * * <p>Note that if CE is an empty String then the entire dataset will be returned, unless a * "sticky" CE has been specified in the constructor. * * @param CE The constraint expression to be applied to this request by the server. This is * combined with any CE given in the constructor. * @param statusUI the <code>StatusUI</code> object to use for GUI updates and user cancellation * notification (may be null). * @param btf The <code>BaseTypeFactory</code> to build the member variables in the DDS with. * @return The <code>DataDDS</code> object that results from applying the given CE, combined with * this object's sticky CE, on the referenced dataset. * @throws MalformedURLException if the URL given to the constructor has an error * @throws IOException if any error connecting to the remote server * @throws ParseException if the DDS parser returned an error * @throws DDSException on an error constructing the DDS * @throws DAP2Exception if any error returned by the remote server */ public DataDDS getData(String CE, StatusUI statusUI, BaseTypeFactory btf) throws MalformedURLException, IOException, ParseException, DDSException, DAP2Exception { DataDDS dds = new DataDDS(ver, btf); DataDDSCommand command = new DataDDSCommand(dds, statusUI); command.setURL(urlString + "?" + CE); if (filePath != null) { // url is file: File dodspath = new File(filePath + ".dods"); // See if the dods file exists if (dodspath.canRead()) { /* WARNING: any constraints are ignored in reading the file */ command.process(new FileInputStream(dodspath)); } } else if (stream != null) { command.process(stream); } else { String urls = urlStringEncoded + ".dods" + EscapeStrings.escapeURLQuery(getCompleteCE(CE)); openConnection(urls, command); } return command.dds; }
/** Retourne le Stream associé à une URL */ public InputStream get(String url) throws Exception { // Cache non accessible, on retourne directement l'appel distant if (!isAvailable()) return Util.openStream(url); String id = codage(url); File f = new File(dir + Util.FS + id); // Présent dans le cache, génial ! if (f.isFile() && f.canRead() && f.length() > 0) { // Devra être mise à jour ? if (outOfDate(f)) add(url); aladin.trace(3, "[" + url + "] read in cache !"); return new FileInputStream(f); } // Absent du cache, on va l'y mettre et appeler à nouveau la méthode if (putInCache(url)) return get(url); // Bon, je n'y arrive pas System.err.println("Caching not available for [" + url + "] !!!"); // return (new URL(url)).openStream(); return Util.openStream(url); }
public void init() throws ServletException { final String CONFIG_PATH = getServletContext().getRealPath("/") + "config.ini"; final String APPLICATION_NAME = getServletContext().getServletContextName(); BasicConfigurator.configure(); FileInputStream config_file = null; File config = new File(CONFIG_PATH); if (config.canRead()) { log.debug("Parsing " + CONFIG_PATH); try { config_file = new FileInputStream(CONFIG_PATH); } catch (java.io.FileNotFoundException e) { throw new ServletException(e); } Properties config_prop = new Properties(); try { config_prop.load(config_file); } catch (java.io.IOException e) { throw new ServletException(e); } this.config = config_prop; log.debug("Parsing finished"); } else { log.fatal("Error, cannot read " + CONFIG_PATH); } log.debug("maximumRecords : " + this.config.getProperty("default_maximumRecords")); log.debug("srw_header_file: " + this.config.getProperty("srw_header_file")); log.debug("srw_diag: " + this.config.getProperty("srw_diag_file")); // log.debug("server_list: " + this.config.getProperty("server_list")); try { FileReader fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_header_file")); BufferedReader in1 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_footer_file")); BufferedReader in2 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_diag_file")); BufferedReader in3 = new BufferedReader(fis); try { String line = null; while ((line = in1.readLine()) != null) { this.SRW_HEADER = this.SRW_HEADER + line; } while ((line = in2.readLine()) != null) { this.SRW_FOOTER = this.SRW_FOOTER + line; } while ((line = in3.readLine()) != null) { this.SRW_DIAG = this.SRW_DIAG + line; } } finally { in1.close(); in2.close(); in3.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
public static boolean fileCanBeLoad(File file) { return fileExists(file) && file.canRead(); }