Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

In this page you can find the example usage for java.util ArrayList set.

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:com.android.mail.browse.SendersView.java

private static void handlePriority(int maxChars, String messageInfoString, ConversationInfo conversationInfo,
        ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames,
        ConversationItemViewModel.SenderAvatarModel senderAvatarModel, Account account,
        final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan,
        final boolean showToHeader) {
    final boolean shouldSelectSenders = displayableSenderNames != null;
    final boolean shouldSelectAvatar = senderAvatarModel != null;
    int maxPriorityToInclude = -1; // inclusive
    int numCharsUsed = messageInfoString.length(); // draft, number drafts,
                                                   // count
    int numSendersUsed = 0;
    int numCharsToRemovePerWord = 0;
    int maxFoundPriority = 0;
    if (numCharsUsed > maxChars) {
        numCharsToRemovePerWord = numCharsUsed - maxChars;
    }/*  w w w. j a  v  a  2  s .  co m*/

    final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get();
    try {
        priorityToLength.clear();
        int senderLength;
        for (ParticipantInfo info : conversationInfo.participantInfos) {
            final String senderName = info.name;
            senderLength = !TextUtils.isEmpty(senderName) ? senderName.length() : 0;
            priorityToLength.put(info.priority, senderLength);
            maxFoundPriority = Math.max(maxFoundPriority, info.priority);
        }
        while (maxPriorityToInclude < maxFoundPriority) {
            if (priorityToLength.containsKey(maxPriorityToInclude + 1)) {
                int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1);
                if (numCharsUsed > 0)
                    length += 2;
                // We must show at least two senders if they exist. If we don't
                // have space for both
                // then we will truncate names.
                if (length > maxChars && numSendersUsed >= 2) {
                    break;
                }
                numCharsUsed = length;
                numSendersUsed++;
            }
            maxPriorityToInclude++;
        }
    } finally {
        PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength);
    }

    SpannableString spannableDisplay;
    boolean appendedElided = false;
    final Map<String, Integer> displayHash = Maps.newHashMap();
    final List<String> senderEmails = Lists.newArrayListWithExpectedSize(MAX_SENDER_COUNT);
    String firstSenderEmail = null;
    String firstSenderName = null;
    for (int i = 0; i < conversationInfo.participantInfos.size(); i++) {
        final ParticipantInfo currentParticipant = conversationInfo.participantInfos.get(i);
        final String currentEmail = currentParticipant.email;

        final String currentName = currentParticipant.name;
        String nameString = !TextUtils.isEmpty(currentName) ? currentName : "";
        if (nameString.length() == 0) {
            // if we're showing the To: header, show the object version of me.
            nameString = getMe(showToHeader /* useObjectMe */);
        }
        if (numCharsToRemovePerWord != 0) {
            nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0));
        }

        final int priority = currentParticipant.priority;
        final CharacterStyle style = CharacterStyle
                .wrap(currentParticipant.readConversation ? readStyleSpan : unreadStyleSpan);
        if (priority <= maxPriorityToInclude) {
            spannableDisplay = new SpannableString(sBidiFormatter.unicodeWrap(nameString));
            // Don't duplicate senders; leave the first instance, unless the
            // current instance is also unread.
            int oldPos = displayHash.containsKey(currentName) ? displayHash.get(currentName) : DOES_NOT_EXIST;
            // If this sender doesn't exist OR the current message is
            // unread, add the sender.
            if (oldPos == DOES_NOT_EXIST || !currentParticipant.readConversation) {
                // If the sender entry already existed, and is right next to the
                // current sender, remove the old entry.
                if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 && oldPos < styledSenders.size()) {
                    // Remove the old one!
                    styledSenders.set(oldPos, null);
                    if (shouldSelectSenders && !TextUtils.isEmpty(currentEmail)) {
                        senderEmails.remove(currentEmail);
                        displayableSenderNames.remove(currentName);
                    }
                }
                displayHash.put(currentName, i);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                styledSenders.add(spannableDisplay);
            }
        } else {
            if (!appendedElided) {
                spannableDisplay = new SpannableString(sElidedString);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                appendedElided = true;
                styledSenders.add(spannableDisplay);
            }
        }

        final String senderEmail = TextUtils.isEmpty(currentName) ? account.getEmailAddress()
                : TextUtils.isEmpty(currentEmail) ? currentName : currentEmail;

        if (shouldSelectSenders) {
            if (i == 0) {
                // Always add the first sender!
                firstSenderEmail = senderEmail;
                firstSenderName = currentName;
            } else {
                if (!Objects.equal(firstSenderEmail, senderEmail)) {
                    int indexOf = senderEmails.indexOf(senderEmail);
                    if (indexOf > -1) {
                        senderEmails.remove(indexOf);
                        displayableSenderNames.remove(indexOf);
                    }
                    senderEmails.add(senderEmail);
                    displayableSenderNames.add(currentName);
                    if (senderEmails.size() > MAX_SENDER_COUNT) {
                        senderEmails.remove(0);
                        displayableSenderNames.remove(0);
                    }
                }
            }
        }

        // if the corresponding message from this participant is unread and no sender avatar
        // is yet chosen, choose this one
        if (shouldSelectAvatar && senderAvatarModel.isNotPopulated() && !currentParticipant.readConversation) {
            senderAvatarModel.populate(currentName, senderEmail);
        }
    }

    // always add the first sender to the display
    if (shouldSelectSenders && !TextUtils.isEmpty(firstSenderEmail)) {
        if (displayableSenderNames.size() < MAX_SENDER_COUNT) {
            displayableSenderNames.add(0, firstSenderName);
        } else {
            displayableSenderNames.set(0, firstSenderName);
        }
    }

    // if all messages in the thread were read, we must search for an appropriate avatar
    if (shouldSelectAvatar && senderAvatarModel.isNotPopulated()) {
        // search for the last sender that is not the current account
        for (int i = conversationInfo.participantInfos.size() - 1; i >= 0; i--) {
            final ParticipantInfo participant = conversationInfo.participantInfos.get(i);
            // empty name implies it is the current account and should not be chosen
            if (!TextUtils.isEmpty(participant.name)) {
                // use the participant name in place of unusable email addresses
                final String senderEmail = TextUtils.isEmpty(participant.email) ? participant.name
                        : participant.email;
                senderAvatarModel.populate(participant.name, senderEmail);
                break;
            }
        }

        // if we still don't have an avatar, the account is emailing itself
        if (senderAvatarModel.isNotPopulated()) {
            senderAvatarModel.populate(account.getDisplayName(), account.getEmailAddress());
        }
    }
}

From source file:NavigableMap.java

/**
 * Reconstitute the <tt>Map</tt> instance from a stream.
 *///from  w w w.j  a  v  a  2  s  .c  om
private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
    // Read in the Comparator and any hidden stuff
    s.defaultReadObject();
    // Reset transients
    initialize();

    /*
     * This is nearly identical to buildFromSorted, but is distinct because
     * readObject calls can't be nicely adapted as the kind of iterator needed
     * by buildFromSorted. (They can be, but doing so requires type cheats
     * and/or creation of adaptor classes.) It is simpler to just adapt the
     * code.
     */

    HeadIndex<K, V> h = head;
    Node<K, V> basepred = h.node;
    ArrayList<Index<K, V>> preds = new ArrayList<Index<K, V>>();
    for (int i = 0; i <= h.level; ++i)
        preds.add(null);
    Index<K, V> q = h;
    for (int i = h.level; i > 0; --i) {
        preds.set(i, q);
        q = q.down;
    }

    for (;;) {
        Object k = s.readObject();
        if (k == null)
            break;
        Object v = s.readObject();
        if (v == null)
            throw new NullPointerException();
        K key = (K) k;
        V val = (V) v;
        int j = randomLevel();
        if (j > h.level)
            j = h.level + 1;
        Node<K, V> z = new Node<K, V>(key, val, null);
        basepred.next = z;
        basepred = z;
        if (j > 0) {
            Index<K, V> idx = null;
            for (int i = 1; i <= j; ++i) {
                idx = new Index<K, V>(z, idx, null);
                if (i > h.level)
                    h = new HeadIndex<K, V>(h.node, h, idx, i);

                if (i < preds.size()) {
                    preds.get(i).right = idx;
                    preds.set(i, idx);
                } else
                    preds.add(idx);
            }
        }
    }
    head = h;
}

From source file:NavigableMap.java

/**
 * Streamlined bulk insertion to initialize from elements of given sorted map.
 * Call only from constructor or clone method.
 *///from   www  .j a v a  2 s  . c om
private void buildFromSorted(SortedMap<K, ? extends V> map) {
    if (map == null)
        throw new NullPointerException();

    HeadIndex<K, V> h = head;
    Node<K, V> basepred = h.node;

    // Track the current rightmost node at each level. Uses an
    // ArrayList to avoid committing to initial or maximum level.
    ArrayList<Index<K, V>> preds = new ArrayList<Index<K, V>>();

    // initialize
    for (int i = 0; i <= h.level; ++i)
        preds.add(null);
    Index<K, V> q = h;
    for (int i = h.level; i > 0; --i) {
        preds.set(i, q);
        q = q.down;
    }

    Iterator<? extends Map.Entry<? extends K, ? extends V>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<? extends K, ? extends V> e = it.next();
        int j = randomLevel();
        if (j > h.level)
            j = h.level + 1;
        K k = e.getKey();
        V v = e.getValue();
        if (k == null || v == null)
            throw new NullPointerException();
        Node<K, V> z = new Node<K, V>(k, v, null);
        basepred.next = z;
        basepred = z;
        if (j > 0) {
            Index<K, V> idx = null;
            for (int i = 1; i <= j; ++i) {
                idx = new Index<K, V>(z, idx, null);
                if (i > h.level)
                    h = new HeadIndex<K, V>(h.node, h, idx, i);

                if (i < preds.size()) {
                    preds.get(i).right = idx;
                    preds.set(i, idx);
                } else
                    preds.add(idx);
            }
        }
    }
    head = h;
}

From source file:org.apache.hadoop.hive.ql.parse.NewGroupByUtils1.java

