private List<URL> generateExecutionClasspath(
      Set<Artifact> resolvedArtifacts, String... excludeGroups) throws MojoExecutionException {
    /*
     * Convert each resolved artifact into a URL/classpath element.
     */
    final ArrayList<URL> classpath = new ArrayList<URL>();

    final List<String> excludes = Arrays.asList(excludeGroups);

    try {

      for (Artifact resolvedArtifact : resolvedArtifacts) {
        if (excludes.contains(resolvedArtifact.getGroupId())) continue;
        final File file = resolvedArtifact.getFile();
        //        System.out.println("artifact " + resolvedArtifact.toString());
        if (file != null) {
          if (artifactIdsToInsertAtStartOfClasspath.contains(resolvedArtifact.getArtifactId())) {
            getLog().info("adding at the start" + file.getAbsolutePath());
            // a patch? grails is full of them, insert it at the start
            classpath.add(0, file.toURI().toURL());
          } else { // insert it at the end
            classpath.add(file.toURI().toURL());
          }
        }
      }
    } catch (MalformedURLException murle) {
      throw new MojoExecutionException("Unable to find files", murle);
    }

    return classpath;
  }
Beispiel #2
0
  public void innerExecute() throws IOException, JerializerException {
    // first arg - schema dir, second arg - dest dir
    // TODO write schemas

    File schemas = new File(schemaDir);
    assert schemas.isDirectory() && schemas.canRead();

    File dest = new File(destDir);
    assert !dest.exists();
    dest.mkdir();
    assert dest.isDirectory() && dest.canWrite();

    Set<Klass> genKlasses = new TreeSet<Klass>();

    JsonParser parser = new JsonParser();
    for (File schema : schemas.listFiles()) {
      BufferedReader reader = new BufferedReader(new FileReader(schema));
      JThing thing = parser.parse(reader);
      System.out.println(thing);
      String rootString = schemas.toURI().toString();
      if (!rootString.endsWith("/")) rootString = rootString + "/";
      String klassName =
          KlassContext.capitalize(schema.toURI().toString().substring(rootString.length()));
      String packageName = basePackage + "." + klassName.toLowerCase();

      GenWritable writable = parseSchemaThing(klassName, packageName, thing);

      Map<String, String> m = writable.makeClassToTextMap();

      final File dir = new File(destDir + "/" + klassName.toLowerCase());
      dir.mkdirs();
      for (Map.Entry<String, String> entry : m.entrySet()) {
        final String fullClass = entry.getKey();
        final String contents = entry.getValue();
        final String relName = fullClass.substring(fullClass.lastIndexOf(".") + 1) + ".java";
        final File f = new File(dir, relName);
        FileWriter writer = new FileWriter(f);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(contents, 0, contents.length());
        bufferedWriter.close();
      }

      genKlasses.add(new Klass(klassName, packageName));
    }

    RegistryGen registryGen =
        new RegistryGen(new Klass("GenschemaRegistryFactory", basePackage), genKlasses);
    final File g = new File(destDir + "/GenschemaRegistryFactory.java");
    for (Map.Entry<String, String> entry : registryGen.makeClassToTextMap().entrySet()) {
      final String contents = entry.getValue();
      FileWriter writer = new FileWriter(g);
      BufferedWriter bufferedWriter = new BufferedWriter(writer);
      bufferedWriter.write(contents, 0, contents.length());
      bufferedWriter.close();
      break;
    }
  }
  /**
   * Generates the classpath to be used by the launcher to execute the requested Grails script.
   *
   * @return An array of {@code URL} objects representing the dependencies required on the classpath
   *     to execute the selected Grails script.
   * @throws MojoExecutionException if an error occurs while attempting to resolve the dependencies
   *     and generate the classpath array.
   */
  @SuppressWarnings("unchecked")
  private URL[] generateGrailsExecutionClasspath(Set<Artifact> resolvedArtifacts)
      throws MojoExecutionException {
    try {

      final List<URL> classpath = generateExecutionClasspath(resolvedArtifacts);

      // check to see if someone is adding build listeners on the classpath, and if so, bring in the
      // system classpath and add it to our urls
      // IDEA for example does this
      if (System.getProperty("grails.build.listeners") != null) {
        String cp = System.getProperty("java.class.path");
        for (String c : cp.split(":")) {
          File f = new File(c);
          if (f.exists()) classpath.add(f.toURI().toURL());
        }
      }

      if (System.getProperty("grails.debug.classpath") != null) {
        for (URL url : classpath) {
          getLog().info("classpath " + url.toString());
        }
      }

      /*
       * Add the "tools.jar" to the classpath so that the Grails scripts can run native2ascii.
       * First assume that "java.home" points to a JRE within a JDK.  NOTE that this will not
       * provide a valid path on Mac OSX.  This is not a big deal, as the JDK on Mac OSX already
       * adds the required JAR's to the classpath.  This logic is really only for Windows/*Unix.
       */
      final String javaHome = System.getProperty("java.home");
      File toolsJar = new File(javaHome, "../lib/tools.jar");
      if (!toolsJar.exists()) {
        // The "tools.jar" cannot be found with that path, so
        // now try with the assumption that "java.home" points
        // to a JDK.
        toolsJar = new File(javaHome, "tools.jar");
      }

      if (toolsJar.exists()) {
        java.net.URL url = toolsJar.toURI().toURL();
        if (url != null) {
          classpath.add(url);
        }
      }

      return classpath.toArray(new URL[classpath.size()]);
    } catch (final Exception e) {
      throw new MojoExecutionException("Failed to create classpath for Grails execution.", e);
    }
  }
  @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;
  }
 private URLClassLoader buildClassLoader() throws PluginException {
   ClassLoader parent = JarPluginProviderLoader.class.getClassLoader();
   try {
     final URL url = getCachedJar().toURI().toURL();
     final URL[] urlarray;
     if (null != getDepLibs() && getDepLibs().size() > 0) {
       final ArrayList<URL> urls = new ArrayList<URL>();
       urls.add(url);
       for (final File extlib : getDepLibs()) {
         urls.add(extlib.toURI().toURL());
       }
       urlarray = urls.toArray(new URL[urls.size()]);
     } else {
       urlarray = new URL[] {url};
     }
     URLClassLoader loaded =
         loadLibsFirst
             ? LocalFirstClassLoader.newInstance(urlarray, parent)
             : URLClassLoader.newInstance(urlarray, parent);
     classLoaders.put(getCachedJar(), loaded);
     return loaded;
   } catch (MalformedURLException e) {
     throw new PluginException("Error creating classloader for " + cachedJar, e);
   }
 }
