Example #1
0
  private void setupEmailConfig() throws IOException, XmlPullParserException {
    FileInputStream fis = null;
    Configuration config = null;
    try {
      fis = new FileInputStream(this.getNexusConfiguration());

      NexusConfigurationXpp3Reader reader = new NexusConfigurationXpp3Reader();
      config = reader.read(fis);

      config.getSmtpConfiguration().setPort(this.emailServerPort);
      config.getSmtpConfiguration().setHostname("localhost");
      // config.getSmtpConfiguration().setDebugMode( true );

    } finally {
      IOUtil.close(fis);
    }

    // now write it back out
    FileWriter writer = null;

    try {
      writer = new FileWriter(this.getNexusConfiguration());
      new NexusConfigurationXpp3Writer().write(writer, config);
    } finally {
      IOUtil.close(writer);
    }
  }
  protected void resultIsFine(String path, Configuration configuration) throws Exception {
    NexusConfigurationXpp3Writer w = new NexusConfigurationXpp3Writer();

    StringWriter sw = new StringWriter();

    w.write(sw, configuration);

    // System.out.println(sw.toString());

    String shouldBe = IOUtil.toString(getClass().getResourceAsStream(path + ".result"));
    shouldBe = shouldBe.replace("\r", "");

    if (!StringUtils.equals(shouldBe, sw.toString())) {
      // write the file out so we can have something to compare

      File expected = FileUtils.toFile(getClass().getResource(path + ".result"));
      File actual = new File("target", expected.getName().replaceFirst("result", "actual"));
      FileOutputStream out = new FileOutputStream(actual);
      try {
        IOUtil.copy(sw.toString(), out);
      } finally {
        IOUtil.close(out);
      }
      String diffMessage = "diff " + expected.getAbsolutePath() + " " + actual.getAbsolutePath();
      String message = "Files differ, you can manually diff them:\n" + diffMessage;

      // the method makes the error pretty, so we can keep it.
      assertEquals(message, shouldBe, sw.toString().replace("\r", ""));
    }
  }
  /**
   * @param from
   * @param to
   * @param encoding
   * @param wrappers
   * @param filterProperties
   * @throws IOException TO DO: Remove this method when Maven moves to plexus-utils version 1.4
   */
  private static void copyFilteredFile(
      File from, File to, String encoding, FilterWrapper[] wrappers, Properties filterProperties)
      throws IOException {
    // buffer so it isn't reading a byte at a time!
    Reader fileReader = null;
    Writer fileWriter = null;
    try {
      // fix for MWAR-36, ensures that the parent dir are created first
      to.getParentFile().mkdirs();

      if (encoding == null || encoding.length() < 1) {
        fileReader = new BufferedReader(new FileReader(from));
        fileWriter = new FileWriter(to);
      } else {
        FileInputStream instream = new FileInputStream(from);

        FileOutputStream outstream = new FileOutputStream(to);

        fileReader = new BufferedReader(new InputStreamReader(instream, encoding));

        fileWriter = new OutputStreamWriter(outstream, encoding);
      }

      Reader reader = fileReader;
      for (FilterWrapper wrapper : wrappers) {
        reader = wrapper.getReader(reader, filterProperties);
      }

      IOUtil.copy(reader, fileWriter);
    } finally {
      IOUtil.close(fileReader);
      IOUtil.close(fileWriter);
    }
  }
