コード例 #1
1
  /**
   * This method open stream through the current context
   *
   * @param aFileStream file pname to open
   * @return Stream on file specified by aFileStream
   * @throws MalformedURLException
   */
  public URL openStreamUrl(String aFileStream, Class<?> clazz) throws MalformedURLException {
    URL out = ClassLoader.getSystemResource(aFileStream);

    if (out == null) {
      ResourceResolver.LOGGER.info("Default class loader failed (file:" + aFileStream + ") !");
      out = clazz.getResource(aFileStream);
    }

    if (out == null) {
      ResourceResolver.LOGGER.info(
          "ResourceResolver class loader failed (file:" + aFileStream + ") !");
      out = ClassLoader.getSystemResource("/" + aFileStream);
    }

    if (out == null) {
      ResourceResolver.LOGGER.info(
          "ResourceResolver class loader failed (+ /) (file:" + aFileStream + ") !");
      out = clazz.getResource("/" + aFileStream);
    }

    if (out == null) {
      out = resourceResolverHook(aFileStream);
    }

    if (out == null) {
      ResourceResolver.LOGGER.log(Level.SEVERE, "FileNotFoundException");
    }

    if (out != null) {
      ResourceResolver.LOGGER.info("Success found file:" + aFileStream + " !");
    }

    return out;
  }
コード例 #2
1
  /**
   * Setting the internal field {@link #document} directly (bypassing {@link #setDocument(URL)}) is
   * used to deplay the document loading until {@link #ready()}.
   */
  @Override
  protected void initialize(final String[] as) {
    if ("Linux".equals(System.getProperty("os.name")))
      getContext().getResourceManager().setPlatform("linux");

    final Class<?> mc = this.getClass();
    {
      final ResourceMap r = Application.getInstance().getContext().getResourceMap();
      initialScene =
          mc.getResource("/" + r.getResourcesDir() + r.getString("Application.defaultDocument"));
      templateScene =
          mc.getResource("/" + r.getResourcesDir() + r.getString("Application.templateDocument"));
    }

    // schedule the document to load in #ready()
    document = initialScene;
    for (final String p : as) {
      // ignore javaws parameters
      if ("-open".equals(p) || "-print".equals(p)) continue;
      try {
        document = new URL(p);
        break;
      } catch (final MalformedURLException e) {
        final File f = new File(p);
        if (f.canRead())
          try {
            document = f.toURL();
            break;
          } catch (final MalformedURLException e2) {
            log.warn("Cannot load '" + p + "'.", e);
          }
        else log.warn("Cannot load '" + p + "'.", e);
      }
    }
  }
コード例 #3
1
  private NativeLibrary openLibraryImpl(final boolean global) throws URISyntaxException {
    final ClassLoader cl = getClass().getClassLoader();
    System.err.println("CL " + cl);

    String libBaseName = null;
    final Class<?> clazz = this.getClass();
    Uri libUri = null;
    try {
      libUri = Uri.valueOf(clazz.getResource("/libtest1.so"));
    } catch (final URISyntaxException e2) {
      // not found .. OK
    }
    if (null != libUri) {
      libBaseName = "libtest1.so";
    } else {
      try {
        libUri = Uri.valueOf(clazz.getResource("/test1.dll"));
        if (null != libUri) {
          libBaseName = "test1.dll";
        }
      } catch (final URISyntaxException e) {
        // not found
      }
    }
    System.err.println("Untrusted Library (URL): " + libUri);

    if (null != libUri) {
      Uri libDir1 = libUri.getContainedUri();
      System.err.println("libDir1.1: " + libDir1);
      libDir1 = libDir1.getParent();
      System.err.println("libDir1.2: " + libDir1);
      System.err.println("Untrusted Library Dir1 (abs): " + libDir1);
      final Uri absLib = libDir1.concat(Uri.Encoded.cast("natives/" + libBaseName));
      Exception se0 = null;
      NativeLibrary nlib = null;
      try {
        nlib = NativeLibrary.open(absLib.toFile().getPath(), cl);
        System.err.println("NativeLibrary: " + nlib);
      } catch (final SecurityException e) {
        se0 = e;
        if (usesSecurityManager) {
          System.err.println("Expected exception for loading native library");
          System.err.println("Message: " + se0.getMessage());
        } else {
          System.err.println("Unexpected exception for loading native library");
          se0.printStackTrace();
        }
      }
      if (!usesSecurityManager) {
        Assert.assertNull("SecurityException thrown on loading native library", se0);
      } else {
        Assert.assertNotNull("SecurityException not thrown on loading native library", se0);
      }
      return nlib;
    } else {
      System.err.println("No library found");
      return null;
    }
  }
