Beispiel #1
1
  public void addExtension(Class<?> loadResourcesUsing, String loadFrom) throws IOException {
    // Is loadFrom a file?
    File file = new File(loadFrom);
    if (file.exists()) {
      addExtension(file);
      return;
    }

    // Try and load it from the classpath
    InputStream resource = loadResourcesUsing.getResourceAsStream(loadFrom);
    if (resource == null && !loadFrom.startsWith("/")) {
      resource = loadResourcesUsing.getResourceAsStream("/" + loadFrom);
    }
    if (resource == null) {
      resource = FirefoxProfile.class.getResourceAsStream(loadFrom);
    }
    if (resource == null && !loadFrom.startsWith("/")) {
      resource = FirefoxProfile.class.getResourceAsStream("/" + loadFrom);
    }
    if (resource == null) {
      throw new FileNotFoundException("Cannot locate resource with name: " + loadFrom);
    }

    File root;
    if (FileHandler.isZipped(loadFrom)) {
      root = FileHandler.unzip(resource);
    } else {
      throw new RuntimeException("Will only install zipped extensions for now");
    }

    addExtension(root);
  }
  /** Tests loading a resource with a global name. */
  @TestTargetNew(
      level = TestLevel.PARTIAL_COMPLETE,
      notes = "",
      method = "getResourceAsStream",
      args = {java.lang.String.class})
  public void testGetResourceAsStream2() throws IOException {
    Class clazz = getClass();

    InputStream stream =
        clazz.getResourceAsStream("/org/apache/harmony/luni/tests/java/lang/HelloWorld.txt");
    assert (stream != null);

    byte[] buffer = new byte[20];
    int length = stream.read(buffer);
    String s = new String(buffer, 0, length);
    assert ("Hello, World.".equals(s));

    stream.close();

    try {
      clazz.getResourceAsStream(null);
      fail("NullPointerException is not thrown.");
    } catch (NullPointerException npe) {
      // expected
    }
    assertNull(clazz.getResourceAsStream("/NonExistentResource"));
    assertNull(clazz.getResourceAsStream("org/apache/harmony/luni/tests/java/lang/HelloWorld.txt"));
  }
  /*--------------------------------------------------------------------------*/
  private InputStream openInputStream(String name, NativeLibraryClient client) throws Exception {
    Class clientClass = client.getClass();
    // ----------------------------------------------------
    // try to open an input stream, assuming the library
    // is located with the client
    // ----------------------------------------------------
    InputStream input = clientClass.getResourceAsStream(name + extension);

    // ----------------------------------------------------
    // if this is not successful, try to load from the
    // location where all native libraries are supposed
    // to be located.
    // ----------------------------------------------------
    if (input == null) {
      input = clientClass.getResourceAsStream('/' + nativeDirectory + '/' + name + extension);
    }

    // ----------------------------------------------------
    // if this fails as well, throw an exception
    // ----------------------------------------------------
    if (input == null) {
      throw (new Exception("can't locate library"));
    } else {
      return (input);
    }
  }
