Example usage for java.util LinkedHashMap isEmpty

List of usage examples for java.util LinkedHashMap isEmpty

Introduction

In this page you can find the example usage for java.util LinkedHashMap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestElasticsearchIndexUtils.java

@Test
public void test_parseDefaultMapping() throws JsonProcessingException, IOException {

    // Check the different components

    // Build/"unbuild" match pair

    assertEquals(Tuples._2T("*", "*"), ElasticsearchIndexUtils.buildMatchPair(_mapper.readTree("{}")));

    assertEquals(Tuples._2T("field*", "*"),
            ElasticsearchIndexUtils.buildMatchPair(_mapper.readTree("{\"match\":\"field*\"}")));

    assertEquals(Tuples._2T("field*field", "type*"), ElasticsearchIndexUtils.buildMatchPair(
            _mapper.readTree("{\"match\":\"field*field\", \"match_mapping_type\": \"type*\"}")));

    assertEquals("testBARSTAR_string",
            ElasticsearchIndexUtils.getFieldNameFromMatchPair(Tuples._2T("test_*", "string")));

    // More complex objects

    final String properties = Resources.toString(
            Resources.getResource("com/ikanow/aleph2/search_service/elasticsearch/utils/properties_test.json"),
            Charsets.UTF_8);//from   ww w. j  av a2 s  . com
    final String templates = Resources.toString(
            Resources.getResource("com/ikanow/aleph2/search_service/elasticsearch/utils/templates_test.json"),
            Charsets.UTF_8);
    final String both = Resources.toString(
            Resources
                    .getResource("com/ikanow/aleph2/search_service/elasticsearch/utils/full_mapping_test.json"),
            Charsets.UTF_8);

    final JsonNode properties_json = _mapper.readTree(properties);
    final JsonNode templates_json = _mapper.readTree(templates);
    final JsonNode both_json = _mapper.readTree(both);

    // Properties, empty + non-empty

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> props_test1 = ElasticsearchIndexUtils
            .getProperties(templates_json);
    assertTrue("Empty map if not present", props_test1.isEmpty());

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> props_test2 = ElasticsearchIndexUtils
            .getProperties(properties_json);
    assertEquals(4, props_test2.size());
    assertEquals(Arrays.asList("@version", "@timestamp", "sourceKey", "geoip"),
            props_test2.keySet().stream().map(e -> e.left().value()).collect(Collectors.toList()));

    assertEquals("{\"type\":\"string\",\"index\":\"not_analyzed\"}",
            props_test2.get(Either.left("sourceKey")).toString());

    // Templates, empty + non-empty

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> templates_test1 = ElasticsearchIndexUtils
            .getTemplates(properties_json, _mapper.readTree("{}"), Collections.emptySet());
    assertTrue("Empty map if not present", templates_test1.isEmpty());

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> templates_test2 = ElasticsearchIndexUtils
            .getTemplates(templates_json, _mapper.readTree("{}"), Collections.emptySet());
    assertEquals("getTemplates: " + templates_test2, 2, templates_test2.size());
    assertEquals(Arrays.asList(Tuples._2T("*", "string"), Tuples._2T("*", "number")),
            templates_test2.keySet().stream().map(e -> e.right().value()).collect(Collectors.toList()));

    // Some more properties test

    final List<String> nested_properties = ElasticsearchIndexUtils.getAllFixedFields_internal(properties_json)
            .collect(Collectors.toList());
    assertEquals(Arrays.asList("@version", "@timestamp", "sourceKey", "geoip", "geoip.location"),
            nested_properties);

    final Set<String> nested_properties_2 = ElasticsearchIndexUtils.getAllFixedFields(both_json);
    assertEquals(Arrays.asList("sourceKey", "@timestamp", "geoip", "geoip.location", "@version"),
            new ArrayList<String>(nested_properties_2));

    // Putting it all together...

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> total_result1 = ElasticsearchIndexUtils
            .parseDefaultMapping(both_json, Optional.of("type_test"), Optional.empty(), Optional.empty(),
                    _config.search_technology_override(), _mapper);

    assertEquals(4, total_result1.size());
    assertEquals(
            "{\"mapping\":{\"type\":\"number\",\"index\":\"analyzed\"},\"path_match\":\"test*\",\"match_mapping_type\":\"number\"}",
            total_result1.get(Either.right(Tuples._2T("test*", "number"))).toString());
    assertEquals("{\"type\":\"date\"}", total_result1.get(Either.left("@timestamp1")).toString());

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> total_result2 = ElasticsearchIndexUtils
            .parseDefaultMapping(both_json, Optional.empty(), Optional.empty(), Optional.empty(),
                    _config.search_technology_override(), _mapper);

    assertEquals(7, total_result2.size());
    assertEquals(true, total_result2.get(Either.right(Tuples._2T("*", "string"))).get("mapping")
            .get("omit_norms").asBoolean());
    assertEquals("{\"type\":\"date\",\"fielddata\":{}}",
            total_result2.get(Either.left("@timestamp")).toString());

    // A couple of error checks:
    // - Missing mapping
    // - Mapping not an object
}

From source file:edu.umd.ks.cm.util.siscm.dao.impl.SisCmDaoImpl.java

