Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:nzilbb.csv.CsvDeserializer.java

/**
 * Loads the serialized form of the graph, using the given set of named streams.
 * @param streams A list of named streams that contain all the
 *  transcription/annotation data required, and possibly (a) stream(s) for the media annotated.
 * @param schema The layer schema, definining layers and the way they interrelate.
 * @return A list of parameters that require setting before {@link IDeserializer#deserialize()}
 * can be invoked. This may be an empty list, and may include parameters with the value already
 * set to a workable default. If there are parameters, and user interaction is possible, then
 * the user may be presented with an interface for setting/confirming these parameters, before
 * they are then passed to {@link IDeserializer#setParameters(ParameterSet)}.
 * @throws SerializationException If the graph could not be loaded.
 * @throws IOException On IO error./*from  www .  j  av a  2 s .  c om*/
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public ParameterSet load(NamedStream[] streams, Schema schema) throws SerializationException, IOException {
    // take the first stream, ignore all others.
    NamedStream csv = Utility.FindSingleStream(streams, ".csv", "text/csv");
    if (csv == null)
        throw new SerializationException("No CSV stream found");
    setName(csv.getName());

    setSchema(schema);

    // create a list of layers we need and possible matching layer names
    LinkedHashMap<Parameter, List<String>> layerToPossibilities = new LinkedHashMap<Parameter, List<String>>();
    HashMap<String, LinkedHashMap<String, Layer>> layerToCandidates = new HashMap<String, LinkedHashMap<String, Layer>>();

    LinkedHashMap<String, Layer> metadataLayers = new LinkedHashMap<String, Layer>();
    for (Layer layer : schema.getRoot().getChildren().values()) {
        if (layer.getAlignment() == Constants.ALIGNMENT_NONE) {
            metadataLayers.put(layer.getId(), layer);
        }
    } // next turn child layer

    // look for person attributes
    for (Layer layer : schema.getParticipantLayer().getChildren().values()) {
        if (layer.getAlignment() == Constants.ALIGNMENT_NONE) {
            metadataLayers.put(layer.getId(), layer);
        }
    } // next turn child layer
    LinkedHashMap<String, Layer> utteranceAndMetadataLayers = new LinkedHashMap<String, Layer>(metadataLayers);
    utteranceAndMetadataLayers.put(getUtteranceLayer().getId(), getUtteranceLayer());
    LinkedHashMap<String, Layer> whoAndMetadataLayers = new LinkedHashMap<String, Layer>(metadataLayers);
    whoAndMetadataLayers.put(getParticipantLayer().getId(), getParticipantLayer());

    // read the header line

    setParser(CSVParser.parse(csv.getStream(), java.nio.charset.Charset.forName("UTF-8"),
            CSVFormat.EXCEL.withHeader()));
    setHeaderMap(parser.getHeaderMap());
    Vector<String> possibleIDHeaders = new Vector<String>();
    Vector<String> possibleUtteranceHeaders = new Vector<String>();
    Vector<String> possibleParticipantHeaders = new Vector<String>();
    for (String header : getHeaderMap().keySet()) {
        if (header.trim().length() == 0)
            continue;
        Vector<String> possibleMatches = new Vector<String>();
        possibleMatches.add("transcript" + header);
        possibleMatches.add("participant" + header);
        possibleMatches.add("speaker" + header);
        possibleMatches.add(header);

        // special cases
        if (header.equalsIgnoreCase("id") || header.equalsIgnoreCase("transcript")) {
            possibleIDHeaders.add(header);
        } else if (header.equalsIgnoreCase("text") || header.equalsIgnoreCase("document")) {
            possibleUtteranceHeaders.add(header);
        } else if (header.equalsIgnoreCase("name") || header.equalsIgnoreCase("participant")
                || header.equalsIgnoreCase("participantid")) {
            possibleParticipantHeaders.add(header);
        }

        layerToPossibilities.put(new Parameter("header_" + getHeaderMap().get(header), Layer.class, header),
                possibleMatches);
        layerToCandidates.put("header_" + getHeaderMap().get(header), metadataLayers);
    } // next header

    ParameterSet parameters = new ParameterSet();

    // add utterance/participant parameters
    int defaultUtterancePossibilityIndex = 0;

    // if there are no obvious participant column possibilities...      
    Parameter idColumn = new Parameter("id", String.class, "ID Column", "Column containing the ID of the text.",
            false);
    if (possibleIDHeaders.size() == 0) { // ...include all columns
        possibleIDHeaders.addAll(getHeaderMap().keySet());
    } else {
        idColumn.setValue(possibleIDHeaders.firstElement());
    }
    idColumn.setPossibleValues(possibleIDHeaders);
    parameters.addParameter(idColumn);

    // if there are no obvious participant column possibilities...      
    if (possibleParticipantHeaders.size() == 0) { // ...include all columns
        possibleParticipantHeaders.addAll(getHeaderMap().keySet());
        // default participant column will be the first column,
        // so default utterance should be the second (if we didn't find obvious possible text column)
        if (possibleParticipantHeaders.size() > 1) // but only if there's more than one column
        {
            defaultUtterancePossibilityIndex = 1;
        }
    }
    Parameter participantColumn = new Parameter("who", "Participant Column",
            "Column containing the ID of the author of the text.", true,
            possibleParticipantHeaders.firstElement());
    participantColumn.setPossibleValues(possibleParticipantHeaders);
    parameters.addParameter(participantColumn);

    // if there are no obvious text column possibilities...
    if (possibleUtteranceHeaders.size() == 0) { // ...include all columns
        possibleUtteranceHeaders.addAll(getHeaderMap().keySet());
    } else {
        // we found a possible text column, so run with it regardless of whether we also found
        // a possible participant column
        defaultUtterancePossibilityIndex = 0;
    }
    Parameter utteranceColumn = new Parameter("text", "Text Column", "Column containing the transcript text.",
            true, possibleUtteranceHeaders.elementAt(defaultUtterancePossibilityIndex));
    utteranceColumn.setPossibleValues(possibleUtteranceHeaders);
    parameters.addParameter(utteranceColumn);

    // add column-mapping parameters, and set possibile/default values
    for (Parameter p : layerToPossibilities.keySet()) {
        List<String> possibleNames = layerToPossibilities.get(p);
        LinkedHashMap<String, Layer> candidateLayers = layerToCandidates.get(p.getName());
        parameters.addParameter(p);
        if (p.getValue() == null && candidateLayers != null && possibleNames != null) {
            p.setValue(Utility.FindLayerById(candidateLayers, possibleNames));
        }
        if (p.getPossibleValues() == null && candidateLayers != null) {
            p.setPossibleValues(candidateLayers.values());
        }
    }
    return parameters;
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_3.java

protected void updateSysGui() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Updating sys_gui...");
    }/*from w ww.ja  va 2 s  .  c  o  m*/

    if (log.isInfoEnabled()) {
        log.info("Inserting initial sys_gui entries...");
    }

    // clean up, to guarantee no old values !
    sqlStr = "DELETE FROM sys_gui";
    jdbc.executeUpdate(sqlStr);

    LinkedHashMap<String, Integer> initialSysGuis = new LinkedHashMap<String, Integer>();
    Integer initialBehaviour = -1;
    initialSysGuis.put("1130", initialBehaviour);
    initialSysGuis.put("1140", initialBehaviour);
    initialSysGuis.put("1220", initialBehaviour);
    initialSysGuis.put("1230", initialBehaviour);
    initialSysGuis.put("1240", initialBehaviour);
    initialSysGuis.put("1250", initialBehaviour);
    initialSysGuis.put("1310", initialBehaviour);
    initialSysGuis.put("1320", initialBehaviour);
    initialSysGuis.put("1350", initialBehaviour);
    initialSysGuis.put("1410", initialBehaviour);
    initialSysGuis.put("3100", initialBehaviour);
    initialSysGuis.put("3110", initialBehaviour);
    initialSysGuis.put("3120", initialBehaviour);
    initialSysGuis.put("3200", initialBehaviour);
    initialSysGuis.put("3210", initialBehaviour);
    initialSysGuis.put("3230", initialBehaviour);
    initialSysGuis.put("3240", initialBehaviour);
    initialSysGuis.put("3250", initialBehaviour);
    initialSysGuis.put("3300", initialBehaviour);
    initialSysGuis.put("3310", initialBehaviour);
    initialSysGuis.put("3320", initialBehaviour);
    initialSysGuis.put("3330", initialBehaviour);
    initialSysGuis.put("3340", initialBehaviour);
    initialSysGuis.put("3345", initialBehaviour);
    initialSysGuis.put("3350", initialBehaviour);
    initialSysGuis.put("3355", initialBehaviour);
    initialSysGuis.put("3360", initialBehaviour);
    initialSysGuis.put("3365", initialBehaviour);
    initialSysGuis.put("3370", initialBehaviour);
    initialSysGuis.put("3375", initialBehaviour);
    initialSysGuis.put("3380", initialBehaviour);
    initialSysGuis.put("3385", initialBehaviour);
    initialSysGuis.put("3400", initialBehaviour);
    initialSysGuis.put("3410", initialBehaviour);
    initialSysGuis.put("3420", initialBehaviour);
    initialSysGuis.put("3500", initialBehaviour);
    initialSysGuis.put("3515", initialBehaviour);
    initialSysGuis.put("3520", initialBehaviour);
    initialSysGuis.put("3530", initialBehaviour);
    initialSysGuis.put("3535", initialBehaviour);
    initialSysGuis.put("3555", initialBehaviour);
    initialSysGuis.put("3565", initialBehaviour);
    initialSysGuis.put("3570", initialBehaviour);
    initialSysGuis.put("5000", initialBehaviour);
    initialSysGuis.put("5020", initialBehaviour);
    initialSysGuis.put("5021", initialBehaviour);
    initialSysGuis.put("5022", initialBehaviour);
    initialSysGuis.put("5040", initialBehaviour);
    initialSysGuis.put("5040", initialBehaviour);
    initialSysGuis.put("5052", initialBehaviour);
    initialSysGuis.put("5062", initialBehaviour);
    initialSysGuis.put("5063", initialBehaviour);
    initialSysGuis.put("5069", initialBehaviour);
    initialSysGuis.put("5070", initialBehaviour);
    initialSysGuis.put("N001", initialBehaviour);
    initialSysGuis.put("N002", initialBehaviour);
    initialSysGuis.put("N003", initialBehaviour);
    initialSysGuis.put("N004", initialBehaviour);
    initialSysGuis.put("N005", initialBehaviour);
    initialSysGuis.put("N007", initialBehaviour);
    initialSysGuis.put("N009", initialBehaviour);
    initialSysGuis.put("N010", initialBehaviour);
    initialSysGuis.put("N011", initialBehaviour);
    initialSysGuis.put("N012", initialBehaviour);
    initialSysGuis.put("N013", initialBehaviour);
    initialSysGuis.put("N014", initialBehaviour);
    initialSysGuis.put("N015", initialBehaviour);
    initialSysGuis.put("N016", initialBehaviour);
    initialSysGuis.put("N017", initialBehaviour);
    initialSysGuis.put("N018", initialBehaviour);
    initialSysGuis.put("4400", initialBehaviour);
    initialSysGuis.put("4405", initialBehaviour);
    initialSysGuis.put("4410", initialBehaviour);
    initialSysGuis.put("4415", initialBehaviour);
    initialSysGuis.put("4420", initialBehaviour);
    initialSysGuis.put("4425", initialBehaviour);
    initialSysGuis.put("4435", initialBehaviour);
    initialSysGuis.put("4440", initialBehaviour);
    initialSysGuis.put("4510", initialBehaviour);
    initialSysGuis.put("4500", initialBehaviour);
    initialSysGuis.put("N019", initialBehaviour);
    initialSysGuis.put("N020", initialBehaviour);
    initialSysGuis.put("N023", initialBehaviour);

    Iterator<String> itr = initialSysGuis.keySet().iterator();
    while (itr.hasNext()) {
        String key = itr.next();
        jdbc.executeUpdate("INSERT INTO sys_gui (id, gui_id, behaviour) VALUES (" + getNextId() + ", '" + key
                + "', " + initialSysGuis.get(key) + ")");
    }

    if (log.isInfoEnabled()) {
        log.info("Updating sys_gui... done");
    }
}