@SuppressWarnings("unchecked")
private GroupByOperator genNewGroupByPlanGroupByOperator(QB qb, String dest, Operator inputOperatorInfo,
        Mode mode, ArrayList<GenericUDAFEvaluator> genericUDAFEvaluators,
        ArrayList<ArrayList<Integer>> tag2AggrPos, ArrayList<ArrayList<ASTNode>> tag2AggrParamAst,
        HashMap<Integer, ArrayList<Integer>> nonDistPos2TagOffs) throws SemanticException {

    RowResolver groupByInputRowResolver = opParseCtx.get(inputOperatorInfo).getRR();
    QBParseInfo parseInfo = qb.getParseInfo();
    RowResolver groupByOutputRowResolver = new RowResolver();
    groupByOutputRowResolver.setIsExprResolver(true);
    RowSchema operatorRowSchema = new RowSchema();
    operatorRowSchema.setSignature(new Vector<ColumnInfo>());
    Map<String, exprNodeDesc> colExprMap = new HashMap<String, exprNodeDesc>();

    ArrayList<exprNodeDesc> groupByKeys = new ArrayList<exprNodeDesc>();
    ArrayList<String> outputColumnNames = new ArrayList<String>();

    List<ASTNode> grpByExprs = SemanticAnalyzer.getGroupByForClause(parseInfo, dest);
    int colid = 0;
    if (qb.getParseInfo().getDestContainsGroupbyCubeOrRollupClause(dest)) {
        String colName = getColumnInternalName(colid++);
        outputColumnNames.add(colName);/*w w  w .  j  a  v  a 2  s  .c  om*/
        ColumnInfo info = groupByInputRowResolver.get("", NewGroupByUtils1._CUBE_ROLLUP_GROUPINGSETS_TAG_);
        exprNodeDesc grpByExprNode = new exprNodeColumnDesc(info.getType(), info.getInternalName(),
                info.getAlias(), info.getIsPartitionCol());
        groupByKeys.add(grpByExprNode);
        ColumnInfo colInfo = new ColumnInfo(colName, grpByExprNode.getTypeInfo(), "", false);

        groupByOutputRowResolver.put("", NewGroupByUtils1._CUBE_ROLLUP_GROUPINGSETS_TAG_, colInfo);

        operatorRowSchema.getSignature().add(colInfo);
        colExprMap.put(colName, grpByExprNode);
    }
    for (int i = 0; i < grpByExprs.size(); i++) {
        ASTNode grpbyExpr = grpByExprs.get(i);
        exprNodeDesc grpByExprNode = SemanticAnalyzer.genExprNodeDesc(grpbyExpr, groupByInputRowResolver, qb,
                -1, conf);
        groupByKeys.add(grpByExprNode);
        String colName = getColumnInternalName(colid++);
        outputColumnNames.add(colName);
        ColumnInfo colInfo = new ColumnInfo(colName, grpByExprNode.getTypeInfo(), "", false);
        groupByOutputRowResolver.putExpression(grpbyExpr, colInfo);
        operatorRowSchema.getSignature().add(colInfo);
        colExprMap.put(colName, grpByExprNode);
    }

    boolean containsfunctions = tag2AggrPos != null && tag2AggrPos.size() > 0;
    boolean containsnondistinctfunctions = containsfunctions && tag2AggrPos.get(0).size() > 0;

    LinkedHashMap<String, ASTNode> aggregationTrees = parseInfo.getAggregationExprsForClause(dest);

    ArrayList<ASTNode> aggregationTreesArray = new ArrayList<ASTNode>(aggregationTrees.size());
    aggregationTreesArray.addAll(aggregationTrees.values());

    HashMap<Integer, Integer> pos2tag = new HashMap<Integer, Integer>();
    for (int tag = 0; tag < tag2AggrPos.size(); tag++) {
        for (Integer pos : tag2AggrPos.get(tag)) {
            pos2tag.put(pos, tag);
        }
    }

    ArrayList<ArrayList<exprNodeDesc>> tag2AggrParamORValueExpr = new ArrayList<ArrayList<exprNodeDesc>>();
    ArrayList<aggregationDesc> aggregations = null;
    aggregations = new ArrayList<aggregationDesc>(aggregationTrees.size());
    for (int i = 0; i < aggregationTrees.size(); i++) {
        aggregations.add(null);
    }
    exprNodeDesc aggrPartExpr = null;

    if (mode == Mode.HASH) {

        if (containsfunctions) {
            String colNameAggrPart = getColumnInternalName(colid++);
            outputColumnNames.add(colNameAggrPart);

            List<TypeInfo> unionTypes = new ArrayList<TypeInfo>();

            for (int tag = 0; tag < tag2AggrParamAst.size(); tag++) {
                tag2AggrParamORValueExpr.add(new ArrayList<exprNodeDesc>());
                ArrayList<exprNodeDesc> aggParameters = new ArrayList<exprNodeDesc>();

                for (int j = 0; j < tag2AggrParamAst.get(tag).size(); j++) {
                    ASTNode paraExpr = (ASTNode) tag2AggrParamAst.get(tag).get(j);
                    exprNodeDesc exprNode = SemanticAnalyzer.genExprNodeDesc(paraExpr, groupByInputRowResolver,
                            qb, -1, conf);
                    tag2AggrParamORValueExpr.get(tag).add(exprNode);
                    aggParameters.add(exprNode);
                }

                ArrayList<String> names = new ArrayList<String>();
                ArrayList<TypeInfo> typeInfos = new ArrayList<TypeInfo>();
                if (tag == 0) {
                    if (!containsnondistinctfunctions) {
                        names.add("nondistnull");
                        typeInfos.add(TypeInfoFactory.voidTypeInfo);
                    } else {
                        int posoff = 0;
                        for (Integer pos : tag2AggrPos.get(tag)) {
                            ASTNode value = aggregationTreesArray.get(pos);
                            String aggName = value.getChild(0).getText();

                            boolean isDistinct = value.getType() == HiveParser.TOK_FUNCTIONDI;
                            GenericUDAFEvaluator.Mode amode = SemanticAnalyzer.groupByDescModeToUDAFMode(mode,
                                    isDistinct);

                            GenericUDAFEvaluator genericUDAFEvaluator = genericUDAFEvaluators.get(pos);
                            assert (genericUDAFEvaluator != null);

                            ArrayList<exprNodeDesc> aggParameters1 = aggParameters;
                            ArrayList<Integer> offs = nonDistPos2TagOffs.get(pos);
                            aggParameters1 = new ArrayList<exprNodeDesc>();
                            for (Integer off : offs) {
                                aggParameters1.add(aggParameters.get(off));
                            }

                            GenericUDAFInfo udaf = SemanticAnalyzer.getGenericUDAFInfo(genericUDAFEvaluator,
                                    amode, aggParameters1);

                            aggregations.set(pos, new aggregationDesc(aggName.toLowerCase(),
                                    udaf.genericUDAFEvaluator, udaf.convertedParameters, isDistinct, amode));

                            String innername = getColumnInternalName(posoff);
                            String field = colNameAggrPart + ":" + tag + "." + innername;

                            ColumnInfo outColInfo = new ColumnInfo(field, udaf.returnType, "", false);
                            groupByOutputRowResolver.put("", _AGGRPARTTAG_ + tag + "_" + posoff, outColInfo);

                            posoff++;

                            names.add(innername);
                            typeInfos.add(udaf.returnType);
                        }
                    }
                } else {
                    for (int i = 0; i < tag2AggrParamORValueExpr.get(tag).size(); i++) {

                        String innername = getColumnInternalName(i);
                        TypeInfo innertype = tag2AggrParamORValueExpr.get(tag).get(i).getTypeInfo();

                        String field = colNameAggrPart + ":" + tag + "." + innername;
                        ColumnInfo outColInfo = new ColumnInfo(field, innertype, "", false);
                        groupByOutputRowResolver.put("", _AGGRPARTTAG_ + tag + "_" + i, outColInfo);

                        names.add(innername);
                        typeInfos.add(innertype);
                    }
                }
                unionTypes.add(TypeInfoFactory.getStructTypeInfo(names, typeInfos));
            }

            ColumnInfo outColInfo = new ColumnInfo(colNameAggrPart,
                    TypeInfoFactory.getUnionTypeInfo(unionTypes), "", false);
            groupByOutputRowResolver.put("", _GBY_AGGRPART_OUTPUT_COLNAME_, outColInfo);
            operatorRowSchema.getSignature().add(outColInfo);
        }

    } else if (mode == Mode.PARTIAL1 || mode == Mode.PARTIALS) {
        if (containsfunctions) {

            ColumnInfo aggrPartInfo = groupByInputRowResolver.get("", _GBY_AGGRPART_OUTPUT_COLNAME_);
            aggrPartExpr = new exprNodeColumnDesc(aggrPartInfo.getType(), aggrPartInfo.getInternalName(), "",
                    false);

            String colNameAggrPart = getColumnInternalName(colid++);
            outputColumnNames.add(colNameAggrPart);
            List<TypeInfo> unionTypes = new ArrayList<TypeInfo>();

            for (int tag = 0; tag < tag2AggrParamAst.size(); tag++) {
                tag2AggrParamORValueExpr.add(new ArrayList<exprNodeDesc>());
                ArrayList<exprNodeDesc> aggParameters = new ArrayList<exprNodeDesc>();

                int paramlen = (tag == 0 && mode == Mode.PARTIALS) ? tag2AggrPos.get(tag).size()
                        : tag2AggrParamAst.get(tag).size();
                for (int j = 0; j < paramlen; j++) {
                    ColumnInfo inputColInfo = groupByInputRowResolver.get("", _AGGRPARTTAG_ + tag + "_" + j);

                    exprNodeDesc exprNode = new exprNodeColumnDesc(inputColInfo.getType(),
                            inputColInfo.getInternalName(), "", false);

                    tag2AggrParamORValueExpr.get(tag).add(exprNode);
                    aggParameters.add(exprNode);
                }

                ArrayList<String> names = new ArrayList<String>();
                ArrayList<TypeInfo> typeInfos = new ArrayList<TypeInfo>();

                int posoff = 0;
                for (Integer pos : tag2AggrPos.get(tag)) {
                    ASTNode value = aggregationTreesArray.get(pos);
                    String aggName = value.getChild(0).getText();

                    boolean isDistinct = value.getType() == HiveParser.TOK_FUNCTIONDI;
                    GenericUDAFEvaluator.Mode amode = SemanticAnalyzer.groupByDescModeToUDAFMode(mode,
                            isDistinct);

                    GenericUDAFEvaluator genericUDAFEvaluator = genericUDAFEvaluators.get(pos);
                    assert (genericUDAFEvaluator != null);

                    ArrayList<exprNodeDesc> aggParameters1 = aggParameters;
                    if (tag == 0 && mode == Mode.PARTIAL1) {
                        ArrayList<Integer> offs = nonDistPos2TagOffs.get(pos);
                        aggParameters1 = new ArrayList<exprNodeDesc>();
                        for (Integer off : offs) {
                            aggParameters1.add(aggParameters.get(off));
                        }
                    } else if (tag == 0) {
                        aggParameters1 = new ArrayList<exprNodeDesc>();
                        aggParameters1.add(aggParameters.get(posoff));
                    }

                    GenericUDAFInfo udaf = SemanticAnalyzer.getGenericUDAFInfo(genericUDAFEvaluator, amode,
                            aggParameters1);

                    aggregations.set(pos, new aggregationDesc(aggName.toLowerCase(), udaf.genericUDAFEvaluator,
                            udaf.convertedParameters, isDistinct, amode));

                    String innername = getColumnInternalName(posoff);
                    String field = colNameAggrPart + ":" + tag + "." + innername;

                    ColumnInfo outColInfo = new ColumnInfo(field, udaf.returnType, "", false);
                    groupByOutputRowResolver.put("", _AGGRPARTTAG_ + tag + "_" + posoff, outColInfo);

                    posoff++;

                    names.add(innername);
                    typeInfos.add(udaf.returnType);
                }

                if (names.isEmpty()) {
                    names.add("nondistnull");
                    typeInfos.add(TypeInfoFactory.voidTypeInfo);
                }

                unionTypes.add(TypeInfoFactory.getStructTypeInfo(names, typeInfos));
            }

            ColumnInfo outColInfo = new ColumnInfo(colNameAggrPart,
                    TypeInfoFactory.getUnionTypeInfo(unionTypes), "", false);
            groupByOutputRowResolver.put("", _GBY_AGGRPART_OUTPUT_COLNAME_, outColInfo);
            operatorRowSchema.getSignature().add(outColInfo);
        }

    } else if (mode == Mode.MERGEPARTIAL || mode == Mode.FINAL || mode == Mode.COMPLETE) {

        if (containsfunctions) {

            ColumnInfo aggrPartInfo = groupByInputRowResolver.get("", _GBY_AGGRPART_OUTPUT_COLNAME_);
            aggrPartExpr = new exprNodeColumnDesc(aggrPartInfo.getType(), aggrPartInfo.getInternalName(), "",
                    false);

            HashMap<Integer, String> pos2colname = new HashMap<Integer, String>();
            for (int pos = 0; pos < aggregationTreesArray.size(); pos++) {
                String colName = getColumnInternalName(colid++);
                outputColumnNames.add(colName);
                pos2colname.put(pos, colName);
            }

            HashMap<Integer, ColumnInfo> pos2valueInfo = new HashMap<Integer, ColumnInfo>();
            for (int tag = 0; tag < tag2AggrPos.size(); tag++) {
                tag2AggrParamORValueExpr.add(new ArrayList<exprNodeDesc>());
                ArrayList<exprNodeDesc> aggParameters = new ArrayList<exprNodeDesc>();

                int aggrlen = (mode == Mode.FINAL) ? tag2AggrPos.get(tag).size()
                        : ((mode == Mode.COMPLETE) ? tag2AggrParamAst.get(tag).size()
                                : ((tag == 0) ? tag2AggrPos.get(tag).size()
                                        : tag2AggrParamAst.get(tag).size()));
                for (int j = 0; j < aggrlen; j++) {
                    ColumnInfo inputColInfo = groupByInputRowResolver.get("", _AGGRPARTTAG_ + tag + "_" + j);

                    exprNodeDesc exprNode = new exprNodeColumnDesc(inputColInfo.getType(),
                            inputColInfo.getInternalName(), "", false);

                    tag2AggrParamORValueExpr.get(tag).add(exprNode);
                    aggParameters.add(exprNode);
                }

                int posoff = 0;
                for (Integer pos : tag2AggrPos.get(tag)) {
                    ASTNode value = aggregationTreesArray.get(pos);
                    String aggName = value.getChild(0).getText();

                    boolean isDistinct = value.getType() == HiveParser.TOK_FUNCTIONDI;
                    GenericUDAFEvaluator.Mode amode = SemanticAnalyzer.groupByDescModeToUDAFMode(mode,
                            isDistinct);

                    GenericUDAFEvaluator genericUDAFEvaluator = genericUDAFEvaluators.get(pos);
                    assert (genericUDAFEvaluator != null);

                    ArrayList<exprNodeDesc> aggParameters1 = aggParameters;
                    if (tag == 0 && mode == Mode.COMPLETE) {
                        ArrayList<Integer> offs = nonDistPos2TagOffs.get(pos);
                        aggParameters1 = new ArrayList<exprNodeDesc>();
                        for (Integer off : offs) {
                            aggParameters1.add(aggParameters.get(off));
                        }
                    } else if (tag == 0 || mode == Mode.FINAL) {
                        aggParameters1 = new ArrayList<exprNodeDesc>();
                        aggParameters1.add(aggParameters.get(posoff));
                    }

                    GenericUDAFInfo udaf = SemanticAnalyzer.getGenericUDAFInfo(genericUDAFEvaluator, amode,
                            aggParameters1);

                    aggregations.set(pos, new aggregationDesc(aggName.toLowerCase(), udaf.genericUDAFEvaluator,
                            udaf.convertedParameters, isDistinct, amode));

                    ColumnInfo valueColInfo = new ColumnInfo(pos2colname.get(pos), udaf.returnType, "", false);
                    pos2valueInfo.put(pos, valueColInfo);

                    posoff++;

                }
            }

            for (int pos = 0; pos < aggregationTreesArray.size(); pos++) {
                groupByOutputRowResolver.putExpression(aggregationTreesArray.get(pos), pos2valueInfo.get(pos));
                operatorRowSchema.getSignature().add(pos2valueInfo.get(pos));
            }
        }

    } else if (mode == Mode.PARTIAL2) {
    }

    GroupByOperator op = (GroupByOperator) putOpInsertMap(
            OperatorFactory.getAndMakeChild(new groupByDesc(mode, outputColumnNames, groupByKeys, aggregations,
                    tag2AggrPos, tag2AggrParamORValueExpr, aggrPartExpr), operatorRowSchema, inputOperatorInfo),
            groupByOutputRowResolver);
    op.setColumnExprMap(colExprMap);
    return op;
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java

public KwlReturnObject getRecruiterPositionstatus(HashMap<String, Object> requestParams) {
    boolean success = false;
    List lst = null, result1 = null, result2 = null;
    KwlReturnObject result = null;//from   w  ww  .  ja  v  a  2s .  co  m
    int totalcount = 0;
    try {
        ArrayList name = null;
        ArrayList value = null;
        String[] searchCol = null;
        ArrayList orderby = null;
        ArrayList ordertype = null;
        String hql = "", filterString = "", searchString = "", orderString = "";
        if (requestParams.containsKey("primary") && (Boolean) requestParams.get("primary")) {
            hql = "from Recruiter where rid=?";
            String id = requestParams.get("id").toString();
            lst = HibernateUtil.executeQuery(hibernateTemplate, hql, new Object[] { id });
            result = new KwlReturnObject(success, "success", "", lst, lst.size());
            return result;
        }

        hql = "from Recruiter ";
        if (requestParams.get("filter_names") != null && requestParams.get("filter_values") != null) {
            name = (ArrayList) requestParams.get("filter_names");
            value = (ArrayList) requestParams.get("filter_values");
            hql += com.krawler.common.util.StringUtil.filterQuery(name, "where");
        }
        if (requestParams.get("searchcol") != null && requestParams.get("ss") != null) {
            searchCol = (String[]) requestParams.get("searchcol");
            searchString = StringUtil.getSearchquery(requestParams.get("ss").toString(), searchCol, value);
        }
        if (requestParams.get("order_by") != null && requestParams.get("order_type") != null) {
            orderby = (ArrayList) requestParams.get("order_by");
            ordertype = (ArrayList) requestParams.get("order_type");
            orderString = com.krawler.common.util.StringUtil.orderQuery(orderby, ordertype);
        }
        String groupstring = " group by allapplication.id";
        if (requestParams.get("searchcol1") == null) {
            result = StringUtil.getPagingquery(requestParams, searchCol, hibernateTemplate,
                    hql + searchString + orderString, value);
        } else {
            result1 = HibernateUtil.executeQuery(hibernateTemplate, hql + searchString + orderString,
                    value.toArray());
            totalcount = result1.size();
            value = (ArrayList) requestParams.get("filter_values1");
            name = (ArrayList) requestParams.get("filter_names1");
            if (name.contains("status"))
                value.set(4, 4); //configjobapplicant=4 reset to 0
            else
                value.set(3, 4); //configjobapplicant=4 reset to 0
            if (requestParams.get("searchcol1") != null && requestParams.get("ss") != null) {
                searchCol = (String[]) requestParams.get("searchcol1");
                searchString = StringUtil.getSearchquery(requestParams.get("ss").toString(), searchCol, value);
            }
            result2 = HibernateUtil.executeQuery(hibernateTemplate, hql + searchString + orderString,
                    value.toArray());
            totalcount += result2.size();
            result1.addAll(result2);
            String allflag = requestParams.get("allflag").toString();
            if (allflag.equals("false")) {
                try {
                    int st = Integer.parseInt(requestParams.get("start").toString());
                    int ed = Math.min(result1.size(),
                            st + Integer.parseInt(requestParams.get("limit").toString()));
                    lst = result1.subList(st, ed);
                    result1 = lst;
                } catch (NumberFormatException ne) {
                    throw ServiceException.FAILURE("hrmsrecjobdaoimpl.getRecruiterPositionstatus", ne);
                }
            }
            result = new KwlReturnObject(success, "success", "", result1, totalcount);
        }
        success = true;
    } catch (Exception ex) {
        success = false;
    } finally {
        return result;
    }
}

From source file:edu.mit.media.funf.probe.Probe.java

/**
 * Updates request list with items in queue, replacing duplicate pending intents for this probe.
 * @param requests//from   w w  w.j  av a 2 s  .  c o m
 */
private void updateRequests(boolean removeRunOnce) {
    assert requestsIntent != null;
    boolean hasChanges = false;
    ArrayList<Intent> requests = requestsIntent.getParcelableArrayListExtra(INTERNAL_REQUESTS_KEY);
    if (requests == null) {
        hasChanges = true;
        requests = new ArrayList<Intent>();
    }

    // Remove run once requests
    Parameter periodParam = Parameter.getAvailableParameter(getAvailableParameters(), Parameter.Builtin.PERIOD);
    if (periodParam != null && removeRunOnce) {
        for (Intent request : requests) {
            ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
            List<Bundle> runOnceDataRequests = new ArrayList<Bundle>();
            for (Bundle dataRequest : dataRequests) {
                long periodValue = Utils.getLong(dataRequest, Parameter.Builtin.PERIOD.name,
                        (Long) periodParam.getValue());
                if (periodValue == 0L) {
                    Log.d(TAG, "Removing run once dataRequest: " + dataRequest);
                    runOnceDataRequests.add(dataRequest);
                }
            }
            dataRequests.removeAll(runOnceDataRequests);
            if (dataRequests.isEmpty()) {
                deadRequests.add(request);
            } else {
                request.putExtra(REQUESTS_KEY, dataRequests);
            }
        }
    }

    // Remove all requests that we aren't able to (or supposed to) send to anymore
    if (!deadRequests.isEmpty()) {
        hasChanges = true;
        for (Intent deadRequest = deadRequests.poll(); deadRequest != null; deadRequest = deadRequests.poll()) {
            Log.d(TAG, "Removing dead request: " + deadRequest);
            requests.remove(deadRequest);
        }
    }
    // Add any pending requests
    if (!pendingRequests.isEmpty()) {
        hasChanges = true;
        Map<PendingIntent, Intent> existingCallbacksToRequests = new HashMap<PendingIntent, Intent>();
        for (Intent existingRequest : requests) {
            PendingIntent callback = existingRequest.getParcelableExtra(CALLBACK_KEY);
            existingCallbacksToRequests.put(callback, existingRequest);
        }
        for (Intent request = pendingRequests.poll(); request != null; request = pendingRequests.poll()) {
            PendingIntent callback = request.getParcelableExtra(CALLBACK_KEY);
            if (packageHasRequiredPermissions(this, callback.getTargetPackage(), getRequiredPermissions())) {
                existingCallbacksToRequests.containsKey(callback);
                int existingRequestIndex = requests.indexOf(existingCallbacksToRequests.get(callback));
                ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
                Log.d(TAG, "Adding pending intent with data requests: " + dataRequests);
                if (existingRequestIndex >= 0) {
                    if (dataRequests == null || dataRequests.isEmpty()) {
                        Log.d(TAG, "Adding pending intent, removing because empty or null");
                        requests.remove(existingRequestIndex);
                    } else {
                        requests.set(existingRequestIndex, request);
                    }
                } else {
                    if (dataRequests != null && !dataRequests.isEmpty()) { // Only add requests with nonempty data requests
                        Log.d(TAG, "Adding new pending intent: " + request);
                        requests.add(request);
                    }
                }
            } else {
                Log.w(TAG, "Package '" + callback.getTargetPackage()
                        + "' does not have the required permissions to get data from this probe.");
            }
        }
    }

    if (hasChanges) {
        requestsIntent.putExtra(INTERNAL_REQUESTS_KEY, requests);
        updateInternalRequestsPendingIntent();
    }
}

From source file:org.lamsfoundation.lams.admin.service.ImportService.java

public List<List> parseV1UsersFile(FormFile fileItem, boolean includeIntegrated) throws IOException {
    ArrayList<V1UserDTO> users = new ArrayList<V1UserDTO>();
    ArrayList<V1OrganisationDTO> orgs = new ArrayList<V1OrganisationDTO>();
    ArrayList<List> results = new ArrayList<List>();
    ArrayList<String> integPrefixes = new ArrayList<String>();
    ArrayList<String> integOrgid = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream()));

    // get username prefixes, for integrations on the lams 1 server
    String line = reader.readLine();
    while (!line.startsWith("login\tpassword")) {
        if (!line.startsWith("prefix")) {
            String[] lineArray = line.split("\t");
            if (lineArray.length > 0) {
                integPrefixes.add(lineArray[0]);
            }//  www  .j  av a 2  s .c o m
            if (lineArray.length > 1) {
                integOrgid.add(lineArray[1]);
            }
        }
        line = reader.readLine();
    }

    // get user details
    // login, password, fname, lname, email
    line = reader.readLine(); // skip line containing column headings
    while (!line.startsWith("sid\tname")) {
        String[] userDetails = line.split("\t");
        line = reader.readLine();
        if (!includeIntegrated && isIntegratedUser(integPrefixes, userDetails[0])) {
            continue;
        }
        V1UserDTO userDTO = new V1UserDTO(userDetails[0], userDetails[1], userDetails[2], userDetails[3]);
        if (userDetails.length > 4 && !StringUtils.equals(userDetails[4], "NULL")) {
            userDTO.setEmail(userDetails[4]);
        }
        users.add(userDTO);
    }

    // get organisations
    // sid, name, description, account_organisation
    line = reader.readLine();
    while (!line.startsWith("login\tg")) {
        String[] orgDetails = line.split("\t");
        line = reader.readLine();
        if (orgDetails.length != 4) {
            log.debug("LAMS 1 text file has troublesome organisation: ");
            for (int i = 0; i < orgDetails.length; i++) {
                log.debug("column: " + orgDetails[i]);
            }
            continue;
        }
        if (!includeIntegrated) {
            if (integOrgid.contains(orgDetails[0])) {
                continue;
            }
        }
        V1OrganisationDTO org = new V1OrganisationDTO(orgDetails[0], orgDetails[1], orgDetails[2],
                orgDetails[3]);
        orgs.add(org);
    }

    // gather user roles which are 1 role per user per line, into a dto of roles for the user
    // login, role id
    line = reader.readLine();
    ArrayList<String> currentRoles = new ArrayList<String>();
    String currentLogin = "";
    while (!line.startsWith("login\tsid")) {
        String[] userRole = line.split("\t");
        line = reader.readLine();
        if (!includeIntegrated && isIntegratedUser(integPrefixes, userRole[0])) {
            continue;
        }
        if (!StringUtils.equals(userRole[0], currentLogin)) {
            if (!currentRoles.isEmpty()) {
                int index = users.indexOf(new V1UserDTO(currentLogin));
                V1UserDTO userDTO = users.get(index);
                userDTO.setRoleIds(new ArrayList<String>(currentRoles));
                users.set(index, userDTO);
            }
            currentLogin = userRole[0];
            currentRoles.clear();
        }
        currentRoles.add(userRole[1]);
    }
    int index = users.indexOf(new V1UserDTO(currentLogin));
    V1UserDTO userDTO = users.get(index);
    userDTO.setRoleIds(new ArrayList<String>(currentRoles));
    users.set(index, userDTO);

    // get user rights
    // login, org id, right id
    line = reader.readLine();
    while (line != null) {
        String[] userRight = line.split("\t");
        line = reader.readLine();
        if (!includeIntegrated && isIntegratedUser(integPrefixes, userRight[0])) {
            continue;
        }
        V1OrgRightDTO orgRightDTO = new V1OrgRightDTO(userRight[1], userRight[2]);
        index = users.indexOf(new V1UserDTO(userRight[0]));
        userDTO = users.get(index);
        List<V1OrgRightDTO> orgRights = userDTO.getOrgRights();
        if (orgRights == null) {
            orgRights = new ArrayList<V1OrgRightDTO>();
        }
        orgRights.add(orgRightDTO);
        userDTO.setOrgRights(orgRights);
        users.set(index, userDTO);
    }

    results.add(users);
    results.add(orgs);

    return results;
}