private String getNaturalLanguageForStatement(String booleanExpression,
        List<ReqComponentReference> reqComponentList) throws Exception {
    HashMap reqComponentMap = new HashMap();
    LinkedHashMap<Integer, Integer> parPositionMap = new LinkedHashMap<Integer, Integer>();
    ArrayList<Integer> parLeftList = new ArrayList<Integer>();

    for (ReqComponentReference reqComponent : reqComponentList) {
        String translation = this.reqComponentTranslator.translate(reqComponent.getReqComponent(),
                "KUALI.RULE.CATALOG", "en");
        if (translation != null && translation.length() > 0
                && translation.substring(translation.length() - 1).equals("."))
            translation = translation.substring(0, translation.length() - 1);
        reqComponentMap.put(reqComponent.getBooleanId(), translation);
    }/*from w w  w .j  ava  2  s .c  o m*/

    BooleanFunction booleanFunction = new BooleanFunction(booleanExpression);
    List<String> funcSymbs = booleanFunction.getSymbols();

    for (int i = 0; i < funcSymbs.size(); i++) {
        if (funcSymbs.get(i).equals("(")) {
            parLeftList.add(i);
        }
        int parLeftLast = parLeftList.size() - 1;
        if (funcSymbs.get(i).equals(")")) {
            parPositionMap.put(parLeftList.get(parLeftLast), i);
            parLeftList.remove(parLeftLast);
        }
    }

    // For the expression (A + B + (C * D)) want to remove outer ()
    if (parPositionMap.containsKey(0) && parPositionMap.get(0) == funcSymbs.size() - 1) {
        parPositionMap.remove(0);
        funcSymbs.set(0, "null");
        funcSymbs.set(funcSymbs.size() - 1, "null");
    }

    if (!parPositionMap.isEmpty()) {
        for (Integer key : parPositionMap.keySet()) {
            StringBuffer funcSymb = new StringBuffer("");
            int pos = 0;
            String expr = "";
            for (int i = key + 1; i < parPositionMap.get(key); i++) {
                String funcSymbAdd = funcSymbs.get(i);
                if (!funcSymbAdd.equals("+") && !funcSymbAdd.equals("*") && !funcSymbAdd.equals("null")) {
                    expr = (String) reqComponentMap.get(funcSymbAdd);
                    if (pos == 0 && !funcSymbAdd.substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")")) {
                        expr = expr.substring(1, expr.length() - 1);
                    }
                    pos = 1;

                    //convert the first character of 'expr' to lower case, if necessary
                    if (expr.length() > 0) {
                        char ch0 = expr.charAt(0);
                        if (ch0 <= 'Z' && ch0 >= 'A') {
                            if (expr.length() > 1) {
                                char ch1 = expr.charAt(1);
                                if (ch1 >= 'a' && ch1 <= 'z') {
                                    expr = expr.substring(0, 1).toLowerCase() + expr.substring(1);
                                }
                            } else {
                                expr = expr.toLowerCase();
                            }
                        }
                    }

                    funcSymb.append(expr);
                } else if (funcSymbAdd.equals("+")) {
                    funcSymb.append("; or ");
                } else if (funcSymbAdd.equals("*")) {
                    funcSymb.append("; and ");
                }
            } // for int i               
            String id = "V" + Integer.toString(key);
            funcSymb.insert(0, "(");
            funcSymb.append(")");
            reqComponentMap.put(id, funcSymb.toString());

            funcSymbs.set(key, id);
            for (int i = key + 1; i < parPositionMap.get(key) + 1; i++)
                funcSymbs.set(i, "null");
        }
    }

    List<String> funcSymbsNew = new ArrayList<String>();
    for (int i = 0; i < funcSymbs.size(); i++) {
        if (!funcSymbs.get(i).equals("null"))
            funcSymbsNew.add(funcSymbs.get(i));
    }

    String nl = "";
    if (funcSymbsNew.size() == 1) {
        nl = (String) reqComponentMap.get(funcSymbsNew.get(0));
        if (nl.substring(0, 1).equals("(") && nl.substring(nl.length() - 1).equals(")"))
            nl = nl.substring(1, nl.length() - 1);
    } else {
        int pos = 0;
        String expr = "";
        for (int i = 0; i < funcSymbsNew.size(); i++) {
            if (!funcSymbsNew.get(i).equals("*") && !funcSymbsNew.get(i).equals("+")) {
                expr = (String) reqComponentMap.get(funcSymbsNew.get(i));
                if (pos == 0) {
                    if (expr.length() > 2 && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                    pos = 1;
                } else {
                    if (funcSymbsNew.get(i).substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                }
                nl = nl + expr;
            } else if (funcSymbsNew.get(i).equals("+")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". Or ";
                else
                    nl = nl + "; or ";
            } else if (funcSymbsNew.get(i).equals("*")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". And ";
                else
                    nl = nl + "; and ";
            }
        }
    }

    //TODO: Fix Capitalization
    nl = nl.substring(0, 1).toUpperCase() + nl.substring(1);
    return nl.trim();
}

From source file:com.zenkey.net.prowser.Request.java

/**************************************************************************
 * Sets parameters from a <code>java.util.Map</code> for this
 * <code>Request</code>. The keys of the map are parameter names; the
 * values of the map are arrays of parameter values associated with each
 * parameter name.//from w  w  w  .j  a  va 2s  .com
 * <p>
 * For each entry in the map argument, if any parameters with the specified
 * name already exist, they will all be replaced by parameters with the
 * spcecfied values. If no parameters with the specified name exist, new
 * parameters with the specified values will be added to the request.
 * <p>
 * If the request is using the HTTP <code>GET</code> method, then the
 * URI's query string will be updated accordingly.
 * 
 * @param parameterMap
 *        Map containing parameters to be set for the request. A
 *        <code>null</code> value is allowed.
 * @return A <code>java.util.Map</code> of any request parameters that
 *         were replaced, or <code>null</code> if no request parameters
 *         were replaced. The structure of the map is the same as the one
 *         returned by {@link #getParameterMap()}.
 */
public Map<String, String[]> setParameters(Map<String, String[]> parameterMap) {

    // If the parameter map is null, just return null
    if (parameterMap == null)
        return null;

    // Create a map to hold the parameters that will be replaced
    LinkedHashMap<String, String[]> replacedParameterMap = new LinkedHashMap<String, String[]>();

    // Set the specified parameters
    for (String name : parameterMap.keySet()) {

        // Save off parameters that are being replaced
        String[] oldValues = null;
        if ((oldValues = getParameterValues(name)) != null)
            replacedParameterMap.put(name, oldValues);

        // Remove parameters that are being replaced
        removeParametersWithoutUpdate(name);

        // Add replacement parameters
        String[] newValues = parameterMap.get(name);
        for (String newValue : newValues)
            addParameterWithoutUpdate(name, newValue);
    }

    // If request is using the GET method, update the URI's query string
    if (getHttpMethod().equalsIgnoreCase(HTTP_METHOD_GET))
        updateQueryString();

    // Return a map of any parameters that were replaced
    if (replacedParameterMap.isEmpty())
        return null;
    else
        return replacedParameterMap;
}

From source file:es.uvigo.ei.sing.adops.datatypes.ProjectExperiment.java

private String checkFastaFile() throws IllegalArgumentException {
    final Set<Character> aminos = new HashSet<Character>(
            Arrays.asList('a', 'c', 't', 'g', 'A', 'C', 'T', 'G', '-'));
    BufferedReader br = null;/*  w w  w. ja  va2  s . c o  m*/

    try {
        final StringBuilder sb = new StringBuilder();
        final LinkedHashMap<String, StringBuilder> replacements = new LinkedHashMap<String, StringBuilder>();

        br = new BufferedReader(new FileReader(this.fastaFile));

        String line = null;
        while ((line = br.readLine()) != null && !line.startsWith(">")) {
            sb.append(line).append('\n');
        }

        String seqId = null;
        String seq = null;
        while (line != null) {
            seqId = line;
            seq = "";
            while ((line = br.readLine()) != null && !line.startsWith(">")) {
                seq += line;
            }

            // Non ACTG characters replacement
            char[] charSequence = seq.toCharArray();
            String data = "";
            for (int i = 0; i < charSequence.length; i++) {
                if (aminos.contains(charSequence[i])) {
                    data += charSequence[i];
                } else {
                    if (replacements.containsKey(seqId)) {
                        replacements.get(seqId).append(String.format(", [%d,%c]", i + 1, charSequence[i]));
                    } else {
                        replacements.put(seqId,
                                new StringBuilder(String.format("[%d,%c]", i + 1, charSequence[i])));
                    }

                    data += '-';
                }
            }

            // Incomplete codons replacement
            charSequence = data.toCharArray();
            data = "";
            String codon = "";
            for (int i = 0; i < charSequence.length; i++) {
                codon += Character.toString(charSequence[i]);
                if ((i + 1) % 3 == 0) {
                    if (codon.contains("-")) {
                        data += "---";
                        if (replacements.containsKey(seqId)) {
                            replacements.get(seqId).append(String.format(", [%s,---]", codon));
                        } else {
                            replacements.put(seqId, new StringBuilder(String.format("[%s,---]", codon)));
                        }
                    } else {
                        data += codon;

                    }

                    codon = "";
                }
            }

            sb.append(seqId).append('\n');
            sb.append(data).append('\n');
        }

        FileUtils.write(this.fastaFile, sb.toString());

        if (replacements.isEmpty()) {
            return "";
        } else {
            final StringBuilder summary = new StringBuilder("Replacements done on input file\n");
            for (Map.Entry<String, StringBuilder> replacement : replacements.entrySet()) {
                summary.append(replacement.getKey()).append('\n');
                summary.append(replacement.getValue()).append('\n');
            }

            summary.append("\n-----\n");

            return summary.toString();
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Input file is not a valida Fasta file");
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:au.org.ala.delta.intkey.Intkey.java

/**
 * Update the view of available characters
 *///from ww w  .j ava  2s . co m
private void updateAvailableCharacters() {

    IntkeyCharacterOrder charOrder = _context.getCharacterOrder();

    Item taxonToSeparate = null;
    String formattedTaxonToSeparateName = null;

    switch (charOrder) {
    case SEPARATE:
        taxonToSeparate = _context.getDataset().getItem(_context.getTaxonToSeparate());
        formattedTaxonToSeparateName = _taxonformatter.formatItemDescription(taxonToSeparate);
        if (!_context.getAvailableTaxa().contains(taxonToSeparate)) {
            _listAvailableCharacters.setModel(new DefaultListModel());
            _lblNumAvailableCharacters
                    .setText(MessageFormat.format(separateCharactersCaption, formattedTaxonToSeparateName, 0));
            break;
        }

        // If taxon to separate has not been eliminated, drop through and
        // display the best characters for taxon separation
    case BEST:
        LinkedHashMap<Character, Double> bestCharactersMap = _context.getBestOrSeparateCharacters();
        if (bestCharactersMap != null) {
            if (charOrder == IntkeyCharacterOrder.BEST) {
                _lblNumAvailableCharacters.setText(
                        MessageFormat.format(bestCharactersCaption, bestCharactersMap.keySet().size()));
            } else {
                _lblNumAvailableCharacters.setText(MessageFormat.format(separateCharactersCaption,
                        formattedTaxonToSeparateName, bestCharactersMap.keySet().size()));
            }
            if (bestCharactersMap.isEmpty()) {
                handleNoAvailableCharacters();
                return;
            } else {
                _availableCharacterListModel = new DefaultListModel();
                for (Character ch : bestCharactersMap.keySet()) {
                    _availableCharacterListModel.addElement(ch);
                }
                _availableCharacterListModel.copyInto(bestCharactersMap.keySet().toArray());

                // Only display character separating powers if in advanced
                // mode.
                if (_advancedMode) {
                    _availableCharactersListCellRenderer = new BestCharacterCellRenderer(bestCharactersMap,
                            _context.displayNumbering());
                } else {
                    _availableCharactersListCellRenderer = new CharacterCellRenderer(
                            _context.displayNumbering());
                }
                _listAvailableCharacters.setCellRenderer(_availableCharactersListCellRenderer);
                _listAvailableCharacters.setModel(_availableCharacterListModel);
            }
        } else {
            _availableCharacterListModel = null;

            // The best characters list is not cached and needs to be
            // calculated. This is a
            // long-running operation so use a
            // SwingWorker to do it on a different thread, and update
            // the
            // available characters list when
            // it is complete.
            GetBestCharactersWorker worker = new GetBestCharactersWorker(_context);
            worker.execute();

            // Show the busy glass pane with a message if worker has not
            // completed within
            // 250 milliseconds. This avoids "flickering" of the
            // glasspane
            // when it takes a
            // very short time to calculate the best characters.
            try {
                Thread.sleep(250);
                if (!worker.isDone()) {
                    displayBusyMessage(calculatingBestCaption);
                }
            } catch (InterruptedException ex) {
                // do nothing
            }

            return;
        }

        break;
    case NATURAL:
        int lastSelectedIndex = _listAvailableCharacters.getSelectedIndex();

        List<Character> availableCharacters = new ArrayList<Character>(_context.getAvailableCharacters());
        _lblNumAvailableCharacters
                .setText(MessageFormat.format(availableCharactersCaption, availableCharacters.size()));
        if (availableCharacters.size() == 0) {
            handleNoAvailableCharacters();
            return;
        } else {
            _availableCharacterListModel = new DefaultListModel();
            for (Character ch : availableCharacters) {
                _availableCharacterListModel.addElement(ch);
            }
            _availableCharactersListCellRenderer = new CharacterCellRenderer(_context.displayNumbering());
            _listAvailableCharacters.setCellRenderer(_availableCharactersListCellRenderer);
            _listAvailableCharacters.setModel(_availableCharacterListModel);

            // Select the same index that was previously selected. This will
            // have the effect of selecting the character after the
            // previously used character.
            _listAvailableCharacters.setSelectedIndex(lastSelectedIndex);
        }
        break;
    default:
        throw new RuntimeException("Unrecognized character order");
    }

    // The viewport of the available characters scroll pane may be
    // displaying a
    // message due to an investigation finishing, or no characters being
    // available
    // previously. Ensure that the available characters list is now
    // displayed again.
    if (!_sclPaneAvailableCharacters.getViewport().getView().equals(_listAvailableCharacters)) {
        _sclPaneAvailableCharacters.setViewportView(_listAvailableCharacters);
        _sclPaneAvailableCharacters.revalidate();
    }
}

From source file:com.espertech.esper.filter.FilterSpecCompiler.java

private static FilterSpecParam handleInSetNode(ExprInNode constituent,
        LinkedHashMap<String, Pair<EventType, String>> arrayEventTypes,
        ExprEvaluatorContext exprEvaluatorContext, String statementName) throws ExprValidationException {
    ExprNode left = constituent.getChildNodes()[0];
    if (!(left instanceof ExprFilterOptimizableNode)) {
        return null;
    }//from ww  w. j ava2 s  .c  om

    ExprFilterOptimizableNode filterOptimizableNode = (ExprFilterOptimizableNode) left;
    FilterSpecLookupable lookupable = filterOptimizableNode.getFilterLookupable();
    FilterOperator op = FilterOperator.IN_LIST_OF_VALUES;
    if (constituent.isNotIn()) {
        op = FilterOperator.NOT_IN_LIST_OF_VALUES;
    }

    int expectedNumberOfConstants = constituent.getChildNodes().length - 1;
    List<FilterSpecParamInValue> listofValues = new ArrayList<FilterSpecParamInValue>();
    Iterator<ExprNode> it = Arrays.asList(constituent.getChildNodes()).iterator();
    it.next(); // ignore the first node as it's the identifier
    while (it.hasNext()) {
        ExprNode subNode = it.next();
        if (ExprNodeUtility.isConstantValueExpr(subNode)) {
            ExprConstantNode constantNode = (ExprConstantNode) subNode;
            Object constant = constantNode.evaluate(null, true, exprEvaluatorContext);
            if (constant instanceof Collection) {
                return null;
            }
            if (constant instanceof Map) {
                return null;
            }
            if ((constant != null) && (constant.getClass().isArray())) {
                for (int i = 0; i < Array.getLength(constant); i++) {
                    Object arrayElement = Array.get(constant, i);
                    Object arrayElementCoerced = handleConstantsCoercion(lookupable, arrayElement);
                    listofValues.add(new InSetOfValuesConstant(arrayElementCoerced));
                    if (i > 0) {
                        expectedNumberOfConstants++;
                    }
                }
            } else {
                constant = handleConstantsCoercion(lookupable, constant);
                listofValues.add(new InSetOfValuesConstant(constant));
            }
        }
        if (subNode instanceof ExprContextPropertyNode) {
            ExprContextPropertyNode contextPropertyNode = (ExprContextPropertyNode) subNode;
            Class returnType = contextPropertyNode.getType();
            if (JavaClassHelper.isImplementsInterface(contextPropertyNode.getType(), Collection.class)
                    || JavaClassHelper.isImplementsInterface(contextPropertyNode.getType(), Map.class)) {
                return null;
            }
            if ((returnType != null) && (returnType.getClass().isArray())) {
                return null;
            }
            SimpleNumberCoercer coercer = getNumberCoercer(left.getExprEvaluator().getType(),
                    contextPropertyNode.getType(), lookupable.getExpression());
            listofValues.add(new InSetOfValuesContextProp(contextPropertyNode.getPropertyName(),
                    contextPropertyNode.getGetter(), coercer));
        }
        if (subNode instanceof ExprIdentNode) {
            ExprIdentNode identNodeInner = (ExprIdentNode) subNode;
            if (identNodeInner.getStreamId() == 0) {
                break; // for same event evals use the boolean expression, via count compare failing below
            }

            boolean isMustCoerce = false;
            Class numericCoercionType = JavaClassHelper.getBoxedType(lookupable.getReturnType());
            if (identNodeInner.getExprEvaluator().getType() != lookupable.getReturnType()) {
                if (JavaClassHelper.isNumeric(lookupable.getReturnType())) {
                    if (!JavaClassHelper.canCoerce(identNodeInner.getExprEvaluator().getType(),
                            lookupable.getReturnType())) {
                        throwConversionError(identNodeInner.getExprEvaluator().getType(),
                                lookupable.getReturnType(), lookupable.getExpression());
                    }
                    isMustCoerce = true;
                } else {
                    break; // assumed not compatible
                }
            }

            FilterSpecParamInValue inValue;
            String streamName = identNodeInner.getResolvedStreamName();
            if (arrayEventTypes != null && !arrayEventTypes.isEmpty()
                    && arrayEventTypes.containsKey(streamName)) {
                Pair<Integer, String> indexAndProp = getStreamIndex(identNodeInner.getResolvedPropertyName());
                inValue = new InSetOfValuesEventPropIndexed(identNodeInner.getResolvedStreamName(),
                        indexAndProp.getFirst(), indexAndProp.getSecond(), isMustCoerce, numericCoercionType,
                        statementName);
            } else {
                inValue = new InSetOfValuesEventProp(identNodeInner.getResolvedStreamName(),
                        identNodeInner.getResolvedPropertyName(), isMustCoerce, numericCoercionType);
            }

            listofValues.add(inValue);
        }
    }

    // Fallback if not all values in the in-node can be resolved to properties or constants
    if (listofValues.size() == expectedNumberOfConstants) {
        return new FilterSpecParamIn(lookupable, op, listofValues);
    }
    return null;
}

From source file:com.concursive.connect.web.modules.members.portlets.InviteMembersPortlet.java

/**
 * @param request/*from  w  ww. j a  v  a2s.co  m*/
 */
private boolean buildMatches(ActionRequest request) throws SQLException {

    Connection db = PortalUtils.useConnection(request);
    String[] membersToInvite = request.getParameter(MEMBERS_TO_INVITE).split(",");
    LinkedHashMap<String, String> members = new LinkedHashMap<String, String>();
    LinkedHashMap<String, String> membersPresent = new LinkedHashMap<String, String>();
    boolean hasMultipleMatches = false;
    for (String member : membersToInvite) {
        members.put(member.trim(), NO_MATCH_FOUND);
    }

    //1. Profile Id based Query
    Iterator<String> keyIterator = members.keySet().iterator();
    while (keyIterator.hasNext()) {
        String profileId = keyIterator.next();
        if (members.get(profileId).equals(NO_MATCH_FOUND) && profileId.contains("(")) {
            // Find user by unique profileId
            String[] arrNameProfile = profileId.split("\\(");
            int endIndex = arrNameProfile[1].indexOf(")") < 0 ? arrNameProfile[1].length()
                    : arrNameProfile[1].indexOf(")");
            arrNameProfile[1] = arrNameProfile[1].substring(0, endIndex);
            Project project = ProjectUtils.loadProject(arrNameProfile[1]);
            if (project == null) {
                continue;
            }
            int userId = project.getOwner();
            if (userId > -1) {
                members = updateMemberList(request, profileId, String.valueOf(userId), members, membersPresent);
            }
        }
    }

    //2. Email based Query
    keyIterator = members.keySet().iterator();
    while (keyIterator.hasNext()) {
        String email = keyIterator.next();
        if (members.get(email).equals(NO_MATCH_FOUND) && email.contains("@")) {
            // Find user by email address
            String strEmail = email.trim();
            HashMap<String, String> mapEmail = DimDimUtils.processEmail(strEmail);
            strEmail = StringUtils.hasText(mapEmail.get(DimDimUtils.EMAIL)) ? mapEmail.get(DimDimUtils.EMAIL)
                    : strEmail;
            int userId = User.getIdByEmailAddress(db, strEmail);
            if (userId > -1) {
                members = updateMemberList(request, email, String.valueOf(userId), members, membersPresent);
            }
        }
    }

    //3. Name based Query based on first and last name
    //for the items that did not match in 1.get the names (i.e., first and last names) only (i.e., filter out the emails)
    //Fetch from users by matching first name and last name if more than one character exists in the last name
    keyIterator = members.keySet().iterator();
    while (keyIterator.hasNext()) {
        String name = keyIterator.next();
        if (members.get(name).equals(NO_MATCH_FOUND) && !name.contains("@")) {
            String[] nameParts = name.split(" ");
            UserList userList = new UserList();
            if (nameParts.length == 1) {
                //search first and last name fields
                UserSearchBean userSearch = new UserSearchBean();
                userSearch.setName(nameParts[0]);
                userList.setSearchCriteria(userSearch);
            } else if (nameParts.length == 2) {
                userList.setFirstName(nameParts[0]);
                userList.setLastName(nameParts[1]);
            }
            userList.buildList(db);
            if (userList.size() > 0) {
                if (userList.size() > 1) {
                    hasMultipleMatches = true;
                }
                StringBuffer idStringBuffer = new StringBuffer();
                for (User user : userList) {
                    idStringBuffer.append("," + user.getId());
                }
                members = updateMemberList(request, name, idStringBuffer.toString().substring(1), members,
                        membersPresent);
            }
        }
    }

    request.getPortletSession().setAttribute(MEMBERS, members);
    request.getPortletSession().setAttribute(HAS_MULTIPLE_MATCHES, String.valueOf(hasMultipleMatches));
    request.getPortletSession().setAttribute(MEMBERS_PRESENT, membersPresent);

    return members.isEmpty();
}

From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java

public static void migrate(final String projectName) {
    try {/*from   ww w.  ja  v a  2 s  .c  o m*/
        Map<String, Reference> referenceMap = new HashMap<String, Reference>();
        XmlSchema projectSchema = null;

        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);

        // Copy all xsd files to project's xsd directory
        File destDir = new File(project.getXsdDirPath());
        copyXsdOfProject(projectName, destDir);

        String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl";
        File wsdlFile = new File(projectWsdlFilePath);

        String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd";
        File xsdFile = new File(projectXsdFilePath);

        if (xsdFile.exists()) {
            // Load project schema from old XSD file
            XmlSchemaCollection collection = new XmlSchemaCollection();
            collection.setSchemaResolver(new DefaultURIResolver() {
                public InputSource resolveEntity(String targetNamespace, String schemaLocation,
                        String baseUri) {
                    // Case of a c8o project location
                    if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) {
                        try {
                            String targetProjectName = schemaLocation.substring(3,
                                    schemaLocation.indexOf("/", 3));
                            File pDir = new File(Engine.PROJECTS_PATH + "/" + targetProjectName);
                            if (pDir.exists()) {
                                File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2));
                                // Case c8o project is already migrated
                                if (!pFile.exists()) {
                                    Document doc = Engine.theApp.schemaManager
                                            .getSchemaForProject(targetProjectName).getSchemaDocument();
                                    DOMSource source = new DOMSource(doc);
                                    StringWriter writer = new StringWriter();
                                    StreamResult result = new StreamResult(writer);
                                    TransformerFactory.newInstance().newTransformer().transform(source, result);
                                    StringReader reader = new StringReader(writer.toString());
                                    return new InputSource(reader);
                                }
                            }
                            return null;
                        } catch (Exception e) {
                            Engine.logDatabaseObjectManager
                                    .warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation
                                            + "\"", e);
                            return null;
                        }
                    } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) {
                        return super.resolveEntity(targetNamespace, schemaLocation,
                                Engine.PROJECTS_PATH + "/" + projectName);
                    }
                    return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
                }

            });
            projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection);
            ConvertigoError.updateXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    try {
                        // Migrate transaction in case of a Web Service consumption project
                        if (transaction instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction;
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!reqn.equals("")) {
                                boolean useRef = reqn.indexOf(";") == -1;
                                // Doc/Literal case
                                if (useRef) {
                                    try {
                                        String[] qn = reqn.split(":");
                                        QName refName = new QName(
                                                projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                qn[1]);
                                        xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                                    } catch (Exception e) {
                                    }
                                }
                                // RPC case
                                else {
                                    int index, index2;
                                    try {
                                        index = reqn.indexOf(";");
                                        String opName = reqn.substring(0, index);
                                        if ((index2 = reqn.indexOf(";", index + 1)) != -1) {
                                            String eltName = reqn.substring(index + 1, index2);
                                            String eltType = reqn.substring(index2 + 1);
                                            String[] qn = eltType.split(":");

                                            QName typeName = new QName(
                                                    projectSchema.getNamespaceContext().getNamespaceURI(qn[0]),
                                                    qn[1]);
                                            String responseElementQName = opName + ";" + eltName + ";" + "{"
                                                    + typeName.getNamespaceURI() + "}"
                                                    + typeName.getLocalPart();
                                            xmlHttpTransaction.setResponseElementQName(responseElementQName);
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        }

                        // Retrieve required XmlSchemaObjects for transaction
                        QName requestQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdRequestElementName());
                        QName responseQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseElementName());
                        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false);
                        dw.walkByElementRef(projectSchema, requestQName);
                        dw.walkByElementRef(projectSchema, responseQName);

                        // Create transaction schema
                        String targetNamespace = projectSchema.getTargetNamespace();
                        String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace);
                        XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace,
                                XsdForm.unqualified.name(), XsdForm.unqualified.name());

                        // Add required prefix declarations
                        List<String> nsList = new LinkedList<String>();
                        for (QName qname : map.keySet()) {
                            String nsURI = qname.getNamespaceURI();
                            if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) {
                                if (!nsList.contains(nsURI)) {
                                    nsList.add(nsURI);
                                }
                            }
                            String nsPrefix = qname.getPrefix();
                            if (!nsURI.equals(targetNamespace)) {
                                NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema);
                                if (nsMap.getNamespaceURI(nsPrefix) == null) {
                                    nsMap.add(nsPrefix, nsURI);
                                    transactionSchema.setNamespaceContext(nsMap);
                                }
                            }
                        }

                        // Add required imports
                        for (String namespaceURI : nsList) {
                            XmlSchemaObjectCollection includes = projectSchema.getIncludes();
                            for (int i = 0; i < includes.getCount(); i++) {
                                XmlSchemaObject xmlSchemaObject = includes.getItem(i);
                                if (xmlSchemaObject instanceof XmlSchemaImport) {
                                    if (((XmlSchemaImport) xmlSchemaObject).getNamespace()
                                            .equals(namespaceURI)) {

                                        // do not allow import with same ns !
                                        if (namespaceURI.equals(project.getTargetNamespace()))
                                            continue;

                                        String location = ((XmlSchemaImport) xmlSchemaObject)
                                                .getSchemaLocation();

                                        // This is a convertigo project reference
                                        if (location.startsWith("../")) {
                                            // Copy all xsd files to xsd directory
                                            String targetProjectName = location.substring(3,
                                                    location.indexOf("/", 3));
                                            copyXsdOfProject(targetProjectName, destDir);
                                        }

                                        // Add reference
                                        addReferenceToMap(referenceMap, namespaceURI, location);

                                        // Add import
                                        addImport(transactionSchema, namespaceURI, location);
                                    }
                                }
                            }
                        }

                        QName responseTypeQName = new QName(project.getTargetNamespace(),
                                transaction.getXsdResponseTypeName());

                        // Add required schema objects
                        for (QName qname : map.keySet()) {
                            if (qname.getNamespaceURI().equals(targetNamespace)) {
                                XmlSchemaObject ob = map.get(qname);

                                if (qname.getLocalPart().startsWith("ConvertigoError"))
                                    continue;
                                transactionSchema.getItems().add(ob);

                                // Add missing response error element and attributes
                                if (qname.equals(responseTypeQName)) {
                                    Transaction.addSchemaResponseObjects(transactionSchema,
                                            (XmlSchemaComplexType) ob);
                                }
                            }
                        }

                        // Add missing ResponseType (with document)
                        if (map.containsKey(responseTypeQName)) {
                            Transaction.addSchemaResponseType(transactionSchema, transaction);
                        }

                        // Add everything
                        if (map.isEmpty()) {
                            Transaction.addSchemaObjects(transactionSchema, transaction);
                        }

                        // Add c8o error objects (for internal xsd edition only)
                        ConvertigoError.updateXmlSchemaObjects(transactionSchema);

                        // Save schema to file
                        String transactionXsdFilePath = transaction.getSchemaFilePath();
                        new File(transaction.getSchemaFileDirPath()).mkdirs();
                        SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema);
                    } catch (Exception e) {
                        Engine.logDatabaseObjectManager
                                .error("[Migration 7.0.0] An error occured while migrating transaction \""
                                        + transaction.getName() + "\"", e);
                    }

                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());

                        // Change SQLQuery variables : i.e. {id} --> {{id}}
                        if (transaction instanceof SqlTransaction) {
                            String sqlQuery = ((SqlTransaction) transaction).getSqlQuery();

                            sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}");
                            ((SqlTransaction) transaction).setSqlQuery(sqlQuery);
                        }

                    }
                }
            }
        } else {// Should only happen for projects which version <= 4.6.0 
            XmlSchemaCollection collection = new XmlSchemaCollection();
            String prefix = project.getName() + "_ns";
            projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(),
                    XsdForm.unqualified.name(), XsdForm.unqualified.name());
            ConvertigoError.addXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);

            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                    }
                }
            }
        }

        // Handle sequence objects
        for (Sequence sequence : project.getSequencesList()) {
            handleSteps(projectSchema, referenceMap, sequence.getSteps());
            handleRequestableVariable(sequence.getVariablesList());
        }

        // Add all references to project
        if (!referenceMap.isEmpty()) {
            for (Reference reference : referenceMap.values())
                project.add(reference);
        }

        // Delete XSD file
        if (xsdFile.exists())
            xsdFile.delete();

        // Delete WSDL file
        if (wsdlFile.exists())
            wsdlFile.delete();

    } catch (Exception e) {
        Engine.logDatabaseObjectManager
                .error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}