From source file:com.skysql.manager.api.SystemInfo.java

public SystemInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException, NullPointerException {
    SystemInfo systemInfo = new SystemInfo();

    JsonArray array = null;//  ww w.  j  av  a 2s.com

    int length = 0;
    if (json.getAsJsonObject().has("systems")) {
        array = json.getAsJsonObject().get("systems").getAsJsonArray();
        length = array.size();
    } else if (json.getAsJsonObject().has("system")) {
        length = 1;
    }

    LinkedHashMap<String, SystemRecord> systemsMap = new LinkedHashMap<String, SystemRecord>(length);
    systemInfo.setSystemsMap(systemsMap);
    if (length == 0) {
        return systemInfo;
    }

    for (int i = 0; i < length; i++) {

        SystemRecord systemRecord = new SystemRecord(SystemInfo.SYSTEM_ROOT);

        JsonObject systemObject = (array != null) ? array.get(i).getAsJsonObject()
                : json.getAsJsonObject().get("system").getAsJsonObject();
        JsonElement element;
        systemRecord
                .setID((element = systemObject.get("systemid")).isJsonNull() ? null : element.getAsString());
        systemRecord.setSystemType(
                (element = systemObject.get("systemtype")).isJsonNull() ? null : element.getAsString());
        systemRecord.setName((element = systemObject.get("name")).isJsonNull() ? null : element.getAsString());
        systemRecord
                .setState((element = systemObject.get("state")).isJsonNull() ? null : element.getAsString());
        systemRecord.setStartDate(
                (element = systemObject.get("started")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastAccess(
                (element = systemObject.get("lastaccess")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastBackup(
                (element = systemObject.get("lastbackup")).isJsonNull() ? null : element.getAsString());
        systemRecord.setDBUsername(
                (element = systemObject.get("dbusername")).isJsonNull() ? null : element.getAsString());
        systemRecord.setDBPassword(
                (element = systemObject.get("dbpassword")).isJsonNull() ? null : element.getAsString());
        systemRecord.setRepUsername(
                (element = systemObject.get("repusername")).isJsonNull() ? null : element.getAsString());
        systemRecord.setRepPassword(
                (element = systemObject.get("reppassword")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastMonitored(
                ((element = systemObject.get("lastmonitored")).isJsonNull()) ? null : element.getAsString());

        MonitorLatest monitorLatest = null;
        if ((element = systemObject.get("monitorlatest")) != null && !element.isJsonNull()) {
            monitorLatest = APIrestful.getGson().fromJson(element.toString(), MonitorLatest.class);
        }
        systemRecord.setMonitorLatest(monitorLatest);

        String[] nodes = null;
        if ((element = systemObject.get("nodes")) != null && !element.isJsonNull()) {
            JsonArray nodesJson = element.getAsJsonArray();
            int nodesCount = nodesJson.size();

            nodes = new String[nodesCount];
            for (int nodesIndex = 0; nodesIndex < nodesCount; nodesIndex++) {
                nodes[nodesIndex] = nodesJson.get(nodesIndex).getAsString();
            }
        }
        systemRecord.setNodes(nodes);

        LinkedHashMap<String, String> properties = new LinkedHashMap<String, String>();
        if ((element = systemObject.get("properties")) != null && !element.isJsonNull()) {

            JsonObject propertiesJson = element.getAsJsonObject();

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_EIP)) != null) {
                properties.put(SystemInfo.PROPERTY_EIP, element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_MONYOG)) != null) {
                properties.put(SystemInfo.PROPERTY_MONYOG, element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_PHPMYADMIN)) != null) {
                properties.put(SystemInfo.PROPERTY_PHPMYADMIN,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMONITORINTERVAL)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMONITORINTERVAL,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMAXBACKUPCOUNT)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMAXBACKUPCOUNT,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMAXBACKUPSIZE)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMAXBACKUPSIZE,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_VERSION)) != null) {
                properties.put(SystemInfo.PROPERTY_VERSION,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_SKIPLOGIN)) != null) {
                properties.put(SystemInfo.PROPERTY_SKIPLOGIN,
                        element.isJsonNull() ? null : element.getAsString());
            }

        }
        systemRecord.setProperties(properties);

        systemsMap.put(systemRecord.getID(), systemRecord);
    }

    if (array != null) {
        // create a "ROOT" system record to contain the series of flat systems; in a hierarchical organization of systems, this might be provided by the API
        SystemRecord rootRecord = new SystemRecord(null);
        rootRecord.setID(SystemInfo.SYSTEM_ROOT);
        rootRecord.setName("Root");
        String[] systems = new String[systemsMap.keySet().size()];
        int i = 0;
        for (String systemID : systemsMap.keySet()) {
            systems[i++] = systemID;
        }
        rootRecord.setNodes(systems);
        systemsMap.put(SystemInfo.SYSTEM_ROOT, rootRecord);
    }

    return systemInfo;
}

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 .jav a2 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;
}