コード例 #4
1
ファイル: PathUtils.java プロジェクト: magicgis/ea
 /**
  * 取得当前类所在的文件
  *
  * @param clazz
  * @return
  */
 public static File getClassFile(Class clazz) {
   URL path =
       clazz.getResource(
           clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) + ".classs");
   if (path == null) {
     String name = clazz.getName().replaceAll("[.]", "/");
     path = clazz.getResource("/" + name + ".class");
   }
   return new File(path.getFile());
 }
コード例 #5
1
 private static String locationFor(String name) throws RemoteException, RemoteException {
   startManagers();
   URL location = CLASS_SERVLET_CONTEXT.getResource("resources/" + name);
   if (location == null && CLASS_JSP_CONTEXT != null) {
     location = CLASS_JSP_CONTEXT.getResource("resources/" + name);
   }
   if (location == null) {
     log.warn(sm.getString("digesterFactory.missingSchema", name));
     return null;
   }
   return location.toExternalForm();
 }
コード例 #6
1
 @NotNull
 @Override
 protected String compute() {
   final Class<JavaFxHtmlPanel> clazz = JavaFxHtmlPanel.class;
   //noinspection StringBufferReplaceableByString
   return new StringBuilder()
       .append("<script src=\"")
       .append(clazz.getResource("scrollToElement.js"))
       .append("\"></script>\n")
       .append("<script src=\"")
       .append(clazz.getResource("processLinks.js"))
       .append("\"></script>\n")
       .toString();
 }
コード例 #7
0
ファイル: Configuration.java プロジェクト: ramtej/zest-java
    @SuppressWarnings("unchecked")
    private <V> V initializeConfigurationInstance(
        ServiceComposite serviceComposite,
        UnitOfWork uow,
        ServiceDescriptor serviceModel,
        String identity)
        throws InstantiationException {
      Module module = api.moduleOf(serviceComposite);
      Usecase usecase = UsecaseBuilder.newUsecase("Configuration:" + me.identity().get());
      UnitOfWork buildUow = module.newUnitOfWork(usecase);

      EntityBuilder<V> configBuilder =
          buildUow.newEntityBuilder(serviceModel.<V>configurationType(), identity);

      // Check for defaults
      String s = identity + ".properties";
      Class<?> type = first(api.serviceDescriptorFor(serviceComposite).types());
      // Load defaults from classpath root if available
      if (type.getResource(s) == null && type.getResource("/" + s) != null) {
        s = "/" + s;
      }
      InputStream asStream = type.getResourceAsStream(s);
      if (asStream != null) {
        try {
          PropertyMapper.map(asStream, (Composite) configBuilder.instance());
        } catch (IOException e1) {
          InstantiationException exception =
              new InstantiationException("Could not read underlying Properties file.");
          exception.initCause(e1);
          throw exception;
        }
      }

      try {
        configBuilder.newInstance();
        buildUow.complete();

        // Try again
        return (V) findConfigurationInstanceFor(serviceComposite, uow);
      } catch (Exception e1) {
        InstantiationException ex =
            new InstantiationException(
                "Could not instantiate configuration, and no Properties file was found ("
                    + s
                    + ")");
        ex.initCause(e1);
        throw ex;
      }
    }