From source file:eionet.cr.staging.exp.ExportRunner.java

/**
 * Export row./*from  ww  w . j  a  v  a2 s .com*/
 *
 * @param rs
 *            the rs
 * @param rowIndex
 *            the row index
 * @param repoConn
 *            the repo conn
 * @param vf
 *            the vf
 * @throws SQLException
 *             the sQL exception
 * @throws RepositoryException
 *             the repository exception
 * @throws DAOException
 */
private void exportRow(ResultSet rs, int rowIndex, RepositoryConnection repoConn, ValueFactory vf)
        throws SQLException, RepositoryException, DAOException {

    if (rowIndex == 1) {
        loadExistingConcepts();
    }

    // Prepare subject URI on the basis of the template in the query configuration.
    String subjectUri = queryConf.getObjectUriTemplate();
    if (StringUtils.isBlank(subjectUri)) {
        throw new IllegalArgumentException(
                "The object URI template in the query configuration must not be blank!");
    }
    subjectUri = StringUtils.replace(subjectUri, "<dataset>", datasetIdentifier);

    // Prepare the map of ObjectDTO to be added to the subject later.
    LinkedHashMap<URI, ArrayList<Value>> valuesByPredicate = new LinkedHashMap<URI, ArrayList<Value>>();

    // Add rdf:type predicate-value.
    addPredicateValue(valuesByPredicate, rdfTypeURI, objectTypeURI);

    // Add the DataCube dataset predicate-value. Assume this point cannot be reached if dataset value is empty.
    addPredicateValue(valuesByPredicate, datasetPredicateURI, datasetValueURI);

    // Add predicate-value pairs for hidden properties.
    if (hiddenProperties != null) {
        for (ObjectHiddenProperty hiddenProperty : hiddenProperties) {
            addPredicateValue(valuesByPredicate, hiddenProperty.getPredicateURI(),
                    hiddenProperty.getValueValue());
        }
    }

    boolean hasIndicatorMapping = false;

    // Loop through the query configuration's column mappings, construct ObjectDTO for each.
    for (Entry<String, ObjectProperty> entry : queryConf.getColumnMappings().entrySet()) {

        String colName = entry.getKey();
        String colValue = rs.getString(colName);
        ObjectProperty property = entry.getValue();
        if (property.getId().equals(INDICATOR)) {
            hasIndicatorMapping = true;
        }

        if (StringUtils.isBlank(colValue)) {
            if (property.getId().equals(BREAKDOWN)) {
                colValue = DEFAULT_BREAKDOWN_CODE;
            } else if (property.getId().equals(INDICATOR)) {
                colValue = DEFAULT_INDICATOR_CODE;
            }
        }

        if (StringUtils.isNotBlank(colValue)) {

            // Replace property place-holders in subject ID
            subjectUri = StringUtils.replace(subjectUri, "<" + property.getId() + ">", colValue);

            URI predicateURI = property.getPredicateURI();
            if (predicateURI != null) {

                String propertyValue = property.getValueTemplate();
                if (propertyValue == null) {
                    propertyValue = colValue;
                } else {
                    // Replace the column value place-holder in the value template (the latter cannot be specified by user)
                    propertyValue = StringUtils.replace(propertyValue, "<value>", colValue);
                }

                recordMissingConcepts(property, colValue, propertyValue);

                Value value = null;
                if (property.isLiteralRange()) {
                    try {
                        String dataTypeUri = property.getDataType();
                        value = vf.createLiteral(propertyValue,
                                dataTypeUri == null ? null : vf.createURI(dataTypeUri));
                    } catch (IllegalArgumentException e) {
                        value = vf.createLiteral(propertyValue);
                    }
                } else {
                    value = vf.createURI(propertyValue);
                }

                addPredicateValue(valuesByPredicate, predicateURI, value);
            }
        }
    }

    // If there was no column mapping for the indicator, but a fixed indicator URI has been provided then use the latter.
    if (!hasIndicatorMapping && indicatorValueURI != null) {
        addPredicateValue(valuesByPredicate, indicatorPredicateURI, indicatorValueURI);
    }

    // If <indicator> column placeholder not replaced yet, then use the fixed indicator URI if given.
    if (subjectUri.indexOf("<indicator>") != -1) {
        String indicatorCode = StringUtils.substringAfterLast(queryConf.getIndicatorUri(), "/");
        if (StringUtils.isBlank(indicatorCode)) {
            // No fixed indicator URI given either, resort to the default.
            indicatorCode = DEFAULT_INDICATOR_CODE;
        }
        subjectUri = StringUtils.replace(subjectUri, "<indicator>", indicatorCode);
    }

    // If <breakdown> column placeholder not replaced yet, then use the default.
    if (subjectUri.indexOf("<breakdown>") != -1) {
        subjectUri = StringUtils.replace(subjectUri, "<breakdown>", DEFAULT_BREAKDOWN_CODE);
    }

    // Loop over predicate-value pairs and create the triples in the triple store.
    if (!valuesByPredicate.isEmpty()) {

        int tripleCountBefore = tripleCount;
        URI subjectURI = vf.createURI(subjectUri);
        for (Entry<URI, ArrayList<Value>> entry : valuesByPredicate.entrySet()) {

            ArrayList<Value> values = entry.getValue();
            if (values != null && !values.isEmpty()) {
                URI predicateURI = entry.getKey();
                for (Value value : values) {
                    repoConn.add(subjectURI, predicateURI, value, graphURI);
                    graphs.add(graphURI.stringValue());
                    tripleCount++;
                    if (tripleCount % 5000 == 0) {
                        LOGGER.debug(tripleCount + " triples exported so far");
                    }

                    // Time periods should be harvested afterwards.
                    if (Predicates.DAS_TIMEPERIOD.equals(predicateURI.stringValue())) {
                        if (value instanceof URI) {
                            timePeriods.add(value.stringValue());
                        }
                    }
                }
            }
        }

        if (tripleCount > tripleCountBefore) {
            subjectCount++;
        }
    }
}

