Search in sources :

Example 1 with Model

use of org.apache.sling.provisioning.model.Model in project sling by apache.

the class ProjectHelper method getEffectiveModel.

/**
     * Get the effective model from the project
     * @param project The maven projet
     * @return The effective model
     * @throws MojoExecutionException If reading fails
     */
public static Model getEffectiveModel(final MavenProject project, ResolverOptions resolverOptions) throws MojoExecutionException {
    Model result = (Model) project.getContextValue(EFFECTIVE_MODEL_CACHE);
    if (result == null) {
        try {
            final StringReader r = new StringReader((String) project.getContextValue(EFFECTIVE_MODEL_TXT));
            result = ModelReader.read(r, project.getId());
            result = ModelUtility.getEffectiveModel(result, resolverOptions);
            project.setContextValue(EFFECTIVE_MODEL_CACHE, result);
        } catch (final IOException ioe) {
            throw new MojoExecutionException(ioe.getMessage(), ioe);
        }
    }
    return result;
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Model(org.apache.sling.provisioning.model.Model) StringReader(java.io.StringReader) IOException(java.io.IOException)

Example 2 with Model

use of org.apache.sling.provisioning.model.Model in project sling by apache.

the class ProjectHelper method storeProjectInfo.

/**
     * Store all relevant information about the project for plugins to be
     * retrieved
     * @param info The project info
     * @throws IOException If writing fails
     */
public static void storeProjectInfo(final ModelPreprocessor.ProjectInfo info) throws IOException {
    // we have to serialize as the dependency lifecycle participant uses a different class loader (!)
    final StringWriter w1 = new StringWriter();
    ModelWriter.write(w1, info.localModel);
    info.project.setContextValue(RAW_MODEL_TXT, w1.toString());
    final StringWriter w2 = new StringWriter();
    ModelWriter.write(w2, info.model);
    info.project.setContextValue(EFFECTIVE_MODEL_TXT, w2.toString());
    // create map with model dependencies
    final Map<String, String> map = new HashMap<String, String>();
    for (final Map.Entry<Artifact, Model> entry : info.includedModels.entrySet()) {
        final StringWriter w3 = new StringWriter();
        ModelWriter.write(w3, entry.getValue());
        map.put(entry.getKey().toMvnUrl(), w3.toString());
    }
    info.project.setContextValue(DEPENDENCY_MODEL, map);
}
Also used : StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) Model(org.apache.sling.provisioning.model.Model) HashMap(java.util.HashMap) Map(java.util.Map) Artifact(org.apache.sling.provisioning.model.Artifact)

Example 3 with Model

use of org.apache.sling.provisioning.model.Model in project sling by apache.

the class InstallModelTask method transform.