コード例 #8
0
  /**
   * This will try and find a resource of the given name using the bundle from which was originally
   * loaded the given class so as to try and detect if it is jarred. If <code>clazz</code> hasn't
   * been loaded from a bundle class loader, we'll resort to the default class loader mechanism.
   * This will only return <code>null</code> in the case where the resource at <code>resourcePath
   * </code> cannot be located at all.
   *
   * @param clazz Class which class loader will be used to try and locate the resource.
   * @param resourcePath Path of the resource we seek, relative to the class.
   * @return The URL of the resource as we could locate it.
   * @throws IOException This will be thrown if we fail to convert bundle-scheme URIs into
   *     file-scheme URIs.
   */
  public static URL getResourceURL(Class<?> clazz, String resourcePath) throws IOException {
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    URL resourceURL = null;
    if (packageAdmin != null) {
      Bundle bundle = packageAdmin.getBundle(clazz);
      if (bundle != null) {
        final String pathSeparator = "/"; // $NON-NLS-1$
        // We found the appropriate bundle. We'll now try and determine whether the emtl is jarred
        resourceURL = getBundleResourceURL(bundle, pathSeparator, resourcePath);
      }
    }
    /*
     * We couldn't locate either the bundle which loaded the class or the resource. Resort to the class
     * loader and return null if it cannot locate the resource either.
     */
    if (resourceURL == null) {
      resourceURL = clazz.getResource(resourcePath);
    }

    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }
    return resourceURL;
  }
コード例 #9
0
  private String _getJavaScript() throws PortalException {
    String javaScript =
        "/com/liferay/frontend/image/editor/integration/document/library"
            + "/internal/display/context/dependencies"
            + "/edit_with_image_editor_js.ftl";

    Class<?> clazz = getClass();

    URLTemplateResource urlTemplateResource =
        new URLTemplateResource(javaScript, clazz.getResource(javaScript));

    Template template =
        TemplateManagerUtil.getTemplate(
            TemplateConstants.LANG_TYPE_FTL, urlTemplateResource, false);

    template.put("editLanguageKey", LanguageUtil.get(_request, "edit"));

    LiferayPortletResponse liferayPortletResponse = _getLiferayPortletResponse();

    template.put("namespace", liferayPortletResponse.getNamespace());

    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

    template.processTemplate(unsyncStringWriter);

    return unsyncStringWriter.toString();
  }
コード例 #10
0
ファイル: IconUtil.java プロジェクト: Guojin118/MPS-1
  @Nullable
  public static Icon getIcon(@NotNull String path, @NotNull final Class aClass) {
    URL url = aClass.getResource(path);
    if (url == null) {
      return null;
    }

    InputStream inputStream = null;
    try {
      inputStream = URLUtil.openStream(url);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      byte[] buf = new byte[16 * 1024];
      while (true) {
        int readBytes = inputStream.read(buf);
        if (readBytes == -1) {
          break;
        }
        byteArrayOutputStream.write(buf, 0, readBytes);
      }
      return new ImageIcon(byteArrayOutputStream.toByteArray());
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      FileUtil.closeFileSafe(inputStream);
    }
  }
コード例 #11
0
 @Override
 public String get(Class<?> clazz) {
   URL url = clazz.getResource(clazz.getSimpleName() + ".java");
   if (url == null) {
     try {
       url =
           new File("../Shared/src/" + clazz.getName().replace(".", "/") + ".java")
               .toURI()
               .toURL();
     } catch (MalformedURLException e) {
       LOGGER.error("", e);
     }
   }
   if (url != null) {
     try {
       InputStream inputStream = url.openStream();
       if (inputStream == null) {
         return null;
       }
       StringWriter out = new StringWriter();
       IOUtils.copy(inputStream, out);
       return out.toString();
     } catch (IOException e) {
       LOGGER.error("", e);
     }
   }
   return null;
 }