Beispiel #4
1
 public static InputStream getSeleniumResourceAsStream(String resourceFile) {
   Class clazz = LauncherUtils.class;
   InputStream input = clazz.getResourceAsStream(resourceFile);
   if (input == null) {
     try {
       // This is hack for the OneJar version of Selenium-Server.
       // Examine the contents of the jar made by
       // https://svn.openqa.org/svn/selenium-rc/trunk/selenium-server-onejar/build.xml
       clazz = Class.forName("OneJar");
       input = clazz.getResourceAsStream(resourceFile);
     } catch (ClassNotFoundException e) {
     }
   }
   return input;
 }
  /**
   * Get an InputStream for a particular file name - first check the sakai.home area and then revert
   * to the classpath.
   *
   * <p>This is a utility method used several places.
   */
  public static java.io.InputStream getConfigStream(String fileName, Class curClass) {
    // Within Sakai default path is usually tomcat/sakai/file.properties
    // Sakai deployers can move this.

    // When we area not in Sakai's JVM, this may be several places
    // depending on the JVM/OS, etc
    //  - the directory where we started Tomcat
    //  - the user's hojme directory
    //  - the root directory of the system
    // Also the user can start the portal JVN with -Dsakai.home= to force this path

    String sakaiHome = System.getProperty("sakai.home");
    String filePath = sakaiHome + fileName;
    // System.out.println("filePath="+filePath);

    try {
      java.io.File f = new java.io.File(filePath);
      if (f.exists()) {
        return new java.io.FileInputStream(f);
      }
    } catch (Throwable t) {
      // Not found in the sakai.home area
    }

    // See if we can find this property file relative to a  class loader
    if (curClass == null) return null;

    java.io.InputStream istream = null;

    // TODO: Figure out *where* the file really needs to go to
    // trigger this first section of code. It would be cool
    // to have this be shared/lib or somewhere - I just cannot
    // figure this out at this point - Chuck

    // Load from the class loader
    istream = curClass.getClassLoader().getResourceAsStream(fileName);
    if (istream != null) return istream;

    // Load from the webapp class relative
    // tomcat/webapps/sakai-webapp/WEB-INF/classes/org/sakaiproject/this/class/file.properties
    istream = curClass.getResourceAsStream(fileName);
    if (istream != null) return istream;

    // Loading from the webapp class at the root
    // tomcat/webapps/sakai-webapp/WEB-INF/classes/file.properties
    istream = curClass.getResourceAsStream("/" + fileName);
    return istream;
  }
 private void copyCustomCssIfDefined() {
   final Class<?> cssClass = customCssPackage();
   final String customCss = customCss();
   if (cssClass == null || customCss == null) {
     return;
   }
   final InputStream cssInputFile = cssClass.getResourceAsStream(customCss);
   final String cssPackageName = cssClass.getPackage().getName();
   final String cssPackagePath = asPath(cssPackageName);
   final String cssOutputFileName =
       StringUtils.combinePaths(outputDir(), cssPackagePath, customCss);
   try {
     final ByteArrayOutputStream baos = new ByteArrayOutputStream();
     IoUtils.copy(cssInputFile, baos);
     if (baos.size() > 0) {
       IoUtils.copy(
           new ByteArrayInputStream(baos.toByteArray()), new FileOutputStream(cssOutputFileName));
     }
   } catch (final IllegalArgumentException e) {
     System.err.printf("failed to copy custom CSS to '%s'\n", customCss, cssOutputFileName);
     return;
   } catch (final IOException e) {
     System.err.printf("failed to copy custom CSS '%s' to '%s'\n", customCss, cssOutputFileName);
     return;
   }
 }
 static String loadTextResource(Class<?> clazz, String path) {
   try {
     return CharStreams.toString(new InputStreamReader(clazz.getResourceAsStream(path), UTF_8));
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Beispiel #8
0
 private static Properties loadProperties(Class clazz, String resourcePath) throws IOException {
   InputStream is = clazz.getResourceAsStream(resourcePath);
   Properties prop = new Properties();
   prop.load(is);
   is.close();
   return prop;
 }
Beispiel #9
0
 public InputStream getInputStream(URI uri) throws IOException {
   InputStream resourceAsStream = clazz.getResourceAsStream(getPath(uri));
   if (resourceAsStream != null) {
     return resourceAsStream;
   }
   throw new FileNotFoundException(uri.toString());
 }
Beispiel #10
0
  /**
   * 根据具体模板生成文件
   *
   * @param templateFileName
   * @param paraMap
   * @param filePath
   */
  public void createFileByTemplete(
      String templateFileName, Map<String, Object> paraMap, String filePath) {
    try {
      Class<?> classes = Class.forName("com.platform.tools.code.GenerateBase");

      InputStream controllerInputStream = classes.getResourceAsStream(templateFileName);
      int count = 0;
      while (count == 0) {
        count = controllerInputStream.available();
      }

      byte[] bytes = new byte[count];
      int readCount = 0; // 已经成功读取的字节的个数
      while (readCount < count) {
        readCount += controllerInputStream.read(bytes, readCount, count - readCount);
      }

      String template = new String(bytes);

      String javaSrc = BeetlKit.render(template, paraMap);

      File file = new File(filePath);

      File path = new File(file.getParent());
      if (!path.exists()) {
        path.mkdirs();
      }

      BufferedWriter output = new BufferedWriter(new FileWriter(file));
      output.write(javaSrc);
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** Loads the resources */
  void initResources() {
    final Class<ControlExample> clazz = ControlExample.class;
    if (resourceBundle != null) {
      try {
        if (images == null) {
          images = new Image[imageLocations.length];

          for (int i = 0; i < imageLocations.length; ++i) {
            InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i]);
            ImageData source = new ImageData(sourceStream);
            if (imageTypes[i] == SWT.ICON) {
              ImageData mask = source.getTransparencyMask();
              images[i] = new Image(null, source, mask);
            } else {
              images[i] = new Image(null, source);
            }
            try {
              sourceStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return;
      } catch (Throwable t) {
      }
    }
    String error =
        (resourceBundle != null)
            ? getResourceString("error.CouldNotLoadResources")
            : "Unable to load resources"; //$NON-NLS-1$
    freeResources();
    throw new RuntimeException(error);
  }
    @Nullable
    public Image load() throws IOException {
      String cacheKey = null;
      InputStream stream = null;
      URL url = null;
      if (cls != null) {
        //noinspection IOResourceOpenedButNotSafelyClosed
        stream = cls.getResourceAsStream(path);
        if (stream == null) return null;
      }
      if (stream == null) {
        cacheKey = path;
        Image image = ourCache.get(cacheKey);
        if (image != null) return image;

        url = new URL(path);
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpURLConnection) {
          if (!original) return null;
          connection.addRequestProperty("User-Agent", "IntelliJ");
        }
        stream = connection.getInputStream();
      }
      Image image = type.load(url, stream, scale);
      if (image != null && cacheKey != null) {
        ourCache.put(cacheKey, image);
      }
      return image;
    }
Beispiel #13
0
  /**
   * Helper method that will try to load version information for specified class. Implementation is
   * simple: class loader that loaded specified class is asked to load resource with name "VERSION"
   * from same location (package) as class itself had. If no version information is found, {@link
   * Version#unknownVersion()} is returned.
   */
  public static Version versionFor(Class<?> cls) {
    InputStream in;
    Version version = null;

    try {
      in = cls.getResourceAsStream(VERSION_FILE);
      if (in != null) {
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
          String groupStr = null, artifactStr = null;
          String versionStr = br.readLine();
          if (versionStr != null) {
            groupStr = br.readLine();
            if (groupStr != null) {
              groupStr = groupStr.trim();
              artifactStr = br.readLine();
              if (artifactStr != null) {
                artifactStr = artifactStr.trim();
              }
            }
          }
          version = parseVersion(versionStr, groupStr, artifactStr);
        } finally {
          try {
            in.close();
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
      }
    } catch (IOException e) {
    }
    return (version == null) ? Version.unknownVersion() : version;
  }
  public static Properties loadProperties(Class<?> clazz, String name, String extraProperty)
      throws IOException {
    Closer closer = Closer.create();
    Properties prop = new Properties();
    try {
      InputStream in = closer.register(clazz.getResourceAsStream(name));
      prop.load(in);
      String extraPath = System.getProperty(extraProperty);
      if (extraPath != null) {
        log.info(
            "Loading extra properties for "
                + clazz.getCanonicalName()
                + ":"
                + name
                + " from "
                + extraPath
                + "...");
        in =
            closer.register(
                new BufferedInputStream(closer.register(new FileInputStream(extraPath))));
        prop.load(in);
      }
    } finally {
      closer.close();
    }

    return prop;
  }
  /**
   * Obtains the {@link XmlMarshaller} for the Class of the Model.
   *
   * @param modelClass Class of the Model.
   * @return {@link XmlMarshaller} for the Model.
   * @throws Exception If fails to obtain the {@link XmlMarshaller}.
   */
  private XmlMarshaller obtainMarshaller(Class<?> modelClass) throws Exception {
    // Obtain the xml marshaller to save office (lazy load)
    XmlMarshaller marshaller = null;
    synchronized (this) {
      // Attempt to obtain from registry
      marshaller = this.marshallers.get(modelClass);
      if (marshaller == null) {
        // Obtain input stream to configuration of marshaller
        InputStream configuration = modelClass.getResourceAsStream("MarshallConfiguration.xml");
        if (configuration == null) {
          throw new IllegalStateException(
              "Unable to configure storing the model type "
                  + modelClass.getName()
                  + ". Can not find MarshallConfiguration.xml");
        }

        // Specify the marshaller
        marshaller = TreeXmlMarshallerFactory.getInstance().createMarshaller(configuration);

        // Register the marshaller
        this.marshallers.put(modelClass, marshaller);
      }
    }

    // Return the marshaller
    return marshaller;
  }
  protected String read(String fileName) throws IOException {
    Class<?> clazz = getClass();

    InputStream inputStream = clazz.getResourceAsStream("dependencies/" + fileName);

    return StringUtil.read(inputStream);
  }
Beispiel #17
0
  public static String load(Class<? extends Template> type) {
    com.vercer.leaf.annotation.Template annotation =
        type.getAnnotation(com.vercer.leaf.annotation.Template.class);
    String name;
    if (annotation != null) {
      name = annotation.value();
    } else {
      name = type.getSimpleName() + ".html";
    }

    InputStream stream = type.getResourceAsStream(name);
    if (stream == null) {
      return null;
    }

    String text;
    try {
      text = CharStreams.toString(new InputStreamReader(stream));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    try {
      stream.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // remove windows carriage returns
    text = text.replaceAll("\r", "");

    return text;
  }
Beispiel #18
0
  /**
   * Loads a design for the given root component.
   *
   * <p>This methods assumes that the component class (or a super class) has been marked with an
   * {@link DesignRoot} annotation and will either use the value from the annotation to locate the
   * design file, or will fall back to using a design with the same same as the annotated class file
   * (with an .html extension)
   *
   * <p>Any {@link Component} type fields in the root component which are not assigned (i.e. are
   * null) are mapped to corresponding components in the design. Matching is done based on field
   * name in the component class and id/local id/caption in the design file.
   *
   * <p>The type of the root component must match the root element in the design
   *
   * @param rootComponent The root component of the layout
   * @return The design context used in the load operation
   * @throws DesignException If the design could not be loaded
   */
  public static DesignContext read(Component rootComponent) throws DesignException {
    // Try to find an @DesignRoot annotation on the class or any parent
    // class
    Class<? extends Component> annotatedClass =
        findClassWithAnnotation(rootComponent.getClass(), DesignRoot.class);
    if (annotatedClass == null) {
      throw new IllegalArgumentException(
          "The class "
              + rootComponent.getClass().getName()
              + " or any of its superclasses do not have an @DesignRoot annotation");
    }

    DesignRoot designAnnotation = annotatedClass.getAnnotation(DesignRoot.class);
    String filename = designAnnotation.value();
    if (filename.equals("")) {
      // No value, assume the html file is named as the class
      filename = annotatedClass.getSimpleName() + ".html";
    }

    InputStream stream = annotatedClass.getResourceAsStream(filename);
    if (stream == null) {
      throw new DesignException(
          "Unable to find design file "
              + filename
              + " in "
              + annotatedClass.getPackage().getName());
    }

    Document doc = parse(stream);
    DesignContext context = designToComponentTree(doc, rootComponent, annotatedClass);

    return context;
  }
  /**
   * Obtains the {@link XmlUnmarshaller} for the Class of the Model.
   *
   * @param modelClass Class of the model.
   * @return {@link XmlUnmarshaller} for the Model.
   * @throws Exception If fails to obtain the {@link XmlUnmarshaller}.
   */
  private XmlUnmarshaller obtainUnmarshaller(Class<?> modelClass) throws Exception {
    // Obtain the xml unmarshaller to load model (lazy load)
    XmlUnmarshaller unmarshaller = null;
    synchronized (this) {
      // Attempt to obtain from registry
      unmarshaller = this.unmarshallers.get(modelClass);
      if (unmarshaller == null) {
        // Obtain input stream to configuration of marshaller
        InputStream unmarshallConfig =
            modelClass.getResourceAsStream("UnmarshallConfiguration.xml");
        if (unmarshallConfig == null) {
          throw new IllegalStateException(
              "Unable to configure retrieving the model type " + modelClass.getName());
        }

        // Specify the unmarshaller
        unmarshaller =
            TreeXmlUnmarshallerFactory.getInstance().createUnmarshaller(unmarshallConfig);

        // Register the unmarshaller
        this.unmarshallers.put(modelClass, unmarshaller);
      }
    }

    // Return the unmarshaller
    return unmarshaller;
  }
Beispiel #20
0
 /**
  * Loads the specified resource for the class' package and returns a {@code BuildInfo} object
  * representing data stored in the resource. Obtained from <a
  * href="http://forum.java.sun.com/thread.jspa?threadID=584408&amp;messageID=3012258">Sun's Java
  * Forum</a>
  *
  * @param resource the resource containing the build date
  * @param c A class in the package containing the resource
  * @return a {@code BuildInfo} object containing the information stored in the resource, or {@code
  *     null} if the resource can't be found.
  */
 public static BuildInfo make(String resource, Class<? extends Object> c) {
   BuildInfo retValue = null;
   try {
     Properties p = new Properties();
     InputStream is = c.getResourceAsStream(resource);
     if (is != null) {
       p.load(is);
       String buildDateString = p.getProperty("builddate");
       Date buildDate;
       try {
         buildDate =
             buildDateString == null
                 ? null
                 : new SimpleDateFormat("yyyy.MM.dd HH.mm.ss").parse(buildDateString);
       } catch (ParseException e) {
         throw new InvalidBuildInfoFile(
             "Date in properties file won't parse: \"" + buildDateString + "\"");
       }
       retValue = new BuildInfo(buildDate, p.getProperty("version"));
     } else {
       throw new InvalidBuildInfoFile(
           "Build info resource file \""
               + resource
               + "\" does not exist for class "
               + c.getName()
               + ".");
     }
   } catch (IOException e) {
     return null;
   }
   return retValue;
 }
Beispiel #21
0
  /** Gets an XSLT template from the given resource location. */
  public static Templates getStylesheet(String resourcePath, Class<?> sourceClass) {
    InputStream xsltStream;
    if (sourceClass == null) {
      try {
        xsltStream = new FileInputStream(resourcePath);
      } catch (IOException exc) {
        LOGGER.debug("Could not open file", exc);
        return null;
      }
    } else {
      xsltStream = sourceClass.getResourceAsStream(resourcePath);
    }

    try {
      StreamSource xsltSource = new StreamSource(xsltStream);
      // Java XML factories are not declared to be thread safe
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      transformerFactory.setErrorListener(new XMLListener());
      return transformerFactory.newTemplates(xsltSource);
    } catch (TransformerConfigurationException exc) {
      LOGGER.debug("Could not construct template", exc);
    } finally {
      try {
        if (xsltStream != null) xsltStream.close();
      } catch (IOException e) {
        LOGGER.debug("Could not close file", e);
      }
    }
    return null;
  }
Beispiel #22
0
 /** Loads the image resources. */
 public void initResources() {
   final Class clazz = PaintExample.class;
   if (PaintExample.resourceBundle != null)
     try {
       for (int i = 0; i < PaintExample.tools.length; ++i) {
         Tool tool = PaintExample.tools[i];
         String id = tool.group + '.' + tool.name;
         InputStream sourceStream =
             clazz.getResourceAsStream(PaintExample.getResourceString(id + ".image"));
         ImageData source = new ImageData(sourceStream);
         ImageData mask = source.getTransparencyMask();
         tool.image = new Image(null, source, mask);
         try {
           sourceStream.close();
         } catch (IOException e) {
           e.printStackTrace();
         }
       }
       return;
     } catch (Throwable t) {
     }
   String error =
       PaintExample.resourceBundle != null
           ? PaintExample.getResourceString("error.CouldNotLoadResources")
           : "Unable to load resources";
   freeResources();
   throw new RuntimeException(error);
 }
  /**
   * This extracts the given class' resource to the specified file if it doesn't already exist.
   *
   * @param resourceClass the class associated with the resource
   * @param name the resource's name
   * @param file where to put the resource
   * @return true if successful, false if not.
   */
  public boolean extractResourceAsFile(Class resourceClass, String name, File file) {
    InputStream stream = resourceClass.getResourceAsStream(name);
    if (stream == null) {
      return false;
    }

    byte[] bytes = new byte[0];
    try {
      bytes = IOUtils.toByteArray(stream);
    } catch (IOException e) {
      logger.error("Extracting resource as file", e);
      return false;
    }

    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(file);
      IOUtils.write(bytes, fileOutputStream);
      return true;
    } catch (IOException e) {
      logger.error("Extracting resource as file (writing bytes)", e);
      return false;
    } finally {
      IOUtils.closeQuietly(fileOutputStream);
    }
  }
  /**
   * This method open stream through the current context
   *
   * @param aFileStream file pname to open
   * @return Stream on file specified by aFileStream
   * @throws FileNotFoundException
   */
  public InputStream openStream(String aFileStream, Class<?> clazz) throws FileNotFoundException {
    InputStream out = ClassLoader.getSystemResourceAsStream(aFileStream);

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

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

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

    if (out == null) {
      try {
        URL temp = resourceResolverHook(aFileStream);
        if (temp != null) {
          out = temp.openStream();
        }
      } catch (IOException e) {
        ResourceResolver.LOGGER.log(Level.SEVERE, "IOException", e);
      }
    }

    if (out == null) {
      try {
        out = new FileInputStream(aFileStream);
      } catch (FileNotFoundException ex) {
        ResourceResolver.LOGGER.log(Level.SEVERE, "FileNotFoundException", ex);
      }
    }

    if (out != null) {
      ResourceResolver.LOGGER.info("Success found file:" + aFileStream + " !");
    } else {
      throw new FileNotFoundException("File not found !!! " + aFileStream + " !");
    }

    return out;
  }
 public static RealmModel baseAdapterTestInitialization(
     KeycloakSession session, RealmManager manager, RealmModel adminRealm, Class<?> clazz) {
   RealmRepresentation representation =
       KeycloakServer.loadJson(
           clazz.getResourceAsStream("/keycloak-saml/testsaml.json"), RealmRepresentation.class);
   RealmModel demoRealm = manager.importRealm(representation);
   return demoRealm;
 }
  /**
   * 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);
      }
    }
  }
  /**
   * Determine imports for the given bundle. Based on the user settings, this method will consider
   * only the the test hierarchy until the testing framework is found or all classes available
   * inside the test bundle.
   *
   * <p>Note that split packages are not supported.
   *
   * @return
   */
  private String[] determineImports() {

    boolean useTestClassOnly = false;

    // no jar entry present, bail out.
    if (jarEntries == null || jarEntries.isEmpty()) {
      logger.debug("No test jar content detected, generating bundle imports from the test class");
      useTestClassOnly = true;
    } else if (createManifestOnlyFromTestClass()) {
      logger.info("Using the test class for generating bundle imports");
      useTestClassOnly = true;
    } else logger.info("Using all classes in the jar for the generation of bundle imports");

    // className, class resource
    Map entries;

    if (useTestClassOnly) {

      entries = new LinkedHashMap(4);

      // get current class (test class that bootstraps the OSGi infrastructure)
      Class<?> clazz = getClass();
      String clazzPackage = null;
      String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName();

      do {

        // consider inner classes as well
        List classes = new ArrayList(4);
        classes.add(clazz);
        CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes);

        for (Iterator iterator = classes.iterator(); iterator.hasNext(); ) {
          Class<?> classToInspect = (Class) iterator.next();

          Package pkg = classToInspect.getPackage();
          if (pkg != null) {
            clazzPackage = pkg.getName();
            String classFile = ClassUtils.getClassFileName(classToInspect);
            entries.put(
                classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX),
                new InputStreamResource(classToInspect.getResourceAsStream(classFile)));
          }
          // handle default package
          else {
            logger.warn("Could not find package for class " + classToInspect + "; ignoring...");
          }
        }

        clazz = clazz.getSuperclass();

      } while (!endPackage.equals(clazzPackage));
    } else entries = jarEntries;

    return determineImportsFor(entries);
  }
 public static PluginDescriptor forPlugin(Class<? extends Plugin> pluginClass) {
   PluginDescriptor pluginDescriptor = null;
   try (InputStream is = pluginClass.getResourceAsStream("/plugin-descriptor.xml")) {
     pluginDescriptor = fromXMLStream(is);
   } catch (IOException e) {
     LOG.info("Error loading descriptor for plugin {}", pluginClass);
     LOG.debug("Error loading descriptor for plugin {}.\n{}", pluginClass, e);
   }
   return pluginDescriptor;
 }
Beispiel #29
0
 static BufferedInputStream getResourceInputStream(String s) {
   Class class1;
   if (class$net$sourceforge$pinyin4j$ResourceHelper == null) {
     class1 = _mthclass$("net.sourceforge.pinyin4j.ResourceHelper");
     class$net$sourceforge$pinyin4j$ResourceHelper = class1;
   } else {
     class1 = class$net$sourceforge$pinyin4j$ResourceHelper;
   }
   return new BufferedInputStream(class1.getResourceAsStream(s));
 }
 @Nullable
 public static Image loadFromResource(String path, Class aClass) {
   for (Pair<String, Integer> each : getFileNames(path)) {
     InputStream stream = aClass.getResourceAsStream(each.first);
     if (stream == null) continue;
     Image image = loadFromStream(stream, each.second);
     if (image != null) return image;
   }
   return null;
 }