From source file:nzilbb.csv.CsvDeserializer.java

/**
 * Sets parameters for deserializer as a whole.  This might include database connection parameters, locations of supporting files, etc.
 * <p>When the deserializer is installed, this method should be invoked with an empty parameter
 *  set, to discover what (if any) general configuration is required. If parameters are
 *  returned, and user interaction is possible, then the user may be presented with an
 *  interface for setting/confirming these parameters.  
 * @param configuration The configuration for the deserializer. 
 * @param schema The layer schema, definining layers and the way they interrelate.
 * @return A list of configuration parameters (still) must be set before {@link IDeserializer#setParameters(ParameterSet)} can be invoked. If this is an empty list, {@link IDeserializer#setParameters(ParameterSet)} can be invoked. If it's not an empty list, this method must be invoked again with the returned parameters' values set.
 *///from w w w .jav  a 2  s  .co m
public ParameterSet configure(ParameterSet configuration, Schema schema) {
    setSchema(schema);
    setParticipantLayer(schema.getParticipantLayer());
    setTurnLayer(schema.getTurnLayer());
    setUtteranceLayer(schema.getUtteranceLayer());
    setWordLayer(schema.getWordLayer());

    // set any values that have been passed in
    for (Parameter p : configuration.values())
        try {
            p.apply(this);
        } catch (Exception x) {
        }

    // create a list of layers we need and possible matching layer names
    LinkedHashMap<Parameter, List<String>> layerToPossibilities = new LinkedHashMap<Parameter, List<String>>();
    HashMap<String, LinkedHashMap<String, Layer>> layerToCandidates = new HashMap<String, LinkedHashMap<String, Layer>>();

    // do we need to ask for participant/turn/utterance/word layers?
    LinkedHashMap<String, Layer> possibleParticipantLayers = new LinkedHashMap<String, Layer>();
    LinkedHashMap<String, Layer> possibleTurnLayers = new LinkedHashMap<String, Layer>();
    LinkedHashMap<String, Layer> possibleTurnChildLayers = new LinkedHashMap<String, Layer>();
    LinkedHashMap<String, Layer> wordTagLayers = new LinkedHashMap<String, Layer>();
    LinkedHashMap<String, Layer> participantTagLayers = new LinkedHashMap<String, Layer>();
    if (getParticipantLayer() == null || getTurnLayer() == null || getUtteranceLayer() == null
            || getWordLayer() == null) {
        for (Layer top : schema.getRoot().getChildren().values()) {
            if (top.getAlignment() == Constants.ALIGNMENT_NONE) {
                if (top.getChildren().size() == 0) { // unaligned childless children of graph
                    participantTagLayers.put(top.getId(), top);
                } else { // unaligned children of graph, with children of their own
                    possibleParticipantLayers.put(top.getId(), top);
                    for (Layer turn : top.getChildren().values()) {
                        if (turn.getAlignment() == Constants.ALIGNMENT_INTERVAL
                                && turn.getChildren().size() > 0) { // aligned children of who with their own children
                            possibleTurnLayers.put(turn.getId(), turn);
                            for (Layer turnChild : turn.getChildren().values()) {
                                if (turnChild.getAlignment() == Constants.ALIGNMENT_INTERVAL) { // aligned children of turn
                                    possibleTurnChildLayers.put(turnChild.getId(), turnChild);
                                    for (Layer tag : turnChild.getChildren().values()) {
                                        if (tag.getAlignment() == Constants.ALIGNMENT_NONE) { // unaligned children of word
                                            wordTagLayers.put(tag.getId(), tag);
                                        }
                                    } // next possible word tag layer
                                }
                            } // next possible turn child layer
                        }
                    } // next possible turn layer
                } // with children
            } // unaligned
        } // next possible participant layer
    } // missing special layers
    else {
        for (Layer turnChild : getTurnLayer().getChildren().values()) {
            if (turnChild.getAlignment() == Constants.ALIGNMENT_INTERVAL) {
                possibleTurnChildLayers.put(turnChild.getId(), turnChild);
            }
        } // next possible word tag layer
        for (Layer tag : getWordLayer().getChildren().values()) {
            if (tag.getAlignment() == Constants.ALIGNMENT_NONE && tag.getChildren().size() == 0) {
                wordTagLayers.put(tag.getId(), tag);
            }
        } // next possible word tag layer
        for (Layer tag : getParticipantLayer().getChildren().values()) {
            if (tag.getAlignment() == Constants.ALIGNMENT_NONE && tag.getChildren().size() == 0) {
                participantTagLayers.put(tag.getId(), tag);
            }
        } // next possible word tag layer
    }
    participantTagLayers.remove("main_participant");
    if (getParticipantLayer() == null) {
        layerToPossibilities.put(
                new Parameter("participantLayer", Layer.class, "Participant layer",
                        "Layer for speaker/participant identification", true),
                Arrays.asList("participant", "participants", "who", "speaker", "speakers"));
        layerToCandidates.put("participantLayer", possibleParticipantLayers);
    }
    if (getTurnLayer() == null) {
        layerToPossibilities.put(
                new Parameter("turnLayer", Layer.class, "Turn layer", "Layer for speaker turns", true),
                Arrays.asList("turn", "turns"));
        layerToCandidates.put("turnLayer", possibleTurnLayers);
    }
    if (getUtteranceLayer() == null) {
        layerToPossibilities.put(new Parameter("utteranceLayer", Layer.class, "Utterance layer",
                "Layer for speaker utterances", true),
                Arrays.asList("utterance", "utterances", "line", "lines"));
        layerToCandidates.put("utteranceLayer", possibleTurnChildLayers);
    }
    if (getWordLayer() == null) {
        layerToPossibilities.put(
                new Parameter("wordLayer", Layer.class, "Word layer", "Layer for individual word tokens", true),
                Arrays.asList("transcript", "word", "words", "w"));
        layerToCandidates.put("wordLayer", possibleTurnChildLayers);
    }

    LinkedHashMap<String, Layer> graphTagLayers = new LinkedHashMap<String, Layer>();
    for (Layer top : schema.getRoot().getChildren().values()) {
        if (top.getAlignment() == Constants.ALIGNMENT_NONE && top.getChildren().size() == 0) { // unaligned childless children of graph
            graphTagLayers.put(top.getId(), top);
        }
    } // next top level layer
    graphTagLayers.remove("corpus");
    graphTagLayers.remove("transcript_type");

    // other layers...

    // add parameters that aren't in the configuration yet, and set possibile/default values
    for (Parameter p : layerToPossibilities.keySet()) {
        List<String> possibleNames = layerToPossibilities.get(p);
        LinkedHashMap<String, Layer> candidateLayers = layerToCandidates.get(p.getName());
        if (configuration.containsKey(p.getName())) {
            p = configuration.get(p.getName());
        } else {
            configuration.addParameter(p);
        }
        if (p.getValue() == null) {
            p.setValue(Utility.FindLayerById(candidateLayers, possibleNames));
        }
        p.setPossibleValues(candidateLayers.values());
    }

    return configuration;
}

