File: ObrRemoteClean.java

package info (click to toggle)
maven-bundle-plugin 2.5.4-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,140 kB
  • ctags: 12,536
  • sloc: java: 7,404; xml: 293; sh: 30; makefile: 5
file content (481 lines) | stat: -rw-r--r-- 16,711 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.felix.obrplugin;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * Clean a remote repository file.
 * It just looks for every resources and check that pointed file exists.
 * 
 * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
 */
@Mojo( name = "remote-clean", requiresProject = false, defaultPhase = LifecyclePhase.CLEAN )
public final class ObrRemoteClean extends AbstractMojo
{
    /**
     * When true, ignore remote locking.
     */
    @Parameter( property = "ignoreLock" )
    private boolean ignoreLock;

    /**
     * Optional public URL prefix for the remote repository.
     */
    @Parameter( property = "prefixUrl" )
    private String prefixUrl;

    /**
     * Remote OBR Repository.
     */
    @Parameter( property = "remoteOBR", defaultValue = "NONE" )
    private String remoteOBR;

    /**
     * Local OBR Repository.
     */
    @Parameter( property = "obrRepository" )
    private String obrRepository;

    /**
     * Project types which this plugin supports.
     */
    @Parameter
    private List supportedProjectTypes = Arrays.asList( new String[]
        { "jar", "bundle" } );

    @Parameter( defaultValue = "${project.distributionManagementArtifactRepository}", readonly = true )
    private ArtifactRepository deploymentRepository;

    /**
     * Alternative deployment repository. Format: id::layout::url
     */
    @Parameter( property = "altDeploymentRepository" )
    private String altDeploymentRepository;

    /**
     * OBR specific deployment repository. Format: id::layout::url
     */
    @Parameter( property = "obrDeploymentRepository" )
    private String obrDeploymentRepository;

    @Parameter( defaultValue = "${settings.interactiveMode}", readonly = true )
    private boolean interactive;

    /**
     * The Maven project.
     */
    @Parameter( defaultValue = "${project}", readonly = true, required = true )
    private MavenProject project;

    /**
     * Local Maven settings.
     */
    @Parameter( defaultValue = "${settings}", readonly = true, required = true )
    private Settings settings;

    /**
     * The Wagon manager.
     */
    @Component
    private WagonManager m_wagonManager;


    public void execute() throws MojoExecutionException
    {
        String projectType = project.getPackaging();

        // ignore unsupported project types, useful when bundleplugin is configured in parent pom
        if ( !supportedProjectTypes.contains( projectType ) )
        {
            getLog().warn(
                "Ignoring project type " + projectType + " - supportedProjectTypes = " + supportedProjectTypes );
            return;
        }
        else if ( "NONE".equalsIgnoreCase( remoteOBR ) || "false".equalsIgnoreCase( remoteOBR ) )
        {
            getLog().info( "Remote OBR update disabled (enable with -DremoteOBR)" );
            return;
        }

        // if the user doesn't supply an explicit name for the remote OBR file, use the local name instead
        if ( null == remoteOBR || remoteOBR.trim().length() == 0 || "true".equalsIgnoreCase( remoteOBR ) )
        {
            remoteOBR = obrRepository;
        }

        URI tempURI = ObrUtils.findRepositoryXml( "", remoteOBR );
        String repositoryName = new File( tempURI.getSchemeSpecificPart() ).getName();

        Log log = getLog();

        RemoteFileManager remoteFile = new RemoteFileManager( m_wagonManager, settings, log );
        openRepositoryConnection( remoteFile );
        if ( null == prefixUrl )
        {
            prefixUrl = remoteFile.toString();
        }

        // ======== LOCK REMOTE OBR ========
        log.info( "LOCK " + remoteFile + '/' + repositoryName );
        remoteFile.lockFile( repositoryName, ignoreLock );
        File downloadedRepositoryXml = null;

        try
        {
            // ======== DOWNLOAD REMOTE OBR ========
            log.info( "Downloading " + repositoryName );
            downloadedRepositoryXml = remoteFile.get( repositoryName, ".xml" );

            URI repositoryXml = downloadedRepositoryXml.toURI();

            Config userConfig = new Config();
            userConfig.setRemoteFile( true );

            // Clean the downloaded file.
            Document doc = parseFile( new File( repositoryXml ), initConstructor() );
            Node finalDocument = cleanDocument( doc.getDocumentElement() );

            if ( finalDocument == null )
            {
                getLog().info( "Nothing to clean in " + repositoryName );
            }
            else
            {
                writeToFile( repositoryXml, finalDocument ); // Write the new file
                getLog().info( "Repository " + repositoryName + " cleaned" );
                // ======== UPLOAD MODIFIED OBR ========
                log.info( "Uploading " + repositoryName );
                remoteFile.put( downloadedRepositoryXml, repositoryName );
            }
        }
        catch ( Exception e )
        {
            log.warn( "Exception while updating remote OBR: " + e.getLocalizedMessage(), e );
        }
        finally
        {
            // ======== UNLOCK REMOTE OBR ========
            log.info( "UNLOCK " + remoteFile + '/' + repositoryName );
            remoteFile.unlockFile( repositoryName );
            remoteFile.disconnect();

            if ( null != downloadedRepositoryXml )
            {
                downloadedRepositoryXml.delete();
            }
        }
    }

