Exemplo n.º 1
0
  public static void writeAssets() {
    JarFile thisJar = JarUtils.jarForClass(Doclava.class, null);
    if (thisJar != null) {
      try {
        List<String> templateDirs = ClearPage.getBundledTemplateDirs();
        for (String templateDir : templateDirs) {
          String assetsDir = ensureSlash(templateDir) + "assets";
          JarUtils.copyResourcesToDirectory(
              thisJar, assetsDir, ensureSlash(ClearPage.outputDir) + assetsOutputDir);
        }

        // write mule-developer-core.css
        Data data = makeHDF();
        ClearPage.write(
            data, "mule-developer-core.cs", assetsOutputDir + "/mule-developer-core.css");
      } catch (IOException e) {
        System.err.println("Error copying assets directory.");
        e.printStackTrace();
        return;
      }
    }

    List<String> templateDirs = ClearPage.getTemplateDirs();
    for (String templateDir : templateDirs) {
      File assets = new File(ensureSlash(templateDir) + "assets");
      if (assets.isDirectory()) {
        writeDirectory(null, assets, assetsOutputDir, null, "");
      }
    }
  }
Exemplo n.º 2
0
  @Test
  public void testLangLabels() throws JAXBException, IOException {

    InputStream[] flist =
        new InputStream[] {
          JarUtils.readJarFileAsStream(LsTestConstants.LANG_SET_RES_PATH + "_test"),
          JarUtils.readJarFileAsStream(LsTestConstants.LANG_SET_RES_PATH),
          JarUtils.readJarFileAsStream(LsTestConstants.LANG_SET_RES_PATH + "_combo")
        };

    LangLabelsSet[] lmap = new LangLabelsSet[flist.length];

    for (int i = 0; i < flist.length; i++) {
      InputStream f = flist[i];
      JAXBElement<?> jaxb = (JAXBElement<?>) _ll.unmarshal(f);
      LangLabelsSet ls = (LangLabelsSet) jaxb.getValue();

      lmap[i] = ls;
      testLangsDef(ls);
    }

    checkLangLabelsSetPartial(lmap[0]);
    checkLangLabelsSetFull(lmap[1]);
    checkLangLabelsSetCombined(lmap[2]);
  }