コード例 #12
0
 /**
  * Returns icon for the specified name.
  *
  * @param icon can be either String icon name, ImageIcon, Image, image File or image URL
  * @return icon for the specified name
  */
 public ImageIcon getIcon(final Object icon) {
   if (icon != null) {
     if (icon instanceof String) {
       try {
         if (nearClass != null) {
           return new ImageIcon(nearClass.getResource(path + icon + extension));
         } else {
           return new ImageIcon(new File(path, icon + extension).getAbsolutePath());
         }
       } catch (final Throwable e) {
         Log.warn("Unable to find menu icon for path: " + path + icon + extension, e);
         return null;
       }
     } else if (icon instanceof ImageIcon) {
       return (ImageIcon) icon;
     } else if (icon instanceof Image) {
       return new ImageIcon((Image) icon);
     } else if (icon instanceof File) {
       return new ImageIcon(((File) icon).getAbsolutePath());
     } else if (icon instanceof URL) {
       return new ImageIcon((URL) icon);
     } else {
       Log.warn("Unknown icon object type provided: " + icon);
       return null;
     }
   } else {
     return null;
   }
 }
コード例 #13
0
  /**
   * Get the URI from where the given class was loaded from. Note that this might be pointing to a
   * JAR or a location on the network. If you want the location as a file or directory, use {@link
   * #getClassLocationFile(Class)} or {@link #getClassLocationDir(Class)}.
   *
   * @see #getClassLocationURI(Class)
   * @return The canonical directory or jar file that this class file was loaded from
   * @throws IOException if the canonical directory or jar file cannot be found, or the class was
   *     not loaded from a file:/// URI.
   */
  public URI getClassLocationURI(Class theClass) throws IOException {

    // Get a URL for where this class was loaded from
    String classResourceName = theClass.getName().replace('.', '/') + ".class";
    URL resource = theClass.getResource("/" + classResourceName);
    if (resource == null) throw new IOException("Source of class " + theClass + " not found");
    String resourcePath = null;
    String embeddedClassName = null;
    String protocol = resource.getProtocol();
    boolean isJar = (protocol != null) && (protocol.equals("jar"));
    if (isJar) {
      // Note: DON'T decode as the part-URL is not double-encoded
      // and otherwise %20 -> " " -> new URI() would fail
      resourcePath = resource.getFile();
      embeddedClassName = "!/" + classResourceName;
    } else {
      resourcePath = resource.toExternalForm();
      embeddedClassName = classResourceName;
    }
    int sep = resourcePath.lastIndexOf(embeddedClassName);
    if (sep >= 0) {
      resourcePath = resourcePath.substring(0, sep);
    }

    URI sourceURI;
    try {
      sourceURI = new URI(resourcePath).normalize();
    } catch (URISyntaxException e) {
      throw new IOException("Invalid URI: " + resourcePath);
    }
    classLocationURIs.add(sourceURI);
    return sourceURI;
  }
コード例 #14
0
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    MyClassLocation myLocation = new MyClassLocation();

    File file = myLocation.getClassLocationFile(Aladin.class);

    System.out.println("Result form my location: " + file);

    Class theClass = Aladin.class;
    String classResourceName = theClass.getName().replace('.', '/') + ".class";
    URL resource = theClass.getResource("/" + classResourceName);
    System.out.println("resource: " + resource);

    URL codeSource = theClass.getProtectionDomain().getCodeSource().getLocation();

    System.out.println("code source: " + codeSource);

    // it returns the path to the class that is running
    System.out.println(
        "Class loader 1: " + ClassLoader.getSystemClassLoader().getResource(".").getPath());
    System.out.println(
        "Class loader 2: "
            + ClassLoader.getSystemClassLoader().getResource(classResourceName).getPath());
    resource = Aladin.class.getClassLoader().getResource("/" + classResourceName);
    System.out.println("Class loader 3: " + resource);
  }
