Search in sources :

Example 16 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class PermissionUtils method setPermissions.

/**
 * Sets permissions on a {@link Resource} - doesn't do anything
 * for unsupported resource types.
 *
 * <p>Supported types are:</p>
 * <ul>
 *  <li>any {@link FileProvider}</li>
 *  <li>{@link ArchiveResource}</li>
 * </ul>
 *
 * @param r the resource to set permissions for
 * @param permissions the permissions
 * @param posixNotSupportedCallback optional callback that is
 * invoked for a file provider resource if the file-system holding
 * the file doesn't support PosixFilePermissions. The Path
 * corresponding to the file is passed to the callback.
 * @throws IOException if something goes wrong
 */
public static void setPermissions(Resource r, Set<PosixFilePermission> permissions, Consumer<Path> posixNotSupportedCallback) throws IOException {
    FileProvider f = r.as(FileProvider.class);
    if (f != null) {
        Path p = f.getFile().toPath();
        PosixFileAttributeView view = Files.getFileAttributeView(p, PosixFileAttributeView.class);
        if (view != null) {
            view.setPermissions(permissions);
        } else if (posixNotSupportedCallback != null) {
            posixNotSupportedCallback.accept(p);
        }
    } else if (r instanceof ArchiveResource) {
        ((ArchiveResource) r).setMode(modeFromPermissions(permissions, FileType.of(r)));
    }
}
Also used : Path(java.nio.file.Path) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ArchiveResource(org.apache.tools.ant.types.resources.ArchiveResource) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Example 17 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class ResourceUtils method areSame.

private static boolean areSame(final Resource resource1, final Resource resource2) throws IOException {
    if (resource1 == null || resource2 == null) {
        return false;
    }
    final FileProvider fileResource1 = resource1.as(FileProvider.class);
    if (fileResource1 == null) {
        return false;
    }
    final FileProvider fileResource2 = resource2.as(FileProvider.class);
    if (fileResource2 == null) {
        return false;
    }
    return FileUtils.getFileUtils().areSame(fileResource1.getFile(), fileResource2.getFile());
}
Also used : FileProvider(org.apache.tools.ant.types.resources.FileProvider)

Example 18 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class IntrospectionHelper method createAttributeSetter.

/**
 * Creates an implementation of AttributeSetter for the given
 * attribute type. Conversions (where necessary) are automatically
 * made for the following types:
 * <ul>
 * <li>String (left as it is)
 * <li>Character/char (first character is used)
 * <li>Boolean/boolean
 * ({@link Project#toBoolean(String) Project.toBoolean(String)} is used)
 * <li>Class (Class.forName is used)
 * <li>File (resolved relative to the appropriate project)
 * <li>Path (resolve relative to the appropriate project)
 * <li>Resource (resolved as a FileResource relative to the appropriate project)
 * <li>FileProvider (resolved as a FileResource relative to the appropriate project)
 * <li>EnumeratedAttribute (uses its own
 * {@link EnumeratedAttribute#setValue(String) setValue} method)
 * <li>Other primitive types (wrapper classes are used with constructors
 * taking String)
 * </ul>
 *
 * If none of the above covers the given parameters, a constructor for the
 * appropriate class taking a String parameter is used if it is available.
 *
 * @param m The method to invoke on the bean when the setter is invoked.
 *          Must not be <code>null</code>.
 * @param arg The type of the single argument of the bean's method.
 *            Must not be <code>null</code>.
 * @param attrName the name of the attribute for which the setter is being
 *                 created.
 *
 * @return an appropriate AttributeSetter instance, or <code>null</code>
 *         if no appropriate conversion is available.
 */