    private static final Pattern ALT_REPO_SYNTAX_PATTERN = Pattern.compile( "(.+)::(.+)::(.+)" );


    private void openRepositoryConnection( RemoteFileManager remoteFile ) throws MojoExecutionException
    {
        // use OBR specific deployment location?
        if ( obrDeploymentRepository != null )
        {
            altDeploymentRepository = obrDeploymentRepository;
        }

        if ( deploymentRepository == null && altDeploymentRepository == null )
        {
            String msg = "Deployment failed: repository element was not specified in the pom inside"
                + " distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter";

            throw new MojoExecutionException( msg );
        }

        if ( altDeploymentRepository != null )
        {
            getLog().info( "Using alternate deployment repository " + altDeploymentRepository );

            Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher( altDeploymentRepository );
            if ( !matcher.matches() )
            {
                throw new MojoExecutionException( "Invalid syntax for alternative repository \""
                    + altDeploymentRepository + "\". Use \"id::layout::url\"." );
            }

            remoteFile.connect( matcher.group( 1 ).trim(), matcher.group( 3 ).trim() );
        }
        else
        {
            remoteFile.connect( deploymentRepository.getId(), deploymentRepository.getUrl() );
        }
    }


    /**
     * Analyze the given XML tree (DOM of the repository file) and remove missing resources.
     * This method ask the user before deleting the resources from the repository.
     * @param elem : the input XML tree
     * @return the cleaned XML tree
     */
    private Element cleanDocument( Element elem )
    {
        NodeList nodes = elem.getElementsByTagName( "resource" );
        List toRemove = new ArrayList();

        // First, look for missing resources
        for ( int i = 0; i < nodes.getLength(); i++ )
        {
            Element n = ( Element ) nodes.item( i );
            String value = n.getAttribute( "uri" );

            URL url;
            try
            {
                url = new URL( new URL( prefixUrl + '/' ), value );
            }
            catch ( MalformedURLException e )
            {
                getLog().error( "Malformed URL when creating the resource absolute URI : " + e.getMessage() );
                return null;
            }

            try
            {
                url.openConnection().getContent();
            }
            catch ( IOException e )
            {
                getLog().info(
                    "The bundle " + n.getAttribute( "presentationname" ) + " - " + n.getAttribute( "version" )
                        + " will be removed : " + e.getMessage() );
                toRemove.add( n );
            }
        }

        Date d = new Date();
        if ( toRemove.size() > 0 )
        {
            String answer = "y";
            if ( interactive )
            {
                System.out.println( "Do you want to remove these bundles from the repository file [y/N]:" );
                BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

                try
                {
                    answer = br.readLine();
                }
                catch ( IOException ioe )
                {
                    getLog().error( "IO error trying to read the user confirmation" );
                    return null;
                }
            }

            if ( answer != null && answer.trim().equalsIgnoreCase( "y" ) )
            {
                // Then remove missing resources.
                for ( int i = 0; i < toRemove.size(); i++ )
                {
                    elem.removeChild( ( Node ) toRemove.get( i ) );
                }

                // If we have to remove resources, we need to update 'lastmodified' attribute
                SimpleDateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss.SSS" );
                d.setTime( System.currentTimeMillis() );
                elem.setAttribute( "lastmodified", format.format( d ) );
                return elem;
            }
            else
            {
                return null;
            }
        }

        return null;
    }


