Search in sources :

Example 61 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project litemall by linlinjava.

the class JacksonUtil method parseIntegerList.

public static List<Integer> parseIntegerList(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = null;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);
        if (leaf != null)
            return mapper.convertValue(leaf, new TypeReference<List<String>>() {
            });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 62 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project repseqio by repseqio.

the class GenerateClonesAction method go.

@Override
public void go(ActionHelper helper) throws Exception {
    GCloneModel model = GModels.getGCloneModelByName(params.getModelName());
    GCloneGenerator generator = model.create(new Well19937c(params.getSeed()), VDJCLibraryRegistry.getDefault());
    VDJCLibrary library = VDJCLibraryRegistry.getDefault().getLibrary(model.libraryId());
    try (BufferedOutputStream s = new BufferedOutputStream(params.getOutput().equals(".") ? System.out : new FileOutputStream(params.getOutput()), 128 * 1024)) {
        s.write(GlobalObjectMappers.toOneLine(model.libraryId()).getBytes());
        s.write('\n');
        ObjectWriter writer = GlobalObjectMappers.ONE_LINE.writerFor(new TypeReference<GClone>() {
        }).withAttribute(VDJCGene.JSON_CURRENT_LIBRARY_ATTRIBUTE_KEY, library);
        OUTER: for (int i = 0; i < params.numberOfClones; i++) {
            GClone clone = generator.sample();
            for (GGene g : clone.genes.values()) {
                NucleotideSequence cdr3 = g.getFeature(GeneFeature.CDR3);
                if (params.isInFrame())
                    if (cdr3.size() % 3 != 0) {
                        --i;
                        continue OUTER;
                    }
                if (params.isNoStops())
                    if (AminoAcidSequence.translateFromCenter(cdr3).containStops()) {
                        --i;
                        continue OUTER;
                    }
            }
            writer.writeValue(new CloseShieldOutputStream(s), clone);
            s.write('\n');
        }
    }
}
Also used : GCloneGenerator(io.repseq.gen.dist.GCloneGenerator) GGene(io.repseq.gen.GGene) FileOutputStream(java.io.FileOutputStream) NucleotideSequence(com.milaboratory.core.sequence.NucleotideSequence) VDJCLibrary(io.repseq.core.VDJCLibrary) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) TypeReference(com.fasterxml.jackson.core.type.TypeReference) GCloneModel(io.repseq.gen.dist.GCloneModel) Well19937c(org.apache.commons.math3.random.Well19937c) BufferedOutputStream(java.io.BufferedOutputStream) GClone(io.repseq.gen.GClone) CloseShieldOutputStream(org.apache.commons.io.output.CloseShieldOutputStream)

Example 63 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project repseqio by repseqio.

the class ExportCloneSequencesAction method parseExtractor.

