Search in sources :

Example 6 with SnowowlRuntimeException

use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.

the class ExpandParser method parse.

public static Options parse(final String expand) {
    String jsonizedOptionPart = String.format("{%s}", expand.replace("(", ":{").replace(')', '}'));
    try {
        JsonParser parser = JSON_FACTORY.createParser(jsonizedOptionPart);
        parser.setCodec(new ObjectMapper());
        Map<String, Object> source = parser.<Map<String, Object>>readValueAs(new TypeReference<Map<String, Object>>() {
        });
        return OptionsBuilder.newBuilder().putAll(source).build();
    } catch (JsonParseException e) {
        throw new BadRequestException("Expansion parameter %s is malformed.", expand);
    } catch (IOException e) {
        throw new SnowowlRuntimeException("Caught I/O exception while reading expansion parameters.", e);
    }
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 7 with SnowowlRuntimeException

use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.

the class SnomedRf2ExportRequest method execute.

@Override
public Attachment execute(final BranchContext context) {
    final String referenceBranch = context.path();
    if (referenceBranch.contains(RevisionIndex.AT_CHAR) && !Rf2ReleaseType.SNAPSHOT.equals(releaseType)) {
        throw new BadRequestException("Only snapshot export is allowed for point-in-time branch path '%s'.", referenceBranch);
    }
    if (referenceBranch.contains(RevisionIndex.REV_RANGE)) {
        if (!Rf2ReleaseType.DELTA.equals(releaseType) || needsVersionBranchesForDeltaExport()) {
            throw new BadRequestException("Only unpublished delta export is allowed for branch path range '%s'.", referenceBranch);
        }
    }
    // register export start time for later use
    final long exportStartTime = Instant.now().toEpochMilli();
    // Step 1: check if the export reference branch is a working branch path descendant
    final CodeSystem referenceCodeSystem = (CodeSystem) context.service(TerminologyResource.class);
    if (!CompareUtils.isEmpty(referenceCodeSystem.getSettings())) {
        if (Strings.isNullOrEmpty(countryNamespaceElement)) {
            if (maintainerType == null) {
                String maintainerType = (String) referenceCodeSystem.getSettings().get(SnomedTerminologyComponentConstants.CODESYSTEM_MAINTAINER_TYPE_CONFIG_KEY);
                String nrcCountryCode = (String) referenceCodeSystem.getSettings().get(SnomedTerminologyComponentConstants.CODESYSTEM_NRC_COUNTRY_CODE_CONFIG_KEY);
                if (!Strings.isNullOrEmpty(maintainerType)) {
                    String customCountryNamespaceElement = getCountryNamespaceElement(context, referenceCodeSystem, Rf2MaintainerType.getByNameIgnoreCase(maintainerType), Strings.nullToEmpty(nrcCountryCode));
                    countryNamespaceElement = customCountryNamespaceElement;
                }
            } else {
                countryNamespaceElement = getCountryNamespaceElement(context, referenceCodeSystem, maintainerType, Strings.nullToEmpty(nrcCountryCode));
            }
        }
        if (refSetExportLayout == null && referenceCodeSystem.getSettings().containsKey(SnomedTerminologyComponentConstants.CODESYSTEM_RF2_EXPORT_LAYOUT_CONFIG_KEY)) {
            String refSetLayout = (String) referenceCodeSystem.getSettings().get(SnomedTerminologyComponentConstants.CODESYSTEM_RF2_EXPORT_LAYOUT_CONFIG_KEY);
            Rf2RefSetExportLayout rf2RefSetExportLayout = Rf2RefSetExportLayout.getByNameIgnoreCase(refSetLayout);
            refSetExportLayout = rf2RefSetExportLayout;
        }
    }
    if (Strings.isNullOrEmpty(countryNamespaceElement)) {
        countryNamespaceElement = getCountryNamespaceElement(context, referenceCodeSystem, DEFAULT_MAINTAINER_TYPE, "");
    }
    if (refSetExportLayout == null) {
        refSetExportLayout = DEFAULT_RF2_EXPORT_LAYOUT;
    }
    // Step 2: retrieve code system versions that are visible from the reference branch
    final TreeSet<Version> versionsToExport = getAllExportableCodeSystemVersions(context, referenceCodeSystem);
    // Step 3: compute branches to export
    final List<String> branchesToExport = computeBranchesToExport(referenceBranch, versionsToExport);
    // Step 4: compute possible language codes
    Multimap<String, String> availableLanguageCodes = getLanguageCodes(context, branchesToExport);
    Path exportDirectory = null;
    try {
        final UUID exportId = UUID.randomUUID();
        // create temporary export directory
        exportDirectory = createExportDirectory(exportId);
        // get archive effective time based on latest version effective / transient effective time / current date
        final LocalDateTime archiveEffectiveDate = getArchiveEffectiveTime(context, versionsToExport);
        final String archiveEffectiveDateShort = EffectiveTimes.format(archiveEffectiveDate.toLocalDate(), DateFormats.SHORT);
        // create main folder including release status and archive effective date
        final Path releaseDirectory = createReleaseDirectory(exportDirectory, archiveEffectiveDate);
        final Set<String> visitedComponentEffectiveTimes = newHashSet();
        final long effectiveTimeStart = startEffectiveTime != null ? EffectiveTimes.getEffectiveTime(startEffectiveTime) : 0;
        final long effectiveTimeEnd = endEffectiveTime != null ? EffectiveTimes.getEffectiveTime(endEffectiveTime) : Long.MAX_VALUE;
        // export content from the pre-computed version branches
        for (String branch : branchesToExport) {
            exportBranch(releaseDirectory, context, branch, archiveEffectiveDateShort, effectiveTimeStart, effectiveTimeEnd, visitedComponentEffectiveTimes, availableLanguageCodes.get(branch));
        }
        // export content from reference branch
        if (includePreReleaseContent) {
            // If a special branch path was given, use it directly
            final String referenceBranchToExport = containsSpecialCharacter(referenceBranch) ? referenceBranch : RevisionIndex.toBranchAtPath(referenceBranch, exportStartTime);
            exportBranch(releaseDirectory, context, referenceBranchToExport, archiveEffectiveDateShort, EffectiveTimes.UNSET_EFFECTIVE_TIME, EffectiveTimes.UNSET_EFFECTIVE_TIME, visitedComponentEffectiveTimes, availableLanguageCodes.get(referenceBranch));
        }
        // Step 6: compress to archive and upload to the file registry
        final AttachmentRegistry fileRegistry = context.service(AttachmentRegistry.class);
        registerResult(fileRegistry, exportId, exportDirectory);
        final String fileName = releaseDirectory.getFileName() + ".zip";
        return new Attachment(exportId, fileName);
    } catch (final Exception e) {
        throw new SnowowlRuntimeException("Failed to export terminology content to RF2.", e);
    } finally {
        if (exportDirectory != null) {
            FileUtils.deleteDirectory(exportDirectory.toFile());
        }
    }
}
Also used : Path(java.nio.file.Path) LocalDateTime(java.time.LocalDateTime) AttachmentRegistry(com.b2international.snowowl.core.attachments.AttachmentRegistry) Attachment(com.b2international.snowowl.core.attachments.Attachment) CodeSystem(com.b2international.snowowl.core.codesystem.CodeSystem) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) IOException(java.io.IOException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Version(com.b2international.snowowl.core.version.Version) BadRequestException(com.b2international.commons.exceptions.BadRequestException) TerminologyResource(com.b2international.snowowl.core.TerminologyResource)

Example 8 with SnowowlRuntimeException

use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.

the class SnomedRf2ImportRequest method read.

private void read(File rf2Archive, Rf2EffectiveTimeSlices slices, Rf2ValidationIssueReporter reporter) {
    final CsvMapper csvMapper = new CsvMapper();
    csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);
    final CsvSchema schema = CsvSchema.emptySchema().withoutQuoteChar().withColumnSeparator('\t').withLineSeparator("\r\n");
    final ObjectReader oReader = csvMapper.readerFor(String[].class).with(schema);
    final Stopwatch w = Stopwatch.createStarted();
    try (final ZipFile zip = new ZipFile(rf2Archive)) {
        for (ZipEntry entry : Collections.list(zip.entries())) {
            final String fileName = Paths.get(entry.getName()).getFileName().toString().toLowerCase();
            if (fileName.endsWith(TXT_EXT)) {
                if (fileName.contains(releaseType.toString().toLowerCase())) {
                    w.reset().start();
                    try (final InputStream in = zip.getInputStream(entry)) {
                        readFile(entry, in, oReader, slices, reporter);
                    }
                    log.info("{} - {}", entry.getName(), w);
                }
            }
        }
    } catch (IOException e) {
        throw new SnowowlRuntimeException(e);
    }
    slices.flushAll();
}
Also used : CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) ZipFile(java.util.zip.ZipFile) InputStream(java.io.InputStream) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) ZipEntry(java.util.zip.ZipEntry) Stopwatch(com.google.common.base.Stopwatch) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) IOException(java.io.IOException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 9 with SnowowlRuntimeException

use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.

the class MapTypeRefSetDSVExporter method executeDSVExport.

@Override
public File executeDSVExport(IProgressMonitor monitor) throws IOException {
    final int memberNumberToSignal = 100;
    final SnomedConcept refSetToExport = SnomedRequests.prepareGetConcept(exportSetting.getRefSetId()).setLocales(exportSetting.getLocales()).setExpand("referenceSet(expand(members(limit:" + Integer.MAX_VALUE + ", expand(referencedComponent(expand(fsn()))))))").build().execute(context);
    final SnomedReferenceSetMembers membersToExport = refSetToExport.getReferenceSet().getMembers();
    final int activeMemberCount = membersToExport.getTotal();
    if (activeMemberCount < memberNumberToSignal) {
        monitor.beginTask("Exporting RefSet to DSV", 1);
    } else {
        monitor.beginTask("Exporting RefSet to DSV", activeMemberCount / memberNumberToSignal);
    }
    final File file = Files.createTempFile("dsv-export-" + refSetToExport.getId() + Dates.now(), ".csv").toFile();
    try (DataOutputStream os = new DataOutputStream(new FileOutputStream(file))) {
        if (exportSetting.getExportItems().isEmpty()) {
            return file;
        }
        writeLine(os, toHeader());
        Map<String, String> labels = prepareLabelCache(membersToExport);
        int count = 0;
        for (final SnomedReferenceSetMember member : membersToExport) {
            writeLine(os, toDsvLine(member, labels));
            count++;
            if (count % memberNumberToSignal == 0) {
                monitor.worked(1);
            }
        }
    } catch (final Exception e) {
        throw new SnowowlRuntimeException(e);
    } finally {
        if (null != monitor) {
            monitor.done();
        }
    }
    return file;
}
Also used : SnomedReferenceSetMember(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember) DataOutputStream(java.io.DataOutputStream) FileOutputStream(java.io.FileOutputStream) SnomedReferenceSetMembers(com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers) SnomedConcept(com.b2international.snowowl.snomed.core.domain.SnomedConcept) File(java.io.File) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) IOException(java.io.IOException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 10 with SnowowlRuntimeException

use of com.b2international.snowowl.core.api.SnowowlRuntimeException in project snow-owl by b2ihealthcare.

the class IdentityPlugin method createProviders.

private List<IdentityProvider> createProviders(Environment env, List<IdentityProviderConfig> providerConfigurations) {
    final List<IdentityProvider> providers = newArrayListWithExpectedSize(3);
    env.plugins().getPlugins().stream().filter(IdentityProviderFactory.class::isInstance).map(IdentityProviderFactory.class::cast).forEach(factory -> {
        Optional<IdentityProviderConfig> providerConfig = providerConfigurations.stream().filter(conf -> conf.getClass() == factory.getConfigType()).findFirst();
        if (providerConfig.isPresent()) {
            try {
                providers.add(factory.create(env, providerConfig.get()));
            } catch (Exception e) {
                throw new SnowowlRuntimeException(String.format("Couldn't initialize '%s' identity provider", factory), e);
            }
        }
    });
    return providers;
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) JwkProvider(com.auth0.jwk.JwkProvider) Iterables(com.google.common.collect.Iterables) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) URL(java.net.URL) BiFunction(java.util.function.BiFunction) Plugin(com.b2international.snowowl.core.setup.Plugin) Hashing(com.google.common.hash.Hashing) Strings(com.google.common.base.Strings) Algorithm(com.auth0.jwt.algorithms.Algorithm) Environment(com.b2international.snowowl.core.setup.Environment) RSAPublicKey(java.security.interfaces.RSAPublicKey) ImmutableList(com.google.common.collect.ImmutableList) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) SnowOwlConfiguration(com.b2international.snowowl.core.config.SnowOwlConfiguration) RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) BadRequestException(com.b2international.commons.exceptions.BadRequestException) ClassPathScanner(com.b2international.snowowl.core.plugin.ClassPathScanner) Charsets(com.google.common.base.Charsets) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) JwkException(com.auth0.jwk.JwkException) MalformedURLException(java.net.MalformedURLException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) ConfigurationRegistry(com.b2international.snowowl.core.setup.ConfigurationRegistry) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) KeyFactory(java.security.KeyFactory) SnowOwl(com.b2international.snowowl.core.SnowOwl) TimeUnit(java.util.concurrent.TimeUnit) Lists.newArrayListWithExpectedSize(com.google.common.collect.Lists.newArrayListWithExpectedSize) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Component(com.b2international.snowowl.core.plugin.Component) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ApplicationContext(com.b2international.snowowl.core.ApplicationContext) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) BadRequestException(com.b2international.commons.exceptions.BadRequestException) JwkException(com.auth0.jwk.JwkException) MalformedURLException(java.net.MalformedURLException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Aggregations

SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)39 IOException (java.io.IOException)27 SctId (com.b2international.snowowl.snomed.cis.domain.SctId)7 Collection (java.util.Collection)7 HttpPost (org.apache.http.client.methods.HttpPost)6 BadRequestException (com.b2international.commons.exceptions.BadRequestException)5 RevisionSearcher (com.b2international.index.revision.RevisionSearcher)4 Promise (com.b2international.snowowl.core.events.util.Promise)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 List (java.util.List)4 TimeUnit (java.util.concurrent.TimeUnit)4 File (java.io.File)3 Path (java.nio.file.Path)3 NamingException (javax.naming.NamingException)3 InitialLdapContext (javax.naming.ldap.InitialLdapContext)3 HttpGet (org.apache.http.client.methods.HttpGet)3 Logger (org.slf4j.Logger)3 JwkException (com.auth0.jwk.JwkException)2 JwkProvider (com.auth0.jwk.JwkProvider)2 JwkProviderBuilder (com.auth0.jwk.JwkProviderBuilder)2