コード例 #15
0
ファイル: SLTestRunner.java プロジェクト: smarr/truffle
 public static Path getRootViaResourceURL(final Class<?> c, String[] paths) {
   URL url = c.getResource(c.getSimpleName() + ".class");
   if (url != null) {
     char sep = File.separatorChar;
     String externalForm = url.toExternalForm();
     String classPart = sep + c.getName().replace('.', sep) + ".class";
     String prefix = null;
     String base;
     if (externalForm.startsWith("jar:file:")) {
       prefix = "jar:file:";
       int bang = externalForm.indexOf('!', prefix.length());
       Assume.assumeTrue(bang != -1);
       File jarfilePath = new File(externalForm.substring(prefix.length(), bang));
       Assume.assumeTrue(jarfilePath.exists());
       base = explodeJarToTempDir(jarfilePath);
     } else if (externalForm.startsWith("file:")) {
       prefix = "file:";
       base = externalForm.substring(prefix.length(), externalForm.length() - classPart.length());
     } else {
       return null;
     }
     for (String path : paths) {
       String candidate = base + sep + path;
       if (new File(candidate).exists()) {
         return FileSystems.getDefault().getPath(candidate);
       }
     }
   }
   return null;
 }
コード例 #16
0
 /**
  * Constructs the absolute paths to the given files, so they can be passed as arguments to the
  * compiler.
  */
 public static String[] sources(Class<?> klass, String... files) throws URISyntaxException {
   String[] result = new String[files.length];
   for (int i = 0; i < result.length; i++) {
     result[i] = new File(klass.getResource("/" + files[i]).toURI()).getAbsolutePath();
   }
   return result;
 }