public static DescriptionExtractor parseExtractor(String str, final VDJCLibrary library) {
    Matcher matcher = extractorPatternFeatureGene.matcher(str);
    if (matcher.matches())
        return new DescriptionExtractorSeq(GeneFeature.parse(matcher.group(2)), null, matcher.group(1).equals("AA"));
    matcher = extractorPatternFeatureClone.matcher(str);
    if (matcher.matches())
        return new DescriptionExtractorSeq(GeneFeature.parse(matcher.group(3)), matcher.group(2), matcher.group(1).equals("AA"));
    if (str.equalsIgnoreCase("JSONClone"))
        return new DescriptionExtractor() {

            final ObjectWriter writer = GlobalObjectMappers.ONE_LINE.writerFor(new TypeReference<GClone>() {
            }).withAttribute(VDJCGene.JSON_CURRENT_LIBRARY_ATTRIBUTE_KEY, library);

            @Override
            public String extract(GClone clone, GGene gene, String chain) {
                try {
                    return writer.writeValueAsString(clone);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    if (str.equalsIgnoreCase("JSONGene"))
        return new DescriptionExtractor() {

            final ObjectWriter writer = GlobalObjectMappers.ONE_LINE.writerFor(new TypeReference<GGene>() {
            }).withAttribute(VDJCGene.JSON_CURRENT_LIBRARY_ATTRIBUTE_KEY, library);

            @Override
            public String extract(GClone clone, GGene gene, String chain) {
                try {
                    return writer.writeValueAsString(gene);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    if (str.equalsIgnoreCase("chain"))
        return new DescriptionExtractor() {

            @Override
            public String extract(GClone clone, GGene gene, String chain) {
                return chain;
            }
        };
    matcher = extractorPatternField.matcher(str);
    if (matcher.matches()) {
        final boolean isGene = matcher.group(1).equalsIgnoreCase("Gene");
        final String fieldName = matcher.group(2);
        return new DescriptionExtractor() {

            final ObjectWriter writer = isGene ? GlobalObjectMappers.ONE_LINE.writerFor(new TypeReference<GGene>() {
            }).withAttribute(VDJCGene.JSON_CURRENT_LIBRARY_ATTRIBUTE_KEY, library) : GlobalObjectMappers.ONE_LINE.writerFor(new TypeReference<GClone>() {
            }).withAttribute(VDJCGene.JSON_CURRENT_LIBRARY_ATTRIBUTE_KEY, library);

            @Override
            public String extract(GClone clone, GGene gene, String chain) {
                try {
                    String str = writer.writeValueAsString(isGene ? gene : clone);
                    JsonNode tree = GlobalObjectMappers.ONE_LINE.readTree(str);
                    JsonNode targetNode = tree.get(fieldName);
                    return targetNode == null ? "" : targetNode.asText();
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
    throw new IllegalArgumentException("Can't parse description extractor: " + str);
}
Also used : Matcher(java.util.regex.Matcher) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 64 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project phoenicis by PhoenicisOrg.

the class GenericContainersManager method fetchContainers.

/**
 * fetches all containers in a given directory
 * @param directory
 * @return found containers
 */
private List<ContainerDTO> fetchContainers(File directory) {
    final List<ContainerDTO> containers = new ArrayList<>();
    final File[] containerDirectories = directory.listFiles();
    if (containerDirectories != null) {
        for (File containerDirectory : containerDirectories) {
            final ConfigFile configFile = compatibleConfigFileFormatFactory.open(new File(containerDirectory, "phoenicis.cfg"));
            final File userRegistryFile = new File(containerDirectory, "user.reg");
            final String containerPath = containerDirectory.getAbsolutePath();
            final String containerName = containerPath.substring(containerPath.lastIndexOf('/') + 1);
            // find shortcuts which use this container
            List<ShortcutDTO> shortcutDTOS = libraryManager.fetchShortcuts().stream().flatMap(shortcutCategory -> shortcutCategory.getShortcuts().stream()).filter(shortcut -> {
                boolean toAdd = false;
                try {
                    final Map<String, Object> shortcutProperties = objectMapper.readValue(shortcut.getScript(), new TypeReference<Map<String, Object>>() {
                    });
                    toAdd = shortcutProperties.get("winePrefix").equals(containerName);
                } catch (IOException e) {
                    LOGGER.warn("Could not parse shortcut script JSON", e);
                }
                return toAdd;
            }).collect(Collectors.toList());
            if (directory.getName().equals("wineprefix")) {
                containers.add(new WinePrefixContainerDTO.Builder().withName(containerDirectory.getName()).withPath(containerPath).withInstalledShortcuts(shortcutDTOS).withArchitecture(configFile.readValue("wineArchitecture", "")).withDistribution(configFile.readValue("wineDistribution", "")).withVersion(configFile.readValue("wineVersion", "")).withGlslValue(winePrefixContainerDisplayConfiguration.getGLSL(userRegistryFile)).withDirectDrawRenderer(winePrefixContainerDisplayConfiguration.getDirectDrawRenderer(userRegistryFile)).withVideoMemorySize(winePrefixContainerDisplayConfiguration.getVideoMemorySize(userRegistryFile)).withOffscreenRenderingMode(winePrefixContainerDisplayConfiguration.getOffscreenRenderingMode(userRegistryFile)).withMultisampling(winePrefixContainerDisplayConfiguration.getMultisampling(userRegistryFile)).withAlwaysOffscreen(winePrefixContainerDisplayConfiguration.getAlwaysOffscreen(userRegistryFile)).withStrictDrawOrdering(winePrefixContainerDisplayConfiguration.getStrictDrawOrdering(userRegistryFile)).withRenderTargetModeLock(winePrefixContainerDisplayConfiguration.getRenderTargetModeLock(userRegistryFile)).withMouseWarpOverride(winePrefixContainerInputConfiguration.getMouseWarpOverride(userRegistryFile)).build());
            }
        }
        containers.sort(ContainerDTO.nameComparator());
    }
    return containers;
}
Also used : ShortcutCategoryDTO(org.phoenicis.library.dto.ShortcutCategoryDTO) WinePrefixContainerInputConfiguration(org.phoenicis.containers.wine.configurations.WinePrefixContainerInputConfiguration) ContainerCategoryDTO(org.phoenicis.containers.dto.ContainerCategoryDTO) LoggerFactory(org.slf4j.LoggerFactory) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) Map(java.util.Map) ShortcutDTO(org.phoenicis.library.dto.ShortcutDTO) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ContainerDTO(org.phoenicis.containers.dto.ContainerDTO) WinePrefixContainerDisplayConfiguration(org.phoenicis.containers.wine.configurations.WinePrefixContainerDisplayConfiguration) Logger(org.slf4j.Logger) FileUtilities(org.phoenicis.tools.files.FileUtilities) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ScriptInterpreter(org.phoenicis.scripts.interpreter.ScriptInterpreter) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) Consumer(java.util.function.Consumer) List(java.util.List) ShortcutManager(org.phoenicis.library.ShortcutManager) ConfigFile(org.phoenicis.tools.config.ConfigFile) Safe(org.phoenicis.configuration.security.Safe) CompatibleConfigFileFormatFactory(org.phoenicis.tools.config.CompatibleConfigFileFormatFactory) CollectionUtils(org.springframework.util.CollectionUtils) WinePrefixContainerDTO(org.phoenicis.containers.dto.WinePrefixContainerDTO) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) InteractiveScriptSession(org.phoenicis.scripts.interpreter.InteractiveScriptSession) LibraryManager(org.phoenicis.library.LibraryManager) Collections(java.util.Collections) WinePrefixContainerDTO(org.phoenicis.containers.dto.WinePrefixContainerDTO) ConfigFile(org.phoenicis.tools.config.ConfigFile) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ContainerDTO(org.phoenicis.containers.dto.ContainerDTO) WinePrefixContainerDTO(org.phoenicis.containers.dto.WinePrefixContainerDTO) ShortcutDTO(org.phoenicis.library.dto.ShortcutDTO) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) ConfigFile(org.phoenicis.tools.config.ConfigFile) Map(java.util.Map)

Example 65 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project BroadleafCommerce by BroadleafCommerce.

the class BroadleafRequestContext method createLightWeightCloneFromJson.

/**
 * Resurrect the BroadleafRequestContext state based on a JSON representation.
 *
 * @param Json
 * @param em
 * @return
 */
public static BroadleafRequestContext createLightWeightCloneFromJson(String Json, EntityManager em) {
    BroadleafRequestContext context = new BroadleafRequestContext();
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
    };
    HashMap<String, String> json;
    try {
        json = mapper.readValue(Json, typeRef);
    } catch (IOException e) {
        throw ExceptionHelper.refineException(e);
    }
    if (!json.get("ignoreSite").equals("null")) {
        context.setIgnoreSite(Boolean.valueOf(json.get("ignoreSite")));
    }
    if (!json.get("sandBox").equals("null")) {
        context.setSandBox(em.find(SandBoxImpl.class, Long.parseLong(json.get("sandBox"))));
    }
    if (!json.get("nonPersistentSite").equals("null")) {
        context.setNonPersistentSite(em.find(SiteImpl.class, Long.parseLong(json.get("nonPersistentSite"))));
    }
    if (!json.get("enforceEnterpriseCollectionBehaviorState").equals("null")) {
        context.setEnforceEnterpriseCollectionBehaviorState(EnforceEnterpriseCollectionBehaviorState.valueOf(json.get("enforceEnterpriseCollectionBehaviorState")));
    }
    if (!json.get("admin").equals("null")) {
        context.setAdmin(Boolean.valueOf(json.get("admin")));
    }
    if (!json.get("adminUserId").equals("null")) {
        context.setAdminUserId(Long.parseLong(json.get("adminUserId")));
    }
    if (!json.get("broadleafCurrency").equals("null")) {
        context.setBroadleafCurrency(em.find(BroadleafCurrencyImpl.class, json.get("broadleafCurrency")));
    }
    if (!json.get("currentCatalog").equals("null")) {
        context.setCurrentCatalog(em.find(CatalogImpl.class, Long.parseLong(json.get("currentCatalog"))));
    }
    if (!json.get("currentProfile").equals("null")) {
        context.setCurrentProfile(em.find(SiteImpl.class, Long.parseLong(json.get("currentProfile"))));
    }
    if (!json.get("deployBehavior").equals("null")) {
        context.setDeployBehavior(DeployBehavior.valueOf(json.get("deployBehavior")));
    }
    if (!json.get("deployState").equals("null")) {
        context.setDeployState(DeployState.valueOf(json.get("deployState")));
    }
    if (!json.get("internalIgnoreFilters").equals("null")) {
        context.setInternalIgnoreFilters(Boolean.valueOf(json.get("internalIgnoreFilters")));
    }
    if (!json.get("locale").equals("null")) {
        context.setLocale(em.find(LocaleImpl.class, json.get("locale")));
    }
    if (!json.get("validateProductionChangesState").equals("null")) {
        context.setValidateProductionChangesState(ValidateProductionChangesState.valueOf(json.get("validateProductionChangesState")));
    }
    if (!json.get("timeZone").equals("null")) {
        context.setTimeZone(TimeZone.getTimeZone(json.get("timeZone")));
    }
    return context;
}
Also used : HashMap(java.util.HashMap) CatalogImpl(org.broadleafcommerce.common.site.domain.CatalogImpl) JsonFactory(com.fasterxml.jackson.core.JsonFactory) IOException(java.io.IOException) LocaleImpl(org.broadleafcommerce.common.locale.domain.LocaleImpl) SiteImpl(org.broadleafcommerce.common.site.domain.SiteImpl) TypeReference(com.fasterxml.jackson.core.type.TypeReference) SandBoxImpl(org.broadleafcommerce.common.sandbox.domain.SandBoxImpl) BroadleafCurrencyImpl(org.broadleafcommerce.common.currency.domain.BroadleafCurrencyImpl) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)316 IOException (java.io.IOException)130 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)113 Test (org.junit.Test)95 ArrayList (java.util.ArrayList)74 Map (java.util.Map)74 List (java.util.List)60 HashMap (java.util.HashMap)58 File (java.io.File)34 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)27 Collectors (java.util.stream.Collectors)25 InputStream (java.io.InputStream)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 ImmutableMap (com.google.common.collect.ImmutableMap)19 lombok.val (lombok.val)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)14 Collections (java.util.Collections)13 ISE (org.apache.druid.java.util.common.ISE)12 URL (java.net.URL)10