Beispiel #6
0
  public PomClassLoader(ArtifactRepository localRepo, DependencyNode node, PomLoader pomLoader) {
    super(new URL[] {}, null);

    if (node.getArtifact().getFile() == null) {
      String s = localRepo.getBasedir() + File.separator + localRepo.pathOf(node.getArtifact());
      node.getArtifact().setFile(new File(s));
    }

    jarFile = node.getArtifact().getFile();
    if (jarFile == null) System.out.println("123");
    try {
      addURL(jarFile.toURI().toURL());
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
    name =
        node.getArtifact().getGroupId()
            + "-"
            + node.getArtifact().getArtifactId()
            + "-"
            + node.getArtifact().getVersion();
    pomLoader.add(this);

    includeDependency(localRepo, pomLoader, node.getChildren());
    getJSClassLoader();
  }
Beispiel #7
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();
 }
Beispiel #8
0
  /**
   * Find mod files in the "mods" folder
   *
   * @param modFolder Folder to search
   * @param modFiles List of mod files to load
   */
  protected void findModFiles(File modFolder, LinkedList<File> modFiles) {
    List<String> supportedVerions = Arrays.asList(SUPPORTED_VERSIONS);

    for (File modFile : modFolder.listFiles(this)) {
      try {
        // Check for a version file
        ZipFile modZip = new ZipFile(modFile);
        ZipEntry version = modZip.getEntry("version.txt");

        if (version != null) {
          // Read the version string
          InputStream versionStream = modZip.getInputStream(version);
          BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
          String strVersion = versionReader.readLine();
          versionReader.close();

          // Only add the mod if the version matches and we were able to successfully add it to the
          // class path
          if (supportedVerions.contains(strVersion) && addURLToClassPath(modFile.toURI().toURL())) {
            modFiles.add(modFile);
          }
        }

        modZip.close();
      } catch (Exception ex) {
        logger.warning(
            "Error enumerating '"
                + modFile.getAbsolutePath()
                + "': Invalid zip file or error reading file");
      }
    }
  }
  /**
   * Reads file import locations from Spring bean application context.
   *
   * @param project
   * @return
   */
  public List<File> getConfigImports(File configFile, Project project) {
    LSParser parser = XMLUtils.createLSParser();

    GetSpringImportsFilter filter = new GetSpringImportsFilter(configFile);
    parser.setFilter(filter);
    parser.parseURI(configFile.toURI().toString());

    return filter.getImportedFiles();
  }