コード例 #17
0
  @Override
  public String getVersion() {
    Class<BricketApplication> clazz = BricketApplication.class;
    String classPath = clazz.getResource(clazz.getSimpleName() + ".class").toString();
    if (!classPath.startsWith("jar")) {
      // class not from JAR
      return UNKNOWN_VERSION;
    }

    try {
      String manifestPath =
          classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
      Manifest manifest = new Manifest(new URL(manifestPath).openStream());
      Attributes attr = manifest.getMainAttributes();
      String version = attr.getValue(Name.IMPLEMENTATION_VERSION);
      return version != null ? version : UNKNOWN_VERSION;
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return UNKNOWN_VERSION;
  }
コード例 #18
0
  @Override
  protected URL getUrl(HttpServletRequest request) {
    String ctxPath = request.getContextPath();
    String reqPath = request.getRequestURI();
    reqPath = reqPath.substring(ctxPath.length());

    // try a few lookups
    URL url = clazz.getResource(reqPath);
    if (url == null && !reqPath.startsWith("/")) {
      url = clazz.getResource("/");
    }
    if (url == null && (reqPath.length() > 1) && reqPath.startsWith("/")) {
      url = clazz.getResource(reqPath.substring(1));
    }
    return url;
  }
コード例 #19
0
ファイル: VersionService.java プロジェクト: cschmack/nexgen
  protected static String getClassJarVersion(Class<?> clazz) {
    StringBuilder output = new StringBuilder();

    String path = clazz.getResource(clazz.getSimpleName() + ".class").toString();
    LOGGER.debug("Output: {}, path: {}", output, path);
    boolean unknown = true;
    if (path.startsWith("jar")) {
      String manifestPath = path.replaceFirst("\\!.*", "!/META-INF/MANIFEST.MF");
      try {
        LOGGER.debug("manifestPath: {}", manifestPath);
        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        LOGGER.debug("manifest main attributes: {}", manifest.getMainAttributes().toString());

        String value = manifest.getMainAttributes().getValue(IMPL_VER);
        if (value != null) {
          output.append(value);
          unknown = false;
        }

        if (LOGGER.isDebugEnabled()) {
          for (Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) {
            LOGGER.debug("entry = {} value = {}", entry.getKey(), entry.getValue());
          }
        }

      } catch (Exception e) {
        LOGGER.debug("Error Loading Manifest", e);
      }
    }
    if (unknown) {
      output.append("unknown");
    }
    return output.toString();
  }
コード例 #20
0
ファイル: FileUtil.java プロジェクト: johnyauyo/JMRTD
  /**
   * Gets the base directory where class <code>c</code> resides.
   *
   * @param c a class
   * @return the base directory
   */
  public static URL getBaseDir(Class<?> c) {
    try {
      String className = c.getCanonicalName();
      if (className == null) {
        className = c.getName();
      }
      String pathToClass = "/" + className.replace(".", "/") + ".class";
      URL url = c.getResource(pathToClass);

      String protocol = url.getProtocol().toLowerCase();
      String host = url.getHost().toLowerCase();
      String dirString = url.getFile();
      int classNameIndex = dirString.indexOf(pathToClass);
      String basePathString = dirString.substring(0, classNameIndex);
      if (basePathString.endsWith("/bin")
          || basePathString.endsWith("/bin/")
          || basePathString.endsWith("/build")
          || basePathString.endsWith("/build/")) {
        basePathString = (new File(basePathString)).getParent();
      }
      URL basePathURL = new URL(protocol, host, basePathString);
      return basePathURL;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #21
0
  public static List<String> validateClass(Class<? extends Messages> classUnderTest)
      throws URISyntaxException, IOException {
    List<String> errors = new ArrayList<String>();

    if (classUnderTest.isInterface()) {
      File messagesDir =
          new File(classUnderTest.getResource(".").toURI().toASCIIString().replaceAll("file:", ""));
      List<Method> messagesMethods = Arrays.asList(classUnderTest.getMethods());

      File[] propertiesFiles =
          getMessagesPropertiesFiles(messagesDir, classUnderTest.getSimpleName());
      if (propertiesFiles != null) {
        for (File localeFile : propertiesFiles) {
          PropertiesFileInfo.properties = loadProperties(localeFile);
          PropertiesFileInfo.fileName = localeFile.getName();

          for (Method method : messagesMethods) {
            checkForMissingDefault(method, errors);
            checkPlaceHolders(method, errors);
          }
        }
      }
    } else {
      errors.add("Class under test is not an interface: " + classUnderTest.getName());
    }

    return errors;
  }
コード例 #22
0
  @Test
  public void testLoadFromJar() throws Exception {
    File jar = Files.createTempFile("battlecode-test", ".jar").toFile();

    jar.deleteOnExit();

    ZipOutputStream z = new ZipOutputStream(new FileOutputStream(jar));

    ZipEntry classEntry = new ZipEntry("instrumentertest/Nothing.class");

    z.putNextEntry(classEntry);

    IOUtils.copy(
        getClass().getClassLoader().getResourceAsStream("instrumentertest/Nothing.class"), z);

    z.closeEntry();
    z.close();

    IndividualClassLoader jarLoader =
        new IndividualClassLoader(
            "instrumentertest", new IndividualClassLoader.Cache(jar.toURI().toURL()));

    Class<?> jarClass = jarLoader.loadClass("instrumentertest.Nothing");

    URL jarClassLocation = jarClass.getResource("Nothing.class");

    // EXTREMELY scientific

    assertTrue(jarClassLocation.toString().startsWith("jar:"));
    assertTrue(jarClassLocation.toString().contains(jar.toURI().toURL().toString()));
  }
コード例 #23
0
  /**
   * Create a splash screen (borderless graphic for display while other operations are taking
   * place).
   *
   * @param filename a class-relative path to the splash graphic
   * @param callingClass the class to which the graphic filename location is relative
   */
  public SplashScreen(String filename, Class callingClass) {
    super(new Frame());
    URL imageURL = callingClass.getResource(filename);
    image = Toolkit.getDefaultToolkit().createImage(imageURL);
    // Load the image
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
      mt.waitForID(0);
    } catch (InterruptedException ie) {
    }

    // Center the window on the screen
    int imgWidth = image.getWidth(this);
    int imgHeight = image.getHeight(this);
    setSize(imgWidth, imgHeight);
    Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((screenDim.width - imgWidth) / 2, (screenDim.height - imgHeight) / 2);

    setVisible(true);
    repaint();
    // if on a single processor machine, wait for painting (see Fast Java Splash Screen.pdf)
    if (!EventQueue.isDispatchThread()) {
      synchronized (this) {
        while (!this.paintCalled) {
          try {
            this.wait();
          } catch (InterruptedException e) {
          }
        }
      }
    }
  }
コード例 #24
0
 /**
  * Get's data from XML file in classpath in specified format.<br>
  * First search the
  *
  * @param className ClassName
  * @param context The context.
  */
 public HierarchicalConfiguration getData(
     final String className, HierarchicalConfiguration context) {
   HierarchicalConfiguration dataForTestCase = null;
   try {
     Class<?> clazz = Class.forName(className);
     String dataFilePath = null;
     URL dataFileURL = null;
     boolean packageFile = false;
     Map<String, HierarchicalConfiguration> dataMap = null;
     String dataFileName = context.getString("supplier.dataFile", null);
     log.debug("Checking the data file in argument...");
     if (dataFileName == null || dataFileName.equals("")) {
       log.debug("Data file not given in argument..Using DataFileFinder..");
       dataFilePath = DDUtils.findDataFile(className, ".xml", context);
     } else {
       log.debug("Got data file in argument");
       dataFilePath = dataFileName;
     }
     log.debug("Data file path: " + dataFilePath);
     if (dataFilePath == null) {
       return null; // No data found, hence it's a normal test case.
     }
     dataFileURL = clazz.getResource(dataFilePath);
     if (packageFile) {
       // The data file is from package file name so check the cache.
       log.debug("Cache: " + cache.size());
       synchronized (XMLDataSupplier.class) {
         if (loadedFiles.contains(dataFilePath)) { // get it from cache.
           log.info("File was loaded before !!!");
           dataForTestCase = cache.get(clazz.getName());
         } else { // not in cache, so load and put it to cache.
           log.info("File was not loaded before, loading now...");
           if (dataFileURL != null) {
             cache.putAll(XMLDataParser.load(dataFileURL, clazz));
           } else {
             cache.putAll(XMLDataParser.load(dataFilePath, clazz));
           }
           dataForTestCase = cache.get(clazz.getName());
           loadedFiles.add(dataFilePath);
         }
       }
       if ((dataForTestCase == null) || dataForTestCase.isEmpty()) {
         log.info("Data for '{}' is not available!", className);
         return null;
       }
     } else { // data file not from package file so go ahead and load.
       log.debug("Loading the xml file...");
       if (dataFileURL != null) {
         dataMap = XMLDataParser.load(dataFileURL, clazz);
       } else {
         dataMap = XMLDataParser.load(dataFilePath, clazz);
       }
       dataForTestCase = dataMap.get(clazz.getName());
     }
   } catch (Exception ex) {
     throw new DDException("Error in loading the data file", ex);
   }
   return dataForTestCase;
 }
コード例 #25
0
ファイル: ClassUtil.java プロジェクト: huangyunbin/codes
 public static File getFileOfClass(Class<?> clazz) {
   try {
     return new File(clazz.getResource(clazz.getSimpleName() + CLASS_FILE_EXTENSION).toURI());
   } catch (URISyntaxException e) {
     logger.error("Error occured while getting file of class " + clazz.getName(), e);
     return null;
   }
 }
コード例 #26
0
 public ImageIcon loadImage(Class cl, String name) {
   URL url = cl.getResource(name);
   ImageIcon icon = null;
   if (url != null) {
     icon = new ImageIcon(url);
   }
   return icon;
 }
コード例 #27
0
  /**
   * Look on the classpath for the named file. Will look at the root package and in the same package
   * as testClass.
   *
   * @param testClass class to look relative to.
   * @param fileName name of file to find. Can be a path.
   */
  public static File getFile(Class<?> testClass, String fileName) {
    final URL resource = testClass.getResource(fileName);
    if (resource == null) {
      throw new AssertionError("Unable to find test resource: " + fileName);
    }

    return new File(resource.getFile());
  }
コード例 #28
0
 public static URL localResource(Class<?> clazz, String location) {
   URL u = clazz.getResource(location);
   if (u == null) {
     throw new IllegalArgumentException(
         String.format(
             "Local resource '%s' from class '%s' does not exist", location, clazz.getName()));
   }
   return u;
 }
コード例 #29
0
 public PropertyResourceResolver(Class<? extends ResourceBundle> bundleClass) {
   this.bundleClass = bundleClass;
   String strippedName = Util.stripPackage(bundleClass);
   URL url = bundleClass.getResource(strippedName + ".properties");
   boolean foundProperties;
   if (url == null) {
     log.debug(
         "No resource {} for bundle {}, trying class name as base URL",
         strippedName + ".properties",
         bundleClass);
     foundProperties = false;
     url = bundleClass.getResource(strippedName + ".class");
   } else {
     foundProperties = true;
   }
   this.baseUrl = url;
   log.debug("Base URL for {} is {}", bundleClass, url);
   if (foundProperties) {
     InputStream stream = null;
     try {
       stream = new BufferedInputStream(url.openStream());
       stream = new BufferedInputStream(stream);
       Reader reader;
       try {
         reader = new InputStreamReader(stream, "UTF-8");
       } catch (UnsupportedEncodingException e) {
         throw new UnexpectedException(e);
       }
       properties.load(reader);
     } catch (IOException e) {
       throw new I18NException(
           "Error reading resource " + strippedName + " for " + bundleClass, e);
     } finally {
       if (stream != null) {
         try {
           stream.close();
         } catch (Exception e) {
           log.warn(
               "Error closing stream from resource " + strippedName + " for " + bundleClass, e);
         }
       }
     }
   }
 }
コード例 #30
0
  /**
   * Ce qui charge les natives
   *
   * @param c une classe
   */
  private static void loadNatives(Class c) {
    final File jarFile = new File(c.getProtectionDomain().getCodeSource().getLocation().getPath());
    final String path = "res/native/";

    if (jarFile.isFile()) {
      try {
        // Run with JAR file
        final JarFile jar = new JarFile(jarFile);

        final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
        final String nativeFolderPath = jarFile.getParent() + "/native/";
        final File nativeFolder = new File(nativeFolderPath);
        nativeFolder.delete();
        nativeFolder.mkdir();

        while (entries.hasMoreElements()) {
          final String name = entries.nextElement().getName();

          if (name.startsWith(path)) { // filter according to the path
            Object temp = null;

            InputStream is = c.getResourceAsStream("/" + name);
            String nativeName = name.replace(path, "");
            File nativePath = new File(nativeFolderPath + nativeName);
            if (!nativeName.isEmpty()) {
              System.out.println("Extracting: " + nativeName);
              OutputStream os = null;
              try {
                os = new FileOutputStream(nativePath);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                  os.write(buffer, 0, length);
                }
              } finally {
                is.close();
                os.close();
              }
            }
          }
        }
        jar.close();

        System.setProperty("org.lwjgl.librarypath", nativeFolderPath);
      } catch (IOException ex) {
        Logger.getLogger(c.getName()).log(Level.SEVERE, null, ex);
      }
    } else {
      try {
        System.setProperty(
            "org.lwjgl.librarypath", new File(c.getResource("/" + path).toURI()).getAbsolutePath());
      } catch (URISyntaxException ex) {
        Logger.getLogger(c.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }