Search in sources :

Example 6 with IRepository

use of org.eclipse.winery.repository.backend.IRepository in project winery by eclipse.

the class WineryUsingHttpServer method main.

/**
 * When in IntelliJ, /tmp/winery-repository is used. See /src/test/resources/winery.properties
 */
public static void main(String[] args) throws Exception {
    // initialize repository
    new Prefs(true);
    Server server = createHttpServer();
    server.start();
    Server uiServer = createHttpServerForRepositoryUi();
    uiServer.start();
    IRepository repository = RepositoryFactory.getRepository();
    if (repository instanceof FilebasedRepository) {
        LOGGER.debug("Using path " + ((FilebasedRepository) repository).getRepositoryRoot());
    } else {
        LOGGER.debug("Repository is not filebased");
    }
    server.join();
    uiServer.join();
}
Also used : Server(org.eclipse.jetty.server.Server) FilebasedRepository(org.eclipse.winery.repository.backend.filebased.FilebasedRepository) Prefs(org.eclipse.winery.repository.rest.Prefs) IRepository(org.eclipse.winery.repository.backend.IRepository)

Example 7 with IRepository

use of org.eclipse.winery.repository.backend.IRepository in project winery by eclipse.

the class WineryCli method main.

public static void main(String[] args) throws ParseException {
    Option repositoryPathOption = new Option("p", "path", true, "use given path as repository path");
    Option serviceTemplatesOnlyOption = new Option("so", "servicetemplatesonly", false, "checks service templates instead of the whole repository");
    Option checkDocumentationOption = new Option("cd", "checkdocumentation", false, "check existence of README.md and LICENSE. Default: No check");
    Option verboseOption = new Option("v", "verbose", false, "be verbose: Output the checked elements");
    Option helpOption = new Option("h", "help", false, "prints this help");
    Options options = new Options();
    options.addOption(repositoryPathOption);
    options.addOption(serviceTemplatesOnlyOption);
    options.addOption(checkDocumentationOption);
    options.addOption(verboseOption);
    options.addOption(helpOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);
    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("winery", options);
        System.exit(0);
    }
    IRepository repository;
    if (line.hasOption("p")) {
        repository = RepositoryFactory.getRepository(Paths.get(line.getOptionValue("p")));
    } else {
        repository = RepositoryFactory.getRepository();
    }
    System.out.println("Using repository path " + ((FilebasedRepository) repository).getRepositoryRoot() + "...");
    EnumSet<ConsistencyCheckerVerbosity> verbosity;
    if (line.hasOption("v")) {
        verbosity = EnumSet.of(ConsistencyCheckerVerbosity.OUTPUT_NUMBER_OF_TOSCA_COMPONENTS, ConsistencyCheckerVerbosity.OUTPUT_CURRENT_TOSCA_COMPONENT_ID, ConsistencyCheckerVerbosity.OUTPUT_ERRORS);
    } else {
        verbosity = EnumSet.of(ConsistencyCheckerVerbosity.OUTPUT_NUMBER_OF_TOSCA_COMPONENTS);
    }
    boolean serviceTemplatesOnly = line.hasOption("so");
    boolean checkDocumentation = line.hasOption("cd");
    ConsistencyCheckerConfiguration configuration = new ConsistencyCheckerConfiguration(serviceTemplatesOnly, checkDocumentation, verbosity, repository);
    ProgressBar progressBar = new ProgressBar("Check", 100, ProgressBarStyle.ASCII);
    progressBar.start();
    ConsistencyErrorLogger errors = ConsistencyChecker.checkCorruption(configuration, new ConsistencyCheckerProgressListener() {

        @Override
        public void updateProgress(float progress) {
            progressBar.stepTo((long) (progress * 100));
        }

        @Override
        public void updateProgress(float progress, String checkingDefinition) {
            progressBar.setExtraMessage("Now checking " + checkingDefinition);
            progressBar.stepTo((long) (progress * 100));
        }
    });
    progressBar.stop();
    System.out.println();
    if (errors.getErrorList().isEmpty()) {
        System.out.println("No errors exist.");
    } else {
        System.out.println("Errors found in the repository:");
        System.out.println();
        for (Map.Entry<QName, ElementErrorList> qName : errors.getErrorList().entrySet()) {
            System.out.println(qName.getKey());
            ElementErrorList elementErrorList = qName.getValue();
            if (Objects.nonNull(elementErrorList.getErrors())) {
                System.out.println("\tErrors:");
                for (String error : elementErrorList.getErrors()) {
                    System.out.println("\t\t" + error);
                }
            }
            if (Objects.nonNull(elementErrorList.getWarnings())) {
                System.out.println("\n\tWarnings:");
                for (String error : elementErrorList.getWarnings()) {
                    System.out.println("\t\t" + error);
                }
            }
            System.out.println();
        }
        System.exit(1);
    }
}
Also used : QName(javax.xml.namespace.QName) IRepository(org.eclipse.winery.repository.backend.IRepository) ProgressBar(me.tongfei.progressbar.ProgressBar) Map(java.util.Map)