Beispiel #10
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();
  }
Beispiel #11
0
 public static List<URL> toURLs(Iterable<File> files) {
   List<URL> urls = new ArrayList<URL>();
   for (File file : files) {
     try {
       urls.add(file.toURI().toURL());
     } catch (MalformedURLException e) {
       throw new UncheckedIOException(e);
     }
   }
   return urls;
 }
Beispiel #12
0
 private List<URL> getModuleClasspath(File modDir) {
   List<URL> urls = new ArrayList<>();
   // Add the urls for this module
   try {
     urls.add(modDir.toURI().toURL());
     File libDir = new File(modDir, "lib");
     if (libDir.exists()) {
       File[] jars = libDir.listFiles();
       for (File jar : jars) {
         URL jarURL = jar.toURI().toURL();
         urls.add(jarURL);
       }
     }
     return urls;
   } catch (MalformedURLException e) {
     // Won't happen
     log.error("malformed url", e);
     return null;
   }
 }
Beispiel #13
0
 public static URL[] toURLs(File[] files) {
   try {
     URL[] urls = new URL[files.length];
     for (int i = 0; i < files.length; i++) {
       File file = files[i];
       urls[i] = file.toURI().toURL();
     }
     return urls;
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
Beispiel #14
0
  public static Plugin loadPlugin(String name) {
    try {
      ArrayList<URL> paths = new ArrayList<URL>();
      File f = new File("plugins/" + name + ".jar");
      paths.add(f.toURI().toURL());

      File f2 = new File("plugins/lib");
      for (File ff : f2.listFiles()) {
        paths.add(ff.toURI().toURL());
      }
      URL[] urls = new URL[paths.size()];
      paths.toArray(urls);
      URLClassLoader newLoader = new URLClassLoader(urls);
      Plugin p = (Plugin) newLoader.loadClass(name).newInstance();
      loadedPlugins.put(name, p);
      return p;
    } catch (Exception ex) {
      System.err.println("Failed to load plugin: " + ex.getMessage());
      ex.printStackTrace();
    }
    return null;
  }
Beispiel #15
0
  /** @see java.lang.ClassLoader#findResource(java.lang.String) */
  @Override
  protected URL findResource(String resourceName) {
    if (resourceCache.containsKey(resourceName)) return resourceCache.get(resourceName);

    // try the runtime/classes directory for conf files and such
    String runtimePath = System.getProperty("moqui.runtime");
    String fullPath = runtimePath + "/classes/" + resourceName;
    File resourceFile = new File(fullPath);
    if (resourceFile.exists())
      try {
        return resourceFile.toURI().toURL();
      } catch (MalformedURLException e) {
        System.out.println(
            "Error making URL for ["
                + resourceName
                + "] in runtime classes directory ["
                + runtimePath
                + "/classes/"
                + "]: "
                + e.toString());
      }

    String webInfResourceName = "WEB-INF/classes/" + resourceName;
    int jarFileListSize = jarFileList.size();
    for (int i = 0; i < jarFileListSize; i++) {
      JarFile jarFile = jarFileList.get(i);
      JarEntry jarEntry = jarFile.getJarEntry(resourceName);
      // to better support war format, look for the resourceName in the WEB-INF/classes directory
      if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName);
      if (jarEntry != null) {
        try {
          String jarFileName = jarFile.getName();
          if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
          URL resourceUrl = new URL("jar:file:" + jarFileName + "!/" + jarEntry);
          resourceCache.put(resourceName, resourceUrl);
          return resourceUrl;
        } catch (MalformedURLException e) {
          System.out.println(
              "Error making URL for ["
                  + resourceName
                  + "] in jar ["
                  + jarFile
                  + "] in war file ["
                  + outerFile
                  + "]: "
                  + e.toString());
        }
      }
    }
    return super.findResource(resourceName);
  }
Beispiel #16
0
 /** Play a sound file (in .wav or .au format) in a background thread. */
 public static void play(String filename) {
   prePlay();
   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.play();
 }
Beispiel #17
0
  /**
   * Get an Archive entry resource URL.
   *
   * @param resName Entry resource name.
   * @return The entry resource URL, or null if the entry is not in the Archive.
   */
  public URL getEntryURL(String resName) {
    File entry = getEntry(resName);

    if (entry != null) {
      try {
        return entry.toURI().toURL();
      } catch (MalformedURLException e) {
        throw new IllegalStateException(
            "Unexpected error getting URL for Archive file '" + entry.getAbsolutePath() + "'.", e);
      }
    } else {
      return null;
    }
  }
  /**
   * Method updates existing Spring bean definitions in a XML application context file. Bean
   * definition is identified by its type defining class.
   *
   * @param project
   * @param type
   * @param jaxbElement
   */
  public void updateBeanDefinitions(
      File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
      parser.setFilter(getBeanFilter);

      for (File file : configFiles) {
        parser.parseURI(file.toURI().toString());
        if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
          xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

          String beanElement = type.getAnnotation(XmlRootElement.class).name();
          String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_element", beanElement);
          transformer.setParameter("bean_namespace", beanNamespace);
          transformer.setParameter(
              "bean_content",
              getXmlContent(jaxbElement)
                  .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                  .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

          // transform
          StringResult result = new StringResult();
          transformer.transform(xmlSource, result);
          FileUtils.writeToFile(
              format(result.toString(), project.getSettings().getTabSize()), file);
          return;
        }
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Beispiel #19
0
  /** @see java.lang.ClassLoader#findResources(java.lang.String) */
  @Override
  public Enumeration<URL> findResources(String resourceName) throws IOException {
    ArrayList<URL> cachedUrls = resourceAllCache.get(resourceName);
    if (cachedUrls != null) return Collections.enumeration(cachedUrls);

    ArrayList<URL> urlList = new ArrayList<>();
    int classesDirectoryListSize = classesDirectoryList.size();
    for (int i = 0; i < classesDirectoryListSize; i++) {
      File classesDir = classesDirectoryList.get(i);
      File testFile = new File(classesDir.getAbsolutePath() + "/" + resourceName);
      try {
        if (testFile.exists() && testFile.isFile()) urlList.add(testFile.toURI().toURL());
      } catch (MalformedURLException e) {
        System.out.println(
            "Error making URL for ["
                + resourceName
                + "] in classes directory ["
                + classesDir
                + "]: "
                + e.toString());
      }
    }
    int jarFileListSize = jarFileList.size();
    for (int i = 0; i < jarFileListSize; i++) {
      JarFile jarFile = jarFileList.get(i);
      JarEntry jarEntry = jarFile.getJarEntry(resourceName);
      if (jarEntry != null) {
        try {
          String jarFileName = jarFile.getName();
          if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
          urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry));
        } catch (MalformedURLException e) {
          System.out.println(
              "Error making URL for ["
                  + resourceName
                  + "] in jar ["
                  + jarFile
                  + "]: "
                  + e.toString());
        }
      }
    }
    // add all resources found in parent loader too
    Enumeration<URL> superResources = getParent().getResources(resourceName);
    while (superResources.hasMoreElements()) urlList.add(superResources.nextElement());
    resourceAllCache.putIfAbsent(resourceName, urlList);
    // System.out.println("finding all resources with name " + resourceName + " got " + urlList);
    return Collections.enumeration(urlList);
  }
Beispiel #20
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);
  }
Beispiel #21
0
  public static String resolveRelativePath(String relativePath, String base) {
    /*System.out.println("===============");
    System.out.println(relativePath);
    System.out.println(base);*/
    // keep simple cases as they were
    if ((base == null) || (new File(relativePath).isAbsolute())) {
      // System.out.println("1");
      return relativePath;
    }
    if (base.startsWith("http")) {
      try {
        // System.out.println("2a");
        return new URI(base).resolve(relativePath).toString();
      } catch (URISyntaxException ex) {
        ex.printStackTrace();
      }
    }
    if (!(relativePath.startsWith(".."))) {
      // System.out.println("2b");
      File parentFile = new File(base).getParentFile();
      if (parentFile == null) {
        return relativePath;
      }
      URI uri2 = parentFile.toURI();
      String modRelPath = relativePath.replaceAll(" ", "%20");
      // String modRelPath = relativePath;
      try {
        URI absoluteURI = uri2.resolve(modRelPath);
        return new File(absoluteURI).getAbsolutePath();
      } catch (IllegalArgumentException use) {
        use.printStackTrace();
        return relativePath;
      }
    }

    // the relative Path starts with ..
    String UP = ".." + System.getProperty("file.separator");
    String OTHER = "../";
    if (relativePath.startsWith(UP) || relativePath.startsWith(OTHER)) {
      String newBase = new File(base).getParent();
      String newRelative = relativePath.substring(3);
      // System.out.println("3");
      return resolveRelativePath(newRelative, newBase);
    }
    // no can do
    // System.out.println("4");
    return relativePath;
  }
  @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;
  }
