@Nullable
  static ClassLoader createPluginClassLoader(
      @NotNull File[] classPath,
      @NotNull ClassLoader[] parentLoaders,
      @NotNull IdeaPluginDescriptor pluginDescriptor) {

    if (pluginDescriptor.getUseIdeaClassLoader()) {
      try {
        final ClassLoader loader = PluginManagerCore.class.getClassLoader();
        final Method addUrlMethod = getAddUrlMethod(loader);

        for (File aClassPath : classPath) {
          final File file = aClassPath.getCanonicalFile();
          addUrlMethod.invoke(loader, file.toURI().toURL());
        }

        return loader;
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    PluginId pluginId = pluginDescriptor.getPluginId();
    File pluginRoot = pluginDescriptor.getPath();

    // if (classPath.length == 0) return null;
    if (isUnitTestMode()) return null;
    try {
      final List<URL> urls = new ArrayList<URL>(classPath.length);
      for (File aClassPath : classPath) {
        final File file =
            aClassPath
                .getCanonicalFile(); // it is critical not to have "." and ".." in classpath
                                     // elements
        urls.add(file.toURI().toURL());
      }
      return new PluginClassLoader(
          urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * 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;
    }
  }
Example #3
0
 static {
   dict = null;
   String wnhome = System.getenv("WNHOME");
   String path =
       (new StringBuilder(String.valueOf(wnhome)))
           .append(File.separator)
           .append("dict")
           .toString();
   System.out.println(
       (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString());
   URL url = null;
   try {
     File f =
         new File(
             (new StringBuilder(String.valueOf(getWNLocation())))
                 .append(File.separator)
                 .append("dict")
                 .toString());
     URI uri = f.toURI();
     url = uri.toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   dict = new Dictionary(url);
   dict.open();
 }
Example #4
0
 private static URL toURL(File file) {
   try {
     return file.toURI().toURL();
   } catch (MalformedURLException ex) {
     return null;
   }
 }
Example #5
0
  public static Image getResourceOutIcon(String icon) throws MalformedURLException {
    File iconFile = new File(ICON_OUT_FOLDER + File.separator + icon);
    if (!iconFile.exists()) {
      return getResourceIcon("user_m.png");
    }

    return new Image(iconFile.toURI().toURL().toString());
  }
 /** Get the default folder URL */
 public URL getDefaultFolderURL() {
   try {
     final File defaultFolder = getDefaultFolder();
     return (defaultFolder != null) ? defaultFolder.toURI().toURL() : null;
   } catch (MalformedURLException exception) {
     throw new RuntimeException("Exception getting the default document URL.", exception);
   }
 }
Example #7
0
  /**
   * Convert an InputStream to an xs:anyURI.
   *
   * <p>The implementation creates a temporary file. The PipelineContext is required so that the
   * file can be deleted when no longer used.
   */
  public static String inputStreamToAnyURI(
      PipelineContext pipelineContext, InputStream inputStream, int scope) {
    // Get FileItem
    final FileItem fileItem = prepareFileItemFromInputStream(pipelineContext, inputStream, scope);

    // Return a file URL
    final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
    return storeLocation.toURI().toString();
  }
Example #8
0
 /** 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();
 }
 public void startup() throws MojoExecutionException {
   handlebarsUrl = getClass().getClassLoader().getResource("script/" + handlebarsName);
   if (handlebarsUrl == null) {
     File cacheFile = new File(cacheDir, handlebarsName);
     if (!cacheFile.exists()) {
       fetchHandlebars(handlebarsName);
     }
     try {
       handlebarsUrl = cacheFile.toURI().toURL();
     } catch (MalformedURLException e) {
       throw new MojoExecutionException("Invalid handlebars cache file.", e);
     }
   }
 }
Example #10
0
  /**
   * opens existing file
   *
   * @param a_file
   */
  public GlyphFile(File a_file) {
    super();

    m_fileName = a_file;

    URL url = null;

    try {
      url = a_file.toURI().toURL();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    init(url);
  }
  @Nullable
  static IdeaPluginDescriptorImpl loadDescriptorFromDir(final File file, @NonNls String fileName) {
    IdeaPluginDescriptorImpl descriptor = null;
    File descriptorFile = new File(file, META_INF + File.separator + fileName);
    if (descriptorFile.exists()) {
      descriptor = new IdeaPluginDescriptorImpl(file);

      try {
        descriptor.readExternal(descriptorFile.toURI().toURL());
      } catch (Exception e) {
        System.err.println("Cannot load: " + descriptorFile.getAbsolutePath());
        e.printStackTrace();
      }
    }
    return descriptor;
  }
  @Nullable
  static IdeaPluginDescriptorImpl loadDescriptorFromJar(File file, @NonNls String fileName) {
    try {
      URI fileURL = file.toURI();
      URL jarURL =
          new URL(
              "jar:"
                  + StringUtil.replace(fileURL.toASCIIString(), "!", "%21")
                  + "!/META-INF/"
                  + fileName);

      IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file);
      FileInputStream in = new FileInputStream(file);
      ZipInputStream zipStream = new ZipInputStream(in);
      try {
        ZipEntry entry = zipStream.getNextEntry();
        if (entry.getName().equals(JarMemoryLoader.SIZE_ENTRY)) {
          entry = zipStream.getNextEntry();
          if (entry.getName().equals("META-INF/" + fileName)) {
            byte[] content = FileUtil.loadBytes(zipStream, (int) entry.getSize());
            Document document = JDOMUtil.loadDocument(new ByteArrayInputStream(content));
            descriptor.readExternal(document, jarURL);
            return descriptor;
          }
        }
      } finally {
        zipStream.close();
        in.close();
      }

      descriptor.readExternal(jarURL);
      return descriptor;
    } catch (XmlSerializationException e) {
      getLogger().info("Cannot load " + file, e);
      prepareLoadingPluginsErrorMessage(
          "Plugin file " + file.getName() + " contains invalid plugin descriptor file.");
    } catch (FileNotFoundException e) {
      return null;
    } catch (Exception e) {
      getLogger().info("Cannot load " + file, e);
    } catch (Throwable e) {
      getLogger().info("Cannot load " + file, e);
    }

    return null;
  }
Example #13
0
  /**
   * Sets the icon for the given file.
   *
   * @param file the file to set an icon for
   * @return the byte array containing the thumbnail
   */
  private byte[] getFileThumbnail(File file) {
    byte[] bytes = null;
    if (FileUtils.isImage(file.getName())) {
      try {
        ImageIcon image = new ImageIcon(file.toURI().toURL());
        int width = image.getIconWidth();
        int height = image.getIconHeight();

        if (width > THUMBNAIL_WIDTH) width = THUMBNAIL_WIDTH;
        if (height > THUMBNAIL_HEIGHT) height = THUMBNAIL_HEIGHT;

        bytes = ImageUtils.getScaledInstanceInBytes(image.getImage(), width, height);
      } catch (MalformedURLException e) {
        if (logger.isDebugEnabled()) logger.debug("Could not locate image.", e);
      }
    }
    return bytes;
  }
Example #14
0
  /**
   * Enables to get the name of an object in the spoken language thanks to the jar file
   *
   * @param jarName the file that contains the object classes
   * @return the object name in the spoken language
   */
  private String getLangName(File jarName) {
    String name = null;

    try {
      URL url = jarName.toURI().toURL();
      JarInputStream jarFile = new JarInputStream(url.openStream());
      JarEntry jarEntry = jarFile.getNextJarEntry();
      while (jarEntry != null) {
        if (!jarEntry.isDirectory()
            && jarEntry.getName().contains(Configuration.instance().getLanguage())) {
          int lang_index = jarEntry.getName().lastIndexOf(Configuration.instance().getLanguage());
          name = jarEntry.getName().substring(lang_index + 3, jarEntry.getName().length() - 6);
        }
        jarEntry = jarFile.getNextJarEntry();
      }
    } catch (Exception e) {
      LOG.error("Error getLangName " + jarName + " " + e);
    }
    return name;
  }
    /**
     * Show the selector for selecting the default folder.
     *
     * @return true if the user selected a default folder and false if not.
     */
    protected boolean showDefaultFolderSelector() throws Exception {
      final JFileChooser selector = new JFileChooser(_activeFileChooser.getCurrentDirectory());
      selector.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      final String title =
          (_subfolderName == null)
              ? "Default Folder"
              : "Default Parent Folder of " + _subfolderName;
      selector.setDialogTitle(title);
      final int status = selector.showDialog(_view, "Make Default");

      switch (status) {
        case JFileChooser.APPROVE_OPTION:
          final File defaultFolder = selector.getSelectedFile();
          if (defaultFolder != null) {
            _folderTracker.cacheURL(defaultFolder.toURI().toURL());
            return true;
          } else {
            return false;
          }
        default:
          return false;
      }
    }
  public static void main(String args[]) throws Exception {

    // Take the path of the audio file from command line

    File f = new File("C:\\Users\\Larry\\AppData\\Local\\Temp\\jgoogle_tts-588881786930740869.mp3");
    // Create a Player object that realizes the audio
    final Player p = Manager.createRealizedPlayer(f.toURI().toURL());
    // Start the music
    p.start();
    // Create a Scanner object for taking input from cmd
    Scanner s = new Scanner(System.in);

    // Read a line and store it in st

    String st = s.nextLine();

    // If user types 's', stop the audio

    if (st.equals("s")) {

      p.stop();
    }
  }
 /**
  * Load string map from a file.
  *
  * @param mapFile Map file.
  * @param separator Field separator.
  * @param qualifier Quote character.
  * @param encoding Character encoding for the file.
  * @throws FileNotFoundException If input file does not exist.
  * @throws IOException If input file cannot be opened.
  * @return Set with values read from file.
  */
 public static Map<String, String> loadMap(
     File mapFile, String separator, String qualifier, String encoding)
     throws IOException, FileNotFoundException {
   return loadMap(mapFile.toURI().toURL(), separator, qualifier, encoding);
 }
  @FXML
  private void OK_click(ActionEvent event) {
    logger.entry();
    FederateHandle federateHandle;
    LogEntry log = new LogEntry("4.9", "Join Federation Execution service");
    try {
      if (!FederateName.getText().isEmpty()) {
        log.getSuppliedArguments()
            .add(new ClassValuePair("Federate Name", String.class, FederateName.getText()));
      }
      log.getSuppliedArguments()
          .add(new ClassValuePair("Federate Type", String.class, FederateType.getText()));
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Federation Execution Name", String.class, FederationExecutionName.getText()));
      List<URL> foms = new ArrayList<>();
      int i = 1;
      for (File file : FomModuleDesignators.getFiles()) {
        foms.add(file.toURI().toURL());
        log.getSuppliedArguments()
            .add(
                new ClassValuePair(
                    "FOM Module Deisgnator " + i++, URL.class, file.toURI().toURL().toString()));
      }
      if (FederateName.getText().isEmpty() && FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(), FederationExecutionName.getText());
      } else if (FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(), FederateType.getText(), FederationExecutionName.getText());
      } else if (FederateName.getText().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      } else {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(),
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      }
      log.getReturnedArguments()
          .add(
              new ClassValuePair(
                  "Federate Handle", FederateHandle.class, federateHandle.toString()));
      log.setDescription("Federate joined federation execution successfully");
      log.setLogType(LogEntryType.REQUEST);
      logicalTimeFactory = rtiAmb.getTimeFactory();
      currentLogicalTime = logicalTimeFactory.makeInitial();

      // subscribe to HLAcurrentFDD to retrieve FDD
      ObjectClassHandle FederationHandle =
          rtiAmb.getObjectClassHandle("HLAobjectRoot.HLAmanager.HLAfederation");
      currentFDDHandle = rtiAmb.getAttributeHandle(FederationHandle, "HLAcurrentFDD");
      AttributeHandleSet set = rtiAmb.getAttributeHandleSetFactory().create();
      set.add(currentFDDHandle);
      rtiAmb.subscribeObjectClassAttributes(FederationHandle, set);
      rtiAmb.requestAttributeValueUpdate(FederationHandle, set, null);
      // In case of HLA_EVOKED we require this line to receive the FDD
      rtiAmb.evokeMultipleCallbacks(
          .05,
          1); // evoke one callback will not be enough because the reflect attribute is the second
              // one
    } catch (CouldNotCreateLogicalTimeFactory
        | CallNotAllowedFromWithinCallback
        | CouldNotOpenFDD
        | ErrorReadingFDD
        | InconsistentFDD
        | FederateNameAlreadyInUse
        | FederateAlreadyExecutionMember
        | FederationExecutionDoesNotExist
        | SaveInProgress
        | RestoreInProgress
        | NotConnected
        | RTIinternalError ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) FederationExecutionName.getScene().getWindow()).close();
    logger.exit();
  }