From source file:org.openmrs.module.chica.DynamicFormAccess.java

/**
 * Returns the results of running rules for the form fields marked as "Prioritized Merge Field". 
 * //from   www.  ja  v  a  2 s.  com
 * @param formId The identifier of the form.
 * @param formInstanceId The form instance Identifier of the form.
 * @param encounterId The encounter identifier associated with the form.
 * @param maxElements The maximum number of elements to populate.
 * @return List of Field objects containing the field information as well as the result information from the rules.
 */
public List<Field> getPrioritizedElements(Integer formId, Integer formInstanceId, Integer encounterId,
        Integer maxElements) {
    List<Field> fields = new ArrayList<Field>(maxElements);
    EncounterService encounterService = Context.getEncounterService();
    Encounter encounter = encounterService.getEncounter(encounterId);
    Integer locationId = encounter.getLocation().getLocationId();

    LocationService locationService = Context.getLocationService();
    Location location = locationService.getLocation(locationId);

    FormService formService = Context.getFormService();
    Form form = formService.getForm(formId);
    String formName = form.getName();

    FormInstance formInstance = new FormInstance(locationId, formId, formInstanceId);
    PatientState patientState = org.openmrs.module.atd.util.Util
            .getProducePatientStateByFormInstanceAction(formInstance);
    Integer locationTagId = patientState.getLocationTagId();

    HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("sessionId", patientState.getSessionId());
    parameters.put("formInstance", new FormInstance(locationId, formId, formInstanceId));
    parameters.put("locationTagId", locationTagId);
    parameters.put("locationId", locationId);
    parameters.put("location", location.getName());
    parameters.put("encounterId", encounterId);
    parameters.put("mode", "PRODUCE");

    Patient patient = patientState.getPatient();
    DssManager dssManager = new DssManager(patient);

    FieldType mergeType = getFieldType("Merge Field");
    FieldType priorMergeType = getFieldType("Prioritized Merge Field");
    LinkedHashMap<FormField, Object> fieldToResult = new LinkedHashMap<FormField, Object>();
    Map<String, Integer> dssMergeCounters = new HashMap<String, Integer>();
    List<FieldType> fieldTypes = new ArrayList<FieldType>();
    fieldTypes.add(mergeType);
    fieldTypes.add(priorMergeType);
    List<FormField> formFields = Context.getService(ChirdlUtilBackportsService.class).getFormFields(form,
            fieldTypes, true);
    List<Integer> fieldIds = new ArrayList<Integer>();
    for (FormField formField : formFields) {
        fieldIds.add(formField.getField().getFieldId());
    }

    Map<Integer, PatientATD> fieldIdToPatientATDMap = org.openmrs.module.atd.util.Util
            .getPatientATDs(formInstance, fieldIds);
    List<DssElement> elementList = new ArrayList<DssElement>();
    ATDService atdService = Context.getService(ATDService.class);
    Integer startPriority = getStartPriority(atdService, formInstanceId, locationId, formName);
    Map<Integer, PatientATD> waitForScanFieldIdToAtdMap = new HashMap<Integer, PatientATD>();

    String numPrompts = org.openmrs.module.chirdlutilbackports.util.Util.getFormAttributeValue(formId,
            "numPrompts", locationTagId, locationId);
    if (numPrompts == null) {
        log.error("Missing form attribute 'numPrompts' for form: " + formId);
        return fields;
    }

    int populatedElements = 0;
    int maxDssElements = 0;
    try {
        maxDssElements = Integer.parseInt(numPrompts);
    } catch (NumberFormatException e) {
    }

    for (FormField currFormField : formFields) {
        org.openmrs.Field currField = currFormField.getField();
        String defaultValue = currField.getDefaultValue();
        if (defaultValue == null) {
            continue;
        }

        FieldType currFieldType = currField.getFieldType();
        HashMap<String, Object> ruleParameters = new HashMap<String, Object>(parameters);

        //fix lazy initialization error
        //currField = formService.getField(currField.getFieldId());

        if (currFieldType.equals(priorMergeType)) {
            // check to see if the current field has already been populated
            PatientATD patientATD = fieldIdToPatientATDMap.get(currField.getFieldId());
            if (patientATD != null) {
                if (++populatedElements == maxDssElements) {
                    break;
                }

                // check to see if it's been answered yet
                List<Statistics> stats = atdService.getStatByIdAndRule(formInstanceId,
                        patientATD.getRule().getRuleId(), formName, locationId);
                if (stats != null && stats.size() > 0) {
                    Statistics stat = stats.get(0);
                    if (stat.getScannedTimestamp() != null) {
                        // add null as a place keeper so we can keep the position for the atd statistics.
                        elementList.add(null);
                        continue;
                    }

                    waitForScanFieldIdToAtdMap.put(currField.getFieldId(), patientATD);
                }
            }

            //---------start set concept rule parameter
            Concept concept = currField.getConcept();
            if (concept != null) {
                try {
                    String elementString = ((ConceptName) concept.getNames().toArray()[0]).getName();
                    ruleParameters.put("concept", elementString);
                } catch (Exception e) {
                    ruleParameters.put("concept", null);
                }
            } else {
                ruleParameters.put("concept", null);
            }
            //---------end set concept rule parameter

            //process prioritized merge type fields
            String ruleType = defaultValue;
            Integer dssMergeCounter = dssMergeCounters.get(ruleType);
            if (dssMergeCounter == null) {
                dssMergeCounter = 0;
            }

            //fill in the dss elements for this type
            //(this will only get executed once even though it is called for each field)
            //We need to set the max number of prioritized elements to generate
            if (dssManager.getMaxDssElementsByType(ruleType) == 0) {
                dssManager.setMaxDssElementsByType(ruleType, maxDssElements);
            }

            dssManager.getPrioritizedDssElements(ruleType, startPriority, maxElements, ruleParameters);
            //get the result for this field
            Result result = processDssElements(dssManager, dssMergeCounter, currField.getFieldId(), ruleType);
            //            if (result != null) {

            elementList.add(dssManager.getDssElement(dssMergeCounter, ruleType));
            //            }

            dssMergeCounter++;
            dssMergeCounters.put(ruleType, dssMergeCounter);

            fieldToResult.put(currFormField, result);
        } else if (currFieldType.equals(mergeType)) {
            //store the leaf index as the result if the
            //current field has a parent
            if (currFormField.getParent() != null) {
                fieldToResult.put(currFormField, defaultValue);
            }
        }
    }

    //process Results
    LinkedHashMap<String, String> fieldNameResult = new LinkedHashMap<String, String>();
    for (FormField currFormField : fieldToResult.keySet()) {
        String resultString = null;

        //fix lazy initialization error
        //org.openmrs.Field currField = formService.getField(currFormField.getField().getFieldId());
        org.openmrs.Field currField = currFormField.getField();
        String fieldName = currField.getName();
        Object fieldResult = fieldToResult.get(currFormField);

        if (fieldResult == null) {
            continue;
        }

        if (fieldResult instanceof Result) {
            resultString = ((Result) fieldResult).get(0).toString();
        } else {
            //if the field has a parent, process the result as a leaf index
            //of the parent results
            if (currFormField.getParent() == null) {
                resultString = (String) fieldResult;
            } else {
                try {
                    int leafPos = Integer.parseInt((String) fieldResult);
                    FormField parentField = currFormField.getParent();
                    Result parentResult = (Result) fieldToResult.get(parentField);

                    if (parentResult != null) {
                        resultString = parentResult.get(leafPos).toString();
                    } else {
                        resultString = null;
                    }
                } catch (NumberFormatException e) {
                }
            }
        }

        if (resultString != null) {
            //remove everything at or after the @ symbol (i.e. @Spanish)
            int atIndex = resultString.indexOf("@");
            if (atIndex >= 0) {
                resultString = resultString.substring(0, atIndex);
            }
        }

        fieldNameResult.put(fieldName, resultString);
    }

    for (String fieldName : fieldNameResult.keySet()) {
        String resultString = fieldNameResult.get(fieldName);
        if (resultString == null) {
            continue;
        }

        Field field = new Field();
        field.setId(fieldName);
        field.setValue(resultString);
        fields.add(field);
    }

    saveDssElementsToDatabase(patient, formInstance, elementList, encounter, locationTagId, formName,
            waitForScanFieldIdToAtdMap);
    serializeFields(formInstance, locationTagId, fields, new ArrayList<String>()); // DWE CHICA-430 Add new ArrayList<String>()

    return fields;
}