Example 8 with IRepository

use of org.eclipse.winery.repository.backend.IRepository in project winery by eclipse.

the class ServiceTemplateComplianceRuleRuleChecker method checkComplianceRules.

public ServiceTemplateCheckingResult checkComplianceRules() {
    StringBuilder checkingResult = new StringBuilder("Rulechecking result for servicetemplate " + serviceTemplate.getIdFromIdOrNameField() + System.lineSeparator());
    ServiceTemplateCheckingResult result = new ServiceTemplateCheckingResult();
    List<ComplianceRuleId> ruleIds = getRuleIds(serviceTemplate);
    if (ruleIds.isEmpty()) {
        checkingResult.append("No rules defined");
    } else {
        IRepository repository = RepositoryFactory.getRepository();
        for (ComplianceRuleId ruleId : ruleIds) {
            TComplianceRule tComplianceRule = repository.getElement(ruleId);
            ComplianceRuleChecker checker = new ComplianceRuleChecker(tComplianceRule, serviceTemplate.getTopologyTemplate());
            List<GraphMapping> graphMappings;
            try {
                graphMappings = checker.checkComplianceRule();
                if (graphMappings.size() > 0) {
                    result.getUnsatisfied().add(ruleId.getQName());
                    checkingResult.append(ruleId.getQName().toString() + " violated:");
                    checkingResult.append(System.lineSeparator());
                    for (GraphMapping mapping : graphMappings) {
                        Map<TOSCANode, TOSCANode> resultMap = checker.getSubGraphMappingAsMap(mapping, checker.getIdentifierGraph());
                        checkingResult.append(System.lineSeparator());
                        checkingResult.append(resultMap.values().stream().map(node -> node.getNodeTemplate().getIdFromIdOrNameField()).collect(Collectors.joining(";", "NodeTemplateIds: ", "")));
                    }
                } else {
                    result.getSatisfied().add(ruleId.getQName());
                    checkingResult.append(ruleId.getQName().toString() + " satisfied");
                }
            } catch (ComplianceCheckingException e) {
                result.getException().add(ruleId.getQName());
                LOGGER.debug("Could not check compliance at rule " + ruleId.getQName().toString(), e);
            }
        }
    }
    LOGGER.debug(checkingResult.toString());
    return result;
}
Also used : ComplianceRuleId(org.eclipse.winery.common.ids.definitions.ComplianceRuleId) TComplianceRule(org.eclipse.winery.model.tosca.TComplianceRule) IRepository(org.eclipse.winery.repository.backend.IRepository) TOSCANode(org.eclipse.winery.compliance.model.TOSCANode) GraphMapping(org.jgrapht.GraphMapping)

Example 9 with IRepository

use of org.eclipse.winery.repository.backend.IRepository in project winery by eclipse.

the class Splitting method composeServiceTemplates.

/**
 * @param serviceTemplateIds
 * @return
 * @throws IOException
 */
