View Javadoc
1   /*
2    * Copyright (C) 2015, David Ostrovsky <david@ostrovsky.org> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.archive;
12  
13  import java.beans.Statement;
14  import java.io.IOException;
15  import java.text.MessageFormat;
16  import java.util.Map;
17  
18  import org.apache.commons.compress.archivers.ArchiveOutputStream;
19  import org.eclipse.jgit.archive.internal.ArchiveText;
20  import org.eclipse.jgit.util.StringUtils;
21  
22  /**
23   * Base format class
24   *
25   * @since 4.0
26   */
27  public class BaseFormat {
28  	/**
29  	 * Compression-level for the archive file. Only values in [0-9] are allowed.
30  	 * @since 5.11
31  	 */
32  	protected static final String COMPRESSION_LEVEL = "compression-level"; //$NON-NLS-1$
33  
34  	/**
35  	 * Apply options to archive output stream
36  	 *
37  	 * @param s
38  	 *            stream to apply options to
39  	 * @param o
40  	 *            options map
41  	 * @return stream with option applied
42  	 * @throws IOException
43  	 */
44  	protected ArchiveOutputStream applyFormatOptions(ArchiveOutputStream s,
45  			Map<String, Object> o) throws IOException {
46  		for (Map.Entry<String, Object> p : o.entrySet()) {
47  			try {
48  				if (p.getKey().equals(COMPRESSION_LEVEL)) {
49  					continue;
50  				}
51  				new Statement(s, "set" + StringUtils.capitalize(p.getKey()), //$NON-NLS-1$
52  						new Object[] { p.getValue() }).execute();
53  			} catch (Exception e) {
54  				throw new IOException(MessageFormat.format(
55  						ArchiveText.get().cannotSetOption, p.getKey()), e);
56  			}
57  		}
58  		return s;
59  	}
60  
61  	/**
62  	 * Removes and returns the {@link #COMPRESSION_LEVEL} key from the input map
63  	 * parameter if it exists, or -1 if this key does not exist.
64  	 *
65  	 * @param o
66  	 *            options map
67  	 * @return The compression level if it exists in the map, or -1 instead.
68  	 * @throws IllegalArgumentException
69  	 *             if the {@link #COMPRESSION_LEVEL} option does not parse to an
70  	 *             Integer.
71  	 * @since 5.11
72  	 */
73  	protected int getCompressionLevel(Map<String, Object> o) {
74  		if (!o.containsKey(COMPRESSION_LEVEL)) {
75  			return -1;
76  		}
77  		Object option = o.get(COMPRESSION_LEVEL);
78  		try {
79  			Integer compressionLevel = (Integer) option;
80  			return compressionLevel.intValue();
81  		} catch (ClassCastException e) {
82  			throw new IllegalArgumentException(
83  					MessageFormat.format(
84  							ArchiveText.get().invalidCompressionLevel, option),
85  					e);
86  		}
87  	}
88  }