private Result transform(final String name, final String modelText, final int featureIndex, final TaskResource rsrc, final File baseDir) {
    Model model = null;
    try (final Reader reader = new StringReader(modelText)) {
        model = ModelUtility.getEffectiveModel(ModelReader.read(reader, name));
    } catch (final IOException ioe) {
        logger.warn("Unable to read model file for feature " + name, ioe);
    }
    if (model == null) {
        return null;
    }
    int index = 0;
    final Iterator<Feature> iter = model.getFeatures().iterator();
    while (iter.hasNext()) {
        iter.next();
        if (index != featureIndex) {
            iter.remove();
        }
        index++;
    }
    if (baseDir != null) {
        final List<Artifact> artifacts = new ArrayList<>();
        final Feature feature = model.getFeatures().get(0);
        for (final RunMode rm : feature.getRunModes()) {
            for (final ArtifactGroup group : rm.getArtifactGroups()) {
                for (final Artifact a : group) {
                    artifacts.add(a);
                }
            }
        }
        // extract artifacts
        final byte[] buffer = new byte[1024 * 1024 * 256];
        try (final InputStream is = rsrc.getInputStream()) {
            ModelArchiveReader.read(is, new ModelArchiveReader.ArtifactConsumer() {

                @Override
                public void consume(final Artifact artifact, final InputStream is) throws IOException {
                    if (artifacts.contains(artifact)) {
                        final File artifactFile = new File(baseDir, artifact.getRepositoryPath().replace('/', File.separatorChar));
                        if (!artifactFile.exists()) {
                            artifactFile.getParentFile().mkdirs();
                            try (final OutputStream os = new FileOutputStream(artifactFile)) {
                                int l = 0;
                                while ((l = is.read(buffer)) > 0) {
                                    os.write(buffer, 0, l);
                                }
                            }
                        }
                    }
                }
            });
        } catch (final IOException ioe) {
            logger.warn("Unable to extract artifacts from model " + name, ioe);
            return null;
        }
    }
    final List<ArtifactDescription> files = new ArrayList<>();
    Map<Traceable, String> errors = collectArtifacts(model, files, baseDir);
    if (errors == null) {
        final Result result = new Result();
        for (final ArtifactDescription desc : files) {
            if (desc.artifactFile != null) {
                try {
                    final InputStream is = new FileInputStream(desc.artifactFile);
                    final String digest = String.valueOf(desc.artifactFile.lastModified());
                    // handle start level
                    final Dictionary<String, Object> dict = new Hashtable<String, Object>();
                    if (desc.startLevel > 0) {
                        dict.put(InstallableResource.BUNDLE_START_LEVEL, desc.startLevel);
                    }
                    dict.put(InstallableResource.RESOURCE_URI_HINT, desc.artifactFile.toURI().toString());
                    result.resources.add(new InstallableResource("/" + desc.artifactFile.getName(), is, dict, digest, InstallableResource.TYPE_FILE, null));
                } catch (final IOException ioe) {
                    logger.warn("Unable to read artifact " + desc.artifactFile, ioe);
                    return null;
                }
            } else if (desc.cfg != null) {
                final String id = (desc.cfg.getFactoryPid() != null ? desc.cfg.getFactoryPid() + "-" + desc.cfg.getPid() : desc.cfg.getPid());
                result.resources.add(new InstallableResource("/" + id + ".config", null, desc.cfg.getProperties(), null, InstallableResource.TYPE_CONFIG, null));
            } else if (desc.section != null) {
                result.repoinit = desc.section.getContents();
            }
        }
        return result;
    }
    logger.warn("Errors during parsing model file {} : {}", name, errors.values());
    return null;
}
Also used : InstallableResource(org.apache.sling.installer.api.InstallableResource) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) ModelArchiveReader(org.apache.sling.provisioning.model.io.ModelArchiveReader) Reader(java.io.Reader) StringReader(java.io.StringReader) ModelReader(org.apache.sling.provisioning.model.io.ModelReader) Feature(org.apache.sling.provisioning.model.Feature) StringReader(java.io.StringReader) Traceable(org.apache.sling.provisioning.model.Traceable) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Hashtable(java.util.Hashtable) IOException(java.io.IOException) Artifact(org.apache.sling.provisioning.model.Artifact) FileInputStream(java.io.FileInputStream) ModelArchiveReader(org.apache.sling.provisioning.model.io.ModelArchiveReader) RunMode(org.apache.sling.provisioning.model.RunMode) FileOutputStream(java.io.FileOutputStream) Model(org.apache.sling.provisioning.model.Model) ArtifactGroup(org.apache.sling.provisioning.model.ArtifactGroup) File(java.io.File)

Example 4 with Model

use of org.apache.sling.provisioning.model.Model in project sling by apache.

the class ModelTransformer method transform.

