#Java - Code Snippets for '#Apache commons' - 73 code snippet(s) found |
|
Sample 1. Usage of Apache Commons - ArrayListValuedHashMap | |
|
ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");
System.out.println(listValuedMap); // Values being added to the List and allow even duplicates
|
|
Like Feedback apache commons apache commons collections ArrayListValuedHashMap ListValuedMap |
|
|
Sample 2. Get all Permutations of List Elements using Apache Commons PermutationIterator | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
PermutationIterator permIterator = new PermutationIterator((Collection) list);
permIterator.forEachRemaining(System.out::print); // prints [Washington, Nevada, California][Washington, California, Nevada][California, Washington, Nevada][California, Nevada, Washington][Nevada, California, Washington][Nevada, Washington, California]
|
|
Like Feedback Permutations of collection elements Permutations of List elements Apache Commons PermutationIterator Iterator Collections .forEachRemaining System.out::print List ArrayList |
|
|
Sample 3. Remove Numbers from a String using CharSetUtils (Apache Commons) | |
|
String str = new String("1H4ello1 World2");
String newStr = CharSetUtils.delete(str, "1234567890");
System.out.println(newStr); // prints Hello World
|
|
Like Feedback Apache Commons CharSetUtils Remove Numbers from String |
|
|
Sample 4. Write a Program for Graph Breadth First Traversal using Apache Commons MultiMap | |
|
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Graph {
private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
private static Set<Integer> alreadyVisited = new HashSet();
static{
adjacentDirectedNodesMap.put(1, 2);
adjacentDirectedNodesMap.put(1, 3);
adjacentDirectedNodesMap.put(1, 5);
adjacentDirectedNodesMap.put(2, 4);
adjacentDirectedNodesMap.put(4, 5);
}
public static void main(String[] args){
ArrayList visited = new ArrayList();
Integer startNode = 1;
displayAdjacentNodes(startNode);
}
private static void displayAdjacentNodes(Integer integer){
System.out.println(integer);
for(Map.Entry<Integer, Collection<Integer>> adjacentNodes: adjacentDirectedNodesMap.asMap().entrySet()){
for(Integer integer1:adjacentNodes.getValue()){
if(alreadyVisited.contains(integer1)){
continue;
}
alreadyVisited.add(integer1);
System.out.println(integer1);
}
}
}
}
|
|
Like Feedback graph traversal breadth first traversal |
|
|
|
Sample 5. Clear Map entries after expiration time using Apache commons PassiveExpiringMap | |
|
PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1000); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));
Thread.sleep(500);
System.out.println(cache.containsKey("Key1"));
|
|
Like Feedback expiring cache using map Clear Map entries after expiration time PassiveExpiringMap |
|
|
Sample 6. Usage of Apache Commons - HashSetValuedHashMap | |
|
SetValuedMap<String,String> setValuedMap = new HashSetValuedHashMap();
setValuedMap.put("United States", "Washington");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("South Africa", "Pretoria");
setValuedMap.put("South Africa", "Cape Town");
setValuedMap.put("South Africa", "Bloemfontein");
System.out.println(setValuedMap); // Values being added to the Set and hence doesn't allow duplicates
|
|
Like Feedback apache commons apache commons collections apache commons map HashSetValuedHashMap SetValuedMap |
|
|
Sample 7. Remove characters from the String using CharSetUtils | |
|
String str = new String("Hello World");
String newStr = CharSetUtils.delete(str, "abcde");
System.out.println(newStr); // prints Hllo Worl
|
|
Like Feedback Remove characters from the String String CharSetUtils Apache Commons |
|
|
Sample 8. Write a Program for Graph Depth First Traversal using Apache Commons MultiMap | |
|
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Graph {
private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
private static Set<Integer> alreadyVisited = new HashSet();
static{
adjacentDirectedNodesMap.put(1, 2);
adjacentDirectedNodesMap.put(1, 3);
adjacentDirectedNodesMap.put(1, 5);
adjacentDirectedNodesMap.put(2, 4);
adjacentDirectedNodesMap.put(4, 5);
}
public static void main(String[] args){
ArrayList visited = new ArrayList();
Integer startNode = 1;
displayAdjacentNodes(startNode);
}
private static void displayAdjacentNodes(Integer integer){
if(alreadyVisited.contains(integer)){
return;
}
alreadyVisited.add(integer);
System.out.println(integer);
for(Integer adjacentNodes: adjacentDirectedNodesMap.get(integer)){
displayAdjacentNodes(adjacentNodes);
}
}
}
|
|
Like Feedback graph traversal depth first algorithm |
|
|
Sample 9. Clear Map entries after expiration time using Apache commons PassiveExpiringMap | |
|
PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1,TimeUnit.SECONDS); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1")); // prints true
Thread.sleep(1000);
System.out.println(cache.containsKey("Key1")); // prints false
|
|
Like Feedback Clear Map entries after expiration PassiveExpiringMap map apache commons TimeUnit.SECONDS Thread.sleep |
|
|
|
Sample 10. Make a map readonly using Apache Commons UnmodifiableMap | |
|
Map<String,String> map = new HashMap();
map.put("Key1", "Value1");
Map<String,String> unmodifiableMap = UnmodifiableMap.unmodifiableMap(map);
unmodifiableMap.put("Key2", "Value2"); // throws java.lang.UnsupportedOperationException
|
|
Like Feedback readonly map apache commons |
|
|
Sample 11. Make a Map entry read only using Apache Commons UnmodifiableMapEntry | |
|
Entry entry = new UnmodifiableMapEntry("Key2", "Value2");
entry.setValue("Value3"); // throws java.lang.UnsupportedOperationException
|
|
Like Feedback read only map entry UnmodifiableMapEntry Apache commons collections |
|
|
Sample 12. Print all elements of a ListValuedMap ( Apache Commons ) using forEach and System.out::println | |
|
ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");
listValuedMap.entries().forEach(System.out::println);
|
|
Like Feedback ListValuedMap apache commons System.out::println collections framework map |
|
|
Sample 13. Count elements of a collection matching a Predicate using Apache Commons IterableUtils | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
list.add("New York");
list.add("New Jersey");
// <String> long org.apache.commons.collections4.IterableUtils.countMatches(Iterable<String> input, Predicate<? super String> predicate)
System.out.println(IterableUtils.countMatches(list, p->((String)p).startsWith("N")));
|
|
Like Feedback Apache Commons IterableUtils Apache Commons Predicate Java 8 Count elements of a collection java8 |
|
|
Sample 14. Find the Frequency of a Particular element in a Collection using apache Commons IterableUtils | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Washington");
list.add("Nevada");
System.out.println(IterableUtils.frequency(list, "Washington")); // prints 2
|
|
Like Feedback Frequency of a Particular element in a Collection Apache Commons IterableUtils IterableUtils.frequency |
|
|
|
Sample 15. Usage of Apache Commons CaseInsensitiveMap | |
|
Map<String, String> map = new CaseInsensitiveMap<String, String>();
map.put("US", "Washington");
map.put("us", "Washington DC");
System.out.println(map); // Prints {us=Washington DC} as Keys are case insensitive
|
|
Like Feedback CaseInsensitiveMap Map with Case insensitive keys apache commons apache commons collections |
|
|
Sample 16. Get Yesterdays Date using Apache Commons DateUtils | |
|
Date yesterdayDate = DateUtils.addDays(new Date(), -1);
|
|
Like Feedback DateUtils Apache Commons |
|
|
Sample 17. Reading / Parsing Command Line options using apache.commons.cli | |
|
public static void main(String[] args) {
Option option1 = OptionBuilder.withArgName("option").hasArg().create("option");
Options options = new Options();
CommandLineParser parser = new GnuParser();
options.addOption(option1);
final CommandLine commandLine = parser.parse(options, args);
final String[] commandLineArgs = commandLine.getArgs();
if (commandLine.hasOption("option")) {
}
}
|
|
Like Feedback Parsing Command Line options apache.commons.cli CommandLineParser GnuParser OptionBuilder Options |
|
|
Sample 18. Usage of Arrays using Apache Commons ArrayUtils | |
|
int array[] = new int[4];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 2;
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 3)); // Prints false
array = ArrayUtils.add(array, 3); // Add element 3 to the array
System.out.println(array.length); // Prints 5
System.out.println(ArrayUtils.contains(array, 3)); // Prints true
ArrayUtils.lastIndexOf(array, 2); // prints 3
array = ArrayUtils.removeElement(array, 1); // Remove element 1 to the array
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 1)); // Prints false
|
|
Like Feedback arrays ArrayUtils Apache Commons ArrayUtils Example ArrayUtils Sample |
|
|
Sample 19. Usage of Apache Commons CharSet | |
|
String str = new String("Hello World");
CharSet charSet = CharSet.getInstance(str);
System.out.println(charSet.contains('W')); // prints true
System.out.println(charSet.contains('w')); // prints false
|
|
Like Feedback CharSet Apache Commons CharSet Example CharSet Sample String characters |
|
|
|
Sample 20. Get the properties of class (i.e package name , interfaces , subclasses etc ) using ClassUtils( Apache Commons ) | |
|
Class class1 = ClassUtils.getClass("BuggyBreadTest");
System.out.println(ClassUtils.getPackageName(class1));
System.out.println(ClassUtils.getAllInterfaces(class1));
|
|
Like Feedback ClassUtils Apache Commons Get Class Properties java.lang.Class |
|
|
Sample 21. Remove special characters from a String using CharSetUtils ( Apache Commons ) | |
|
String str = new String("What's Up ?");
String newStr = CharSetUtils.delete(str, "'?");
System.out.println(newStr); // prints Whats Up
|
|
Like Feedback Apache Commons CharSetUtils Remove characters from String |
|
|
Sample 22. Check if the String contains specified characters using CharSetUtils (Apache Commons) | |
|
System.out.println(CharSetUtils.containsAny("Whats Up ?", "W")); // Prints true as the String contains character W System.out.println(CharSetUtils.containsAny("Whats Up ?", "YZ")); // Prints false as the String doesn't contain character Y or Z
|
|
Like Feedback CharSetUtils (Apache Commons) Check if String contains characters |
|
|
Sample 23. Print the characters that exist in the specified String using CharSetUtils ( Apache Commons ) | |
|
System.out.println(CharSetUtils.keep("Whats Up ?", "Watch")); // Prints Wat as only those characters matches in the String
|
|
Like Feedback Characters that exist in String CharSetUtils ( Apache Commons ) |
|
|
Sample 24. Apache Commons MultiSet Example | |
|
MultiSet<String> multiSet = new HashMultiSet();
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");
System.out.println(multiSet); // Prints [Albama:3]
|
|
Like Feedback Set with duplicate values MultiSet Apache Commons Collections |
|
|
|
Sample 25. Create an UnmodifiableMultiSet ( Read only set allowing multiple values ) using Apache Commons | |
|
MultiSet<String> multiSet = new HashMultiSet();
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");
System.out.println(multiSet); // Prints [Albama:3]
UnmodifiableMultiSet<String> unmodifiablemultiSet = (UnmodifiableMultiSet<String>) MultiSetUtils.unmodifiableMultiSet(multiSet);
unmodifiablemultiSet.add("Albama"); // throws java.lang.UnsupportedOperationException
|
|
Like Feedback UnmodifiableMultiSet Apache Commons Collections Set MultiSet |
|
|
Sample 26. Assign value to BigInteger upon validating the value using BigIntegerValidator ( Apache Commons ) | |
|
BigIntegerValidator bigIntegerValidator = BigIntegerValidator.getInstance();
BigInteger bigInteger = bigIntegerValidator.validate("1AD2345");
System.out.println(bigInteger); // prints null as the validation fails because of non numeric characters
|
|
Like Feedback Validate a Number Apache Commons Assign if the Number is valid BigInteger |
|
|
Sample 27. Check if the numerical value is within a specified range using BigIntegerValidator ( Apache Commons ) | |
|
System.out.println(bigIntegerValidator.isInRange(12, 0, 100)); // prints true because the value 12 falls in range 0-100
|
|
Like Feedback Check if the numerical value is within a specified range Apache Commons BigIntegerValidator |
|
|
Sample 28. Usage of Bit Flags ( Apache Commons ) | |
|
int male = 1 << 0;
int female = 1 << 1;
Flags flag = new Flags(1); // Select the Option
System.out.println(flag); //Prints 0000000000000000000000000000000000000000000000000000000000000001
if(flag.isOn(male)){
System.out.println("Male"); // Prints Male
}
if(flag.isOn(female)){
System.out.println("female");
}
flag = new Flags(2); // Select the Option
System.out.println(flag); //Prints 0000000000000000000000000000000000000000000000000000000000000010
if(flag.isOn(male)){
System.out.println("Male");
}
if(flag.isOn(female)){
System.out.println("female"); // prints female
}
|
|
Like Feedback Bit Flags Apache Commons |
|
|
Sample 29. Validate an IP Address using InetAddressValidator ( Apache Commons ) | |
|
InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
if (inetAddressValidator.isValid("123.123.123.123")) {
System.out.println("true"); // prints true
}
if (inetAddressValidator.isValid("www.buggybread.com")) {
System.out.println("true"); // doesn't print true here
}
|
|
Like Feedback Validate IP Address Apache Commons Validator |
|
|
|
Sample 30. Card Number Validation using CodeValidator and RegexValidator | |
|
String CARD_REGEX = "^(5[1-5]d{2})(?:[- ])?(d{4})(?:[- ])?(d{4})(?:[- ])?(d{4})$";
CodeValidator validator = new CodeValidator(CARD_REGEX, LuhnCheckDigit.LUHN_CHECK_DIGIT);
RegexValidator regex = validator.getRegexValidator();
|
|
Like Feedback Card Number Validation Apache Commons CodeValidator LuhnCheckDigit.LUHN_CHECK_DIGIT RegexValidator |
|
|
Sample 31. Email Validation using org.apache.commons.validator.routines.EmailValidator | |
|
EmailValidator validator = new EmailValidator();
validator.isValid("xyz@buggybread.com");
|
|
Like Feedback email validation |
|
|
Sample 32. Usage of org.apache.commons.validator.ValidatorAction | |
|
ValidatorAction va = new ValidatorAction();
va.setName(action);
va.setClassname("org.apache.commons.validator.ValidatorTest");
va.setMethod("formatDate");
va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");
FormSet fs = new FormSet();
Form form = new Form();
form.setName("testForm");
Field field = new Field();
field.setProperty(property);
field.setDepends(action);
form.addField(field);
fs.addForm(form);
resources.addValidatorAction(va);
resources.addFormSet(fs);
|
|
Like Feedback Apache Commons ValidatorAction FormSet |
|
|
Sample 33. Count Occurences of substring in a String using StringUtils ( Apache Commons ) | |
|
if(StringUtils.countMatches(snippet, "{") == StringUtils.countMatches(snippet, "}")){
System.out.println("Yes a Valid Code Snippet");
}
|
|
Like Feedback StringUtils Apache Commons Count Occurences of substring |
|
|
Sample 34. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory | |
|
public File getFsEditName() throws IOException {
return getEditLog().getFsEditName();
}
File getFsTimeName() {
StorageDirectory sd = null;
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();)
sd = it.next();
return getImageFile(sd, NameNodeFile.TIME);
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory |
|
|
|
Sample 35. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.UpgradeStatusReport | |
|
public String getUpgradeStatusText() {
String statusText = "";
try {
UpgradeStatusReport status =
fsn.distributedUpgradeProgress(UpgradeAction.GET_STATUS);
statusText = (status == null ?
"There are no upgrades in progress." :
status.getStatusText(false));
} catch(IOException e) {
statusText = "Upgrade status unknown.";
}
return statusText;
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.common.UpgradeStatusReport |
|
|
Sample 36. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpMethod | |
|
private static int httpNotification(String uri) throws IOException {
URI url = new URI(uri, false);
HttpClient m_client = new HttpClient();
HttpMethod method = new GetMethod(url.getEscapedURI());
method.setRequestHeader("Accept", "*/*");
return m_client.executeMethod(method);
}
|
|
Like Feedback org.apache.commons.httpclient.HttpMethod |
|
|
Sample 37. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpClient | |
|
private static int httpNotification(String uri) throws IOException {
URI url = new URI(uri, false);
HttpClient m_client = new HttpClient();
HttpMethod method = new GetMethod(url.getEscapedURI());
method.setRequestHeader("Accept", "*/*");
return m_client.executeMethod(method);
}
|
|
Like Feedback org.apache.commons.httpclient.HttpClient |
|
|
Sample 38. Printing Stack trace using Apache Commons ExceptionUtils | |
|
try {
} catch (Exception ex){
System.out.println(ExceptionUtils.getFullStackTrace(ex));
}
|
|
Like Feedback Apache Commons ExceptionUtils Apache commons |
|
|
Sample 39. Code Sample / Example / Snippet of org.apache.commons.crypto.cipher.CryptoCipher | |
|
public void testDefaultCipher() throws GeneralSecurityException {
CryptoCipher defaultCipher = CryptoCipherFactory
.getCryptoCipher("AES/CBC/NoPadding");
final String name = defaultCipher.getClass().getName();
if (OpenSsl.getLoadingFailureReason() == null) {
Assert.assertEquals(OpenSslCipher.class.getName(), name);
} else {
Assert.assertEquals(JceCipher.class.getName(), name);
}
}
|
|
Like Feedback org.apache.commons.crypto.cipher.CryptoCipher |
|
|
|
Sample 40. Code Sample / Example / Snippet of org.apache.commons.crypto.random.CryptoRandom | |
|
protected CryptoRandom getRandom(String className) throws Exception {
Properties props = new Properties();
props.setProperty(CryptoRandomFactory.CLASSES_KEY, className);
final CryptoRandom cryptoRandom = CryptoRandomFactory.getCryptoRandom(props);
Assert.assertEquals(className, cryptoRandom.getClass().getCanonicalName());
return cryptoRandom;
}
|
|
Like Feedback org.apache.commons.crypto.random.CryptoRandom |
|
|
Sample 41. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveEntry | |
|
private void addArchiveEntry(final ArchiveOutputStream out, final String filename, final File infile)
throws IOException, FileNotFoundException {
final ArchiveEntry entry = out.createArchiveEntry(infile, filename);
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(infile), out);
out.closeArchiveEntry();
archiveList.add(filename);
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveEntry |
|
|
Sample 42. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveOutputStream | |
|
protected File createEmptyArchive(final String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList<String>();
try {
archive = File.createTempFile("empty", "." + archivename);
archive.deleteOnExit();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
out.finish();
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveOutputStream |
|
|
Sample 43. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveInputStream | |
|
protected void checkArchiveContent(final File archive, final List<String> expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in = factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveInputStream |
|
|
Sample 44. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveEntry | |
|
protected String getExpectedString(final ArchiveEntry entry) {
if (entry instanceof TarArchiveEntry) {
final TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
if (tarEntry.isSymbolicLink()) {
return tarEntry.getName() + " -> " + tarEntry.getLinkName();
}
}
return entry.getName();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveEntry |
|
|
|
Sample 45. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveInputStream | |
|
private void testZipStreamWithImplodeCompression(final String filename, final String entryName) throws IOException {
final ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(new File(filename)));
final ZipArchiveEntry entry = zin.getNextZipEntry();
assertEquals("entry name", entryName, entry.getName());
assertTrue("entry can't be read", zin.canReadEntryData(entry));
assertEquals("method", ZipMethod.IMPLODING.getCode(), entry.getMethod());
final InputStream bio = new BoundedInputStream(zin, entry.getSize());
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final CheckedOutputStream out = new CheckedOutputStream(bout, new CRC32());
IOUtils.copy(bio, out);
out.flush();
assertEquals("CRC32", entry.getCrc(), out.getChecksum().getValue());
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveInputStream |
|
|
Sample 46. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.arj.ArjArchiveInputStream | |
|
public void testArjUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
expected.append("test1.xml<?xml version="1.0"?>
");
expected.append("<empty/>test2.xml<?xml version="1.0"?>
");
expected.append("<empty/>
");
final ArjArchiveInputStream in = new ArjArchiveInputStream(new FileInputStream(getFile("bla.arj")));
ArjArchiveEntry entry;
final StringBuilder result = new StringBuilder();
while ((entry = in.getNextEntry()) != null) {
result.append(entry.getName());
int tmp;
while ((tmp = in.read()) != -1) {
result.append((char) tmp);
}
assertFalse(entry.isDirectory());
}
in.close();
assertEquals(result.toString(), expected.toString());
}
|
|
Like Feedback org.apache.commons.compress.archivers.arj.ArjArchiveInputStream |
|
|
Sample 47. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ar.ArArchiveEntry | |
|
public void testLongFileNamesCauseExceptionByDefault() {
ArArchiveOutputStream os = null;
try {
os = new ArArchiveOutputStream(new ByteArrayOutputStream());
final ArArchiveEntry ae = new ArArchiveEntry("this_is_a_long_name.txt",
0);
os.putArchiveEntry(ae);
fail("Expected an exception");
} catch (final IOException ex) {
assertTrue(ex.getMessage().startsWith("filename too long"));
} finally {
closeQuietly(os);
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.ar.ArArchiveEntry |
|
|
Sample 48. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveEntry | |
|
public void testCompressionMethod() throws Exception {
final ZipArchiveOutputStream zos =
new ZipArchiveOutputStream(new ByteArrayOutputStream());
final ZipArchiveEntry entry = new ZipArchiveEntry("foo");
assertEquals(-1, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.STORED);
assertEquals(ZipEntry.STORED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.DEFLATED);
assertEquals(ZipEntry.DEFLATED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(6);
assertEquals(6, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
zos.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveEntry |
|
|
Sample 49. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipFile | |
|
private void removeEntriesFoundInZipFile(final File result, final Map<String, byte[]> entries) throws IOException {
final ZipFile zf = new ZipFile(result);
final Enumeration<ZipArchiveEntry> entriesInPhysicalOrder = zf.getEntriesInPhysicalOrder();
while (entriesInPhysicalOrder.hasMoreElements()){
final ZipArchiveEntry zipArchiveEntry = entriesInPhysicalOrder.nextElement();
final InputStream inputStream = zf.getInputStream(zipArchiveEntry);
final byte[] actual = IOUtils.toByteArray(inputStream);
final byte[] expected = entries.remove(zipArchiveEntry.getName());
assertArrayEquals( "For " + zipArchiveEntry.getName(), expected, actual);
}
zf.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipFile |
|
|
|
Sample 50. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZOutputFile | |
|
public void testReadingBackLZMA2DictSize() throws Exception {
final File output = new File(dir, "lzma2-dictsize.7z");
final SevenZOutputFile outArchive = new SevenZOutputFile(output);
try {
outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setName("foo.txt");
outArchive.putArchiveEntry(entry);
outArchive.write(new byte[] { 'A' });
outArchive.closeArchiveEntry();
} finally {
outArchive.close();
}
final SevenZFile archive = new SevenZFile(output);
try {
final SevenZArchiveEntry entry = archive.getNextEntry();
final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();
assertEquals(SevenZMethod.LZMA2, m.getMethod());
assertEquals(1 << 20, m.getOptions());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZOutputFile |
|
|
Sample 51. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZFile | |
|
public void testAllEmptyFilesArchive() throws Exception {
final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"));
try {
assertNotNull(archive.getNextEntry());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZFile |
|
|
Sample 52. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry | |
|
public void testReadingBackLZMA2DictSize() throws Exception {
final File output = new File(dir, "lzma2-dictsize.7z");
final SevenZOutputFile outArchive = new SevenZOutputFile(output);
try {
outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setName("foo.txt");
outArchive.putArchiveEntry(entry);
outArchive.write(new byte[] { 'A' });
outArchive.closeArchiveEntry();
} finally {
outArchive.close();
}
final SevenZFile archive = new SevenZFile(output);
try {
final SevenZArchiveEntry entry = archive.getNextEntry();
final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();
assertEquals(SevenZMethod.LZMA2, m.getMethod());
assertEquals(1 << 20, m.getOptions());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry |
|
|
Sample 53. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream | |
|
public void testCpioUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
expected.append("./test1.xml<?xml version="1.0"?>
");
expected.append("<empty/>./test2.xml<?xml version="1.0"?>
");
expected.append("<empty/>
");
final CpioArchiveInputStream in = new CpioArchiveInputStream(new FileInputStream(getFile("bla.cpio")));
CpioArchiveEntry entry;
final StringBuilder result = new StringBuilder();
while ((entry = (CpioArchiveEntry) in.getNextEntry()) != null) {
result.append(entry.getName());
int tmp;
while ((tmp = in.read()) != -1) {
result.append((char) tmp);
}
}
in.close();
assertEquals(result.toString(), expected.toString());
}
|
|
Like Feedback org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream |
|
|
Sample 54. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipEncoding | |
|
private static void assertUnicodeName(final ZipArchiveEntry ze,
final String expectedName,
final String encoding)
throws IOException {
if (!expectedName.equals(ze.getName())) {
final UnicodePathExtraField ucpf = findUniCodePath(ze);
assertNotNull(ucpf);
final ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding);
final ByteBuffer ne = enc.encode(ze.getName());
final CRC32 crc = new CRC32();
crc.update(ne.array(), ne.arrayOffset(),
ne.limit() - ne.position());
assertEquals(crc.getValue(), ucpf.getNameCRC32());
assertEquals(expectedName, new String(ucpf.getUnicodeName(),
CharsetNames.UTF_8));
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipEncoding |
|
|
|
Sample 55. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveStreamFactory | |
|
public void testEncodingCtor() {
ArchiveStreamFactory fac = new ArchiveStreamFactory();
assertNull(fac.getEntryEncoding());
fac = new ArchiveStreamFactory(null);
assertNull(fac.getEntryEncoding());
fac = new ArchiveStreamFactory("UTF-8");
assertEquals("UTF-8", fac.getEntryEncoding());
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveStreamFactory |
|
|
Sample 56. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorStreamFactory | |
|
public void testOverride() {
CompressorStreamFactory fac = new CompressorStreamFactory();
assertFalse(fac.getDecompressConcatenated());
fac.setDecompressConcatenated(true);
assertTrue(fac.getDecompressConcatenated());
fac = new CompressorStreamFactory(false);
assertFalse(fac.getDecompressConcatenated());
try {
fac.setDecompressConcatenated(true);
fail("Expected IllegalStateException");
} catch (final IllegalStateException ise) {
}
fac = new CompressorStreamFactory(true);
assertTrue(fac.getDecompressConcatenated());
try {
fac.setDecompressConcatenated(true);
fail("Expected IllegalStateException");
} catch (final IllegalStateException ise) {
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.CompressorStreamFactory |
|
|
Sample 57. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorInputStream | |
|
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final FileOutputStream os = new FileOutputStream(output);
IOUtils.copy(in, os);
is.close();
os.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.CompressorInputStream |
|
|
Sample 58. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipParameters | |
|
public void testInvalidCompressionLevel() {
final GzipParameters parameters = new GzipParameters();
try {
parameters.setCompressionLevel(10);
fail("IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
}
try {
parameters.setCompressionLevel(-5);
fail("IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.gzip.GzipParameters |
|
|
Sample 59. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream | |
|
private void testExtraFlags(final int compressionLevel, final int flag) throws Exception {
final FileInputStream fis = new FileInputStream(getFile("test3.xml"));
byte[] content;
try {
content = IOUtils.toByteArray(fis);
} finally {
fis.close();
}
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final GzipParameters parameters = new GzipParameters();
parameters.setCompressionLevel(compressionLevel);
final GzipCompressorOutputStream out = new GzipCompressorOutputStream(bout, parameters);
IOUtils.copy(new ByteArrayInputStream(content), out);
out.flush();
out.close();
assertEquals("extra flags (XFL)", flag, bout.toByteArray()[8]);
}
|
|
Like Feedback org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream |
|
|
|
Sample 60. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateParameters | |
|
public void testRawDeflateCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.deflate");
final OutputStream out = new FileOutputStream(output);
try {
final DeflateParameters params = new DeflateParameters();
params.setWithZlibHeader(false);
final CompressorOutputStream cos = new DeflateCompressorOutputStream(out, params);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateParameters |
|
|
Sample 61. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveInputStream | |
|
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
final Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463
"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveInputStream |
|
|
Sample 62. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream | |
|
public void readOfLength0ShouldReturn0() throws Exception {
final byte[] rawData = new byte[1048576];
for (int i=0; i < rawData.length; ++i) {
rawData[i] = (byte) Math.floor(Math.random()*256);
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);
bzipOut.write(rawData);
bzipOut.flush();
bzipOut.close();
baos.flush();
baos.close();
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);
final byte[] buffer = new byte[1024];
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
bzipIn.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream |
|
|
Sample 63. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BitInputStream | |
|
public void testClearBitCache() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x08, bis.readBits(4));
bis.clearBitCache();
assertEquals(0, bis.readBits(1));
bis.close();
}
|
|
Like Feedback org.apache.commons.compress.utils.BitInputStream |
|
|
Sample 64. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BoundedInputStream | |
|
public void writeTo(final ZipArchiveOutputStream target) throws IOException {
backingStore.closeForWriting();
final InputStream data = backingStore.getInputStream();
for (final CompressedEntry compressedEntry : items) {
final BoundedInputStream rawStream = new BoundedInputStream(data, compressedEntry.compressedSize);
target.addRawArchiveEntry(compressedEntry.transferToArchiveEntry(), rawStream);
rawStream.close();
}
data.close();
}
|
|
Like Feedback org.apache.commons.compress.utils.BoundedInputStream |
|
|
|
Sample 65. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream | |
|
public void testCompressionMethod() throws Exception {
final ZipArchiveOutputStream zos =
new ZipArchiveOutputStream(new ByteArrayOutputStream());
final ZipArchiveEntry entry = new ZipArchiveEntry("foo");
assertEquals(-1, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.STORED);
assertEquals(ZipEntry.STORED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.DEFLATED);
assertEquals(ZipEntry.DEFLATED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(6);
assertEquals(6, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
zos.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream |
|
|
Sample 66. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveOutputStream | |
|
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final String encoding = CharsetNames.UTF_16;
final String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890u00e4";
final TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
final byte[] data = bos.toByteArray();
final ByteArrayInputStream bis = new ByteArrayInputStream(data);
final TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveOutputStream |
|
|
Sample 67. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.dump.DumpArchiveInputStream | |
|
public void testConsumesArchiveCompletely() throws Exception {
final InputStream is = DumpArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.dump");
final DumpArchiveInputStream dump = new DumpArchiveInputStream(is);
while (dump.getNextDumpEntry() != null) {
}
final byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '
'
};
final byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
dump.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.dump.DumpArchiveInputStream |
|
|
Sample 68. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream | |
|
public void readOfLength0ShouldReturn0() throws Exception {
final byte[] rawData = new byte[1048576];
for (int i=0; i < rawData.length; ++i) {
rawData[i] = (byte) Math.floor(Math.random()*256);
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);
bzipOut.write(rawData);
bzipOut.flush();
bzipOut.close();
baos.flush();
baos.close();
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);
final byte[] buffer = new byte[1024];
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
bzipIn.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream |
|
|
Sample 69. Code Sample / Example / Snippet of org.apache.commons.compress.utils.CountingOutputStream | |
|
public void output() throws Exception {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final CountingOutputStream o = new CountingOutputStream(bos);
o.write(1);
assertEquals(1, o.getBytesWritten());
o.write(new byte[] { 2, 3 });
assertEquals(3, o.getBytesWritten());
o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);
assertEquals(4, o.getBytesWritten());
o.count(-1);
assertEquals(4, o.getBytesWritten());
o.count(-2);
assertEquals(2, o.getBytesWritten());
o.close();
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());
}
|
|
Like Feedback org.apache.commons.compress.utils.CountingOutputStream |
|
|
|
Sample 70. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream | |
|
public void testRemainingChunkTypes() throws Exception {
final FileInputStream isSz = new FileInputStream(getFile("mixed.txt.sz"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
final FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(isSz);
IOUtils.copy(in, out);
out.close();
} finally {
isSz.close();
}
assertArrayEquals(new byte[] { '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9', 10,
'1', '2', '3', '4',
'1', '2', '3', '4',
}, out.toByteArray());
}
|
|
Like Feedback org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream |
|
|
Sample 71. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream | |
|
public void availableShouldReturnNonZero() throws IOException {
final File input = AbstractTestCase.getFile("bla.tar.deflatez");
final InputStream is = new FileInputStream(input);
try {
final DeflateCompressorInputStream in =
new DeflateCompressorInputStream(is);
Assert.assertTrue(in.available() > 0);
in.close();
} finally {
is.close();
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream |
|
|
Sample 72. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream | |
|
public void canReadASingleByteFlushAndFinish() throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final DeflateCompressorOutputStream cos = new DeflateCompressorOutputStream(bos);
cos.write(99);
cos.flush();
cos.finish();
Assert.assertTrue(bos.toByteArray().length > 0);
cos.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream |
|
|
Sample 73. GunZip file using Apache Commons
| |
|
public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
try {
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}
|
|
Like Feedback Zip file using Apache Commons Compress file using Apache Commons GunZip file using Apache Commons Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorOutputStream IOUtils.copy |
|
|