Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

In this page you can find the example usage for java.util Map putIfAbsent.

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:io.druid.indexing.jdbc.supervisor.JDBCSupervisor.java

private void updateDataFromJDBC() {

    Map<Integer, Long> partitions = ioConfig.getJdbcOffsets().getOffsetMaps();
    int numPartitions = (partitions != null ? partitions.size() : 0);
    log.info("Found [%d] JDBC partitions for table [%s]", numPartitions, ioConfig.getTable());

    for (int partition = 0; partition < numPartitions; partition++) {
        int taskGroupId = getTaskGroup(partition);
        groups.putIfAbsent(taskGroupId, new ConcurrentHashMap<Integer, Long>());
        Map<Integer, Long> offsetsMap = groups.get(taskGroupId);

        // The starting offset for a table in [groups] is initially set to NOT_SET; when a new task group
        // is created , if the offset in [groups] is NOT_SET it will take the starting
        // offset value from the metadata store, and if it can't find it there, from Table. Once a task begins
        // publishing, the offset in groups will be updated to the ending offset of the publishing-but-not-yet-
        // completed task, which will cause the next set of tasks to begin reading from where the previous task left
        // off. If that previous task now fails, we will set the offset in [groups] back to NOT_SET which will
        // cause successive tasks to again grab their starting offset from metadata store. This mechanism allows us to
        // start up successive tasks without waiting for the previous tasks to succeed and still be able to handle task
        // failures during publishing.

        if (offsetsMap.putIfAbsent(partition, NOT_SET) == null) {
            log.info("New  [%s] added to task group [%d]", ioConfig.getTable(), taskGroupId);
        }/*w  w w  .  j a  v a 2s .  com*/
    }
}

From source file:org.apache.samza.execution.JobNodeConfigurationGenerator.java

/**
 * Serializes the {@link Serde} instances for operators, adds them to the provided config, and
 * sets the serde configuration for the input/output/intermediate streams appropriately.
 *
 * We try to preserve the number of Serde instances before and after serialization. However we don't
 * guarantee that references shared between these serdes instances (e.g. an Jackson ObjectMapper shared
 * between two json serdes) are shared after deserialization too.
 *
 * Ideally all the user defined objects in the application should be serialized and de-serialized in one pass
 * from the same output/input stream so that we can maintain reference sharing relationships.
 *
 * @param configs the configs to add serialized serde instances and stream serde configs to
 *///from ww  w .  j a  v a2  s  .  co m