@Override
public TransformationResult[] transform(final RegisteredResource resource) {
    Model model = null;
    File baseDir = null;
    if (resource.getType().equals(InstallableResource.TYPE_FILE) && resource.getURL().endsWith(".model")) {
        try (final Reader reader = new InputStreamReader(resource.getInputStream(), "UTF-8")) {
            model = ModelReader.read(reader, resource.getURL());
        } catch (final IOException ioe) {
            logger.info("Unable to read model from " + resource.getURL(), ioe);
        }
    }
    if (resource.getType().equals(InstallableResource.TYPE_FILE) && resource.getURL().endsWith(".mar")) {
        baseDir = this.bundleContext.getDataFile("");
        try (final InputStream is = resource.getInputStream()) {
            model = ModelArchiveReader.read(is, new ModelArchiveReader.ArtifactConsumer() {

                @Override
                public void consume(final Artifact artifact, final InputStream is) throws IOException {
                // nothing to do, install task does extraction
                }
            });
        } catch (final IOException ioe) {
            logger.info("Unable to read model from " + resource.getURL(), ioe);
        }
    }
    if (model != null) {
        Map<Traceable, String> errors = ModelUtility.validate(model);
        if (errors == null) {
            try {
                final Model effectiveModel = ModelUtility.getEffectiveModel(model);
                errors = ModelUtility.validateIncludingVersion(effectiveModel);
                if (errors == null) {
                    String modelTxt = null;
                    try (final StringWriter sw = new StringWriter()) {
                        ModelWriter.write(sw, effectiveModel);
                        modelTxt = sw.toString();
                    } catch (final IOException ioe) {
                        logger.info("Unable to read model from " + resource.getURL(), ioe);
                    }
                    if (modelTxt != null) {
                        final TransformationResult[] result = new TransformationResult[effectiveModel.getFeatures().size()];
                        int index = 0;
                        for (final Feature f : effectiveModel.getFeatures()) {
                            final TransformationResult tr = new TransformationResult();
                            tr.setResourceType(TYPE_PROV_MODEL);
                            tr.setId(f.getName());
                            tr.setVersion(new Version(f.getVersion()));
                            final Map<String, Object> attributes = new HashMap<>();
                            attributes.put(ATTR_MODEL, modelTxt);
                            attributes.put(ATTR_FEATURE_INDEX, index);
                            attributes.put(ATTR_FEATURE_NAME, f.getName() + "-" + f.getVersion());
                            if (baseDir != null) {
                                final File dir = new File(baseDir, f.getName() + "-" + f.getVersion());
                                attributes.put(ATTR_BASE_PATH, dir.getAbsolutePath());
                            }
                            tr.setAttributes(attributes);
                            result[index] = tr;
                            index++;
                        }
                        return result;
                    }
                }
            } catch (final IllegalArgumentException iae) {
                errors = Collections.singletonMap((Traceable) model, iae.getMessage());
            }
        }
        if (errors != null) {
            logger.warn("Errors during parsing model at {} : {}", resource.getURL(), errors.values());
        }
    }
    return null;
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ModelArchiveReader(org.apache.sling.provisioning.model.io.ModelArchiveReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ModelReader(org.apache.sling.provisioning.model.io.ModelReader) IOException(java.io.IOException) Feature(org.apache.sling.provisioning.model.Feature) Artifact(org.apache.sling.provisioning.model.Artifact) StringWriter(java.io.StringWriter) Version(org.osgi.framework.Version) Model(org.apache.sling.provisioning.model.Model) Traceable(org.apache.sling.provisioning.model.Traceable) TransformationResult(org.apache.sling.installer.api.tasks.TransformationResult) File(java.io.File)

Example 5 with Model

use of org.apache.sling.provisioning.model.Model in project sling by apache.

the class ModelArchiveReader method read.

/**
     * Read a model archive.
     * The input stream is not closed. It is up to the caller to close the input stream.
     * @param in The input stream to read from.
     * @return The model
     * @throws IOException If anything goes wrong
     */
@SuppressWarnings("resource")
public static Model read(final InputStream in, final ArtifactConsumer consumer) throws IOException {
    Model model = null;
    final JarInputStream jis = new JarInputStream(in);
    // check manifest
    final Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Not a model archive - manifest is missing.");
    }
    // check manifest header
    final String version = manifest.getMainAttributes().getValue(ModelArchiveWriter.MANIFEST_HEADER);
    if (version == null) {
        throw new IOException("Not a model archive - manifest header is missing.");
    }
    // validate manifest header
    try {
        final int number = Integer.valueOf(version);
        if (number < 1 || number > ModelArchiveWriter.ARCHIVE_VERSION) {
            throw new IOException("Not a model archive - invalid manifest header value: " + version);
        }
    } catch (final NumberFormatException nfe) {
        throw new IOException("Not a model archive - invalid manifest header value: " + version);
    }
    // read contents
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (ModelArchiveWriter.MODEL_NAME.equals(entry.getName())) {
            model = ModelUtility.getEffectiveModel(ModelReader.read(new InputStreamReader(jis, "UTF-8"), null));
        } else if (!entry.isDirectory() && entry.getName().startsWith(ModelArchiveWriter.ARTIFACTS_PREFIX)) {
            // artifact
            final Artifact artifact = Artifact.fromMvnUrl("mvn:" + entry.getName().substring(ModelArchiveWriter.ARTIFACTS_PREFIX.length()));
            consumer.consume(artifact, jis);
        }
        jis.closeEntry();
    }
    if (model == null) {
        throw new IOException("Not a model archive - model file is missing.");
    }
    return model;
}
Also used : InputStreamReader(java.io.InputStreamReader) JarInputStream(java.util.jar.JarInputStream) Model(org.apache.sling.provisioning.model.Model) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) Artifact(org.apache.sling.provisioning.model.Artifact)

Aggregations

Model (org.apache.sling.provisioning.model.Model)23 IOException (java.io.IOException)12 File (java.io.File)11 StringReader (java.io.StringReader)8 Feature (org.apache.sling.provisioning.model.Feature)7 Traceable (org.apache.sling.provisioning.model.Traceable)7 Artifact (org.apache.sling.provisioning.model.Artifact)6 MavenExecutionException (org.apache.maven.MavenExecutionException)5 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)5 Test (org.junit.Test)5 InputStream (java.io.InputStream)4 ArrayList (java.util.ArrayList)4 ModelReader (org.apache.sling.provisioning.model.io.ModelReader)4 FileInputStream (java.io.FileInputStream)3 Reader (java.io.Reader)3 StringWriter (java.io.StringWriter)3 Map (java.util.Map)3 Manifest (java.util.jar.Manifest)3 FileOutputStream (java.io.FileOutputStream)2 FileReader (java.io.FileReader)2