From source file:es.pode.catalogadorWeb.presentacion.categoriasAvanzado.clasificacion.detalleClasificacion.DetalleClasificacionControllerImpl.java

private void cambioFormulario(HttpServletRequest request, int longitudTextosDesc, int[] longitudTextosPCla,
        int longitudPalabrasClave, int longitudRutasTax, int[] longiTextosFuente, int[] longiTaxones,
        Object formRequestSession) throws Exception {

    descripcion = new DescripcionVO();
    palabrasClave = new PalabraClaveVO[longitudPalabrasClave];
    rutasTaxonomicas = new RutaTaxonomicaVO[longitudRutasTax];

    String[] textoDescripcion = new String[longitudTextosDesc];
    String[] idiomaDescripcion = new String[longitudTextosDesc];
    ArrayList[] textoPalabrasClave = new ArrayList[longitudPalabrasClave];
    ArrayList[] idiomaPalabrasClave = new ArrayList[longitudPalabrasClave];
    ArrayList[] textoRutasTaxFuente = new ArrayList[longitudRutasTax];
    ArrayList textoRutasTaxTaxones = new ArrayList();
    Hashtable hDatos = new Hashtable();

    for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
        String name = String.valueOf(names.nextElement());

        if (name.startsWith("Des")) { //Descripciones
            if (name.startsWith("DesTex")) {
                int i = Integer.parseInt(name.substring(6, name.length()));
                textoDescripcion[i] = request.getParameter(name);
            }//from w w w  . j  ava2s  . co  m
            if (name.startsWith("DesIdio")) {
                int i = Integer.parseInt(name.substring(7, name.length()));
                idiomaDescripcion[i] = request.getParameter(name);
            }
        } else if (name.startsWith("Pcla")) {//Palabras Clave
            String[] namePartido = name.split("_");
            int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length()));
            if (namePartido[1].startsWith("Tex")) {
                int j = Integer.parseInt(namePartido[1].substring(3, namePartido[1].length()));
                ArrayList lPCla = textoPalabrasClave[i];
                if (lPCla == null) {
                    lPCla = new ArrayList();
                    for (int k = 0; k < longitudTextosPCla[i]; k++)
                        lPCla.add("");
                }

                lPCla.set(j, request.getParameter(name));
                textoPalabrasClave[i] = lPCla;
            } else {//Idio
                int j = Integer.parseInt(namePartido[1].substring(4, namePartido[1].length()));
                ArrayList lPCla = idiomaPalabrasClave[i];
                if (lPCla == null) {
                    lPCla = new ArrayList();
                    for (int k = 0; k < longitudTextosPCla[i]; k++)
                        lPCla.add("");
                }

                lPCla.set(j, request.getParameter(name));
                idiomaPalabrasClave[i] = lPCla;
            }
        } else if (name.startsWith("rutaTax")) {
            //              rutaTax${i }_source, rutaTax${i}_taxon${t}_Id${u }//rutaTax${i}_taxon${t}_EntryTex${u} //rutaTax${i}_taxon${t}_EntryIdio${u}
            hDatos.put(name, request.getParameter(name));
        } else if (name.startsWith("razon")) {
            razon = request.getParameter(name);
        }
    }

    if (hDatos.size() > 0) {
        ArrayList arrRutaTax = new ArrayList();
        for (int i = 0; i < longitudRutasTax; i++) {
            RutaTaxonomicaVO rutavo = new RutaTaxonomicaVO();
            //rellenams fuentes
            //               String source= hDatos.get("rutaTax" + i + "_source").toString();
            String source = hDatos.get("rutaTax" + i + "_source") != null
                    ? hDatos.get("rutaTax" + i + "_source").toString()
                    : "";
            //               String idio= hDatos.get("rutaTax" + i + "_idio").toString();
            String idio = hDatos.get("rutaTax" + i + "_idio") != null
                    ? hDatos.get("rutaTax" + i + "_idio").toString()
                    : "";
            LangStringVO textFuente = new LangStringVO();
            textFuente.setTexto(source);
            textFuente.setIdioma(idio);
            FuenteVO fuente = new FuenteVO();
            LangStringVO[] textosFuentes = new LangStringVO[1];
            textosFuentes[0] = textFuente;
            fuente.setTextos(textosFuentes);//metidas las fuentes de una RutaTaxonomica

            //rutasTaxonomicas[i].setFuente(fuente);
            //ahora metemos los taxones para esa fuente
            ArrayList taxones = new ArrayList();
            for (int j = 0; j < longiTaxones[i]; j++) {
                ArrayList taxonij = new ArrayList();
                TaxonVO tax = new TaxonVO();
                EntryVO entry = new EntryVO();
                ArrayList lans = new ArrayList();

                String textoId = "";
                if (hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0) != null)
                    textoId = hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0).toString();

                IdVO id = new IdVO();
                id.setTexto(textoId);
                for (int u = 0; u < hDatos.size(); u++) {
                    LangStringVO lanvo = new LangStringVO();
                    if (hDatos.containsKey("rutaTax" + i + "_taxon" + j + "_EntryTex" + u)) {
                        String textoTax = "";
                        if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u) != null)
                            textoTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u).toString();
                        lanvo.setTexto(textoTax);
                        String idioTax = "";
                        if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u) != null)
                            idioTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u).toString();
                        lanvo.setIdioma(idioTax);
                        lans.add(lanvo); //array d langs para entryvo
                    }
                }
                //*****************
                if (lans.size() == 0) {
                    LangStringVO lanvo = new LangStringVO();
                    lanvo.setIdioma("");
                    lanvo.setTexto("");
                    lans.add(lanvo);
                }
                //*****************
                LangStringVO[] textosEnt = (LangStringVO[]) lans.toArray(new LangStringVO[lans.size()]);
                entry.setTextos(textosEnt);

                tax.setId(id);
                tax.setEntry(entry); //un Taxon
                taxones.add(tax);
            }
            TaxonVO[] rutaTaxones = (TaxonVO[]) taxones.toArray(new TaxonVO[taxones.size()]);
            rutavo.setFuente(fuente);
            rutavo.setTaxones(rutaTaxones);//tenemos una RutaTaxonomica
            arrRutaTax.add(rutavo);
        }
        rutasTaxonomicas = (RutaTaxonomicaVO[]) arrRutaTax.toArray(new RutaTaxonomicaVO[arrRutaTax.size()]);
        RutaTaxonomicaVO[] rutasTaxonomicas2 = rutaLimpia(rutasTaxonomicas);
        rutasTaxonomicas = new RutaTaxonomicaVO[rutasTaxonomicas2.length];
        rutasTaxonomicas = rutasTaxonomicas2;
    }

    //descripcion
    DescripcionVO descVO = new DescripcionVO();
    LangStringVO[] aLangDescripciones = new LangStringVO[textoDescripcion.length];
    for (int i = 0; i < textoDescripcion.length; i++) {
        LangStringVO langDescripciones = new LangStringVO();
        langDescripciones.setTexto(textoDescripcion[i]);
        langDescripciones.setIdioma(idiomaDescripcion[i]);
        aLangDescripciones[i] = langDescripciones;
    }
    descVO.setTextos(aLangDescripciones);
    descripcion = descVO;

    //palabras clave
    for (int i = 0; i < textoPalabrasClave.length; i++) {
        PalabraClaveVO pClaVO = new PalabraClaveVO();
        if (textoPalabrasClave[i] != null) {
            LangStringVO[] aLangPCla = new LangStringVO[textoPalabrasClave[i].size()];
            for (int j = 0; j < textoPalabrasClave[i].size(); j++) {
                LangStringVO langPCla = new LangStringVO();
                langPCla.setTexto(textoPalabrasClave[i].get(j).toString());
                langPCla.setIdioma(idiomaPalabrasClave[i].get(j).toString());
                aLangPCla[j] = langPCla;
            }
            pClaVO.setTextos(aLangPCla);
        } else {
            LangStringVO[] aLangString = new LangStringVO[1];
            LangStringVO langString = new LangStringVO();
            langString.setIdioma("");
            langString.setTexto("");
            aLangString[0] = langString;
            pClaVO.setTextos(aLangString);
        }
        palabrasClave[i] = pClaVO;
    }

}