public ServiceTemplateId composeServiceTemplates(String composedSolutionServiceTemplateID, List<ServiceTemplateId> serviceTemplateIds) throws IOException, SplittingException {
    IRepository repository = RepositoryFactory.getRepository();
    String solutionNamespace = "http://www.opentosca.org/solutions/";
    // create composed service template
    ServiceTemplateId composedServiceTemplateId = new ServiceTemplateId(solutionNamespace, composedSolutionServiceTemplateID, false);
    repository.forceDelete(composedServiceTemplateId);
    repository.flagAsExisting(composedServiceTemplateId);
    TServiceTemplate composedServiceTemplate = new TServiceTemplate();
    composedServiceTemplate.setName(composedServiceTemplateId.getXmlId().getDecoded());
    composedServiceTemplate.setId(composedServiceTemplate.getName());
    composedServiceTemplate.setTargetNamespace(solutionNamespace);
    TTopologyTemplate composedTopologyTemplate = new TTopologyTemplate();
    composedServiceTemplate.setTopologyTemplate(composedTopologyTemplate);
    repository.setElement(composedServiceTemplateId, composedServiceTemplate);
    // add all node and relationship templates from the solution fragements to the composed topology template
    for (ServiceTemplateId id : serviceTemplateIds) {
        BackendUtils.mergeServiceTemplateAinServiceTemplateB(id, composedServiceTemplateId);
    }
    composedServiceTemplate = repository.getElement(composedServiceTemplateId);
    composedTopologyTemplate = composedServiceTemplate.getTopologyTemplate();
    List<TRequirement> openRequirements = getOpenRequirements(composedTopologyTemplate);
    for (TRequirement requirement : openRequirements) {
        QName requiredCapabilityTypeQName = getRequiredCapabilityTypeQNameOfRequirement(requirement);
        TNodeTemplate nodeWithOpenCapability = composedTopologyTemplate.getNodeTemplates().stream().filter(nt -> nt.getCapabilities() != null).filter(nt -> nt.getCapabilities().getCapability().stream().anyMatch(c -> c.getType().equals(requiredCapabilityTypeQName))).findFirst().orElse(null);
        if (nodeWithOpenCapability != null) {
            TCapability matchingCapability = nodeWithOpenCapability.getCapabilities().getCapability().stream().filter(c -> c.getType().equals(requiredCapabilityTypeQName)).findFirst().get();
            TRelationshipType matchingRelationshipType = getMatchingRelationshipType(requirement, matchingCapability);
            if (matchingRelationshipType != null) {
                addMatchingRelationshipTemplateToTopologyTemplate(composedTopologyTemplate, matchingRelationshipType, requirement, matchingCapability);
            } else {
                throw new SplittingException("No suitable relationship type found for matching");
            }
        }
    }
    LOGGER.debug("Persisting...");
    repository.setElement(composedServiceTemplateId, composedServiceTemplate);
    LOGGER.debug("Persisted.");
    return composedServiceTemplateId;
}
Also used : java.util(java.util) RequirementTypeId(org.eclipse.winery.common.ids.definitions.RequirementTypeId) ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) CapabilityTypeId(org.eclipse.winery.common.ids.definitions.CapabilityTypeId) Util(org.eclipse.winery.common.Util) Collectors(java.util.stream.Collectors) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) RelationshipTypeId(org.eclipse.winery.common.ids.definitions.RelationshipTypeId) org.eclipse.winery.model.tosca(org.eclipse.winery.model.tosca) DASpecification(org.eclipse.winery.repository.driverspecificationandinjection.DASpecification) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) IRepository(org.eclipse.winery.repository.backend.IRepository) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) DriverInjection(org.eclipse.winery.repository.driverspecificationandinjection.DriverInjection) QName(javax.xml.namespace.QName) NonNull(org.eclipse.jdt.annotation.NonNull) QName(javax.xml.namespace.QName) ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) IRepository(org.eclipse.winery.repository.backend.IRepository)

Example 10 with IRepository