Beispiel #23
0
  /**
   * Look inside a jar file, find the plugin.xml file, and use it to determine the name and version
   * of the plugin.
   *
   * @param f The file to investigate.
   * @return A string array containing the plugin name in the first element and the version number
   *     in the second, or null if the filename couldn't be interpreted.
   */
  public static String[] getNameAndVersion(File f) {

    try {
      File temp = unpackPluginXML(f);
      if (temp == null) return null; // Couldn't find the plugin.xml file
      ManifestInfo mi =
          PluginCore.getManager().getRegistry().readManifestInfo(temp.toURI().toURL());
      temp.delete();
      return new String[] {mi.getId(), mi.getVersion().toString()};
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    } catch (ManifestProcessingException e) {
      return null; // Couldn't make sense of the plugin.xml
    }
  }
Beispiel #24
0
 /** Loop a sound file (in .wav or .au format) in a background thread. */
 public static void loop(String filename) {
   if (muted) {
     return;
   }
   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();
   notifyListeners(new AudioEvent(AudioEvent.Type.LOOP));
 }
  @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;
  }
Beispiel #26
0
  /*
      public PomClassLoader(File file, PomLoader pomLoader) throws IOException, XmlPullParserException {
          super(new URL[]{}, null);
          this.pomLoader = pomLoader;
          if (file.getName().endsWith(".xml") || file.getName().endsWith(".pom"))
              setJarFile(file);
          else {
              haveJSLib = false;
              addURL(file.toURI().toURL());
          }
      }
  */
  public PomClassLoader(
      ArtifactRepository localRepo,
      DependencyNode node,
      File file,
      String name,
      PomLoader pomLoader) {
    super(new URL[] {}, null);
    haveJSLib = false;
    jarFile = file;
    try {
      addURL(jarFile.toURI().toURL());
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
    this.name = name;
    pomLoader.add(this);

    includeDependency(localRepo, pomLoader, node.getChildren());
    getJSClassLoader();
  }
  /**
   * Finds bean definition element by id and type in Spring application context and performs
   * unmarshalling in order to return JaxB object.
   *
   * @param project
   * @param id
   * @param type
   * @return
   */
  public <T> T getBeanDefinition(File configFile, Project project, String id, Class<T> type) {
    LSParser parser = XMLUtils.createLSParser();

    GetSpringBeanFilter filter = new GetSpringBeanFilter(id, type);
    parser.setFilter(filter);

    List<File> configFiles = new ArrayList<>();
    configFiles.add(configFile);
    configFiles.addAll(getConfigImports(configFile, project));

    for (File file : configFiles) {
      parser.parseURI(file.toURI().toString());

      if (filter.getBeanDefinition() != null) {
        return createJaxbObjectFromElement(filter.getBeanDefinition());
      }
    }

    return null;
  }
Beispiel #28
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;
  }
  /**
   * Finds all bean definition elements by type and attribute values in Spring application context
   * and performs unmarshalling in order to return a list of JaxB object.
   *
   * @param project
   * @param type
   * @param attributes
   * @return
   */
  public <T> List<T> getBeanDefinitions(
      File configFile, Project project, Class<T> type, Map<String, String> attributes) {
    List<T> beanDefinitions = new ArrayList<T>();

    List<File> importedFiles = getConfigImports(configFile, project);
    for (File importLocation : importedFiles) {
      beanDefinitions.addAll(getBeanDefinitions(importLocation, project, type, attributes));
    }

    LSParser parser = XMLUtils.createLSParser();

    GetSpringBeansFilter filter = new GetSpringBeansFilter(type, attributes);
    parser.setFilter(filter);
    parser.parseURI(configFile.toURI().toString());

    for (Element element : filter.getBeanDefinitions()) {
      beanDefinitions.add(createJaxbObjectFromElement(element));
    }

    return beanDefinitions;
  }
  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();
    }
  }