private AttributeSetter createAttributeSetter(final Method m, final Class<?> arg, final String attrName) {
    // use wrappers for primitive classes, e.g. int and
    // Integer are treated identically
    final Class<?> reflectedArg = PRIMITIVE_TYPE_MAP.containsKey(arg) ? PRIMITIVE_TYPE_MAP.get(arg) : arg;
    // Object.class - it gets handled differently by AttributeSetter
    if (java.lang.Object.class == reflectedArg) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                throw new BuildException("Internal ant problem - this should not get called");
            }
        };
    }
    // simplest case - setAttribute expects String
    if (String.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, (Object[]) new String[] { value });
            }
        };
    }
    // char and Character get special treatment - take the first character
    if (java.lang.Character.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                if (value.length() == 0) {
                    throw new BuildException("The value \"\" is not a " + "legal value for attribute \"" + attrName + "\"");
                }
                m.invoke(parent, (Object[]) new Character[] { value.charAt(0) });
            }
        };
    }
    // boolean and Boolean get special treatment because we have a nice method in Project
    if (java.lang.Boolean.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, (Object[]) new Boolean[] { Project.toBoolean(value) ? Boolean.TRUE : Boolean.FALSE });
            }
        };
    }
    // Class doesn't have a String constructor but a decent factory method
    if (java.lang.Class.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException {
                try {
                    m.invoke(parent, Class.forName(value));
                } catch (final ClassNotFoundException ce) {
                    throw new BuildException(ce);
                }
            }
        };
    }
    // resolve relative paths through Project
    if (java.io.File.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, p.resolveFile(value));
            }
        };
    }
    // resolve relative nio paths through Project
    if (java.nio.file.Path.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, p.resolveFile(value).toPath());
            }
        };
    }
    // resolve Resources/FileProviders as FileResources relative to Project:
    if (Resource.class.equals(reflectedArg) || FileProvider.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException {
                m.invoke(parent, new FileResource(p, p.resolveFile(value)));
            }
        };
    }
    // EnumeratedAttributes have their own helper class
    if (EnumeratedAttribute.class.isAssignableFrom(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException {
                try {
                    final EnumeratedAttribute ea = (EnumeratedAttribute) reflectedArg.newInstance();
                    ea.setValue(value);
                    m.invoke(parent, ea);
                } catch (final InstantiationException ie) {
                    throw new BuildException(ie);
                }
            }
        };
    }
    final AttributeSetter setter = getEnumSetter(reflectedArg, m, arg);
    if (setter != null) {
        return setter;
    }
    if (java.lang.Long.class.equals(reflectedArg)) {
        return new AttributeSetter(m, arg) {

            @Override
            public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException {
                try {
                    m.invoke(parent, StringUtils.parseHumanSizes(value));
                } catch (final NumberFormatException e) {
                    throw new BuildException("Can't assign non-numeric" + " value '" + value + "' to" + " attribute " + attrName);
                } catch (final InvocationTargetException e) {
                    throw e;
                } catch (final IllegalAccessException e) {
                    throw e;
                } catch (final Exception e) {
                    throw new BuildException(e);
                }
            }
        };
    }
    // worst case. look for a public String constructor and use it
    // also supports new Whatever(Project, String) as for Path or Reference
    // This is used (deliberately) for all primitives/wrappers other than
    // char, boolean, and long.
    boolean includeProject;
    Constructor<?> c;
    try {
        // First try with Project.
        c = reflectedArg.getConstructor(Project.class, String.class);
        includeProject = true;
    } catch (final NoSuchMethodException nme) {
        // OK, try without.
        try {
            c = reflectedArg.getConstructor(String.class);
            includeProject = false;
        } catch (final NoSuchMethodException nme2) {
            // Well, no matching constructor.
            return null;
        }
    }
    final boolean finalIncludeProject = includeProject;
    final Constructor<?> finalConstructor = c;
    return new AttributeSetter(m, arg) {

        @Override
        public void set(final Project p, final Object parent, final String value) throws InvocationTargetException, IllegalAccessException, BuildException {
            try {
                final Object[] args = finalIncludeProject ? new Object[] { p, value } : new Object[] { value };
                final Object attribute = finalConstructor.newInstance(args);
                if (p != null) {
                    p.setProjectReference(attribute);
                }
                m.invoke(parent, attribute);
            } catch (final InvocationTargetException e) {
                final Throwable cause = e.getCause();
                if (cause instanceof IllegalArgumentException) {
                    throw new BuildException("Can't assign value '" + value + "' to attribute " + attrName + ", reason: " + cause.getClass() + " with message '" + cause.getMessage() + "'");
                }
                throw e;
            } catch (final InstantiationException ie) {
                throw new BuildException(ie);
            }
        }
    };
}
Also used : Resource(org.apache.tools.ant.types.Resource) FileResource(org.apache.tools.ant.types.resources.FileResource) FileResource(org.apache.tools.ant.types.resources.FileResource) EnumeratedAttribute(org.apache.tools.ant.types.EnumeratedAttribute) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) FileProvider(org.apache.tools.ant.types.resources.FileProvider)