From source file:com.maxl.java.aips2sqlite.RealExpertInfo.java

private String updateSectionPackungen(String title, String atc_code, Map<String, ArrayList<String>> pack_info,
        String regnr_str, String content_str, List<String> tIndex_list) {
    Document doc = Jsoup.parse(content_str, "UTF-16");
    // package info string for original
    List<String> pinfo_originals_str = new ArrayList<String>();
    // package info string for generika
    List<String> pinfo_generics_str = new ArrayList<String>();
    // package info string for the rest
    List<String> pinfo_str = new ArrayList<String>();
    // String containg all barcodes
    List<String> barcode_list = new ArrayList<String>();

    int index = 0;

    // Extract swissmedicno5 registration numbers
    List<String> swissmedicno5_list = Arrays.asList(regnr_str.split("\\s*,\\s*"));
    for (String smno5 : swissmedicno5_list) {
        // Extract original / generika info + Selbstbehalt info from
        // "add_info_map"
        String orggen_str = ""; // O=Original, G=Generika
        String flagsb_str = ""; // SB=Selbstbehalt 
        String addinfo_str = m_add_info_map.get(smno5);
        if (addinfo_str != null) {
            List<String> ai_list = Arrays.asList(addinfo_str.split("\\s*;\\s*"));
            if (ai_list != null) {
                if (!ai_list.get(0).isEmpty())
                    orggen_str = ", " + ai_list.get(0); // O + G
                if (!ai_list.get(1).isEmpty())
                    flagsb_str = ", " + ai_list.get(1); // SB
            }/*from  www.jav a 2 s .c  om*/
        }
        // Now generate many swissmedicno8 = swissmedicno5 + ***, check if they're keys and retrieve package info
        String swissmedicno8_key = "";
        for (int n = 0; n < 1000; ++n) {
            swissmedicno8_key = getSwissmedicNo8(smno5, n);
            // Check if swissmedicno8_key is a key of the map
            if (pack_info.containsKey(swissmedicno8_key)) {
                ArrayList<String> pi_row = m_package_info.get(swissmedicno8_key);
                if (pi_row != null) {
                    // This string is used for "shopping carts" and contatins:
                    // Prparatname | Package size | Package unit | Public price
                    // | Exfactory price | Spezialittenliste, Swissmedic Kategorie, Limitations
                    // | EAN code | Pharma code
                    String barcode_html = "";
                    String pup = pi_row.get(7); // public price
                    String efp = pi_row.get(8); // exfactory price      
                    String fep = "";
                    String fap = "";
                    String vat = "";
                    String eancode = pi_row.get(14);
                    int visible = 0xff; // by default visible to all!
                    int has_free_samples = 0x00; // by default no free samples
                    // Exctract fep and fap pricing information
                    // FAP = Fabrikabgabepreis = EFP?
                    // FEP = Fachhandelseinkaufspreis
                    // EFP = FAP < FEP < PUP
                    if (m_map_products != null && eancode != null && m_map_products.containsKey(eancode)) {
                        Product product = m_map_products.get(eancode);
                        // Correct these prices, if necessary... the m_map_products info comes from the owner directly!
                        // @maxl: Added on 30.08.2015
                        if (product.efp > 0.0f)
                            efp = String.format("CHF %.2f", product.efp);
                        if (product.pp > 0.0f)
                            pup = String.format("CHF %.2f", product.pp);
                        if (product.fap > 0.0f)
                            fap = String.format("CHF %.2f", product.fap);
                        if (product.fep > 0.0f)
                            fep = String.format("CHF %.2f", product.fep);
                        if (product.vat > 0.0f)
                            vat = String.format("%.2f", product.vat);
                        visible = product.visible;
                        has_free_samples = product.free_sample;
                    }

                    // Some articles are listed in swissmedic_packages file but are not in the refdata file
                    if (pi_row.get(10).equals("a.H.")) {
                        pi_row.set(10, "ev.nn.i.H.");
                    }
                    if (pi_row.get(10).equals("p.c.")) {
                        pi_row.set(10, "ev.ep.e.c.");
                    }

                    // Add only if medication is "in Handel" -> check pi_row.get(10)                  
                    if (pi_row.get(10).isEmpty() || pi_row.get(10).equals("ev.nn.i.H.")
                            || pi_row.get(10).equals("ev.ep.e.c.")) {
                        // --> Extract EAN-13 or EAN-12 and generate barcodes                     
                        try {
                            if (!eancode.isEmpty()) {
                                BarCode bc = new BarCode();
                                if (eancode.length() == 12) {
                                    int cs = bc.getChecksum(eancode);
                                    eancode += cs;
                                }
                                String barcodeImg64 = bc.encode(eancode);
                                barcode_html = "<p class=\"barcode\">" + barcodeImg64 + "</p>";
                                barcode_list.add(barcode_html);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        m_list_of_packages.add(pi_row.get(1) + "|" + pi_row.get(3) + "|" + pi_row.get(4) + "|"
                                + efp + "|" + pup + "|" + fap + "|" + fep + "|" + vat + "|" + pi_row.get(5)
                                + ", " + pi_row.get(11) + ", " + pi_row.get(12) + "|" + eancode + "|"
                                + pi_row.get(15) + "|" + visible + "|" + has_free_samples + "\n");
                        m_list_of_eancodes.add(eancode);
                    }

                    // Remove double spaces in title and capitalize
                    String medtitle = capitalizeFully(pi_row.get(1).replaceAll("\\s+", " "), 1);
                    // Remove [QAP?] -> not an easy one!
                    medtitle = medtitle.replaceAll("\\[(.*?)\\?\\] ", "");
                    // --> Add "ausser Handel" information
                    String withdrawn_str = "";
                    if (pi_row.get(10).length() > 0)
                        withdrawn_str = ", " + pi_row.get(10);
                    // --> Add ex factory price information
                    String price_efp = !efp.isEmpty() ? "EFP" + efp.replace("CHF", "")
                            : "FEP" + fep.replace("CHF", "");
                    String price_pp = !pup.isEmpty() ? ", PP" + pup.replace("CHF", "") : "";
                    if (efp.length() > 0 || fep.length() > 0) {
                        // The rest of the package information
                        String append_str = ", " + price_efp + price_pp + withdrawn_str + " [" + pi_row.get(5)
                                + pi_row.get(11) + pi_row.get(12) + flagsb_str + orggen_str + "]";
                        // Generate package info string
                        if (orggen_str.equals(", O"))
                            pinfo_originals_str.add(
                                    "<p class=\"spacing1\">" + medtitle + append_str + "</p>" + barcode_html);
                        else if (orggen_str.equals(", G"))
                            pinfo_generics_str.add(
                                    "<p class=\"spacing1\">" + medtitle + append_str + "</p>" + barcode_html);
                        else
                            pinfo_str.add(
                                    "<p class=\"spacing1\">" + medtitle + append_str + "</p>" + barcode_html);
                    } else {
                        //
                        // @maxl (10.01.2014): Price for swissmedicNo8 pack is not listed in bag_preparations.xml!!
                        //
                        pinfo_str.add("<p class=\"spacing1\">" + medtitle + withdrawn_str + " [" + pi_row.get(5)
                                + "]</p>" + barcode_html);
                    }

                    // --> Add "tindex_str" and "application_str" (see
                    // SqlDatabase.java)
                    if (index == 0) {
                        tIndex_list.add(pi_row.get(9)); // therapeutic index
                        tIndex_list.add(pi_row.get(6)); // application area
                        index++;
                    }
                }
            }
        }
    }
    // Re-order the string alphabetically
    if (!m_list_of_packages.isEmpty()) {
        Collections.sort(m_list_of_packages, new AlphanumComp());
    }
    if (!pinfo_originals_str.isEmpty()) {
        Collections.sort(pinfo_originals_str, new AlphanumComp());
    }
    if (!pinfo_generics_str.isEmpty()) {
        Collections.sort(pinfo_generics_str, new AlphanumComp());
    }
    if (!pinfo_str.isEmpty()) {
        Collections.sort(pinfo_str, new AlphanumComp());
    }
    // Concatenate lists...
    pinfo_originals_str.addAll(pinfo_generics_str);
    pinfo_originals_str.addAll(pinfo_str);
    // Put everything in pinfo_str
    pinfo_str = pinfo_originals_str;

    // In case nothing was found
    if (index == 0) {
        tIndex_list.add("");
        tIndex_list.add("");
    }

    /*
    * Replace package information
    */
    if (CmlOptions.PLAIN == false) {
        // Replace original package information with pinfo_str   
        String p_str = "";
        for (String p : pinfo_str) {
            p_str += p;
        }

        // Generate a html-deprived string file
        m_pack_info_str = p_str.replaceAll("<p class=\"spacing1\">[<](/)?img[^>]*[>]</p>", "");
        m_pack_info_str = m_pack_info_str.replaceAll("<p class=\"barcode\">[<](/)?img[^>]*[>]</p>", "");
        m_pack_info_str = m_pack_info_str.replaceAll("\\<p.*?\\>", "");
        m_pack_info_str = m_pack_info_str.replaceAll("<\\/p\\>", "\n");

        // Remove last \n
        if (m_pack_info_str.length() > 0)
            m_pack_info_str = m_pack_info_str.substring(0, m_pack_info_str.length() - 1);

        doc.outputSettings().escapeMode(EscapeMode.xhtml);
        Element div7800 = doc.select("[id=Section7800]").first();

        // Initialize section titles
        String packages_title = "Packungen";
        String swiss_drg_title = "Swiss DRG";
        if (CmlOptions.DB_LANGUAGE.equals("fr")) {
            packages_title = "Prsentation";
            swiss_drg_title = "Swiss DRG";
        }

        // Generate html for chapter "Packagungen" and subchapter "Swiss DRGs"
        // ** Chapter "Packungen"
        String section_html = "<div class=\"absTitle\">" + packages_title + "</div>" + p_str;
        // ** Subchapter "Swiss DRGs"
        // Loop through list of dosages for a particular atc code and format appropriately
        if (atc_code != null) {
            // Update DRG footnote super scripts
            String footnotes = "1";
            String fn = m_swiss_drg_footnote.get(atc_code);
            if (fn != null)
                footnotes += (", " + fn);
            // Generate Swiss DRG string
            String drg_str = "";
            ArrayList<String> dosages = m_swiss_drg_info.get(atc_code);
            // For most atc codes, there are NO special DRG sanctioned dosages...
            if (dosages != null) {
                System.out.println(title + " (DRG)");
                for (String drg : dosages)
                    drg_str += "<p class=\"spacing1\">" + drg + "</p>";
                if (!drg_str.isEmpty()) {
                    section_html += ("<p class=\"paragraph\"></p><div class=\"absTitle\">" + swiss_drg_title
                            + "<sup>" + footnotes + "</sup></div>" + drg_str);
                }

                section_html += "<p class=\"noSpacing\"></p>";
                if (CmlOptions.DB_LANGUAGE.equals("de")) {
                    section_html += "<p class=\"spacing1\"><sup>1</sup> Alle Spitler mssen im Rahmen der jhrlichen Datenerhebung (Detaillieferung) die SwissDRG AG zwingend ber die Hhe der in Rechnung gestellten Zusatzentgelte informieren.</p>";
                    section_html += "<p class=\"spacing1\"><sup>2</sup> Eine zustzliche Abrechnung ist im Zusammenhang mit einer Fallpauschale der Basis-DRGs L60 oder L71 nicht mglich.</p>";
                    section_html += "<p class=\"spacing1\"><sup>3</sup> Eine Abrechnung des Zusatzentgeltes ist nur ber die in der Anlage zum Fallpauschalenkatalog aufgefhrten Dosisklassen mglich.</p>";
                    section_html += "<p class=\"spacing1\"><sup>4</sup> Dieses Zusatzentgelt ist nur abrechenbar fr Patienten mit einem Alter < 15 Jahre.</p>";
                    section_html += "<p class=\"spacing1\"><sup>5</sup> Dieses Zusatzentgelt darf nicht zustzlich zur DRG A91Z abgerechnet werden, da in dieser DRG Apheresen die Hauptleistung darstellen. "
                            + "Die Verfahrenskosten der  Apheresen sind in dieser DRG bereits vollumfnglich enthalten.</p>";
                } else if (CmlOptions.DB_LANGUAGE.equals("fr")) {
                    section_html += "<p class=\"spacing1\"><sup>1</sup> Tous les hpitaux doivent imprativement informer SwissDRG SA lors du relev (relev dtaill) sur le montant des rmunrations supplmentaires factures.</p>";
                    section_html += "<p class=\"spacing1\"><sup>2</sup> Une facturation supplmentaire aux forfaits par cas des DRG de base L60 ou L71 nest pas possible.</p>";
                    section_html += "<p class=\"spacing1\"><sup>3</sup> Une facturation des rmunration supplmentaires n'est possible que pour les classes de dosage dfinies dans cette annexe.</p>";
                    section_html += "<p class=\"spacing1\"><sup>4</sup> Cette rmunration supplmentaire n'est facturable que pour les patients gs de moins de 15 ans.</p>";
                    section_html += "<p class=\"spacing1\"><sup>5</sup> Cette rmunration supplmentaire ne peut pas tre facture en plus du DRG A91Z, la prestation principale de ce DRG tant l'aphrse. "
                            + "Les cots du traitement par aphrse sont dj intgralement compris dans le DRG.</p>";
                }
            }
        }

        if (div7800 != null) {
            div7800.html(section_html);
        } else {
            Element div18 = doc.select("[id=section18]").first();
            if (div18 != null) {
                div18.html(section_html);
            } else {
                if (CmlOptions.SHOW_ERRORS)
                    System.err.println(">> ERROR: elem is null, sections 18/7800 does not exist: " + title);
            }
        }
    }

    return doc.html();
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java

public KwlReturnObject getPositionstatus(HashMap<String, Object> requestParams) {
    boolean success = false;
    List lst = null, result1 = null, result2 = null;
    KwlReturnObject result = null;/*  w  w w .  jav a2s  .  c  o  m*/
    int totalcount = 0;
    try {
        ArrayList name = null;
        ArrayList value = null;
        String[] searchCol = null;
        ArrayList orderby = null;
        ArrayList ordertype = null;
        String hql = "", filterString = "", searchString = "", orderString = "";
        if (requestParams.containsKey("primary") && (Boolean) requestParams.get("primary")) {
            hql = "from Allapplications where id=?";
            String id = requestParams.get("id").toString();
            lst = HibernateUtil.executeQuery(hibernateTemplate, hql, new Object[] { id });
            result = new KwlReturnObject(success, "success", "", lst, lst.size());
            return result;
        }

        hql = "from Allapplications ";
        if (requestParams.get("filter_names") != null && requestParams.get("filter_values") != null) {
            name = (ArrayList) requestParams.get("filter_names");
            value = (ArrayList) requestParams.get("filter_values");
            hql += com.krawler.common.util.StringUtil.filterQuery(name, "where");
        }
        if (requestParams.get("searchcol") != null && requestParams.get("ss") != null) {
            searchCol = (String[]) requestParams.get("searchcol");
            searchString = StringUtil.getSearchquery(requestParams.get("ss").toString(), searchCol, value);
        }
        if (requestParams.get("order_by") != null && requestParams.get("order_type") != null) {
            orderby = (ArrayList) requestParams.get("order_by");
            ordertype = (ArrayList) requestParams.get("order_type");
            orderString = com.krawler.common.util.StringUtil.orderQuery(orderby, ordertype);
        }
        if (requestParams.get("searchcol1") == null) {
            result = StringUtil.getPagingquery(requestParams, searchCol, hibernateTemplate,
                    hql + searchString + orderString, value);
        } else {
            result1 = HibernateUtil.executeQuery(hibernateTemplate, hql + searchString + orderString,
                    value.toArray());
            totalcount = result1.size();
            hql = "from Allapplications ";
            if (requestParams.get("filter_names1") != null && requestParams.get("filter_values1") != null) {
                name = (ArrayList) requestParams.get("filter_names1");
                value = (ArrayList) requestParams.get("filter_values1");
                hql += com.krawler.common.util.StringUtil.filterQuery(name, "where");
            }
            if (name.contains("status"))
                value.set(5, 4); //configjobapplicant=4 reset to 0
            else
                value.set(4, 4); //configjobapplicant=4 reset to 0
            if (requestParams.get("searchcol1") != null && requestParams.get("ss") != null) {
                searchCol = (String[]) requestParams.get("searchcol1");
                searchString = StringUtil.getSearchquery(requestParams.get("ss").toString(), searchCol, value);
            }
            result2 = HibernateUtil.executeQuery(hibernateTemplate, hql + searchString + orderString,
                    value.toArray());
            totalcount += result2.size();
            result1.addAll(result2);
            String allflag = requestParams.get("allflag").toString();
            if (allflag.equals("false")) {
                try {
                    int st = Integer.parseInt(requestParams.get("start").toString());
                    int ed = Math.min(result1.size(),
                            st + Integer.parseInt(requestParams.get("limit").toString()));
                    lst = result1.subList(st, ed);
                    result1 = lst;
                } catch (NumberFormatException ne) {
                    throw ServiceException.FAILURE("CompanyHandler.getGoodsReceipts", ne);
                }
            }
            result = new KwlReturnObject(success, "success", "", result1, totalcount);
        }
        success = true;
    } catch (Exception ex) {
        success = false;
        ex.printStackTrace();
    } finally {
        return result;
    }
}