    /**
     * Initialize the document builder from Xerces.
     * 
     * @return DocumentBuilder ready to create new document
     * @throws MojoExecutionException : occurs when the instantiation of the document builder fails
     */
    private DocumentBuilder initConstructor() throws MojoExecutionException
    {
        DocumentBuilder constructor = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            constructor = factory.newDocumentBuilder();
        }
        catch ( ParserConfigurationException e )
        {
            getLog().error( "Unable to create a new xml document" );
            throw new MojoExecutionException( "Cannot create the Document Builder : " + e.getMessage() );
        }
        return constructor;
    }


    /**
     * Open an XML file.
     * 
     * @param file : XML file
     * @param constructor DocumentBuilder get from xerces
     * @return Document which describes this file
     * @throws MojoExecutionException occurs when the given file cannot be opened or is a valid XML file.
     */
    private Document parseFile( File file, DocumentBuilder constructor ) throws MojoExecutionException
    {
        if ( constructor == null )
        {
            return null;
        }
        // The document is the root of the DOM tree.
        File targetFile = file.getAbsoluteFile();
        getLog().info( "Parsing " + targetFile );
        Document doc = null;
        try
        {
            doc = constructor.parse( targetFile );
        }
        catch ( SAXException e )
        {
            getLog().error( "Cannot parse " + targetFile + " : " + e.getMessage() );
            throw new MojoExecutionException( "Cannot parse " + targetFile + " : " + e.getMessage() );
        }
        catch ( IOException e )
        {
            getLog().error( "Cannot open " + targetFile + " : " + e.getMessage() );
            throw new MojoExecutionException( "Cannot open " + targetFile + " : " + e.getMessage() );
        }
        return doc;
    }


    /**
     * write a Node in a xml file.
     * 
     * @param outputFilename URI to the output file
     * @param treeToBeWrite Node root of the tree to be write in file
     * @throws MojoExecutionException if the plugin failed
     */
    private void writeToFile( URI outputFilename, Node treeToBeWrite ) throws MojoExecutionException
    {
        // init the transformer
        Transformer transformer = null;
        TransformerFactory tfabrique = TransformerFactory.newInstance();
        try
        {
            transformer = tfabrique.newTransformer();
        }
        catch ( TransformerConfigurationException e )
        {
            getLog().error( "Unable to write to file: " + outputFilename.toString() );
            throw new MojoExecutionException( "Unable to write to file: " + outputFilename.toString() + " : "
                + e.getMessage() );
        }
        Properties proprietes = new Properties();
        proprietes.put( "method", "xml" );
        proprietes.put( "version", "1.0" );
        proprietes.put( "encoding", "ISO-8859-1" );
        proprietes.put( "standalone", "yes" );
        proprietes.put( "indent", "yes" );
        proprietes.put( "omit-xml-declaration", "no" );
        transformer.setOutputProperties( proprietes );

        DOMSource input = new DOMSource( treeToBeWrite );

        File fichier = new File( outputFilename );
        FileOutputStream flux = null;
        try
        {
            flux = new FileOutputStream( fichier );
        }
        catch ( FileNotFoundException e )
        {
            getLog().error( "Unable to write to file: " + fichier.getName() );
            throw new MojoExecutionException( "Unable to write to file: " + fichier.getName() + " : " + e.getMessage() );
        }
        Result output = new StreamResult( flux );
        try
        {
            transformer.transform( input, output );
        }
        catch ( TransformerException e )
        {
            throw new MojoExecutionException( "Unable to write to file: " + outputFilename.toString() + " : "
                + e.getMessage() );
        }

        try
        {
            flux.flush();
            flux.close();
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "IOException when closing file : " + e.getMessage() );
        }
    }
}