Example 19 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class Unpack method setSrcResource.

/**
 * The resource to expand; required.
 * @param src resource to expand
 */
public void setSrcResource(Resource src) {
    if (!src.isExists()) {
        throw new BuildException("the archive %s doesn't exist", src.getName());
    }
    if (src.isDirectory()) {
        throw new BuildException("the archive %s can't be a directory", src.getName());
    }
    FileProvider fp = src.as(FileProvider.class);
    if (fp != null) {
        source = fp.getFile();
    } else if (!supportsNonFileResources()) {
        throw new BuildException("The source %s is not a FileSystem Only FileSystem resources are supported.", src.getName());
    }
    srcResource = src;
}
Also used : FileProvider(org.apache.tools.ant.types.resources.FileProvider) BuildException(org.apache.tools.ant.BuildException)

Example 20 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class XmlProperty method execute.

/**
 * Run the task.
 * @throws BuildException The exception raised during task execution.
 * @todo validate the source file is valid before opening, print a better error message
 * @todo add a verbose level log message listing the name of the file being loaded
 */
@Override
public void execute() throws BuildException {
    Resource r = getResource();
    if (r == null) {
        throw new BuildException("XmlProperty task requires a source resource");
    }
    try {
        log("Loading " + src, Project.MSG_VERBOSE);
        if (r.isExists()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validate);
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(getEntityResolver());
            Document document;
            FileProvider fp = src.as(FileProvider.class);
            if (fp != null) {
                document = builder.parse(fp.getFile());
            } else {
                document = builder.parse(src.getInputStream());
            }
            Element topElement = document.getDocumentElement();
            // Keep a hashtable of attributes added by this task.
            // This task is allow to override its own properties
            // but not other properties.  So we need to keep track
            // of which properties we've added.
            addedAttributes = new Hashtable<>();
            if (keepRoot) {
                addNodeRecursively(topElement, prefix, null);
            } else {
                NodeList topChildren = topElement.getChildNodes();
                int numChildren = topChildren.getLength();
                for (int i = 0; i < numChildren; i++) {
                    addNodeRecursively(topChildren.item(i), prefix, null);
                }
            }
        } else {
            log("Unable to find property resource: " + r, Project.MSG_VERBOSE);
        }
    } catch (SAXException sxe) {
        // Error generated during parsing
        Exception x = sxe;
        if (sxe.getException() != null) {
            x = sxe.getException();
        }
        throw new BuildException("Failed to load " + src, x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        throw new BuildException(pce);
    } catch (IOException ioe) {
        // I/O error
        throw new BuildException("Failed to load " + src, ioe);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) IOException(java.io.IOException) Document(org.w3c.dom.Document) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileProvider(org.apache.tools.ant.types.resources.FileProvider) BuildException(org.apache.tools.ant.BuildException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

FileProvider (org.apache.tools.ant.types.resources.FileProvider)22 BuildException (org.apache.tools.ant.BuildException)13 Resource (org.apache.tools.ant.types.Resource)13 FileResource (org.apache.tools.ant.types.resources.FileResource)12 File (java.io.File)8 IOException (java.io.IOException)4 ArchiveResource (org.apache.tools.ant.types.resources.ArchiveResource)4 ResourceCollection (org.apache.tools.ant.types.ResourceCollection)3 URL (java.net.URL)2 Path (java.nio.file.Path)2 PosixFileAttributeView (java.nio.file.attribute.PosixFileAttributeView)2 ArrayList (java.util.ArrayList)2 Vector (java.util.Vector)2 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)2 FileSet (org.apache.tools.ant.types.FileSet)2 URLProvider (org.apache.tools.ant.types.resources.URLProvider)2 ZipResource (org.apache.tools.ant.types.resources.ZipResource)2 ZipFile (org.apache.tools.zip.ZipFile)2 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1