Example #4
0
  @Override
  public CompoundArtifactDelta getDelta(File baseline, File reactor) throws IOException {
    Map<String, ArtifactDelta> result = new LinkedHashMap<>();

    ZipFile jar = new ZipFile(baseline);
    try {
      ZipFile jar2 = new ZipFile(reactor);
      try {
        Map<String, ZipEntry> entries = toEntryMap(jar);
        Map<String, ZipEntry> entries2 = toEntryMap(jar2);

        Set<String> names = new TreeSet<>();
        names.addAll(entries.keySet());
        names.addAll(entries2.keySet());

        for (String name : names) {
          ZipEntry entry = entries.get(name);
          if (entry == null) {
            result.put(name, new SimpleArtifactDelta("not present in baseline"));
            continue;
          }
          ZipEntry entry2 = entries2.get(name);
          if (entry2 == null) {
            result.put(name, new SimpleArtifactDelta("present in baseline only"));
            continue;
          }

          InputStream is = jar.getInputStream(entry);
          try {
            InputStream is2 = jar2.getInputStream(entry2);
            try {
              ContentsComparator comparator = comparators.get(getContentType(name));
              ArtifactDelta differences = comparator.getDelta(is, is2);
              if (differences != null) {
                result.put(name, differences);
                continue;
              }
            } finally {
              IOUtil.close(is2);
            }
          } finally {
            IOUtil.close(is);
          }
        }
      } finally {
        try {
          jar2.close();
        } catch (IOException e) {
          // too bad
        }
      }
    } finally {
      try {
        jar.close();
      } catch (IOException e) {
        // ouch
      }
    }
    return !result.isEmpty() ? new CompoundArtifactDelta("different", result) : null;
  }
  /**
   * Minifies CSS file.
   *
   * @param mergedFile input file resulting from the merged step
   * @param minifiedFile output file resulting from the minify step
   */
  @Override
  protected void minify(File mergedFile, File minifiedFile) throws IOException {
    if (minifiedFile != null) {
      try {
        log.info(
            "Creating minified file ["
                + ((debug) ? minifiedFile.getPath() : minifiedFile.getName())
                + "].");

        InputStream in = new FileInputStream(mergedFile);
        OutputStream out = new FileOutputStream(minifiedFile);
        InputStreamReader reader;
        OutputStreamWriter writer;
        if (charset == null) {
          reader = new InputStreamReader(in);
          writer = new OutputStreamWriter(out);
        } else {
          reader = new InputStreamReader(in, charset);
          writer = new OutputStreamWriter(out, charset);
        }

        CssCompressor compressor = new CssCompressor(reader);
        compressor.compress(writer, linebreak);

        IOUtil.close(reader);
        IOUtil.close(writer);
        IOUtil.close(in);
        IOUtil.close(out);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw e;
      }
    }
  }
 protected void writeStringToFile(File iniFile, String string) throws IOException {
   OutputStream os = new BufferedOutputStream(new FileOutputStream(iniFile));
   try {
     IOUtil.copy(string, os);
   } finally {
     IOUtil.close(os);
   }
 }
 /**
  * Writes a StringBuilder into a file.
  *
  * @param outFile The file to read.
  * @param input The contents of the file.
  * @throws IOException when things go wrong.
  */
 protected final void writeFile(File outFile, StringBuilder input) throws IOException {
   Writer writer = WriterFactory.newXmlWriter(outFile);
   try {
     IOUtil.copy(input.toString(), writer);
   } finally {
     IOUtil.close(writer);
   }
 }
  private void mergeMetadata(File existingMetadata) throws IOException, XmlPullParserException {
    // Existing Metadata in target stage

    Reader existingMetadataReader = new FileReader(existingMetadata);

    Metadata existing = reader.read(existingMetadataReader);

    // Staged Metadata

    File stagedMetadataFile = new File(existingMetadata.getParentFile(), MAVEN_METADATA);

    Reader stagedMetadataReader = new FileReader(stagedMetadataFile);

    Metadata staged = reader.read(stagedMetadataReader);

    // Merge

    existing.merge(staged);

    Writer writer = new FileWriter(existingMetadata);

    this.writer.write(writer, existing);

    IOUtil.close(writer);

    IOUtil.close(stagedMetadataReader);

    IOUtil.close(existingMetadataReader);

    // Mark all metadata as in-process and regenerate the checksums as they will be different
    // after the merger

    try {
      File newMd5 =
          new File(existingMetadata.getParentFile(), MAVEN_METADATA + ".md5" + IN_PROCESS_MARKER);

      FileUtils.fileWrite(newMd5.getAbsolutePath(), checksum(existingMetadata, MD5));

      File oldMd5 = new File(existingMetadata.getParentFile(), MAVEN_METADATA + ".md5");

      oldMd5.delete();

      File newSha1 =
          new File(existingMetadata.getParentFile(), MAVEN_METADATA + ".sha1" + IN_PROCESS_MARKER);

      FileUtils.fileWrite(newSha1.getAbsolutePath(), checksum(existingMetadata, SHA1));

      File oldSha1 = new File(existingMetadata.getParentFile(), MAVEN_METADATA + ".sha1");

      oldSha1.delete();
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }

    // We have the new merged copy so we're good

    stagedMetadataFile.delete();
  }
  protected Model getPom(Variant variant, Request request, Response response)
      throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    // TODO: enable only one section retrieval of POM, ie. only mailing lists, or team members

    String groupId = form.getFirstValue("g");

    String artifactId = form.getFirstValue("a");

    String version = form.getFirstValue("v");

    String repositoryId = form.getFirstValue("r");

    if (groupId == null || artifactId == null || version == null || repositoryId == null) {
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    ArtifactStoreRequest gavRequest =
        getResourceStoreRequest(
            request, false, repositoryId, groupId, artifactId, version, null, null, "pom");

    try {
      MavenRepository mavenRepository = getMavenRepository(repositoryId);

      ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper();

      InputStream pomContent = null;

      InputStreamReader ir = null;

      Model pom = null;

      try {
        StorageFileItem file = helper.retrieveArtifactPom(gavRequest);

        pomContent = file.getInputStream();

        MavenXpp3Reader reader = new MavenXpp3Reader();

        ir = new InputStreamReader(pomContent);

        pom = reader.read(ir);
      } finally {
        IOUtil.close(pomContent);

        IOUtil.close(ir);
      }

      return pom;

    } catch (Exception e) {
      handleException(request, response, e);
    }

    return null;
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {
    File basedir = new File(prefix);
    TemplateLoader loader = new FileTemplateLoader(basedir, suffix);
    Handlebars handlebars = new Handlebars(loader);
    File output = new File(this.output);
    PrintWriter writer = null;
    boolean error = true;
    InputStream runtimeIS = getClass().getResourceAsStream("/handlebars.runtime.js");
    try {
      writer = new PrintWriter(output);
      if (includeRuntime) {
        IOUtil.copy(runtimeIS, writer);
      }
      List<File> files = FileUtils.getFiles(basedir, "/**/*" + suffix, null);
      getLog().info("Compiling templates...");
      getLog().debug("Options:");
      getLog().debug("  output: " + output);
      getLog().debug("  prefix: " + prefix);
      getLog().debug("  suffix: " + suffix);
      getLog().debug("  minimize: " + minimize);
      getLog().debug("  includeRuntime: " + includeRuntime);

      Context nullContext = Context.newContext(null);
      for (File file : files) {
        String templateName = file.getPath().replace(prefix, "").replace(suffix, "");
        if (templateName.startsWith("/")) {
          templateName = templateName.substring(1);
        }
        getLog().debug("compiling: " + templateName);
        Template template = handlebars.compileInline("{{precompile \"" + templateName + "\"}}");
        Options opts = new Options.Builder(handlebars, TagType.VAR, nullContext, template).build();

        writer.append("// Source: ").append(file.getPath()).append("\n");
        writer.append(PrecompileHelper.INSTANCE.apply(templateName, opts)).append("\n\n");
      }
      writer.flush();
      IOUtil.close(writer);
      if (minimize) {
        minimize(output);
      }
      if (files.size() > 0) {
        getLog().info("  templates were saved in: " + output);
        error = false;
      } else {
        getLog().warn("  no templates were found");
      }
    } catch (IOException ex) {
      throw new MojoFailureException("Can't scan directory " + basedir, ex);
    } finally {
      IOUtil.close(runtimeIS);
      IOUtil.close(writer);
      if (error) {
        output.delete();
      }
    }
  }
  private void scanDirectory(
      File basedir, File dir, ZipOutputStream zos, String version, Set moveCommands)
      throws IOException {
    if (dir == null) {
      return;
    }

    File[] files = dir.listFiles();

    for (File f : files) {
      if (f.isDirectory()) {
        if (f.getName().equals(".svn")) {
          continue;
        }

        if (f.getName().endsWith(version)) {
          String s = f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1);
          s = StringUtils.replace(s, "\\", "/");

          moveCommands.add("mv " + s + IN_PROCESS_MARKER + " " + s);
        }

        scanDirectory(basedir, f, zos, version, moveCommands);
      } else {
        InputStream is = new FileInputStream(f);

        String s = f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1);
        s = StringUtils.replace(s, "\\", "/");

        // We are marking any version directories with the in-process flag so that
        // anything being unpacked on the target side will not be recogized by Maven
        // and so users cannot download partially uploaded files.

        String vtag = "/" + version;

        s = StringUtils.replace(s, vtag + "/", vtag + IN_PROCESS_MARKER + "/");

        ZipEntry e = new ZipEntry(s);

        zos.putNextEntry(e);

        IOUtil.copy(is, zos);

        IOUtil.close(is);

        int idx = s.indexOf(IN_PROCESS_MARKER);

        if (idx > 0) {
          String d = s.substring(0, idx);

          moveCommands.add("mv " + d + IN_PROCESS_MARKER + " " + d);
        }
      }
    }
  }