Exemplo n.º 3
0
 private void loadingRequiredLibs() {
   try {
     final File[] libs =
         new File[] {
           new File(this.getDataFolder() + "/lib/", "c3p0-0.9.5.jar"),
           new File(this.getDataFolder() + "/lib/", "mchange-commons-java-0.2.9.jar")
         };
     for (final File lib : libs) {
       if (!lib.exists()) {
         JarUtils.extractFromJar(lib.getName(), lib.getAbsolutePath());
       }
     }
     for (final File lib : libs) {
       if (!lib.exists()) {
         this.getLogger()
             .warning(
                 "There was a critical error loading bedwars plugin! Could not find lib: "
                     + lib.getName());
         Bukkit.getServer().getPluginManager().disablePlugin(this);
         return;
       }
       this.addClassPath(JarUtils.getJarUrl(lib));
     }
   } catch (final Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 4
0
  public void run() throws Throwable {
    if (Files.notExists(jdkMods)) {
      return;
    }

    if (!CompilerUtils.compile(src, classes)) {
      throw new AssertionError("Compilation failure. See log.");
    }

    String modName = "test";
    Files.createDirectories(jmods);
    Files.createDirectories(jars);
    Path jarfile = jars.resolve("test.jar");
    JarUtils.createJarFile(jarfile, classes);

    Path image = Paths.get("mysmallimage");
    runJmod(jarfile.toString(), modName);
    runJlink(image, modName, "--compress", "2");
    execute(image, modName);

    Files.delete(jmods.resolve(modName + ".jmod"));

    image = Paths.get("myimage");
    runJmod(classes.toString(), modName);
    runJlink(image, modName);
    execute(image, modName);
  }
Exemplo n.º 5
0
 private boolean isValidBase(File basePath) {
   if (basePath.exists()) {
     String baseVersion = JarUtils.getManifestProperty(basePath, BASE_VERSION_PROPERTY);
     if ((baseVersion != null) && (baseVersion.compareTo(getString("tangara.version")) == 0)) {
       return true;
     }
   }
   return false;
 }
 /**
  * Read File by Name from jar file
  *
  * @param fname File Name
  * @param cfg Resource Configuration object
  * @return InputStream with Main Demo File
  * @throws IOException
  */
 public static InputStream readDemoFileAsStream(String fname, ITestResourceConfig cfg)
     throws IOException {
   return JarUtils.readJarFileAsStream(cfg.getTopResDir() + "/" + fname);
 }
 /**
  * Copy all demo files from jar file into physical directory
  *
  * @param base Top root directory to copy files
  * @param dir Sub-directory from top resource tree defined by Package Name to read test files from
  * @param cfg Resource Configuration object
  * @throws IOException
  * @throws URISyntaxException
  */
 public static void copyJarDemoProj(String base, String dir, ITestResourceConfig cfg)
     throws IOException, URISyntaxException {
   JarUtils.copyJarDir(base, cfg.getTopResDir(), dir);
 }
Exemplo n.º 8
0
  public boolean collectCertificates(Package pkg, int flags) {
    JarFile jarFile = new JarFile(mArchiveSourcePath);

    Enumeration entries = jarFile.entries();
    // bypass files in "META-INF", which is the certificate file itself
    je.getName().startsWith("META-INF/");

    // XXX: load one file in jar package's certificate, which including dex file and resource
    Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
    // libcore/luni/src/main/java/java/util/jar/JarEntry.java
    // private Certificate[] loadCertificates(JarFile jarFile, JarEntry je, byte[] readBuffer)
    {
      // get read buffer from JarEntry
      InputStream is = new BufferedInputStream(jarFile.getInputStream(je));
      // load the JarEntry
      is.read(readBuffer, 0, readBuffer.length);
      // Calculate certificate
      return je.getCertificates();
      // libcore/luni/src/main/java/java/util/jar/JarEntry.java
      // public Certificate[] getCertificates()
      {
        JarVerifier jarVerifier = parentJar.verifier;
        jarVerifier.getCertificates(getName());
        // Certificate[] getCertificates(String name)
        {
          Certificate[] verifiedCerts = verifiedEntries.get(name);
          // libcore/luni/src/main/java/java/util/jar/JarVerifier.java
          // private void verifyCertificate(String certFile)
          {
            Certificate[] signerCertChain =
                JarUtils.verifySignature(
                    new ByteArrayInputStream(sfBytes), new ByteArrayInputStream(sBlockBytes));
            // libcore/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
            // This method handle all the work with  PKCS7, ASN1 encoding, signature verifying,
            // and certification path building.
            // See also PKCS #7: Cryptographic Message Syntax Standard:
            // http://www.ietf.org/rfc/rfc2315.txt
            //
            // public static Certificate[] verifySignature(InputStream signature, InputStream
            //            signatureBlock) throws IOException, GeneralSecurityException
            // @param signature - the input stream of signature file to be verified
            // @param signatureBlock - the input stream of corresponding signature block file
            {
              // read certificate raw data
              BerInputStream bis = new BerInputStream(signatureBlock);
              ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);

              // XXX: get X.509 certificate
              SignedData signedData = info.getSignedData();
              Collection encCerts = signedData.getCertificates();
              X509Certificate[] certs = new X509Certificate[encCerts.size()];

              // get all X.509 certificate
              for (Iterator it = encCerts.iterator(); it.hasNext(); ) {
                certs[i++] =
                    new X509CertImpl((org.apache.harmony.security.x509.Certificate) it.next());
              }

              // return certificate
              return createChain(certs[issuerSertIndex], certs);
            } // JarUtils.verifySignature()
          } //
        } // JarVerifier.JarVerifier()
      } // JarEntry.getCertificates()
    } //

    // set signature from X509Certificate
    pkg.mSignatures[i] = new Signature(certs[i].getEncoded());
    // libcore/luni/src/main/java/org/apache/harmony/security/x509/Certificate.java
    // public byte[] getEncoded()
    {
      // public class Certificate {
      //      public static final ASN1Sequence ASN1 =
      //          new ASN1Sequence(new ASN1Type[]
      //              {
      //                  TBSCertificate.ASN1,
      //                  AlgorithmIdentifier.ASN1,
      //                  ASN1BitString.getInstance(),
      //              })
      //      {
      //
      //
      //
      //      }
      // }
      /**
       * The class encapsulates the ASN.1 DER encoding/decoding work with TBSCertificate structure
       * which is the part of X.509 certificate (as specified in RFC 3280 - Internet X.509 Public
       * Key Infrastructure. Certificate and Certificate Revocation List (CRL) Profile.
       * http://www.ietf.org/rfc/rfc3280.txt):
       *
       * <pre>
       *  TBSCertificate  ::=  SEQUENCE  {
       *       version         [0]  EXPLICIT Version DEFAULT v1,
       *       serialNumber         CertificateSerialNumber,
       *       signature            AlgorithmIdentifier,
       *       issuer               Name,
       *       validity             Validity,
       *       subject              Name,
       *       subjectPublicKeyInfo SubjectPublicKeyInfo,
       *       issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
       *                            -- If present, version MUST be v2 or v3
       *       subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
       *                            -- If present, version MUST be v2 or v3
       *       extensions      [3]  EXPLICIT Extensions OPTIONAL
       *                            -- If present, version MUST be v3
       *  }
       * </pre>
       *
       * X.509 ASN.1 encoding
       */
      encoding = Certificate.ASN1.encode(this);
    }
  }
Exemplo n.º 9
0
  @Override
  public void execute() throws BuildException {
    build = (Build) getProject().getReference(Key.build.referenceId());
    console = build.getConsole();

    if (!configured) {
      // called from moxie.package
      configure(build);
    }

    if (fatjar && excludeClasspathJars) {
      throw new BuildException("Can not specify fatjar and excludeClasspathJars!");
    }

    // automatic manifest entries from Moxie metadata
    configureManifest(mft);

    if (mainclass == null) {
      String mc = build.getConfig().getProjectConfig().getMainclass();
      if (!StringUtils.isEmpty(mc)) {
        ClassSpec cs = new ClassSpec(getProject());
        mainclass = cs;
        mainclass.setName(mc);
        jarSpecs.add(cs);
      }
    }

    if (mainclass != null) {
      String mc = mainclass.getName().replace('/', '.');
      if (mc.endsWith(".class")) {
        mc = mc.substring(0, mc.length() - ".class".length());
      }
      if (launcher == null) {
        // use specified mainclass
        setManifest(mft, "Main-Class", mc);
      } else {
        // inject Moxie Launcher class
        String mx = launcher.getName().replace('/', '.');
        if (mx.endsWith(".class")) {
          mx = mx.substring(0, mx.length() - ".class".length());
        }
        setManifest(mft, "Main-Class", mx);
        setManifest(mft, "mxMain-Class", mc);
        String paths = launcher.getPaths();
        if (!StringUtils.isEmpty(paths)) {
          setManifest(mft, "mxMain-Paths", paths);
        }
      }
    }

    // automatic classpath resolution, if not manually specified
    if (classpath == null) {
      Path cp = buildClasspath(build, Scope.compile, tag);
      if (fatjar) {
        // FatJar generation
        classpath = createClasspath();
        for (String path : cp.list()) {
          if (path.toLowerCase().endsWith(".jar")) {
            LibrarySpec lib = createLibrary();
            lib.setJar(path);
          } else {
            PathElement element = classpath.createPathElement();
            element.setPath(path);
          }
        }
      } else {
        // standard GenJar class dependency resolution
        classpath = cp;
      }
    }

    if (destFile == null) {
      setDestfile(build.getBuildArtifact(classifier));
    }

    if (destFile.getParentFile() != null) {
      destFile.getParentFile().mkdirs();
    }

    version = build.getPom().version;

    File outputFolder = build.getConfig().getOutputDirectory(Scope.compile);

    if (excludes == null) {
      excludes = Toolkit.DEFAULT_RESOURCE_EXCLUDES;
    }

    // include resources from the project source folders
    Resource resources = createResource();
    if (!StringUtils.isEmpty(resourceFolderPrefix)) {
      resources.setPrefix(resourceFolderPrefix);
    }
    for (File dir : build.getConfig().getSourceDirectories(Scope.compile, tag)) {
      FileSet res = resources.createFileset();
      res.setDir(dir);
      res.setExcludes(excludes);
    }

    if (includeResources) {
      // include resources from the project resource folders
      for (File dir : build.getConfig().getResourceDirectories(Scope.compile, tag)) {
        FileSet res = resources.createFileset();
        res.setExcludes(excludes);
        res.setDir(dir);
      }

      for (Build module : build.getSolver().getLinkedModules()) {
        // include resources from module source folders
        File dir = module.getConfig().getOutputDirectory(Scope.compile);
        FileSet res = resources.createFileset();
        res.setDir(dir);
        res.setExcludes(excludes);

        // include resources from the module resource folders
        for (File resDir : module.getConfig().getResourceDirectories(Scope.compile)) {
          FileSet resSet = resources.createFileset();
          res.setExcludes(Toolkit.DEFAULT_RESOURCE_EXCLUDES);
          resSet.setDir(resDir);
        }
      }
    }

    if (isShowTitle()) {
      console.title(getClass(), destFile.getName());
    }

    console.debug(getTaskName() + " configuration");

    // display specified mxgenjar attributes
    MaxmlMap attributes = build.getConfig().getTaskAttributes(getTaskName());
    AttributeReflector.logAttributes(this, attributes, console);

    // optionally inject MxLauncher utility
    if (launcher != null) {
      if (launcher.getName().equals(MxLauncher.class.getName().replace('.', '/') + ".class")) {
        // inject MxLauncher into the output folder of the project
        for (String cn :
            Arrays.asList(MxLauncher.class.getName(), MxLauncher.class.getName() + "$1")) {
          try {
            String fn = cn.replace('.', '/') + ".class";
            InputStream is = MxLauncher.class.getResourceAsStream("/" + fn);
            if (is == null) {
              continue;
            }
            build.getConsole().log("Injecting {0} into output folder", cn);
            File file = new File(outputFolder, fn.replace('/', File.separatorChar));
            if (file.exists()) {
              file.delete();
            }
            file.getParentFile().mkdirs();
            FileOutputStream os = new FileOutputStream(file, false);
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
              os.write(buffer, 0, len);
            }
            is.close();
            os.flush();
            os.close();

            // add these files to the jarSpecs
            ClassSpec cs = new ClassSpec(getProject());
            cs.setName(cn);
            jarSpecs.add(cs);
          } catch (Exception e) {
            build
                .getConsole()
                .error(e, "Failed to inject {0} into {1}", launcher.getName(), outputFolder);
          }
        }
      }
    }

    long start = System.currentTimeMillis();
    try {
      super.execute();
    } catch (ResolutionFailedException e) {
      String msg;
      if (tag == null) {
        String template = "Unable to resolve: {0}\n\n{1} could not be located on the classpath.\n";
        msg =
            MessageFormat.format(
                template,
                e.resolvingclass,
                e.missingclass,
                tag == null ? "classpath" : ("\"" + tag + "\" classpath"),
                tag);
      } else {
        String template =
            "Unable to resolve: {0}\n\n{1} could not be located on the \"{2}\" classpath.\nPlease add the \":{2}\" tag to the appropriate dependency in your Moxie descriptor file.\n";
        msg = MessageFormat.format(template, e.resolvingclass, e.missingclass, tag);
      }
      throw new MoxieException(msg);
    }

    if (fatjar) {
      // try to merge duplicate META-INF/services files
      JarUtils.mergeMetaInfServices(console, destFile);
    }

    console.log(1, destFile.getAbsolutePath());
    console.log(
        1,
        "{0} KB, generated in {1} ms",
        (destFile.length() / 1024),
        System.currentTimeMillis() - start);

    /*
     * Build sources jar
     */
    if (packageSources) {
      String name = destFile.getName();
      if (!StringUtils.isEmpty(classifier)) {
        // replace the classifier with "sources"
        name = name.replace(classifier, "sources");
      } else {
        // append -sources to the filename before the extension
        name =
            name.substring(0, name.lastIndexOf('.'))
                + "-sources"
                + name.substring(name.lastIndexOf('.'));
      }
      File sourcesFile = new File(destFile.getParentFile(), name);
      if (sourcesFile.exists()) {
        sourcesFile.delete();
      }

      Jar jar = new Jar();
      jar.setTaskName(getTaskName());
      jar.setProject(getProject());

      // set the destination file
      jar.setDestFile(sourcesFile);

      // use the resolved classes to determine included source files
      List<FileResource> sourceFiles = new ArrayList<FileResource>();
      Map<File, Set<String>> packageResources = new HashMap<File, Set<String>>();

      if (resolvedLocal.size() == 0) {
        console.warn(
            getTaskName() + " has not resolved any class files local to {0}",
            build.getPom().getManagementId());
      }

      List<File> folders = build.getConfig().getSourceDirectories(Scope.compile, tag);
      for (String className : resolvedLocal) {
        String sourceName =
            className.substring(0, className.length() - ".class".length()).replace('.', '/')
                + ".java";
        console.debug(sourceName);
        for (File folder : folders) {
          File file = new File(folder, sourceName);
          if (file.exists()) {
            FileResource resource = new FileResource(getProject(), file);
            resource.setBaseDir(folder);
            sourceFiles.add(resource);
            if (!packageResources.containsKey(folder)) {
              // always include default package resources
              packageResources.put(folder, new TreeSet<String>(Arrays.asList("/*")));
            }
            String packagePath = FileUtils.getRelativePath(folder, file.getParentFile());
            packageResources.get(folder).add(packagePath + "/*");
            console.debug(1, file.getAbsolutePath());
            break;
          }
        }
      }

      // add the discovered source files for the resolved classes
      jar.add(new FileResourceSet(sourceFiles));

      // add the resolved package folders for resource files
      for (Map.Entry<File, Set<String>> entry : packageResources.entrySet()) {
        FileSet res = new FileSet();
        res.setDir(entry.getKey());
        res.setExcludes(excludes);
        StringBuilder includes = new StringBuilder();
        for (String packageName : entry.getValue()) {
          includes.append(packageName + ",");
        }
        includes.setLength(includes.length() - 1);
        res.setIncludes(includes.toString());
        console.debug("adding resource fileset {0}", entry.getKey());
        console.debug(1, "includes={0}", includes.toString());
        jar.add(res);
      }

      if (includeResources) {
        for (File dir : build.getConfig().getResourceDirectories(Scope.compile, tag)) {
          FileSet res = resources.createFileset();
          res.setDir(dir);
          res.setExcludes(Toolkit.DEFAULT_RESOURCE_EXCLUDES);
          jar.add(res);
        }
      }

      // set the source jar manifest
      try {
        Manifest mft = new Manifest();
        configureManifest(mft);
        jar.addConfiguredManifest(mft);
      } catch (ManifestException e) {
        console.error(e);
      }

      start = System.currentTimeMillis();
      jar.execute();

      console.log(1, sourcesFile.getAbsolutePath());
      console.log(
          1,
          "{0} KB, generated in {1} ms",
          (sourcesFile.length() / 1024),
          System.currentTimeMillis() - start);
    }
  }