From source file:jmri.enginedriver.throttle.java

void set_function_labels_and_listeners_for_view(int whichThrottle) {
    // Log.d("Engine_Driver","starting set_function_labels_and_listeners_for_view");

    //        // implemented in derived class, but called from this class

    if (fbs != null) { // if it is null it probably because the Throttle Screen Type does not have Functions Buttons
        if (fbs[0] != null) {
            ViewGroup tv; // group
            ViewGroup r; // row
            function_button_touch_listener fbtl;
            Button b; // button
            int k = 0; // button count
            LinkedHashMap<Integer, String> function_labels_temp;
            LinkedHashMap<Integer, Button> functionButtonMap = new LinkedHashMap<>();

            tv = fbs[whichThrottle];//from www.  j  av  a2  s  .c o  m

            // note: we make a copy of function_labels_x because TA might change it
            // while we are using it (causing issues during button update below)
            function_labels_temp = mainapp.function_labels_default;
            if (!prefAlwaysUseDefaultFunctionLabels) { //avoid npe
                if (mainapp.function_labels != null && mainapp.function_labels[whichThrottle] != null
                        && mainapp.function_labels[whichThrottle].size() > 0) {
                    function_labels_temp = new LinkedHashMap<>(mainapp.function_labels[whichThrottle]);
                } else {
                    if (mainapp.consists != null) { //avoid npe maybe
                        if (mainapp.consists[whichThrottle] != null
                                && !mainapp.consists[whichThrottle].isLeadFromRoster()) {
                            function_labels_temp = mainapp.function_labels_default;
                        } else {
                            function_labels_temp = mainapp.function_labels_default_for_roster;
                        }
                    }
                }
            }

            // put values in array for indexing in next step
            // to do this
            ArrayList<Integer> aList = new ArrayList<>(function_labels_temp.keySet());

            if (tv != null) {
                for (int i = 0; i < tv.getChildCount(); i++) {
                    r = (ViewGroup) tv.getChildAt(i);
                    for (int j = 0; j < r.getChildCount(); j++) {
                        b = (Button) r.getChildAt(j);
                        if (k < function_labels_temp.size()) {
                            Integer func = aList.get(k);
                            functionButtonMap.put(func, b); // save function to button
                            // mapping
                            String bt = function_labels_temp.get(func);
                            fbtl = new function_button_touch_listener(func, whichThrottle, bt);
                            b.setOnTouchListener(fbtl);
                            //                                if ((mainapp.getCurrentTheme().equals(THEME_DEFAULT))) {
                            //                                    bt = bt + "        ";  // pad with spaces, and limit to 7 characters
                            //                                    b.setText(bt.substring(0, 7));
                            //                                } else {
                            bt = bt + "                      "; // pad with spaces, and limit to 20 characters
                            b.setText(bt.trim());
                            //                                }
                            b.setVisibility(View.VISIBLE);
                            b.setEnabled(false); // start out with everything disabled
                        } else {
                            b.setVisibility(View.GONE);
                        }
                        k++;
                    }
                }
            }

            // update the function-to-button map for the current throttle
            functionMaps[whichThrottle] = functionButtonMap;
        }
    }
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static NetworkNode readDevice(NetworkNode node) {
    try {/*from ww w.j  a v a2 s  . c  om*/
        LinkedHashMap<String, String> queryTypes = node.getQueryTypes();
        if (queryTypes != null) {
            for (String qtype : queryTypes.keySet()) {
                InventoryDBHelper.loadQuery(node, queryTypes.get(qtype), qtype);
            }
        }
    } catch (Exception ee) {
        logger.warn("Error in readDevice for the deviceId=" + node.getNodeId(), ee);
    }

    return node;
}

From source file:lu.fisch.unimozer.Diagram.java

@Override
public void actionPerformed(ActionEvent e) {

    if (isEnabled()) {
        if (e.getSource() instanceof JMenuItem) {
            JMenuItem item = (JMenuItem) e.getSource();
            if (item.getText().equals("Compile")) {
                compile();//  w  ww .  ja  v a2  s  .  c o  m
            } else if (item.getText().equals("Remove class") && mouseClass != null) {
                int answ = JOptionPane.showConfirmDialog(frame,
                        "Are you sure to remove the class " + mouseClass.getFullName() + "",
                        "Remove a class", JOptionPane.YES_NO_OPTION);
                if (answ == JOptionPane.YES_OPTION) {
                    cleanAll();// clean(mouseClass);
                    removedClasses.add(mouseClass.getFullName());
                    classes.remove(mouseClass.getFullName());
                    mouseClass = null;
                    updateEditor();
                    repaint();
                    objectizer.repaint();
                }
            } else if (mouseClass.getName().contains("abstract")) {
                JOptionPane.showMessageDialog(frame, "Can't create an object of an abstract class ...",
                        "Instatiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
            } else if (item.getText().startsWith("new")) // we have constructor
            {
                Logger.getInstance().log("Click on <new> registered");
                // get full signature
                String fSign = item.getText();
                if (fSign.startsWith("new"))
                    fSign = fSign.substring(3).trim();
                // get signature
                final String fullSign = fSign;
                Logger.getInstance().log("fullSign = " + fSign);
                final String sign = mouseClass.getSignatureByFullSignature(fullSign);
                Logger.getInstance().log("sign = " + sign);

                Logger.getInstance().log("Creating runnable ...");
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        //System.out.println("Calling method (full): "+fullSign);
                        //System.out.println("Calling method       : "+sign);
                        try {
                            Logger.getInstance().log("Loading the class <" + mouseClass.getName() + ">");
                            Class<?> cla = Runtime5.getInstance().load(mouseClass.getFullName()); //mouseClass.load();
                            Logger.getInstance().log("Loaded!");

                            // check if we need to specify a generic class
                            boolean cont = true;
                            String generics = "";
                            TypeVariable[] tv = cla.getTypeParameters();
                            Logger.getInstance().log("Got TypeVariables with length = " + tv.length);
                            if (tv.length > 0) {
                                LinkedHashMap<String, String> gms = new LinkedHashMap<String, String>();
                                for (int i = 0; i < tv.length; i++) {
                                    gms.put(tv[i].getName(), "");
                                }
                                MethodInputs gi = new MethodInputs(frame, gms, "Generic type declaration",
                                        "Please specify the generic types");
                                cont = gi.OK;

                                // build the string
                                generics = "<";
                                Object[] keys = gms.keySet().toArray();
                                mouseClass.generics.clear();
                                for (int in = 0; in < keys.length; in++) {
                                    String kname = (String) keys[in];
                                    // save generic type to myClass
                                    mouseClass.generics.put(kname, gi.getValueFor(kname));
                                    generics += gi.getValueFor(kname) + ",";
                                }
                                generics = generics.substring(0, generics.length() - 1);
                                generics += ">";
                            }

                            if (cont == true) {
                                Logger.getInstance().log("Getting the constructors.");

                                Constructor[] constr = cla.getConstructors();
                                for (int c = 0; c < constr.length; c++) {
                                    // get signature
                                    String full = objectizer.constToFullString(constr[c]);
                                    Logger.getInstance().log("full = " + full);
                                    /*
                                    String full = constr[c].getName();
                                    full+="(";
                                    Class<?>[] tvm = constr[c].getParameterTypes();
                                    for(int t=0;t<tvm.length;t++)
                                    {
                                        String sn = tvm[t].toString();
                                        sn=sn.substring(sn.lastIndexOf('.')+1,sn.length());
                                        if(sn.startsWith("class")) sn=sn.substring(5).trim();
                                        // array is shown as ";"  ???
                                        if(sn.endsWith(";"))
                                        {
                                            sn=sn.substring(0,sn.length()-1)+"[]";
                                        }
                                        full+= sn+", ";
                                    }
                                    if(tvm.length>0) full=full.substring(0,full.length()-2);
                                    full+= ")";
                                    */
                                    /*System.out.println("Loking for S : "+sign);
                                    System.out.println("Loking for FS: "+fullSign);
                                    System.out.println("Found: "+full);*/

                                    if (full.equals(sign) || full.equals(fullSign)) {
                                        Logger.getInstance().log("We are in!");
                                        //editor.setEnabled(false);
                                        //Logger.getInstance().log("Editor disabled");
                                        String name;
                                        Logger.getInstance().log("Ask user for a name.");
                                        do {
                                            String propose = mouseClass.getShortName().substring(0, 1)
                                                    .toLowerCase() + mouseClass.getShortName().substring(1);
                                            int count = 0;
                                            String prop = propose + count;
                                            while (objectizer.hasObject(prop) == true) {
                                                count++;
                                                prop = propose + count;
                                            }

                                            name = (String) JOptionPane.showInputDialog(frame,
                                                    "Please enter the name for you new instance of "
                                                            + mouseClass.getShortName() + "",
                                                    "Create object", JOptionPane.QUESTION_MESSAGE, null, null,
                                                    prop);
                                            if (Java.isIdentifierOrNull(name) == false) {
                                                JOptionPane.showMessageDialog(frame,
                                                        "" + name + " is not a correct identifier.",
                                                        "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                            } else if (objectizer.hasObject(name) == true) {
                                                JOptionPane.showMessageDialog(frame,
                                                        "An object with the name " + name
                                                                + " already exists.\nPlease choose another name ...",
                                                        "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                            }
                                        } while (Java.isIdentifierOrNull(name) == false
                                                || objectizer.hasObject(name) == true);
                                        Logger.getInstance().log("name = " + name);

                                        if (name != null) {
                                            Logger.getInstance().log("Need to get inputs ...");
                                            LinkedHashMap<String, String> inputs = mouseClass
                                                    .getInputsBySignature(sign);
                                            if (inputs.size() == 0)
                                                inputs = mouseClass.getInputsBySignature(fullSign);

                                            //System.out.println("1) "+sign);
                                            //System.out.println("2) "+fullSign);

                                            MethodInputs mi = null;
                                            boolean go = true;
                                            if (inputs.size() > 0) {
                                                mi = new MethodInputs(frame, inputs, full,
                                                        mouseClass.getJavaDocBySignature(sign));
                                                go = mi.OK;
                                            }
                                            Logger.getInstance().log("go = " + go);
                                            if (go == true) {
                                                Logger.getInstance().log("Building string ...");
                                                //Object arglist[] = new Object[inputs.size()];
                                                String constructor = "new " + mouseClass.getFullName()
                                                        + generics + "(";
                                                if (inputs.size() > 0) {
                                                    Object[] keys = inputs.keySet().toArray();
                                                    for (int in = 0; in < keys.length; in++) {
                                                        String kname = (String) keys[in];
                                                        //String type = inputs.get(kname);

                                                        //if(type.equals("int"))  { arglist[in] = Integer.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("short"))  { arglist[in] = Short.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("byte"))  { arglist[in] = Byte.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("long"))  { arglist[in] = Long.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("float"))  { arglist[in] = Float.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("double"))  { arglist[in] = Double.valueOf(mi.getValueFor(kname)); }
                                                        //else if(type.equals("boolean"))  { arglist[in] = Boolean.valueOf(mi.getValueFor(kname)); }
                                                        //else arglist[in] = mi.getValueFor(kname);

                                                        String val = mi.getValueFor(kname);
                                                        if (val.equals(""))
                                                            val = "null";
                                                        else {
                                                            String type = mi.getTypeFor(kname);
                                                            if (type.toLowerCase().equals("byte"))
                                                                constructor += "Byte.valueOf(\"" + val + "\"),";
                                                            else if (type.toLowerCase().equals("short"))
                                                                constructor += "Short.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("float"))
                                                                constructor += "Float.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("long"))
                                                                constructor += "Long.valueOf(\"" + val + "\"),";
                                                            else if (type.toLowerCase().equals("double"))
                                                                constructor += "Double.valueOf(\"" + val
                                                                        + "\"),";
                                                            else if (type.toLowerCase().equals("char"))
                                                                constructor += "'" + val + "',";
                                                            else
                                                                constructor += val + ",";
                                                        }

                                                        //constructor+=mi.getValueFor(kname)+",";
                                                    }
                                                    constructor = constructor.substring(0,
                                                            constructor.length() - 1);
                                                }
                                                //System.out.println(arglist);
                                                constructor += ")";
                                                //System.out.println(constructor);
                                                Logger.getInstance().log("constructor = " + constructor);

                                                //LOAD: 
                                                //addLibs();
                                                Object obj = Runtime5.getInstance().getInstance(name,
                                                        constructor); //mouseClass.getInstance(name, constructor);
                                                Logger.getInstance().log("Objet is now instantiated!");
                                                //Runtime.getInstance().interpreter.getNameSpace().i
                                                //System.out.println(obj.getClass().getSimpleName());
                                                //Object obj = constr[c].newInstance(arglist);
                                                MyObject myo = objectizer.addObject(name, obj);
                                                myo.setMyClass(mouseClass);
                                                obj = null;
                                                cla = null;
                                            }

                                            objectizer.repaint();
                                            Logger.getInstance().log("Objectizer repainted ...");
                                            repaint();
                                            Logger.getInstance().log("Diagram repainted ...");
                                        }
                                        //editor.setEnabled(true);
                                        //Logger.getInstance().log("Editor enabled again ...");

                                    }
                                }
                            }
                        } catch (Exception ex) {
                            //ex.printStackTrace();
                            MyError.display(ex);
                            JOptionPane.showMessageDialog(frame, ex.toString(), "Instantiation error",
                                    JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                        }
                    }
                };
                Thread t = new Thread(r);
                t.start();
            } else // we have a static method
            {
                try {
                    // get full signature
                    String fullSign = ((JMenuItem) e.getSource()).getText();
                    // get signature
                    String sign = mouseClass.getSignatureByFullSignature(fullSign).replace(", ", ",");
                    String complete = mouseClass.getCompleteSignatureBySignature(sign).replace(", ", ",");

                    /*System.out.println("Calling method (full): "+fullSign);
                    System.out.println("Calling method       : "+sign);
                    System.out.println("Calling method (comp): "+complete);/**/

                    // find method
                    Class c = Runtime5.getInstance().load(mouseClass.getFullName());
                    Method m[] = c.getMethods();
                    for (int i = 0; i < m.length; i++) {
                        /*String full = "";
                        full+= m[i].getReturnType().getSimpleName();
                        full+=" ";
                        full+= m[i].getName();
                        full+= "(";
                        Class<?>[] tvm = m[i].getParameterTypes();
                        LinkedHashMap<String,String> genericInputs = new LinkedHashMap<String,String>();
                        for(int t=0;t<tvm.length;t++)
                        {
                        String sn = tvm[t].toString();
                        //System.out.println(sn);
                        if(sn.startsWith("class")) sn=sn.substring(5).trim();
                        sn=sn.substring(sn.lastIndexOf('.')+1,sn.length());
                        // array is shown as ";"  ???
                        if(sn.endsWith(";"))
                        {
                            sn=sn.substring(0,sn.length()-1)+"[]";
                        }
                        full+= sn+", ";
                        genericInputs.put("param"+t,sn);
                        }
                        if(tvm.length>0) full=full.substring(0,full.length()-2);
                        full+= ")";*/
                        String full = objectizer.toFullString(m[i]);
                        LinkedHashMap<String, String> genericInputs = objectizer.getInputsReplaced(m[i], null);

                        /*System.out.println("Looking for S : "+sign);
                        System.out.println("Looking for FS: "+fullSign);
                        System.out.println("Found         : "+full);*/

                        if (full.equals(sign) || full.equals(fullSign)) {
                            LinkedHashMap<String, String> inputs = mouseClass.getInputsBySignature(sign);
                            //Objectizer.printLinkedHashMap("inputs", inputs);
                            if (inputs.size() != genericInputs.size()) {
                                inputs = genericInputs;
                            }
                            //Objectizer.printLinkedHashMap("inputs", inputs);
                            MethodInputs mi = null;
                            boolean go = true;
                            if (inputs.size() > 0) {
                                mi = new MethodInputs(frame, inputs, full,
                                        mouseClass.getJavaDocBySignature(sign));
                                go = mi.OK;
                            }
                            if (go == true) {
                                try {
                                    String method = mouseClass.getFullName() + "." + m[i].getName() + "(";
                                    if (inputs.size() > 0) {
                                        Object[] keys = inputs.keySet().toArray();
                                        //int cc = 0;
                                        for (int in = 0; in < keys.length; in++) {
                                            String name = (String) keys[in];
                                            String val = mi.getValueFor(name);

                                            if (val.equals(""))
                                                method += val + "null,";
                                            else {
                                                String type = mi.getTypeFor(name);
                                                if (type.toLowerCase().equals("byte"))
                                                    method += "Byte.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("short"))
                                                    method += "Short.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("float"))
                                                    method += "Float.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("long"))
                                                    method += "Long.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("double"))
                                                    method += "Double.valueOf(\"" + val + "\"),";
                                                else if (type.toLowerCase().equals("char"))
                                                    method += "'" + val + "',";
                                                else
                                                    method += val + ",";
                                            }

                                            //if (val.equals("")) val="null";
                                            //method+=val+",";
                                        }
                                        if (!method.endsWith("("))
                                            method = method.substring(0, method.length() - 1);
                                    }
                                    method += ")";

                                    //System.out.println(method);

                                    // Invoke method in a new thread
                                    final String myMeth = method;
                                    Runnable r = new Runnable() {
                                        public void run() {
                                            try {
                                                Object retobj = Runtime5.getInstance().executeMethod(myMeth);
                                                if (retobj != null)
                                                    JOptionPane.showMessageDialog(frame, retobj.toString(),
                                                            "Result", JOptionPane.INFORMATION_MESSAGE,
                                                            Unimozer.IMG_INFO);
                                            } catch (EvalError ex) {
                                                JOptionPane.showMessageDialog(frame, ex.toString(),
                                                        "Invokation error", JOptionPane.ERROR_MESSAGE,
                                                        Unimozer.IMG_ERROR);
                                                MyError.display(ex);
                                            }
                                        }
                                    };
                                    Thread t = new Thread(r);
                                    t.start();

                                    //System.out.println(method);
                                    //Object retobj = Runtime5.getInstance().executeMethod(method);
                                    //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO);
                                } catch (Throwable ex) {
                                    JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error",
                                            JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                    MyError.display(ex);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error",
                            JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                    MyError.display(ex);
                }
            }
        }
    }
}

From source file:lu.fisch.unimozer.Diagram.java

public void run() {
    try {//from w w w  . j  av a 2 s .  c  o  m
        // compile all
        //doCompilationOnly(null);
        //frame.setCompilationErrors(new Vector<CompilationError>());
        if (compile()) {

            Vector<String> mains = getMains();
            String runnable = null;
            if (mains.size() == 0) {
                JOptionPane.showMessageDialog(frame,
                        "Sorry, but your project does not contain any runnable public class ...", "Error",
                        JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
            } else {

                if (mains.size() == 1) {
                    runnable = mains.get(0);
                } else {
                    String[] classNames = new String[mains.size()];
                    for (int c = 0; c < mains.size(); c++)
                        classNames[c] = mains.get(c);
                    runnable = (String) JOptionPane.showInputDialog(frame,
                            "Unimozer detected more than one runnable class.\n"
                                    + "Please select which one you want to run.",
                            "Run", JOptionPane.QUESTION_MESSAGE, Unimozer.IMG_QUESTION, classNames, "");
                }

                // we know now what to run
                MyClass runnClass = classes.get(runnable);

                // set full signature
                String fullSign = "void main(String[] args)";
                if (runnClass.hasMain2())
                    fullSign = "void main(String args[])";

                // get signature
                String sign = runnClass.getSignatureByFullSignature(fullSign);
                String complete = runnClass.getCompleteSignatureBySignature(sign);

                if ((runnClass.hasMain2()) && (sign.equals("void main(String)"))) {
                    sign = "void main(String[])";
                }

                //System.out.println("Calling method (full): "+fullSign);
                //System.out.println("Calling method       : "+sign);

                // find method
                Class c = Runtime5.getInstance().load(runnClass.getFullName());
                Method m[] = c.getMethods();
                for (int i = 0; i < m.length; i++) {
                    String full = "";
                    full += m[i].getReturnType().getSimpleName();
                    full += " ";
                    full += m[i].getName();
                    full += "(";
                    Class<?>[] tvm = m[i].getParameterTypes();
                    LinkedHashMap<String, String> genericInputs = new LinkedHashMap<String, String>();
                    for (int t = 0; t < tvm.length; t++) {
                        String sn = tvm[t].toString();
                        genericInputs.put("param" + t, sn);
                        sn = sn.substring(sn.lastIndexOf('.') + 1, sn.length());
                        if (sn.startsWith("class"))
                            sn = sn.substring(5).trim();
                        // array is shown as ";"  ???
                        if (sn.endsWith(";")) {
                            sn = sn.substring(0, sn.length() - 1) + "[]";
                        }
                        full += sn + ", ";
                    }
                    if (tvm.length > 0)
                        full = full.substring(0, full.length() - 2);
                    full += ")";

                    //if((full.equals(sign) || full.equals(fullSign)))
                    //    System.out.println("Found: "+full);

                    if ((full.equals(sign) || full.equals(fullSign))) {
                        LinkedHashMap<String, String> inputs = runnClass.getInputsBySignature(sign);
                        //System.out.println(inputs);
                        //System.out.println(genericInputs);
                        if (inputs.size() != genericInputs.size()) {
                            inputs = genericInputs;
                        }
                        MethodInputs mi = null;
                        boolean go = true;
                        if (inputs.size() > 0) {
                            mi = new MethodInputs(frame, inputs, full, runnClass.getJavaDocBySignature(sign));
                            go = mi.OK;
                        }
                        if (go == true) {
                            try {
                                String method = runnClass.getFullName() + "." + m[i].getName() + "(";
                                if (inputs.size() > 0) {
                                    Object[] keys = inputs.keySet().toArray();
                                    //int cc = 0;
                                    for (int in = 0; in < keys.length; in++) {
                                        String name = (String) keys[in];
                                        String val = mi.getValueFor(name);
                                        if (val.equals(""))
                                            val = "null";
                                        else if (!val.startsWith("new String[]")) {
                                            String[] pieces = val.split("\\s+");
                                            String inp = "";
                                            for (int iin = 0; iin < pieces.length; iin++) {
                                                if (inp.equals(""))
                                                    inp = pieces[iin];
                                                else
                                                    inp += "\",\"" + pieces[iin].replace("\"", "\\\"");
                                            }
                                            val = "new String[] {\"" + inp + "\"}";
                                        }

                                        method += val + ",";
                                    }
                                    method = method.substring(0, method.length() - 1);
                                }
                                method += ")";

                                // Invoke method in a new thread
                                final String myMeth = method;
                                Console.disconnectAll();
                                System.out.println("Running now: " + myMeth);
                                Console.connectAll();
                                Runnable r = new Runnable() {
                                    public void run() {
                                        Console.cls();
                                        try {
                                            //Console.disconnectAll();
                                            //System.out.println(myMeth);
                                            Object retobj = Runtime5.getInstance().executeMethod(myMeth);
                                            if (retobj != null)
                                                JOptionPane.showMessageDialog(frame, retobj.toString(),
                                                        "Result", JOptionPane.INFORMATION_MESSAGE,
                                                        Unimozer.IMG_INFO);
                                        } catch (EvalError ex) {
                                            JOptionPane.showMessageDialog(frame, ex.toString(),
                                                    "Execution error", JOptionPane.ERROR_MESSAGE,
                                                    Unimozer.IMG_ERROR);
                                            MyError.display(ex);
                                        }
                                    }
                                };
                                Thread t = new Thread(r);
                                t.start();

                                //System.out.println(method);
                                //Object retobj = Runtime5.getInstance().executeMethod(method);
                                //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO);
                            } catch (Throwable ex) {
                                JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error",
                                        JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
                                MyError.display(ex);
                            }
                        }
                    }
                }
            }
        }
    } catch (ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(frame, "There was an error while running your project ...",
                "Error :: ClassNotFoundException", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR);
    }
}