1 package org.apache.maven.shared.dependency.analyzer;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.codehaus.plexus.util.IOUtil;
23 import org.junit.After;
24 import org.junit.Before;
25 import org.junit.Test;
26
27 import java.io.ByteArrayOutputStream;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.HashSet;
35 import java.util.Set;
36 import java.util.jar.JarOutputStream;
37 import java.util.zip.ZipEntry;
38 import java.util.zip.ZipException;
39
40 import static org.assertj.core.api.Assertions.assertThat;
41 import static org.assertj.core.api.Assertions.fail;
42
43
44
45
46
47
48
49 public class DefaultClassAnalyzerTest
50 {
51 private Path file;
52
53 @Before
54 public void setUp() throws IOException
55 {
56 file = Files.createTempFile( "test", ".jar" );
57 try ( JarOutputStream out = new JarOutputStream( new FileOutputStream( file.toFile() ) ) )
58 {
59 addZipEntry( out, "a/b/c.class", "class a.b.c" );
60 addZipEntry( out, "x/y/z.class", "class x.y.z" );
61 }
62 }
63
64 @After
65 public void cleanup() throws IOException
66 {
67 if ( file != null )
68 {
69 Files.deleteIfExists( file );
70 }
71 }
72
73 @Test
74 public void testAnalyzeWithJar() throws IOException
75 {
76 Set<String> expectedClasses = new HashSet<>();
77 expectedClasses.add( "a.b.c" );
78 expectedClasses.add( "x.y.z" );
79
80 DefaultClassAnalyzer analyzer = new DefaultClassAnalyzer();
81 Set<String> actualClasses = analyzer.analyze( file.toUri().toURL() );
82
83 assertThat( actualClasses ).isEqualTo( expectedClasses );
84 }
85
86 @Test
87 public void testAnalyzeBadJar() throws IOException
88 {
89
90
91 FileInputStream fis = new FileInputStream( file.toFile() );
92 ByteArrayOutputStream baos = new ByteArrayOutputStream( 100 );
93 IOUtil.copy( fis, baos, 100 );
94 fis.close();
95 byte[] ba = baos.toByteArray();
96 ba[50] = 1;
97 FileOutputStream fos = new FileOutputStream( file.toFile() );
98 IOUtil.copy( ba, fos );
99 fos.close();
100
101 ClassAnalyzer analyzer = new DefaultClassAnalyzer();
102
103 try
104 {
105 analyzer.analyze( file.toUri().toURL() );
106 fail( "Exception expected" );
107 }
108 catch ( ZipException e )
109 {
110 assertThat( e ).hasMessageStartingWith( "Cannot process Jar entry on URL:" );
111 }
112 }
113
114 private void addZipEntry( JarOutputStream out, String fileName, String content ) throws IOException
115 {
116 out.putNextEntry( new ZipEntry( fileName ) );
117 byte[] bytes = content.getBytes( StandardCharsets.UTF_8 );
118 out.write( bytes, 0, bytes.length );
119 }
120 }