Example #12
0
 protected void copyResource(String resource, String dest) throws IOException {
   InputStream stream = null;
   FileOutputStream ostream = null;
   try {
     stream = getClass().getResourceAsStream(resource);
     ostream = new FileOutputStream(dest);
     IOUtil.copy(stream, ostream);
   } finally {
     IOUtil.close(stream);
     IOUtil.close(ostream);
   }
 }
  public void writeLinkContent(final StorageLinkItem link, final OutputStream os)
      throws IOException {
    try {
      final String linkBody = LINK_PREFIX + link.getTarget().toString();

      IOUtil.copy(new ByteArrayInputStream(linkBody.getBytes(UTF8_CHARSET)), os);

      os.flush();
    } finally {
      IOUtil.close(os);
    }
  }
  protected StringBuffer readFileToString(File iniFile) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(iniFile));
    try {
      StringWriter buffer = new StringWriter();

      IOUtil.copy(is, buffer, "UTF-8");

      return buffer.getBuffer();
    } finally {
      IOUtil.close(is);
    }
  }
 private File newTempFile(final String source) throws IOException, FileNotFoundException {
   File result = temporaryFolder.newFile();
   final InputStream dummyData = UpdateCouchDocsTest.class.getResourceAsStream(source);
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(result);
     IOUtil.copy(dummyData, fos);
   } finally {
     IOUtil.close(dummyData);
     IOUtil.close(fos);
   }
   return result;
 }
 protected static String getAsString(IFile file) throws IOException, CoreException {
   assert file != null;
   assert file.isAccessible();
   InputStream ins = null;
   String content = null;
   try {
     ins = file.getContents();
     content = IOUtil.toString(ins, 1024);
   } finally {
     IOUtil.close(ins);
   }
   return content;
 }
 private String interpolate(final String text) {
   if (null == text || !text.contains("${")) {
     return text;
   }
   // use same interpolation method as XML for sake of consistency
   final Reader r = new InterpolationFilterReader(new StringReader(text), variables);
   try {
     return IOUtil.toString(r);
   } catch (final IOException e) {
     return text; // should never actually happen, as no actual I/O involved
   } finally {
     IOUtil.close(r);
   }
 }
  private void merge(File originalFile, File extraContentFile, String type)
      throws MojoFailureException, MojoExecutionException {
    InputStream originalReader = null;
    InputStream extraContentReader = null;
    OutputStream originalWriter = null;
    try {
      String name = FileUtils.removeExtension(extraContentFile.getName());
      String extension = FileUtils.getExtension(extraContentFile.getName());

      if ("properties".equals(type)) {
        File tempFile = File.createTempFile(name, extension);
        mavenFileFilter.copyFile(
            extraContentFile, tempFile, true, project, null, true, "UTF-8", session);

        originalReader = new FileInputStream(originalFile);
        extraContentReader = new FileInputStream(tempFile);

        Properties original = new Properties();
        original.load(originalReader);
        IOUtil.close(originalReader);

        originalWriter = new FileOutputStream(originalFile);

        Properties extra = new Properties();
        extra.load(extraContentReader);
        IOUtil.close(extraContentReader);

        for (Object key : extra.keySet()) {
          original.put(key, extra.get(key));
        }

        original.store(originalWriter, "Updated by EnvironmentMojo");
      } else {
        throw new MojoFailureException("Invalid file type: " + type);
      }
    } catch (Exception e) {
      throw new MojoExecutionException(
          "Error merging files: Original '"
              + originalFile.getAbsolutePath()
              + "', extraContent '"
              + extraContentFile.getAbsolutePath()
              + "'.",
          e);
    } finally {
      IOUtil.close(originalReader);
      IOUtil.close(extraContentReader);
      IOUtil.close(originalWriter);
    }
  }
  /** @see org.apache.maven.plugin.eclipse.writers.EclipseWriter#write() */
  public void write() throws MojoExecutionException {
    // check for existence
    if (!config.getManifestFile().exists()) {
      log.warn(
          Messages.getString(
              "EclipseOSGiManifestWriter.nomanifestfile",
              config.getManifestFile().getAbsolutePath()));
      return;
    }

    StringBuffer manifestSb = rewriteManifest(config.getManifestFile());
    FileWriter fos = null;
    try {
      fos = new FileWriter(config.getManifestFile());
      fos.write(manifestSb.toString());
    } catch (FileNotFoundException e) {
      throw new MojoExecutionException(
          Messages.getString("cantwritetofile", config.getManifestFile().getAbsolutePath()));
    } catch (IOException e) {
      throw new MojoExecutionException(
          Messages.getString("cantwritetofile", config.getManifestFile().getAbsolutePath()), e);
    } finally {
      IOUtil.close(fos);
    }
  }
  protected Metadata downloadMetadataFromRepository(Gav gav, String repoId)
      throws IOException, XmlPullParserException {
    // File f =
    // new File( nexusWorkDir, "storage/" + repoId + "/" + gav.getGroupId() + "/" +
    // gav.getArtifactId()
    // + "/maven-metadata.xml" );
    //
    // if ( !f.exists() )
    // {
    // throw new FileNotFoundException( "Metadata do not exist! " + f.getAbsolutePath() );
    // }

    String url =
        this.getBaseNexusUrl()
            + REPOSITORY_RELATIVE_URL
            + repoId
            + "/"
            + gav.getGroupId()
            + "/"
            + gav.getArtifactId()
            + "/maven-metadata.xml";

    Response response = RequestFacade.sendMessage(new URL(url), Method.GET, null);
    if (response.getStatus().isError()) {
      return null;
    }

    InputStream stream = response.getEntity().getStream();
    try {
      MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
      return metadataReader.read(stream);
    } finally {
      IOUtil.close(stream);
    }
  }
  protected AbstractNexusIntegrationTest(String testRepositoryId) {
    // we also need to setup a couple fields, that need to be pulled out of a bundle
    this.testRepositoryId = testRepositoryId;
    // this.nexusTestRepoUrl = baseNexusUrl + REPOSITORY_RELATIVE_URL + testRepositoryId + "/";

    InputStream is = null;

    Properties props = new Properties();
    try {
      is = getClass().getResourceAsStream("/log4j.properties");

      if (is != null) {
        props.load(is);
        PropertyConfigurator.configure(props);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IOUtil.close(is);
    }

    // configure the logging
    SLF4JBridgeHandler.install();

    // redirect filePrefs
    FilePreferencesFactory.setPreferencesFile(
        ITAppBooterCustomizer.getFilePrefsFile(new File(getNexusBaseDir()), getTestId()));
  }
  /**
   * Reads a property file, resolving all internal variables.
   *
   * @param propfile The property file to load
   * @return the loaded and fully resolved Properties object
   */
  public static Properties loadPropertyFile(File propfile) {
    if (!propfile.exists()) {
      throw new PropertiesException(
          "unable to locate spercified prop file [" + propfile.toString() + "]");
    }

    Properties props = new Properties();
    if (propfile.exists()) {
      try {
        FileInputStream inStream = new FileInputStream(propfile);
        try {
          props.load(inStream);
        } finally {
          IOUtil.close(inStream);
        }
      } catch (IOException ioe) {
        throw new PropertiesException("unable to load properties file [" + propfile + "]");
      }
    }

    for (Enumeration n = props.propertyNames(); n.hasMoreElements(); ) {
      String k = (String) n.nextElement();
      props.setProperty(k, PropertiesHelper.getInterpolatedPropertyValue(k, props));
    }

    return props;
  }
Example #23
0
 public static LifecycleMappingMetadataSource getLifecycleMappingMetadataSource(CatalogItem ci) {
   try {
     URL url = getLifecycleMappingMetadataSourceURL(ci);
     if (url == null) {
       return null;
     }
     // To ensure we can delete the temporary file we need to prevent caching, see
     // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4386865
     URLConnection conn = url.openConnection();
     if (conn instanceof JarURLConnection) {
       ((JarURLConnection) conn).setDefaultUseCaches(false);
     }
     InputStream is = conn.getInputStream();
     try {
       return LifecycleMappingFactory.createLifecycleMappingMetadataSource(is);
     } finally {
       IOUtil.close(is);
     }
   } catch (FileNotFoundException e) {
     // CatalogItem does not contain lifecycle mapping
   } catch (Exception e) {
     log.warn(NLS.bind(Messages.MavenCatalogViewer_Error_loading_lifecycle, ci.getId()), e);
   }
   return null;
 }
  /** Generates a manifest file to be included in the .hpi file */
  protected void generateManifest(MavenArchiveConfiguration archive, File manifestFile)
      throws MojoExecutionException {
    // create directory if it doesn't exist yet
    if (!manifestFile.getParentFile().exists()) manifestFile.getParentFile().mkdirs();

    getLog().info("Generating " + manifestFile);

    MavenArchiver ma = new MavenArchiver();
    ma.setOutputFile(manifestFile);

    PrintWriter printWriter = null;
    try {
      Manifest mf = ma.getManifest(project, archive.getManifest());
      Section mainSection = mf.getMainSection();
      setAttributes(mainSection);

      printWriter =
          new PrintWriter(new OutputStreamWriter(new FileOutputStream(manifestFile), "UTF-8"));
      mf.write(printWriter);
    } catch (ManifestException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } catch (IOException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } finally {
      IOUtil.close(printWriter);
    }
  }
 /** Writes the .classpath file for Eclipse. */
 public void write(String projectName) throws Exception {
   final File projectFile = this.getFile(".project");
   final FileWriter fileWriter = new FileWriter(projectFile);
   final XMLWriter writer = new PrettyPrintXMLWriter(fileWriter, "UTF-8", null);
   writer.startElement("projectDescription");
   writer.startElement("name");
   writer.writeText(projectName);
   writer.endElement();
   writer.startElement("comment");
   writer.endElement();
   writer.startElement("projects");
   writer.endElement();
   writer.startElement("buildSpec");
   writer.startElement("buildCommand");
   writer.startElement("name");
   writer.writeText("org.eclipse.jdt.core.javabuilder");
   writer.endElement();
   writer.startElement("arguments");
   writer.endElement();
   writer.endElement();
   writer.endElement();
   writer.startElement("natures");
   writer.startElement("nature");
   writer.writeText("org.eclipse.jdt.core.javanature");
   writer.endElement();
   writer.endElement();
   writer.endElement();
   IOUtil.close(fileWriter);
   this.logger.info("Project file written --> '" + projectFile + "'");
 }
Example #26
0
  protected boolean createEmptyZip(File zipFile) throws ArchiverException {
    if (!createEmpty) {
      return true;
    }

    ZipArchiveOutputStream zOut = null;
    try {
      getLogger().debug("Building MANIFEST-only jar: " + getDestFile().getAbsolutePath());
      zOut =
          new ZipArchiveOutputStream(bufferedOutputStream(fileOutputStream(getDestFile(), "jar")));

      zOut.setEncoding(getEncoding());
      if (isCompress()) {
        zOut.setMethod(ZipArchiveOutputStream.DEFLATED);
      } else {
        zOut.setMethod(ZipArchiveOutputStream.STORED);
      }
      initZipOutputStream(zOut);
      finalizeZipOutputStream(zOut);
    } catch (IOException ioe) {
      throw new ArchiverException(
          "Could not create almost empty JAR archive (" + ioe.getMessage() + ")", ioe);
    } finally {
      // Close the output stream.
      IOUtil.close(zOut);
      createEmpty = false;
    }
    return true;
  }
    public void packageToFile(File packageFile) throws Exception {
      F2<
              RelativePath,
              PackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>>,
              Boolean>
          pathFilter = pathFilter();

      fileSystem = fileSystem.prettify();

      Stream<PackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>>> items =
          fileSystem.toList().filter(compose(BooleanF.invert, curry(pathFilter, BASE)));

      ZipArchiveOutputStream zos = null;
      try {
        zos = new ZipArchiveOutputStream(packageFile);
        zos.setLevel(Deflater.BEST_COMPRESSION);

        for (PackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>>
            fileSystemObject : items) {
          fileSystemObject.getExtension().f(fileSystemObject.getUnixFsObject(), zos).run();
        }
      } finally {
        IOUtil.close(zos);
      }
    }
Example #28
0
 /**
  * Construct a manifest from Ant's default manifest file.
  *
  * @return the default manifest.
  * @throws ArchiverException if there is a problem loading the default manifest
  */
 public static Manifest getDefaultManifest() throws ArchiverException {
   try {
     String defManifest = "/org/codehaus/plexus/archiver/jar/defaultManifest.mf";
     InputStream in = Manifest.class.getResourceAsStream(defManifest);
     if (in == null) {
       throw new ArchiverException("Could not find default manifest: " + defManifest);
     }
     try {
       Manifest defaultManifest = new Manifest(new InputStreamReader(in, "UTF-8"));
       Attribute createdBy =
           new Attribute(
               "Created-By",
               System.getProperty("java.vm.version")
                   + " ("
                   + System.getProperty("java.vm.vendor")
                   + ")");
       defaultManifest.getMainSection().storeAttribute(createdBy);
       return defaultManifest;
     } catch (UnsupportedEncodingException e) {
       return new Manifest(new InputStreamReader(in));
     } finally {
       IOUtil.close(in);
     }
   } catch (ManifestException e) {
     throw new ArchiverException("Default manifest is invalid !!", e);
   } catch (IOException e) {
     throw new ArchiverException("Unable to read default manifest", e);
   }
 }
Example #29
0
  @SuppressWarnings("deprecation")
  @Override
  public Bundle assemble(IssueSubmissionRequest request) throws IssueSubmissionException {
    OutputStream out = null;
    try {
      final ManagedBundle bundle = storageManager.createBundle("nexus.xml", "application/xml");
      final Configuration configuration =
          configHelper.maskPasswords(nexusConfig.getConfigurationModel());

      // No config ?
      if (configuration != null) {
        NexusConfigurationXpp3Writer writer = new NexusConfigurationXpp3Writer();
        out = bundle.getOutputStream();
        writer.write(out, configuration);
        out.close();
      } else {
        ByteStreams.write(
            "Got no configuration from config helper".getBytes("utf-8"),
            new OutputSupplier<OutputStream>() {
              @Override
              public OutputStream getOutput() throws IOException {
                return bundle.getOutputStream();
              }
            });
      }
      return bundle;
    } catch (IOException e) {
      IOUtil.close(out);
      throw new IssueSubmissionException("Could not assemble nexus.xml: " + e.getMessage(), e);
    }
  }
Example #30
0
  /**
   * @param xstreamObject not null
   * @param jarFile not null
   * @param packageFilter a package name to filter.
   */
  private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
      jarStream = new JarInputStream(new FileInputStream(jarFile));
      JarEntry jarEntry = jarStream.getNextJarEntry();
      while (jarEntry != null) {
        if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
          String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
          name = name.replaceAll("/", "\\.");

          if (name.indexOf(packageFilter) != -1) {
            try {
              Class<?> clazz = ClassUtils.getClass(name);
              String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
              xstreamObject.alias(alias, clazz);
              if (!clazz.equals(Model.class)) {
                xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
              }
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }
          }
        }

        jarStream.closeEntry();
        jarEntry = jarStream.getNextJarEntry();
      }
    } catch (IOException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("IOException: " + e.getMessage(), e);
      }
    } finally {
      IOUtil.close(jarStream);
    }
  }