private void configureSerdes(Map<String, String> configs, Map<String, StreamEdge> inEdges,
        Map<String, StreamEdge> outEdges, List<StoreDescriptor> stores, Collection<String> tables,
        JobNode jobNode) {
    // collect all key and msg serde instances for streams
    Map<String, Serde> streamKeySerdes = new HashMap<>();
    Map<String, Serde> streamMsgSerdes = new HashMap<>();
    inEdges.keySet().forEach(streamId -> addSerdes(jobNode.getInputSerdes(streamId), streamId, streamKeySerdes,
            streamMsgSerdes));
    outEdges.keySet().forEach(streamId -> addSerdes(jobNode.getOutputSerde(streamId), streamId, streamKeySerdes,
            streamMsgSerdes));

    Map<String, Serde> storeKeySerdes = new HashMap<>();
    Map<String, Serde> storeMsgSerdes = new HashMap<>();
    stores.forEach(storeDescriptor -> {
        storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde());
        storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde());
    });

    Map<String, Serde> tableKeySerdes = new HashMap<>();
    Map<String, Serde> tableMsgSerdes = new HashMap<>();
    tables.forEach(tableId -> {
        addSerdes(jobNode.getTableSerdes(tableId), tableId, tableKeySerdes, tableMsgSerdes);
    });

    // for each unique stream or store serde instance, generate a unique name and serialize to config
    HashSet<Serde> serdes = new HashSet<>(streamKeySerdes.values());
    serdes.addAll(streamMsgSerdes.values());
    serdes.addAll(storeKeySerdes.values());
    serdes.addAll(storeMsgSerdes.values());
    serdes.addAll(tableKeySerdes.values());
    serdes.addAll(tableMsgSerdes.values());
    SerializableSerde<Serde> serializableSerde = new SerializableSerde<>();
    Base64.Encoder base64Encoder = Base64.getEncoder();
    Map<Serde, String> serdeUUIDs = new HashMap<>();
    serdes.forEach(serde -> {
        String serdeName = serdeUUIDs.computeIfAbsent(serde,
                s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString());
        configs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE(), serdeName),
                base64Encoder.encodeToString(serializableSerde.toBytes(serde)));
    });

    // set key and msg serdes for streams to the serde names generated above
    streamKeySerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String keySerdeConfigKey = streamIdPrefix + StreamConfig.KEY_SERDE();
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    streamMsgSerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String valueSerdeConfigKey = streamIdPrefix + StreamConfig.MSG_SERDE();
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for stores to the serde names generated above
    storeKeySerdes.forEach((storeName, serde) -> {
        String keySerdeConfigKey = String.format(StorageConfig.KEY_SERDE, storeName);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    storeMsgSerdes.forEach((storeName, serde) -> {
        String msgSerdeConfigKey = String.format(StorageConfig.MSG_SERDE, storeName);
        configs.put(msgSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for stores to the serde names generated above
    tableKeySerdes.forEach((tableId, serde) -> {
        String keySerdeConfigKey = String.format(JavaTableConfig.STORE_KEY_SERDE, tableId);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    tableMsgSerdes.forEach((tableId, serde) -> {
        String valueSerdeConfigKey = String.format(JavaTableConfig.STORE_MSG_SERDE, tableId);
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });
}

From source file:org.xmlsh.sh.shell.Shell.java

private void setGlobalVars() throws InvalidArgumentException {

    // System env first
    Map<String, String> env = new HashMap<>();

    env.putAll(System.getenv());//  www .jav a 2 s. c o  m
    Properties props = System.getProperties();
    props.stringPropertyNames().stream().filter(s -> s.startsWith(ShellConstants.kXMLSH_PROP_PREFIX))
            .forEach(key -> env.putIfAbsent(key.substring(ShellConstants.kXMLSH_PROP_PREFIX.length()),
                    props.getProperty(key)));

    env.keySet().stream()
            .filter(name -> (!Util.isBlank(name) && !Util.isPath(name) && name.matches("^[a-zA-Z_0-9]+$") &&
            // Ignore reserved vars that are set internally
                    !Util.contains(_reservedEnvVars, name)))
            .forEach(name -> getEnv().initVariable(
                    XVariable.newInstance(name, XValue.newXValue(env.get(name)), XVariable.systemFlags())));

    // Builtins may come from env or properties
    // Export path to shell path
    String path = FileUtils.toJavaPath(getSystemProperty(ShellConstants.PATH));
    getEnv().initVariable(XVariable.newInstance(ShellConstants.PATH,
            Util.isBlank(path) ? XValue.empytSequence() : XValue.newXValue(path.split(File.pathSeparator)),
            XVariable.systemFlags()));

    String xpath = FileUtils.toJavaPath(getSystemProperty(ShellConstants.ENV_XPATH));
    getEnv().initVariable(XVariable.newInstance(ShellConstants.ENV_XPATH,
            Util.isBlank(xpath) ? XValue.newXValue(".") : XValue.newXValue(xpath.split(File.pathSeparator)),
            XVariable.systemFlags()));

    String xmlsh = getSystemProperty(ShellConstants.ENV_XMLSH);
    String xmlshhome = getSystemProperty(ShellConstants.ENV_XMLSH_HOME);
    if (Util.isBlank(xmlshhome))
        xmlshhome = xmlsh;

    if (Util.isBlank(xmlshhome))
        xmlshhome = tryFindHome();

    if (Util.isBlank(xmlsh))
        xmlsh = xmlshhome;

    if (Util.isBlank(xmlshhome)) {
        getLogger().warn("Required  property {} missing - limited functionalty.",
                ShellConstants.ENV_XMLSH_HOME);
    }
    getEnv().setVar(ShellConstants.ENV_XMLSH, XValue.newXValue(FileUtils.toJavaPath(xmlsh)),
            XVariable.standardFlags());

    getEnv().setVar(ShellConstants.ENV_XMLSH_HOME, XValue.newXValue(FileUtils.toJavaPath(xmlshhome)),
            XVariable.standardFlags());

    String xmpath = FileUtils.toJavaPath(getSystemProperty(ShellConstants.ENV_XMODPATH));

    getEnv().setVar(ShellConstants.ENV_XMODPATH,
            Util.isBlank(xmpath) ? XValue.empytSequence() : XValue.newXValue(xmpath.split(File.pathSeparator)),
            XVariable.standardFlags());

    // PWD
    getEnv().initVariable(
            new XDynamicVariable(ShellConstants.ENV_PWD, EnumSet.of(XVarFlag.READONLY, XVarFlag.EXPORT)) {
                @Override
                public XValue getValue() {
                    return XValue.newXValue(FileUtils.toJavaPath(getEnv().getCurdir().getAbsolutePath()));
                }

            });

    // RANDOM
    getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM, EnumSet.of(XVarFlag.READONLY)) {
        Random mRand = new Random();

        @Override
        public XValue getValue() {
            return XValue.newXValue(mRand.nextInt(0x7FFF));
        }

    });

    // RANDOM32
    getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM32, EnumSet.of(XVarFlag.READONLY)) {
        Random mRand = new Random();

        @Override
        public XValue getValue() {
            long v = mRand.nextInt();
            v &= 0x7FFFFFFFL;
            return XValue.newXValue((int) v);
        }

    });

    // RANDOM
    getEnv().initVariable(new XDynamicVariable(ShellConstants.VAR_RANDOM64, EnumSet.of(XVarFlag.READONLY)) {
        Random mRand = new Random();

        @Override
        public XValue getValue() {
            return XValue.newXValue(mRand.nextLong() & 0x7FFFFFFFFFFFFFFFL);
        }
    });

    getEnv().setVar(ShellConstants.ENV_TMPDIR,
            XValue.newXValue(FileUtils.toJavaPath(System.getProperty(ShellConstants.PROP_JAVA_IO_TMPDIR))),
            XVariable.systemFlags());

    if (getEnv().getVar(ShellConstants.ENV_HOME) == null)
        getEnv().setVar(ShellConstants.ENV_HOME,
                XValue.newXValue(FileUtils.toJavaPath(System.getProperty(ShellConstants.PROP_USER_HOME))),
                XVariable.systemFlags());

}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Reader.java

private int addAnnotationWithNoFeature(JCas aJCas, Type aType, AnnotationUnit aUnit, List<AnnotationFS> aAnnos,
        Map<AnnotationUnit, Map<Integer, AnnotationFS>> aMultiTokUnits, int aEnd, int aRef) {
    String anno = annotationsPerPostion.get(aType).get(aUnit).get(0);
    if (!anno.equals("_")) {
        int i = 0;
        String stackedAnnoRegex = "(?<!\\\\)" + Pattern.quote("|");
        for (String mAnnos : anno.split(stackedAnnoRegex)) {
            String multipleSlotAnno = "(?<!\\\\)" + Pattern.quote(";");
            for (String mAnno : mAnnos.split(multipleSlotAnno)) {
                String depRef = "";
                if (mAnno.endsWith("]")) {
                    depRef = mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1);
                    aRef = depRef.contains("_") ? 0
                            : Integer.valueOf(mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1));
                    mAnno = mAnno.substring(0, mAnno.indexOf("["));
                }//  w w  w.j a  v  a2  s  . c  om

                boolean isMultitoken = false;
                AnnotationFS multiAnnoFs = null;

                if (!aMultiTokUnits.isEmpty())
                    for (AnnotationUnit u : aMultiTokUnits.keySet()) {
                        for (Integer r : aMultiTokUnits.get(u).keySet()) {
                            if (aRef == r) {
                                isMultitoken = true;
                                multiAnnoFs = aMultiTokUnits.get(u).get(r);
                                break;
                            }
                        }
                    }

                if (isMultitoken) {

                    Feature endF = aType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                    multiAnnoFs.setIntValue(endF, aEnd);
                    setAnnoRefPerUnit(aUnit, aType, aRef, multiAnnoFs);

                } else {

                    aMultiTokUnits.putIfAbsent(aUnit, new HashMap<>());
                    aMultiTokUnits.get(aUnit).put(aRef, aAnnos.get(i));
                    aJCas.addFsToIndexes(aAnnos.get(i));
                    setAnnoRefPerUnit(aUnit, aType, aRef, aAnnos.get(i));
                }
                aRef++;
            }
            i++;
        }
    }
    return aRef;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Writer.java

private void setRelationAnnoPerFeature(Map<AnnotationUnit, List<List<String>>> annotationsPertype, Type type,
        AnnotationFS fs, AnnotationUnit depUnit, AnnotationUnit govUnit, int aGovRef, int aDepRef,
        Type aDepType) {//from   ww  w . j  a  v a2 s .  c  om
    List<String> annoPerFeatures = new ArrayList<>();
    featurePerLayer.putIfAbsent(type.getName(), new LinkedHashSet<>());
    for (Feature feature : type.getFeatures()) {
        if (feature.toString().equals("uima.cas.AnnotationBase:sofa")
                || feature.toString().equals("uima.tcas.Annotation:begin")
                || feature.toString().equals("uima.tcas.Annotation:end")
                || feature.getShortName().equals(GOVERNOR) || feature.getShortName().equals(DEPENDENT)
                || feature.getShortName().equals(FIRST) || feature.getShortName().equals(NEXT)) {
            continue;
        }
        int ref = getRefId(type, fs, depUnit);
        String annotation = fs.getFeatureValueAsString(feature);
        if (annotation == null) {
            annotation = "*";
        } else {
            annotation = replaceEscapeChars(annotation);
        }
        annoPerFeatures.add(annotation);// +(ref > 0 ? "[" + ref + "]" : ""));
        featurePerLayer.get(type.getName()).add(feature.getShortName());
    }
    // add the governor and dependent unit addresses (separated by _
    String govRef = unitsLineNumber.get(govUnit)
            + ((aDepRef > 0 || aGovRef > 0) ? "[" + aGovRef + "_" + aDepRef + "]" : "");
    annoPerFeatures.add(govRef);
    featurePerLayer.get(type.getName()).add(BT + aDepType.getName());
    // the column for the dependent unit address
    annotationsPertype.putIfAbsent(depUnit, new ArrayList<>());
    if (annoPerFeatures.size() == 0)
        annoPerFeatures.add("*");
    annotationsPertype.get(depUnit).add(annoPerFeatures);
}

From source file:uk.ac.cam.cl.dtg.segue.comm.EmailManager.java

/**
 * Method to take a random (potentially nested map) and flatten it into something where values can be easily extracted
 * for email templates.//from   ww  w.  ja  v  a 2s.  c  om
 *
 * Nested fields are addressed as per json objects and separated with the dot operator.
 *
 * @param inputMap - A map of string to random object
 * @param outputMap - the flattened map which is also the returned object
 * @param keyPrefix - the key prefix - used for recursively creating the map key.
 * @return a flattened map for containing strings that can be used in email template replacement.
 */
public Map<String, String> flattenTokenMap(final Map<String, Object> inputMap,
        final Map<String, String> outputMap, String keyPrefix) {
    if (null == keyPrefix) {
        keyPrefix = "";
    }

    for (Map.Entry<String, Object> mapEntry : inputMap.entrySet()) {
        String valueToStore = "";

        if (mapEntry.getValue() == null) {
            valueToStore = "";

        } else if (mapEntry.getValue() instanceof Map) {
            // if we have a general map we should recurse until we get objects we can do something with.
            this.flattenTokenMap((Map) mapEntry.getValue(), outputMap, keyPrefix + mapEntry.getKey() + ".");

        } else if (mapEntry.getValue() instanceof ContentDTO) {
            Map objectWithJavaTypes = new org.apache.commons.beanutils.BeanMap(mapEntry.getValue());

            // go through and convert any known java types into our preferred string representation
            Map<String, String> temp = this.flattenTokenMap(objectWithJavaTypes, Maps.newHashMap(),
                    keyPrefix + mapEntry.getKey() + ".");
            outputMap.putAll(temp);

            // now convert any java types we haven't defined specific conversions for into the basic Jackson serialisations.
            ObjectMapper om = new ObjectMapper();
            this.flattenTokenMap(om.convertValue(mapEntry.getValue(), HashMap.class), outputMap,
                    keyPrefix + mapEntry.getKey() + ".");

        } else {
            valueToStore = this.emailTokenValueMapper(mapEntry.getValue());
        }

        if (valueToStore != null) {
            String existingValue = outputMap.get(keyPrefix + mapEntry.getKey());
            if (existingValue != null && "".equals(existingValue) && !"".equals(valueToStore)) {
                // we can safely replace it with a better value
                outputMap.put(keyPrefix + mapEntry.getKey(), valueToStore);
            }

            // assume that the first entry into the output map is the correct one and only replace if something isn't already there
            outputMap.putIfAbsent(keyPrefix + mapEntry.getKey(), valueToStore);
        }
    }

    return outputMap;
}

From source file:com.uber.stream.kafka.mirrormaker.manager.core.ControllerHelixManager.java

public synchronized void updateCurrentStatus() {
    _lock.lock();/*from   ww  w  .j  ava2 s .  co m*/
    try {
        long currTimeMs = System.currentTimeMillis();
        if (currTimeMs - lastUpdateTimeMs < _conf.getUpdateStatusCoolDownMs()) {
            LOGGER.info("Only {} ms since last updateCurrentStatus, wait for next one",
                    currTimeMs - lastUpdateTimeMs);
            return;
        }
        LOGGER.info("Trying to run controller updateCurrentStatus");

        _workerHelixManager.updateCurrentStatus();

        // Map<InstanceName, InstanceTopicPartitionHolder>
        Map<String, InstanceTopicPartitionHolder> instanceMap = new HashMap<>();
        // Map<TopicName, Map<Pipeline, Instance>>
        Map<String, Map<String, InstanceTopicPartitionHolder>> currTopicToPipelineInstanceMap = new HashMap<>();
        // Map<Pipeline, PriorityQueue<Instance>>
        Map<String, PriorityQueue<InstanceTopicPartitionHolder>> currPipelineToInstanceMap = new HashMap<>();
        // Set<InstanceName>
        List<String> currAvailableControllerList = new ArrayList<>();

        Map<TopicPartition, List<String>> workerRouteToInstanceMap = _workerHelixManager
                .getWorkerRouteToInstanceMap();
        // Map<Instance, Set<Pipeline>> from IdealState
        Map<String, Set<TopicPartition>> instanceToTopicPartitionsMap = HelixUtils
                .getInstanceToTopicPartitionsMap(_helixManager,
                        _srcKafkaValidationManager.getClusterToObserverMap());

        List<String> liveInstances = HelixUtils.liveInstances(_helixManager);
        currAvailableControllerList.addAll(liveInstances);

        int assignedControllerCount = 0;
        for (String instanceId : instanceToTopicPartitionsMap.keySet()) {
            Set<TopicPartition> topicPartitions = instanceToTopicPartitionsMap.get(instanceId);
            // TODO: one instance suppose to have only one route
            for (TopicPartition tp : topicPartitions) {
                String topicName = tp.getTopic();
                if (topicName.startsWith(SEPARATOR)) {
                    currPipelineToInstanceMap.putIfAbsent(topicName, new PriorityQueue<>(1,
                            InstanceTopicPartitionHolder.totalWorkloadComparator(_pipelineWorkloadMap)));
                    InstanceTopicPartitionHolder itph = new InstanceTopicPartitionHolder(instanceId, tp);
                    if (workerRouteToInstanceMap.get(tp) != null) {
                        itph.addWorkers(workerRouteToInstanceMap.get(tp));
                    }
                    currPipelineToInstanceMap.get(topicName).add(itph);
                    instanceMap.put(instanceId, itph);
                    currAvailableControllerList.remove(instanceId);
                    assignedControllerCount++;
                }
            }

            for (TopicPartition tp : topicPartitions) {
                String topicName = tp.getTopic();
                if (!topicName.startsWith(SEPARATOR)) {
                    if (instanceMap.containsKey(instanceId)) {
                        instanceMap.get(instanceId).addTopicPartition(tp);
                        currTopicToPipelineInstanceMap.putIfAbsent(topicName, new ConcurrentHashMap<>());
                        currTopicToPipelineInstanceMap.get(tp.getTopic())
                                .put(getPipelineFromRoute(tp.getPipeline()), instanceMap.get(instanceId));
                    }
                }
            }
        }

        _pipelineToInstanceMap = currPipelineToInstanceMap;
        _topicToPipelineInstanceMap = currTopicToPipelineInstanceMap;
        _availableControllerList = currAvailableControllerList;

        if (_helixManager.isLeader()) {
            _availableController.inc(_availableControllerList.size() - _availableController.getCount());
            _availableWorker
                    .inc(_workerHelixManager.getAvailableWorkerList().size() - _availableWorker.getCount());
            _assignedControllerCount.inc(assignedControllerCount - _assignedControllerCount.getCount());
        }

        // Validation
        validateInstanceToTopicPartitionsMap(instanceToTopicPartitionsMap, instanceMap);

        //LOGGER.info("For controller _pipelineToInstanceMap: {}", _pipelineToInstanceMap);
        //LOGGER.info("For controller _topicToPipelineInstanceMap: {}", _topicToPipelineInstanceMap);
        LOGGER.info("For controller {} available", _availableControllerList.size());

        lastUpdateTimeMs = System.currentTimeMillis();
    } catch (Exception e) {
        LOGGER.error("Got exception in updateCurrentStatus", e);
    } finally {
        _lock.unlock();
    }
}

From source file:ru.ruranobe.wicket.webpages.common.ProjectPage.java

public ProjectPage(PageParameters parameters) {
    String projectUrl = parameters.get("project").toString();
    redirectTo404IfArgumentIsNull(projectUrl);

    SqlSessionFactory sessionFactory = MybatisUtil.getSessionFactory();

    try (SqlSession session = sessionFactory.openSession()) {
        ProjectsMapper projectsMapperCacheable = CachingFacade.getCacheableMapper(session,
                ProjectsMapper.class);

        final Project mainProject = projectsMapperCacheable.getProjectByUrl(projectUrl);

        redirectTo404IfArgumentIsNull(mainProject);
        redirectTo404(mainProject.getProjectHidden() && !mainProject.getWorks()
                && !LoginSession.get().isProjectEditAllowedByUser(mainProject.getUrl()));

        if (mainProject.getWorks()) {
            addBodyClassAttribute("works");
        }/*from  w ww.  j av  a  2 s . c  o m*/

        titleName = mainProject.getTitle();
        Collection<Project> subProjects = projectsMapperCacheable
                .getSubProjectsByParentProjectId(mainProject.getProjectId());
        final ArrayList<Project> projects = new ArrayList<>();
        projects.add(mainProject);
        projects.addAll(subProjects);

        VolumesMapper volumesMapperCacheable = CachingFacade.getCacheableMapper(session, VolumesMapper.class);

        ExternalResourcesMapper externalResourcesMapperCacheable = CachingFacade.getCacheableMapper(session,
                ExternalResourcesMapper.class);

        setDefaultModel(new CompoundPropertyModel<>(mainProject));

        add(new Label("title"));
        add(new LabelHideableOnNull("nameJp"));
        add(new LabelHideableOnNull("nameRomaji"));
        add(new LabelHideableOnNull("nameEn"));
        add(new LabelHideableOnNull("nameRu"));
        add(new LabelHideableOnNull("author"));
        add(new LabelHideableOnNull("illustrator"));
        add(new LabelHideableOnNull("originalStory"));
        add(new LabelHideableOnNull("originalDesign"));
        add(new LabelHideableOnNull("issueStatus"));
        add(new LabelHideableOnNull("translationStatus"));
        add(new Label("franchiseParsed").setEscapeModelStrings(false));
        add(new Label("annotationParsed").setEscapeModelStrings(false));

        ArrayList<Volume> mainProjectFirstCovers = new ArrayList<>();
        ArrayList<Volume> mainProjectActiveCovers = new ArrayList<>();
        ArrayList<Volume> firstCovers = new ArrayList<>();
        ArrayList<Volume> activeCovers = new ArrayList<>();
        Volume mainProjectLastCover = null;
        Volume lastCover = null;

        final Map<SimpleEntry<String, String>, Integer> shortNameLabelWidthMap = new HashMap<>();
        final Map<String, ArrayList<SimpleEntry<String, ArrayList<Volume>>>> volumeTypeToSubProjectToVolumes = new HashMap<>();
        for (Project project : projects) {
            String subProjectTitle = project.getTitle();
            if (project == mainProject) {
                subProjectTitle = "";
            }
            Collection<Volume> volumes = volumesMapperCacheable.getVolumesByProjectId(project.getProjectId());
            for (Volume volume : volumes) {
                String type = volume.getVolumeType();
                if (!type.isEmpty()) {
                    if (volume.getImageOne() != null) {
                        if (subProjectTitle.isEmpty() && type.equals(DISPLAYABLE_NAMES.get(0))
                                && mainProjectFirstCovers.size() < 3) {
                            mainProjectFirstCovers.add(volume);
                        } else if (mainProjectFirstCovers.isEmpty() && firstCovers.size() < 3) {
                            firstCovers.add(volume);
                        }

                        if (volume.getVolumeStatus().equals(RuraConstants.VOLUME_STATUS_ONGOING)
                                || volume.getVolumeStatus().equals(RuraConstants.VOLUME_STATUS_TRANSLATING)
                                || volume.getVolumeStatus().equals(RuraConstants.VOLUME_STATUS_PROOFREAD)) {
                            if (subProjectTitle.isEmpty() && type.equals(DISPLAYABLE_NAMES.get(0))
                                    && mainProjectActiveCovers.size() < 3) {
                                mainProjectActiveCovers.add(volume);
                            } else if (mainProjectActiveCovers.isEmpty() && activeCovers.size() < 3) {
                                activeCovers.add(volume);
                            }
                        }

                        if (subProjectTitle.isEmpty() && type.equals(DISPLAYABLE_NAMES.get(0))
                                && (mainProjectLastCover == null
                                        || mainProjectLastCover.getProjectId() < volume.getProjectId())) {
                            mainProjectLastCover = volume;
                        }
                        if (lastCover == null || lastCover.getProjectId() < volume.getProjectId()) {
                            lastCover = volume;
                        }
                    }

                    volumeTypeToSubProjectToVolumes.putIfAbsent(type,
                            new ArrayList<SimpleEntry<String, ArrayList<Volume>>>());
                    ArrayList<SimpleEntry<String, ArrayList<Volume>>> subProjectToVolumes = volumeTypeToSubProjectToVolumes
                            .get(type);
                    if (subProjectToVolumes.isEmpty() || !subProjectToVolumes
                            .get(subProjectToVolumes.size() - 1).getKey().equals(subProjectTitle)) {
                        subProjectToVolumes.add(new SimpleEntry<>(subProjectTitle, new ArrayList<Volume>()));
                    }
                    subProjectToVolumes.get(subProjectToVolumes.size() - 1).getValue().add(volume);

                    SimpleEntry<String, String> volumeTypeAndSubProject = new SimpleEntry<>(type,
                            subProjectTitle);
                    if (volume.getNameShort() != null) {
                        if (shortNameLabelWidthMap.get(volumeTypeAndSubProject) == null
                                || shortNameLabelWidthMap.get(volumeTypeAndSubProject) < volume.getNameShort()
                                        .length()) {
                            shortNameLabelWidthMap.put(volumeTypeAndSubProject, volume.getNameShort().length());
                        }
                    }
                }
            }
        }

        ListView<String> volumeTypeRepeater = new ListView<String>("volumeTypeRepeater", DISPLAYABLE_NAMES) {
            @Override
            protected void populateItem(final ListItem<String> listItem1) {
                final String displayableName = listItem1.getModelObject();
                Label volumeType = new Label("volumeType", displayableName);
                if (volumeTypeToSubProjectToVolumes.get(displayableName) == null) {
                    volumeType.setVisible(false);
                }
                listItem1.add(volumeType);
                ListView<SimpleEntry<String, ArrayList<Volume>>> volumeSubProjectRepeater = new ListView<SimpleEntry<String, ArrayList<Volume>>>(
                        "volumeSubProjectRepeater", volumeTypeToSubProjectToVolumes.get(displayableName)) {
                    @Override
                    protected void populateItem(ListItem<SimpleEntry<String, ArrayList<Volume>>> listItem2) {
                        SimpleEntry<String, ArrayList<Volume>> projectTitleAndVolumes = listItem2
                                .getModelObject();
                        String subProjectNameString = projectTitleAndVolumes.getKey();
                        Label projectName = new Label("projectName", subProjectNameString);
                        if (subProjectNameString.isEmpty()) {
                            projectName.setVisible(false);
                        }
                        listItem2.add(projectName);
                        ArrayList<Volume> volumes = projectTitleAndVolumes.getValue();
                        Collections.sort(volumes, COMPARATOR);
                        final Integer shortNameLabelWidth = shortNameLabelWidthMap
                                .get(new SimpleEntry<>(displayableName, subProjectNameString));
                        ListView<Volume> volumeRepeater = new ListView<Volume>("volumeRepeater",
                                projectTitleAndVolumes.getValue()) {
                            @Override
                            protected void populateItem(final ListItem<Volume> listItem3) {
                                Volume volume = listItem3.getModelObject();
                                String nameShort = volume.getNameShort();
                                Label volumeName = new Label("volumeName", nameShort);
                                if (shortNameLabelWidth != null) {
                                    volumeName.add(new AttributeModifier("style",
                                            "width:" + (shortNameLabelWidth * 7.5 + 10) + "px;"));
                                }
                                listItem3.add(volumeName);
                                String volumeStatusStr = volume.getVolumeStatus();
                                Label volumeStatus = new Label("volumeStatus",
                                        RuraConstants.VOLUME_STATUS_TO_LABEL_TEXT.get(volumeStatusStr));
                                volumeStatus.add(new AttributeAppender("class",
                                        " label-" + VOLUME_STATUS_LABEL_COLOR_CLASS.get(volumeStatusStr)));
                                listItem3.add(volumeStatus);
                                if (volumeStatusStr.equals(RuraConstants.VOLUME_STATUS_HIDDEN) && !LoginSession
                                        .get().isProjectShowHiddenAllowedByUser(mainProject.getUrl())) {
                                    listItem3.setVisible(false);
                                }
                                BookmarkablePageLink volumeLink = volume.makeBookmarkablePageLink("volumeLink");
                                volumeLink.setBody(new Model<>(volume.getNameTitle()));
                                listItem3.add(volumeLink);
                            }
                        };
                        listItem2.add(volumeRepeater);
                    }
                };
                listItem1.add(volumeSubProjectRepeater);
            }
        };
        add(volumeTypeRepeater);

        Set<Volume> allCoversSet = new HashSet<>();
        if (mainProjectFirstCovers.isEmpty()) {
            allCoversSet.addAll(firstCovers);
        } else {
            allCoversSet.addAll(mainProjectFirstCovers);
        }
        if (mainProjectActiveCovers.isEmpty()) {
            allCoversSet.addAll(activeCovers);
        } else {
            allCoversSet.addAll(mainProjectActiveCovers);
        }
        if (mainProjectLastCover != null) {
            allCoversSet.add(mainProjectLastCover);
        }
        if (lastCover != null) {
            allCoversSet.add(lastCover);
        }
        ArrayList<Volume> allCovers = new ArrayList<>(allCoversSet);
        Collections.sort(allCovers, COMPARATOR);
        ArrayList<SimpleEntry<String, ExternalResource>> allCoverIds = new ArrayList<>();
        for (Volume volume : allCovers) {
            allCoverIds.add(new SimpleEntry<>(volume.getNameTitle(),
                    externalResourcesMapperCacheable.getExternalResourceById(volume.getImageOne())));
        }

        add(new CoverCarousel("projectCoverCarousel", allCoverIds));
        if (!allCoverIds.isEmpty()) {
            WebMarkupContainer ogImage = new WebMarkupContainer("ogImage");
            add(ogImage);
            String absoluteUrl = RequestCycle.get().getUrlRenderer()
                    .renderFullUrl(Url.parse(allCoverIds.iterator().next().getValue().getThumbnail(240)));
            ogImage.add(new AttributeModifier("content", absoluteUrl));
        }

        sidebarModules.add(new ActionsSidebarModule(ProjectEdit.class, mainProject.getUrlParameters()));
        sidebarModules.add(new UpdatesSidebarModule(mainProject.getProjectId()));
        sidebarModules.add(new RequisitesSidebarModule());
        sidebarModules.add(new ProjectsSidebarModule());
        sidebarModules.add(new FriendsSidebarModule());
    }
}

From source file:org.apache.samza.execution.JobNode.java

/**
 * Serializes the {@link Serde} instances for operators, adds them to the provided config, and
 * sets the serde configuration for the input/output/intermediate streams appropriately.
 *
 * We try to preserve the number of Serde instances before and after serialization. However we don't
 * guarantee that references shared between these serdes instances (e.g. an Jackson ObjectMapper shared
 * between two json serdes) are shared after deserialization too.
 *
 * Ideally all the user defined objects in the application should be serialized and de-serialized in one pass
 * from the same output/input stream so that we can maintain reference sharing relationships.
 *
 * @param configs the configs to add serialized serde instances and stream serde configs to
 *///from w  ww  . j  a va  2  s .c om
void addSerdeConfigs(Map<String, String> configs) {
    // collect all key and msg serde instances for streams
    Map<String, Serde> streamKeySerdes = new HashMap<>();
    Map<String, Serde> streamMsgSerdes = new HashMap<>();
    Map<StreamSpec, InputOperatorSpec> inputOperators = streamGraph.getInputOperators();
    inEdges.forEach(edge -> {
        String streamId = edge.getStreamSpec().getId();
        InputOperatorSpec inputOperatorSpec = inputOperators.get(edge.getStreamSpec());
        streamKeySerdes.put(streamId, inputOperatorSpec.getKeySerde());
        streamMsgSerdes.put(streamId, inputOperatorSpec.getValueSerde());
    });
    Map<StreamSpec, OutputStreamImpl> outputStreams = streamGraph.getOutputStreams();
    outEdges.forEach(edge -> {
        String streamId = edge.getStreamSpec().getId();
        OutputStreamImpl outputStream = outputStreams.get(edge.getStreamSpec());
        streamKeySerdes.put(streamId, outputStream.getKeySerde());
        streamMsgSerdes.put(streamId, outputStream.getValueSerde());
    });

    // collect all key and msg serde instances for stores
    Map<String, Serde> storeKeySerdes = new HashMap<>();
    Map<String, Serde> storeMsgSerdes = new HashMap<>();
    streamGraph.getAllOperatorSpecs().forEach(opSpec -> {
        if (opSpec instanceof StatefulOperatorSpec) {
            ((StatefulOperatorSpec) opSpec).getStoreDescriptors().forEach(storeDescriptor -> {
                storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde());
                storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde());
            });
        }
    });

    // collect all key and msg serde instances for tables
    Map<String, Serde> tableKeySerdes = new HashMap<>();
    Map<String, Serde> tableValueSerdes = new HashMap<>();
    tables.forEach(tableSpec -> {
        tableKeySerdes.put(tableSpec.getId(), tableSpec.getSerde().getKeySerde());
        tableValueSerdes.put(tableSpec.getId(), tableSpec.getSerde().getValueSerde());
    });

    // for each unique stream or store serde instance, generate a unique name and serialize to config
    HashSet<Serde> serdes = new HashSet<>(streamKeySerdes.values());
    serdes.addAll(streamMsgSerdes.values());
    serdes.addAll(storeKeySerdes.values());
    serdes.addAll(storeMsgSerdes.values());
    serdes.addAll(tableKeySerdes.values());
    serdes.addAll(tableValueSerdes.values());
    SerializableSerde<Serde> serializableSerde = new SerializableSerde<>();
    Base64.Encoder base64Encoder = Base64.getEncoder();
    Map<Serde, String> serdeUUIDs = new HashMap<>();
    serdes.forEach(serde -> {
        String serdeName = serdeUUIDs.computeIfAbsent(serde,
                s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString());
        configs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE(), serdeName),
                base64Encoder.encodeToString(serializableSerde.toBytes(serde)));
    });

    // set key and msg serdes for streams to the serde names generated above
    streamKeySerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String keySerdeConfigKey = streamIdPrefix + StreamConfig.KEY_SERDE();
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    streamMsgSerdes.forEach((streamId, serde) -> {
        String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId);
        String valueSerdeConfigKey = streamIdPrefix + StreamConfig.MSG_SERDE();
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for stores to the serde names generated above
    storeKeySerdes.forEach((storeName, serde) -> {
        String keySerdeConfigKey = String.format(StorageConfig.KEY_SERDE(), storeName);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    storeMsgSerdes.forEach((storeName, serde) -> {
        String msgSerdeConfigKey = String.format(StorageConfig.MSG_SERDE(), storeName);
        configs.put(msgSerdeConfigKey, serdeUUIDs.get(serde));
    });

    // set key and msg serdes for tables to the serde names generated above
    tableKeySerdes.forEach((tableId, serde) -> {
        String keySerdeConfigKey = String.format(JavaTableConfig.TABLE_KEY_SERDE, tableId);
        configs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
    });

    tableValueSerdes.forEach((tableId, serde) -> {
        String valueSerdeConfigKey = String.format(JavaTableConfig.TABLE_VALUE_SERDE, tableId);
        configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
    });
}

From source file:GestoSAT.GestoSAT.java

public Map getStock() {

    try {//from  ww  w. jav a  2s. c o  m
        Map stock = new HashMap();
        Class.forName("com.mysql.jdbc.Driver");
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery(
                "Select * From stock S INNER JOIN proveedores P ON S.id_proveedor = P.id_Proveedor");
        Proveedor p;
        this.getProveedores();
        while (res.next()) {
            p = (Proveedor) this.proveedor.get(res.getInt("P.id_Proveedor"));
            Stock s = new Stock(res.getString("S.Nombre"), res.getFloat("S.Unidades"),
                    res.getFloat("S.Precio_venta"), (String) res.getObject("S.Descripcion"),
                    res.getFloat("S.Precio_compra"), res.getFloat("S.num_Alertar"), p);
            s = p.setStock(res.getInt("s.id_Stock"), s);
            stock.putIfAbsent(res.getInt("S.id_Stock"), s);
        }
        return stock;
    } catch (Exception ex) {
        Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex);
        return new HashMap();
    }
}