use of org.eclipse.winery.repository.backend.IRepository in project winery by eclipse.

the class AbstractComponentsResource method getListOfAllIds.

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>.
 * <p>
 * If grouped is set, the list will be grouped by namespace.
 * <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped, @QueryParam("full") @ApiParam("If set, the full information of the definition's child is returned. E.g., in the case of node types, the same result as a GET on {ns}/{id] is returned. Works only in the case of grouped.") String full) {
    Class<? extends DefinitionsChildId> idClass = RestUtils.getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    final IRepository repository = RepositoryFactory.getRepository();
    SortedSet<? extends DefinitionsChildId> allDefinitionsChildIds = repository.getAllDefinitionsChildIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.setCodec(BackendUtils.mapper);
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (DefinitionsChildId id : allDefinitionsChildIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource.getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                if (full != null) {
                    try {
                        jg.writeFieldName("full");
                        jg.writeObject(BackendUtils.getDefinitionsHavingCorrectImports(repository, id));
                    } catch (Exception e) {
                        throw new WebApplicationException(e);
                    }
                }
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends DefinitionsChildId>> groupedIds = allDefinitionsChildIds.stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource.getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            if (full != null) {
                                try {
                                    jg.writeFieldName("full");
                                    jg.writeObject(BackendUtils.getDefinitionsHavingCorrectImports(repository, id));
                                } catch (Exception e) {
                                    throw new WebApplicationException(e);
                                }
                            }
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}
Also used : java.util(java.util) ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) LoggerFactory(org.slf4j.LoggerFactory) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) Constructor(java.lang.reflect.Constructor) NotFoundException(com.sun.jersey.api.NotFoundException) MediaType(javax.ws.rs.core.MediaType) ArtifactTemplateId(org.eclipse.winery.common.ids.definitions.ArtifactTemplateId) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Status(javax.ws.rs.core.Response.Status) PolicyTemplateId(org.eclipse.winery.common.ids.definitions.PolicyTemplateId) Logger(org.slf4j.Logger) StringWriter(java.io.StringWriter) IOException(java.io.IOException) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) Util(org.eclipse.winery.common.Util) Collectors(java.util.stream.Collectors) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) InvocationTargetException(java.lang.reflect.InvocationTargetException) JsonFactory(com.fasterxml.jackson.core.JsonFactory) javax.ws.rs(javax.ws.rs) IRepository(org.eclipse.winery.repository.backend.IRepository) RestUtils(org.eclipse.winery.repository.rest.RestUtils) Namespace(org.eclipse.winery.common.ids.Namespace) QName(javax.xml.namespace.QName) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) JsonFactory(com.fasterxml.jackson.core.JsonFactory) IOException(java.io.IOException) NotFoundException(com.sun.jersey.api.NotFoundException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Namespace(org.eclipse.winery.common.ids.Namespace) StringWriter(java.io.StringWriter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) IRepository(org.eclipse.winery.repository.backend.IRepository)

Aggregations

IRepository (org.eclipse.winery.repository.backend.IRepository)14 IOException (java.io.IOException)7 QName (javax.xml.namespace.QName)6 ServiceTemplateId (org.eclipse.winery.common.ids.definitions.ServiceTemplateId)5 WebApplicationException (javax.ws.rs.WebApplicationException)4 NonNull (org.eclipse.jdt.annotation.NonNull)4 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 Util (org.eclipse.winery.common.Util)3 BackendUtils (org.eclipse.winery.repository.backend.BackendUtils)3 RepositoryFactory (org.eclipse.winery.repository.backend.RepositoryFactory)3 LoggerFactory (org.slf4j.LoggerFactory)3 MalformedURLException (java.net.MalformedURLException)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 Namespace (org.eclipse.winery.common.ids.Namespace)2 ArtifactTemplateId (org.eclipse.winery.common.ids.definitions.ArtifactTemplateId)2 DefinitionsChildId (org.eclipse.winery.common.ids.definitions.DefinitionsChildId)2