예제 #1
0
  void writeImageToDisk(Document document, String imgURLString, String fileName) {
    // We could just reference the image on the netscape site,
    // but the point of this example is to show how to write
    // a file to the disk.

    // In order to do this, we need to have the ability access files.
    netscape.security.PrivilegeManager.enablePrivilege("UniversalFileAccess");
    // And the ability to connect to an arbitrary URL.
    netscape.security.PrivilegeManager.enablePrivilege("UniversalConnect");

    // Copy the image to the work directory.
    File outFile = new File(document.getWorkDirectory(), fileName);
    if (!outFile.exists()) {
      try {
        InputStream in = new URL(imgURLString).openStream();
        FileOutputStream outStream = new FileOutputStream(outFile);
        int chunkSize = 1024;
        byte[] bytes = new byte[chunkSize];
        int readSize;
        while ((readSize = in.read(bytes)) >= 0) {
          outStream.write(bytes, 0, readSize);
        }
        outStream.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
예제 #2
0
 public void loadMacros() {
   File f = new File(System.getProperty("user.dir"));
   String[] files = f.list();
   for (int i = 0; i < files.length; i++) {
     try {
       if (files[i].startsWith("macro_")
           && files[i].endsWith(".class")
           && files[i].indexOf('$') == -1) {
         System.out.println(files[i]);
         Class clazz = Class.forName(files[i].substring(0, files[i].length() - ".class".length()));
         Macro macro =
             (Macro)
                 clazz
                     .getConstructor(new Class[] {mudclient_Debug.class})
                     .newInstance(new Object[] {inner});
         String[] commands = macro.getCommands();
         for (int j = 0; j < commands.length; j++) {
           System.out.println("command registered:" + commands[j]);
           mudclient_Debug.macros.put(commands[j], macro);
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
예제 #3
0
파일: Installer.java 프로젝트: suever/CTP
 private void fixConfigSchema() {
   File configFile;
   File ctpDir = new File(directory, "CTP");
   if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml");
   else configFile = new File(directory, "config.xml");
   if (configFile.exists()) {
     try {
       Document doc = getDocument(configFile);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       moveAttributes(server, sslAttrs, "SSL");
       moveAttributes(server, proxyAttrs, "ProxyServer");
       moveAttributes(server, ldapAttrs, "LDAP");
       if (programName.equals("ISN")) fixRSNAROOT(server);
       if (isMIRC(root)) fixFileServiceAnonymizerID(root);
       setFileText(configFile, toString(doc));
     } catch (Exception ex) {
       cp.appendln(Color.red, "\nUnable to convert the config file schema.");
       cp.appendln(Color.black, "");
     }
   } else {
     cp.appendln(Color.red, "\nUnable to find the config file to check the schema.");
     cp.appendln(Color.black, "");
   }
 }
예제 #4
0
 /** Разархивация файла с БД */
 private void dearchiveDB() {
   String zipFile = RES_ABS_PATH + File.separator + DB_ARCHIVE_NAME;
   String outputFolder = RES_ABS_PATH;
   try {
     ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
     ZipEntry ze = zis.getNextEntry();
     while (ze != null) {
       String fileName = ze.getName();
       File newFile = new File(outputFolder + File.separator + fileName);
       System.out.println("File unzip : " + newFile.getAbsoluteFile());
       new File(newFile.getParent()).mkdirs();
       FileOutputStream fos = new FileOutputStream(newFile);
       int len;
       byte[] buffer = new byte[1024];
       while ((len = zis.read(buffer)) > 0) {
         fos.write(buffer, 0, len);
       }
       fos.close();
       ze = zis.getNextEntry();
     }
     zis.closeEntry();
     zis.close();
     System.out.println("File unziped");
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
 public static void loadDescriptors(
     String pluginsPath,
     List<IdeaPluginDescriptorImpl> result,
     @Nullable StartupProgress progress,
     int pluginsCount) {
   final File pluginsHome = new File(pluginsPath);
   final File[] files = pluginsHome.listFiles();
   if (files != null) {
     int i = result.size();
     for (File file : files) {
       final IdeaPluginDescriptorImpl descriptor = loadDescriptor(file, PLUGIN_XML);
       if (descriptor == null) continue;
       if (progress != null) {
         progress.showProgress(
             descriptor.getName(), PLUGINS_PROGRESS_MAX_VALUE * ((float) ++i / pluginsCount));
       }
       int oldIndex = result.indexOf(descriptor);
       if (oldIndex >= 0) {
         final IdeaPluginDescriptorImpl oldDescriptor = result.get(oldIndex);
         if (StringUtil.compareVersionNumbers(oldDescriptor.getVersion(), descriptor.getVersion())
             < 0) {
           result.set(oldIndex, descriptor);
         }
       } else {
         result.add(descriptor);
       }
     }
   }
 }
예제 #6
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
예제 #7
0
  void ReceiveFile() throws Exception {
    String fileName;

    fileName = din.readUTF();

    if (fileName != null && !fileName.equals("NOFILE")) {
      System.out.println("Receiving File");
      File f =
          new File(
              System.getProperty("user.home")
                  + "/Desktop"
                  + "/"
                  + fileName.substring(fileName.lastIndexOf("/") + 1));
      System.out.println(f.toString());
      f.createNewFile();
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      System.out.println("Received File : " + fileName);
      fout.close();
    } else {
    }
  }
예제 #8
0
  protected static long getTorrentDataSizeFromFileOrDirSupport(File file) {
    String name = file.getName();

    if (name.equals(".") || name.equals("..")) {

      return (0);
    }

    if (!file.exists()) {

      return (0);
    }

    if (file.isFile()) {

      return (file.length());

    } else {

      File[] dir_files = file.listFiles();

      long length = 0;

      for (int i = 0; i < dir_files.length; i++) {

        length += getTorrentDataSizeFromFileOrDirSupport(dir_files[i]);
      }

      return (length);
    }
  }
  public static int rollbackGUIConfigurationTransaction(String sConfigurationFileName) {

    String sConfigurationLockFile;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.delete() == false) {
      JOptionPane.showMessageDialog(
          null,
          "fFile.delete on " + sConfigurationLockFile + " failed",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 3;
    }

    return 0;
  }
예제 #10
0
 private void LoadQueriesBtnMouseClicked(
     java.awt.event.MouseEvent evt) { // GEN-FIRST:event_LoadQueriesBtnMouseClicked
   // Algorithm
   /*
    * Goto queries' directory and load all queryfile.query to Combobox
    * Change local directory to repository diretory
    * List all file there
    * Try to load all file and add to combobox
    *
    *
    */
   String sQueryRepositoryPath = "/home/natuan/Documents/OntologyMysql/QueriesRepository/";
   File dir = new File(sQueryRepositoryPath);
   String[] children = dir.list();
   if (children == null) {
     // Either dir does not exist or is not a directory
   } else {
     System.out.println("list files");
     for (int i = 0; i < children.length; i++) {
       // Get filename of file or directory
       String filename = children[i];
       String sContent = ReadWholeFileToString(sQueryRepositoryPath + filename);
       queryList.add(sContent);
       QueriesCmb.addItem(filename);
       SparqlTxtArea.setText(sContent);
       //   System.out.println(filename);
     }
     QueriesCmb.setSelectedIndex(children.length - 1);
   }
 } // GEN-LAST:event_LoadQueriesBtnMouseClicked
예제 #11
0
  /** DOCUMENT ME! */
  public void loadRaids() {
    File f = new File(REPO);

    if (!f.exists()) {
      return;
    }

    FileInputStream fIn = null;
    ObjectInputStream oIn = null;

    try {
      fIn = new FileInputStream(REPO);
      oIn = new ObjectInputStream(fIn);
      // de-serializing object
      raids = (HashMap<String, GregorianCalendar>) oIn.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        oIn.close();
        fIn.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
 private Parser readContent() {
   Parser infoParser;
   String filename = FILE_READ_PATH + FILE_READ_BASE_NAME + "." + FILE_READ_EXT_NUM;
   FILE_READ_EXT_NUM++;
   try {
     File file = new File(filename);
     if (DEBUG)
       displayMessage(
           "DEBUG",
           "WCNForecastWeatherQueryFn.readContent:: File "
               + filename
               + " file.length="
               + file.length());
     byte bytes[] = new byte[(int) (file.length())];
     FileInputStream fis = new FileInputStream(file);
     int cnt = fis.read(bytes, 0, bytes.length);
     if (DEBUG)
       displayMessage(
           "DEBUG",
           "WCNForecastWeatherQueryFn.readContent:: File " + filename + " read cnt=" + cnt);
     fis.close();
     if (cnt != bytes.length) return null;
     String content = new String(bytes);
     infoParser = new Parser(content, true, display);
   } catch (FileNotFoundException e) {
     if (DEBUG) displayMessage("ERROR", "File " + filename + " not found.");
     return null;
   } catch (IOException e) {
     if (DEBUG) displayMessage("ERROR", "Read failed on file " + filename);
     return null;
   }
   return infoParser;
 }
예제 #13
0
  // Raises the Save As dialog to have the user identify the location to save groups of things.
  public File determineSaveLocation(String dialogTitle, String defaultFolderName) {
    String defaultPath = this.getFileChooser().getCurrentDirectory().getPath();
    if (!WWUtil.isEmpty(defaultPath)) defaultPath += File.separatorChar + defaultFolderName;

    File outFile;

    while (true) {
      this.getFileChooser().setDialogTitle(dialogTitle);
      this.getFileChooser().setSelectedFile(new File(defaultPath));
      this.getFileChooser().setMultiSelectionEnabled(false);
      this.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

      int status = this.getFileChooser().showSaveDialog(this.getFrame());
      if (status != JFileChooser.APPROVE_OPTION) return null;

      outFile = this.getFileChooser().getSelectedFile();
      if (outFile == null) {
        this.showMessageDialog("No location selected", "No Selection", JOptionPane.ERROR_MESSAGE);
        continue;
      }

      break;
    }

    if (!outFile.exists())
      //noinspection ResultOfMethodCallIgnored
      outFile.mkdir();

    return outFile;
  }
예제 #14
0
파일: Main.java 프로젝트: damacode/MyTumblr
 private static void tryResUrls(Picture picture) {
   String hi_res = "";
   String url = picture.media_url.toString();
   for (String ending : Main.endings) {
     try {
       hi_res = url.replace(url.substring(url.lastIndexOf("_"), url.lastIndexOf(".")), ending);
       URL hi_url = new URL(hi_res);
       File hi_name = Helper.extractMediaFileNameFromURL(hi_url);
       if (hi_name.equals(picture.media_name)) {
         picture.hi_url = hi_url;
         picture.hi_name = hi_name;
         picture.downloaded_hi = true;
         break;
       } else {
         boolean success = Helper.downloadFileFromURLToFileInTemp(hi_url, hi_name);
         if (success) {
           picture.hi_url = hi_url;
           picture.hi_name = hi_name;
           picture.downloaded_hi = true;
           Helper.moveTempImageToStore(hi_name, new File(Main.blogdir, picture.md5_id));
           break;
         }
       }
     } catch (MalformedURLException ex) {
       Main.error(String.format("Attempted hi res url %s is a malformed URL.", hi_res));
     }
   }
 }
예제 #15
0
  private void deleteLocation(LocationInfo info) {
    if (NavigineApp.Navigation == null) return;

    if (info != null) {
      try {
        (new File(info.archiveFile)).delete();
        info.localVersion = -1;
        info.localModified = false;

        String locationDir = LocationLoader.getLocationDir(mContext, info.title);
        File dir = new File(locationDir);
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; ++i) files[i].delete();
        dir.delete();

        String mapFile = NavigineApp.Settings.getString("map_file", "");
        if (mapFile.equals(info.archiveFile)) {
          NavigineApp.Navigation.loadArchive(null);
          SharedPreferences.Editor editor = NavigineApp.Settings.edit();
          editor.putString("map_file", "");
          editor.commit();
        }

        mAdapter.updateList();
      } catch (Throwable e) {
        Log.e(TAG, Log.getStackTraceString(e));
      }
    }
  }
  /**
   * Resolves a reference to a local element identified by address and identifier, where {@code
   * linkBase} identifies a document, including the current document, and {@code linkRef} is the id
   * of the desired element.
   *
   * <p>If {@code linkBase} refers to a local COLLADA file and {@code linkRef} is non-null, the
   * return value is the element identified by {@code linkRef}. If {@code linkRef} is null, the
   * return value is a parsed {@link ColladaRoot} for the COLLADA file identified by {@code
   * linkBase}. Otherwise, {@code linkBase} is returned.
   *
   * @param linkBase the address of the document containing the requested element.
   * @param linkRef the element's identifier.
   * @return the requested element, or null if the element is not found.
   * @throws IllegalArgumentException if the address is null.
   */
  protected Object resolveLocalReference(String linkBase, String linkRef) {
    if (linkBase == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      File file = new File(linkBase);

      if (!file.exists()) return null;

      // Determine whether the file is a COLLADA document. If not, just return the file path.
      if (!WWIO.isContentType(file, ColladaConstants.COLLADA_MIME_TYPE))
        return file.toURI().toString();

      // Attempt to open and parse the COLLADA file.
      ColladaRoot refRoot = ColladaRoot.createAndParse(file);
      // An exception is thrown if parsing fails, so no need to check for null.

      // Add the parsed file to the session cache so it doesn't have to be parsed again.
      WorldWind.getSessionCache().put(linkBase, refRoot);

      // Now check the newly opened COLLADA file for the referenced item, if a reference was
      // specified.
      if (linkRef != null) return refRoot.getItemByID(linkRef);
      else return refRoot;
    } catch (Exception e) {
      String message =
          Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef);
      Logging.logger().warning(message);
      return null;
    }
  }
예제 #17
0
 private byte[] loadClassData(String className) throws IOException {
   Playground.println("Loading class " + className + ".class", warning);
   File f = new File(System.getProperty("user.dir") + "/" + className + ".class");
   byte[] b = new byte[(int) f.length()];
   new FileInputStream(f).read(b);
   return b;
 }
예제 #18
0
 public Properties loadUpdateProperties() {
   File propertiesDirectory;
   Properties updateProperties = new Properties();
   // First we look at local configuration directory
   propertiesDirectory = new File(System.getProperty("user.home"), PROPERTIES_DIRECTORY_NAME);
   if (!propertiesDirectory.exists()) {
     // Second we look at tangara binary path
     propertiesDirectory = getTangaraPath().getParentFile();
   }
   BufferedInputStream input = null;
   try {
     input =
         new BufferedInputStream(
             new FileInputStream(
                 new File(propertiesDirectory, getProperty("checkUpdate.fileName"))));
     updateProperties.load(input);
     input.close();
     return updateProperties;
   } catch (IOException e) {
     LOG.warn("Error trying to load update properties");
   } finally {
     IOUtils.closeQuietly(input);
   }
   return null;
 }
예제 #19
0
  private String getTitle(File f) {
    String result = "";
    if (!f.getName().endsWith(".html")) return "not HTML";
    else {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String ligne = reader.readLine();
        while (ligne != null && !ligne.contains("<TITLE>") && !ligne.contains("<title>")) {
          ligne = reader.readLine();
        }
        reader.close();
        if (ligne == null) return "No TITLE in page " + f.getName();
        else {
          String fin = "";
          String debut = "";
          if (ligne.contains("</TITLE>")) {
            debut = "<TITLE>";
            fin = "</TITLE>";
          } else if (ligne.contains("</title>")) {
            debut = "<title>";
            fin = "</title>";
          } else return "No title in page " + f.getName();

          int fin_index = ligne.lastIndexOf(fin);
          result = ligne.substring(ligne.indexOf(debut) + 7, fin_index);
          return result;
        }
      } catch (Exception e) {
        LOG.error("Error while reading file " + e);
        return "Error for file " + f.getName();
      }
    }
  }
예제 #20
0
 /**
  * Gets the urlClassLoader that enables to access to the objects jar files.
  *
  * @return an URLClassLoader
  */
 public URLClassLoader getObjectsClassLoader() {
   if (objectsClassLoader == null) {
     try {
       if (isExecutionMode()) {
         URL[] listUrl = new URL[1];
         listUrl[0] = instance.getTangaraPath().toURI().toURL();
         objectsClassLoader = new URLClassLoader(listUrl);
       } else {
         File f = new File(instance.getTangaraPath().getParentFile(), "objects");
         File[] list = f.listFiles();
         Vector<URL> vector = new Vector<URL>();
         for (int i = 0; i < list.length; i++) {
           if (list[i].getName().endsWith(".jar")) vector.add(list[i].toURI().toURL());
         }
         File flib =
             new File(
                 instance.getTangaraPath().getParentFile().getAbsolutePath().replace("\\", "/")
                     + "/objects/lib");
         File[] listflib = flib.listFiles();
         for (int j = 0; j < listflib.length; j++) {
           if (listflib[j].getName().endsWith(".jar")) vector.add(listflib[j].toURI().toURL());
         }
         URL[] listUrl = new URL[vector.size()];
         for (int j = 0; j < vector.size(); j++) listUrl[j] = vector.get(j);
         objectsClassLoader = new URLClassLoader(listUrl);
       }
     } catch (Exception e1) {
       displayError("URL MAL FORMED " + e1);
       return null;
     }
   }
   return objectsClassLoader;
 }
예제 #21
0
    @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);
      }
    }
예제 #22
0
  private Service getService(File base) throws Exception {
    File dataFile = new File(base, "data");
    if (!dataFile.isFile()) return null;

    ServiceData data = getData(ServiceData.class, dataFile);
    return new Service(this, data);
  }
  /**
   * Resolve COLLADA references relative to the COLLADA document. If the reference is relative then
   * it will resolved relative to the .dae file, not the kml file. If the COLLADA document may be
   * contained in a KMZ archive the resources will be resolved relative to the .dae file within the
   * archive. Normally references in a KMZ are resolved relative to the root of the archive, but
   * Model references are an exception. See
   * https://developers.google.com/kml/documentation/kmzarchives and
   * https://developers.google.com/kml/documentation/kmlreference#model
   *
   * <p>{@inheritDoc}.
   */
  public String resolveFilePath(String path) throws IOException {
    KMLLink link = this.model.getLink();

    // Check the resource map to see if an alias is defined for this resource.
    String alias = this.resourceMap.get(path);
    if (alias != null) path = alias;

    // If the path is relative then resolve it relative to the COLLADA file.
    File f = new File(path);
    if (!f.isAbsolute() && link != null && link.getHref() != null) {
      try {
        URI base = new URI(null, link.getHref(), null);
        URI ref = new URI(null, path, null);

        path = base.resolve(ref).getPath();
      } catch (URISyntaxException ignored) {
        // Ignored
      }
    }

    Object o = this.parent.getRoot().resolveReference(path);
    if (o instanceof URL || o instanceof String) return o.toString();

    return null;
  }
예제 #24
0
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
예제 #25
0
  private final String findcachedir() {
    System.out.println("here@!");
    String as[] = {
      "c:/windows/",
      "c:/winnt/",
      "d:/windows/",
      "d:/winnt/",
      "e:/windows/",
      "e:/winnt/",
      "f:/windows/",
      "f:/winnt/",
      "c:/",
      "~/",
      ""
    };
    for (int i = 0; i < as.length; i++)
      try {
        String s = as[i];
        if (s.length() > 0) {
          File file = new File(s);
          if (!file.exists()) continue;
        }
        File file1 = new File(s + ".file_store_32");
        if (file1.exists() || file1.mkdir()) return s + ".file_store_32" + "/";
      } catch (Exception _ex) {
      }

    return null;
  }
예제 #26
0
 /**
  * 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);
 }
예제 #27
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
  /** Load the collection of CRLs. */
  protected Collection<? extends CRL> getCRLs(String crlf)
      throws IOException, CRLException, CertificateException {

    File crlFile = new File(crlf);
    if (!crlFile.isAbsolute()) {
      crlFile = new File(System.getProperty("catalina.base"), crlf);
    }
    Collection<? extends CRL> crls = null;
    InputStream is = null;
    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      is = new FileInputStream(crlFile);
      crls = cf.generateCRLs(is);
    } catch (IOException iex) {
      throw iex;
    } catch (CRLException crle) {
      throw crle;
    } catch (CertificateException ce) {
      throw ce;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (Exception ex) {
        }
      }
    }

    return crls;
  }
예제 #29
0
  /*
   * Return data as a byte array.
   */
  private static byte[] readByte(String filename) {
    byte[] data = null;
    AudioInputStream ais = null;
    try {

      // try to read from file
      File file = new File(filename);
      if (file.exists()) {
        ais = AudioSystem.getAudioInputStream(file);
        data = new byte[ais.available()];
        ais.read(data);
      }

      // try to read from URL
      else {
        URL url = StdAudio.class.getResource(filename);
        ais = AudioSystem.getAudioInputStream(url);
        data = new byte[ais.available()];
        ais.read(data);
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      throw new RuntimeException("Could not read " + filename);
    }

    return data;
  }
 public int runDirectorToInstall(
     String message, File installFolder, String sourceRepo, String iuToInstall) {
   String[] command =
       new String[] { //
         "-application",
         "org.eclipse.equinox.p2.director", //
         "-repository",
         sourceRepo,
         "-installIU",
         iuToInstall, //
         "-destination",
         installFolder.getAbsolutePath(), //
         "-bundlepool",
         installFolder.getAbsolutePath(), //
         "-roaming",
         "-profile",
         "PlatformProfile",
         "-profileProperties",
         "org.eclipse.update.install.features=true", //
         "-p2.os",
         Platform.getOS(),
         "-p2.ws",
         Platform.getWS(),
         "-p2.arch",
         Platform.getOSArch()
       };
   return runEclipse(message, command);
 }