From source file:com.gp.cong.logisoft.lcl.report.LclAllBLPdfCreator.java

public PdfPTable appendChargesAndCommodity() throws Exception {
    LclBlAcDAO lclBlAcDAO = new LclBlAcDAO();
    List<LclBlPiece> lclBlPiecesList = lclbl.getLclFileNumber().getLclBlPieceList();
    List<LclBlAc> chargeList = lclBlAcDAO.getLclCostByFileNumberAsc(lclbl.getFileNumberId());
    PdfPTable chargeTable = new PdfPTable(6);
    PdfPCell chargeCell = null;// ww w  . j  a v a 2  s. c  o  m
    chargeTable.setWidths(new float[] { 3.8f, 1.5f, .8f, 3.8f, 1.5f, .8f });
    chargeTable.setWidthPercentage(100f);
    Paragraph p = null;

    this.total_ar_amount = 0.00;
    this.total_ar_col_amount = 0.00;
    this.total_ar_ppd_amount = 0.00;

    List<LinkedHashMap<String, PdfPCell>> listChargeMap = null;
    LinkedHashMap<String, PdfPCell> chargeMap = null;
    if ("BOTH".equalsIgnoreCase(billType)) {
        listChargeMap = this.getTotalChargesList(chargeList, lclBlPiecesList);
    } else {
        chargeMap = this.getTotalCharges(chargeList, lclBlPiecesList);
    }

    LclBlAc blAC = lclBlAcDAO.manualChargeValidate(lclbl.getFileNumberId(), "OCNFRT", false);
    if (lclBlPiecesList != null && lclBlPiecesList.size() > 0 && blAC != null) {
        BigDecimal CFT = BigDecimal.ZERO, LBS = BigDecimal.ZERO;
        LclBlPiece lclBlPiece = (LclBlPiece) lclBlPiecesList.get(0);
        if (blAC.getRatePerUnitUom() != null) {
            CFT = blAC.getRatePerUnitUom().equalsIgnoreCase("FRV") ? blAC.getRatePerVolumeUnit()
                    : BigDecimal.ZERO;
            LBS = blAC.getRatePerUnitUom().equalsIgnoreCase("FRW") ? blAC.getRatePerWeightUnit()
                    : BigDecimal.ZERO;
        }
        if (CFT != BigDecimal.ZERO || LBS != BigDecimal.ZERO) {
            StringBuilder cbmValues = new StringBuilder();
            if (CFT != BigDecimal.ZERO && lclBlPiece.getActualVolumeImperial() != null) {
                cbmValues.append(NumberUtils
                        .convertToThreeDecimalhash(lclBlPiece.getActualVolumeImperial().doubleValue()));
            }
            if (LBS != BigDecimal.ZERO && lclBlPiece.getActualWeightImperial() != null) {
                cbmValues.append(NumberUtils
                        .convertToThreeDecimalhash(lclBlPiece.getActualWeightImperial().doubleValue()));
            }
            if (null != blAC.getArAmount() && blAC.getArAmount().toString().equalsIgnoreCase(OCNFRT_Total)) {
                if (CFT == BigDecimal.ZERO) {
                    cbmValues.append(" LBS @ ").append(LBS).append(" PER 100 LBS @ ")
                            .append(blAC.getArAmount());
                } else {
                    cbmValues.append(" CFT @ ").append(CFT).append(" PER CFT @").append(blAC.getArAmount());
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(6);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(6);
                p = new Paragraph(2f, "" + cbmValues.toString().toUpperCase(), totalFontQuote);
                p.add(new Paragraph(2f,
                        null != lclBlPiece && null != lclBlPiece.getCommodityType()
                                ? "   Commodity# " + lclBlPiece.getCommodityType().getCode()
                                : "   Commodity#",
                        totalFontQuote));
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
        }
    }
    this.OCNFRT_Total = "";
    LinkedHashMap<String, PdfPCell> left_chargeMap = new LinkedHashMap<String, PdfPCell>();
    LinkedHashMap<String, PdfPCell> right_chargeMap = new LinkedHashMap<String, PdfPCell>();
    if ("BOTH".equalsIgnoreCase(billType) && listChargeMap != null && !listChargeMap.isEmpty()) {
        if (listChargeMap.size() > 1) {
            if (listChargeMap.get(0).size() > 6 || listChargeMap.get(1).size() > 6) {
                chargeMap = new LinkedHashMap<String, PdfPCell>();
                chargeMap.putAll(listChargeMap.get(0));
                chargeMap.putAll(listChargeMap.get(1));
                int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2;
                for (String key : chargeMap.keySet()) {
                    if (count++ < size) {
                        left_chargeMap.put(key, chargeMap.get(key));
                    } else {
                        right_chargeMap.put(key, chargeMap.get(key));
                    }
                }
            } else {
                left_chargeMap.putAll(listChargeMap.get(0));
                right_chargeMap.putAll(listChargeMap.get(1));
            }
        } else {
            int count = 0, size = listChargeMap.get(0).size() / 2 <= 6 ? 6 : listChargeMap.get(0).size() / 2;
            for (String key : listChargeMap.get(0).keySet()) {
                if (count++ < size) {
                    left_chargeMap.put(key, listChargeMap.get(0).get(key));
                } else {
                    right_chargeMap.put(key, listChargeMap.get(0).get(key));
                }
            }
        }
    } else if (chargeMap != null && !chargeMap.isEmpty()) {
        int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2;
        for (String key : chargeMap.keySet()) {
            if (count++ < size) {
                left_chargeMap.put(key, chargeMap.get(key));
            } else {
                right_chargeMap.put(key, chargeMap.get(key));
            }
        }
    }

    if (!left_chargeMap.isEmpty()) {
        String chargeDesc = null;
        PdfPTable innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidthPercentage(100f);
        PdfPCell inner_chargeCell = null;

        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(3);
        chargeCell.setBorderWidthRight(0.6f);
        chargeCell.setPadding(0);
        innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidths(new float[] { 5f, 3f });
        if (!left_chargeMap.isEmpty()) {
            for (String key : left_chargeMap.keySet()) {
                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell.setPaddingLeft(-15);
                chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$"));
                inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote));
                innner_chargeTable.addCell(inner_chargeCell);

                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell = left_chargeMap.get(key);
                innner_chargeTable.addCell(inner_chargeCell);
            }
        }
        chargeCell.addElement(innner_chargeTable);
        chargeTable.addCell(chargeCell);

        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(3);
        chargeCell.setPadding(0);
        innner_chargeTable = new PdfPTable(2);
        innner_chargeTable.setWidths(new float[] { 5f, 3f });
        if (!left_chargeMap.isEmpty()) {
            for (String key : right_chargeMap.keySet()) {
                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell.setPaddingLeft(-15);
                chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$"));
                inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote));
                innner_chargeTable.addCell(inner_chargeCell);

                inner_chargeCell = new PdfPCell();
                inner_chargeCell.setBorder(0);
                inner_chargeCell = right_chargeMap.get(key);
                innner_chargeTable.addCell(inner_chargeCell);
            }
        }
        chargeCell.addElement(innner_chargeTable);
        chargeTable.addCell(chargeCell);
    } else {
        this.total_ar_amount = 0.00;
        this.total_ar_ppd_amount = 0.00;
        this.total_ar_col_amount = 0.00;
    }
    String acctNo = "";
    String billToParty = "";
    if (CommonFunctions.isNotNull(lclbl.getBillToParty()) && CommonUtils.isNotEmpty(lclbl.getBillToParty())) {
        if (lclbl.getBillToParty().equalsIgnoreCase("T")
                && CommonFunctions.isNotNull(lclbl.getThirdPartyAcct())) {
            billToParty = "THIRD PARTY";
            acctNo = lclbl.getThirdPartyAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("S")
                && CommonFunctions.isNotNull(lclbl.getShipAcct())) {
            billToParty = "SHIPPER";
            acctNo = lclbl.getShipAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("F")
                && CommonFunctions.isNotNull(lclbl.getFwdAcct())) {
            billToParty = "FORWARDER";
            acctNo = lclbl.getFwdAcct().getAccountno();
        } else if (lclbl.getBillToParty().equalsIgnoreCase("A")
                && CommonFunctions.isNotNull(lclbl.getAgentAcct())) {
            billToParty = "AGENT";
            if (lclBooking.getBookingType().equals("T")
                    && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) {
                acctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo().getAccountno();
            } else if (lclBooking.getAgentAcct() != null) {
                acctNo = lclBooking.getAgentAcct().getAccountno();
            } else {
                acctNo = lclbl.getAgentAcct().getAccountno();
            }
        }
    }

    if ("BOTH".equalsIgnoreCase(billType)) {
        if (this.total_ar_ppd_amount != 0.00 || this.total_ar_col_amount != 0.00) {
            if (this.total_ar_ppd_amount != 0.00) {
                if (CommonFunctions.isNotNullOrNotEmpty(ppdBillToSet) && ppdBillToSet.size() == 1) {
                    for (String billTo : ppdBillToSet) {
                        arBillToParty = billTo;
                        break;
                    }
                    if (arBillToParty.equalsIgnoreCase("T")) {
                        billToParty = "THIRD PARTY";
                        acctNo = null != lclbl.getThirdPartyAcct() ? lclbl.getThirdPartyAcct().getAccountno()
                                : acctNo;
                    } else if (arBillToParty.equalsIgnoreCase("S")) {
                        acctNo = null != lclbl.getShipAcct() ? lclbl.getShipAcct().getAccountno() : acctNo;
                        billToParty = "SHIPPER";
                    } else if (arBillToParty.equalsIgnoreCase("F")) {
                        billToParty = "FORWARDER";
                        acctNo = null != lclbl.getFwdAcct() ? lclbl.getFwdAcct().getAccountno() : acctNo;
                    }
                } else {
                    acctNo = null;
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(2);
                p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setColspan(4);
                chargeCell.setBorder(0);
                if (null != acctNo) {
                    p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount)
                            + " PPD " + billToParty + "-" + acctNo, totalFontQuote);
                } else {
                    p = new Paragraph(7f,
                            "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount) + " PPD ",
                            totalFontQuote);
                }
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }

            if (this.total_ar_col_amount != 0.00) {
                String colAcctNo = "";
                if (lclBooking.getBookingType().equals("T")
                        && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) {
                    colAcctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo()
                            .getAccountno();
                } else if (lclBooking.getAgentAcct() != null) {
                    colAcctNo = lclBooking.getAgentAcct().getAccountno();
                } else if (lclbl.getAgentAcct() != null) {
                    colAcctNo = lclbl.getAgentAcct().getAccountno();
                }
                chargeCell = new PdfPCell();
                chargeCell.setBorder(0);
                chargeCell.setColspan(2);
                if (this.total_ar_ppd_amount == 0.00) {
                    p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
                } else {
                    p = new Paragraph(7f, "", totalFontQuote);
                }
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);

                chargeCell = new PdfPCell();
                chargeCell.setColspan(4);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_col_amount)
                        + " COL AGENT-" + colAcctNo, totalFontQuote);
                p.setAlignment(Element.ALIGN_LEFT);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }

            NumberFormat numberFormat = new DecimalFormat("###,###,##0.000");
            if (this.total_ar_ppd_amount != 0.00) {
                String totalString1 = numberFormat.format(this.total_ar_ppd_amount).replaceAll(",", "");
                int indexdot = totalString1.indexOf(".");
                String beforeDecimal = totalString1.substring(0, indexdot);
                String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
                chargeCell = new PdfPCell();
                chargeCell.setColspan(6);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                        + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS",
                        totalFontQuote);
                chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
            if (this.total_ar_col_amount != 0.00) {
                String totalString1 = numberFormat.format(this.total_ar_col_amount).replaceAll(",", "");
                int indexdot = totalString1.indexOf(".");
                String beforeDecimal = totalString1.substring(0, indexdot);
                String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
                chargeCell = new PdfPCell();
                chargeCell.setColspan(6);
                chargeCell.setBorder(0);
                p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                        + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS",
                        totalFontQuote);
                chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                chargeCell.addElement(p);
                chargeTable.addCell(chargeCell);
            }
        }
    } else if (this.total_ar_amount != 0.00) {
        chargeCell = new PdfPCell();
        chargeCell.setBorder(0);
        chargeCell.setColspan(2);
        chargeCell.setPaddingTop(8f);
        p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote);
        p.setAlignment(Element.ALIGN_LEFT);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);

        chargeCell = new PdfPCell();
        chargeCell.setColspan(4);
        chargeCell.setBorder(0);
        chargeCell.setPaddingTop(8f);
        p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_amount) + " " + billType + " "
                + billToParty + "-" + acctNo, totalFontQuote);
        p.setAlignment(Element.ALIGN_LEFT);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);

        NumberFormat numberFormat = new DecimalFormat("###,###,##0.000");

        String totalString1 = numberFormat.format(this.total_ar_amount).replaceAll(",", "");
        int indexdot = totalString1.indexOf(".");
        String beforeDecimal = totalString1.substring(0, indexdot);
        String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length());
        chargeCell = new PdfPCell();
        chargeCell.setColspan(6);
        chargeCell.setBorder(0);
        p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal))
                + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS", totalFontQuote);
        chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        chargeCell.addElement(p);
        chargeTable.addCell(chargeCell);
    }

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(4);
    p = new Paragraph(5f, "" + sailDateFormat, totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setColspan(5);
    chargeCell.setBorder(0);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setColspan(3);
    chargeCell.setBorder(0);
    chargeCell.setRowspan(3);
    String fdPodValue = null;
    if (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[2])) {
        fdPodValue = agencyInfo[2];
    } else if (CommonFunctions.isNotNull(lclbl.getFinalDestination())
            && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId())
            && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId().getCodedesc())) {
        fdPodValue = lclbl.getFinalDestination().getUnLocationName() + ","
                + lclbl.getFinalDestination().getCountryId().getCodedesc();
    }
    p = new Paragraph(7f, fdPodValue != null ? fdPodValue.toUpperCase() : podValues.toUpperCase(),
            totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    p = new Paragraph(5f, "UNIT# " + unitNumber, headingblackBoldFont);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    chargeCell.setPaddingTop(2f);
    p = new Paragraph(5f, "SEAL# " + sealOut, headingblackBoldFont);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    chargeCell = new PdfPCell();
    chargeCell.setBorder(0);
    chargeCell.setColspan(3);
    chargeCell.setPaddingTop(2f);
    p = new Paragraph(5f, "CONTROL-VOY# " + voyageNumber, totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    chargeCell.addElement(p);
    chargeTable.addCell(chargeCell);

    String emailId = "";
    StringBuilder agentDetails = new StringBuilder();
    //Agent Details
    String agentAcctNo = "";
    if ("Y".equalsIgnoreCase(altAgentKey)) {
        agentAcctNo = CommonUtils.isNotEmpty(altAgentValue) ? altAgentValue : "";
    } else if (lclbl.getAgentAcct() != null) {
        agentAcctNo = (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[0])) ? agencyInfo[0]
                : lclbl.getAgentAcct().getAccountno();
    }
    if (CommonUtils.isNotEmpty(agentAcctNo)) {
        CustAddress custAddress = new CustAddressDAO().findPrimeContact(agentAcctNo);
        if (CommonFunctions.isNotNull(custAddress)) {
            if (CommonFunctions.isNotNull(custAddress.getAcctName())) {
                agentDetails.append(custAddress.getAcctName()).append("  ");
            }
            if (CommonFunctions.isNotNull(custAddress.getPhone())) {
                agentDetails.append("Phone: ").append(custAddress.getPhone()).append("\n");
            } else {
                agentDetails.append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getCoName())) {
                agentDetails.append(custAddress.getCoName()).append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getAddress1())) {
                agentDetails.append(custAddress.getAddress1().replace(", ", "\n")).append("\n");
            }
            if (CommonFunctions.isNotNull(custAddress.getCity1())) {
                agentDetails.append(custAddress.getCity1());
            }
            if (CommonFunctions.isNotNull(custAddress.getState())) {
                agentDetails.append("  ").append(custAddress.getState());
            }
            if (CommonFunctions.isNotNull(custAddress.getEmail1())) {
                emailId = custAddress.getEmail1();
            }
        }
    }
    BigDecimal PrintInvoiceValue = null;
    if (lclbl.getPortOfDestination() != null) {
        boolean schnum = new LCLPortConfigurationDAO().getSchnumValue(lclbl.getPortOfDestination().getId());
        if (schnum) {
            BigDecimal printInvoice = lclbl.getInvoiceValue();
            Long fileId = lclbl.getFileNumberId();
            if (!CommonUtils.isEmpty(printInvoice) && !CommonUtils.isEmpty(fileId)) {
                PrintInvoiceValue = printInvoice;
            }
        }
    }

    chargeCell = new PdfPCell();
    chargeCell.setBorder(2);
    chargeCell.setColspan(6);
    chargeCell.setPadding(0f);
    PdfPTable agent_Contact_Table = new PdfPTable(3);
    agent_Contact_Table.setWidthPercentage(100f);
    agent_Contact_Table.setWidths(new float[] { 2.3f, 1.7f, 1.8f });
    PdfPCell agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setBorderWidthTop(1f);
    agent_Contact_cell.setBorderWidthLeft(1f);
    agent_Contact_cell.setBorderWidthBottom(0.06f);
    agent_Contact_cell.setBorderWidthRight(1f);
    p = new Paragraph(7f, "To Pick Up Freight Please Contact: ", blackContentNormalFont);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setColspan(2);
    agent_Contact_cell.setBorderWidthTop(1f);
    agent_Contact_cell.setPaddingBottom(2f);
    p = new Paragraph(7f, "Email: " + emailId.toLowerCase(), totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setColspan(2);
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setBorderWidthLeft(1f);
    p = new Paragraph(7f, "" + agentDetails.toString(), totalFontQuote);
    p.setAlignment(Element.ALIGN_LEFT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setPaddingTop(27f);
    p = new Paragraph(7f, "" + agentAcctNo, totalFontQuote);
    p.setAlignment(Element.ALIGN_RIGHT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);

    agent_Contact_cell = new PdfPCell();
    agent_Contact_cell.setBorder(0);
    agent_Contact_cell.setColspan(3);
    agent_Contact_cell.setBorderWidthLeft(1f);
    StringBuilder builder = new StringBuilder();
    builder.append(PrintInvoiceValue != null ? "Value of Goods:USD $" + PrintInvoiceValue : "");
    p = new Paragraph(3f, "" + builder.toString(), totalFontQuote);
    p.setAlignment(Element.ALIGN_RIGHT);
    agent_Contact_cell.addElement(p);
    agent_Contact_Table.addCell(agent_Contact_cell);
    chargeCell.addElement(agent_Contact_Table);
    chargeTable.addCell(chargeCell);

    return chargeTable;
}