Example usage for java.util Map toString

List of usage examples for java.util Map toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.biomart.configurator.controller.MartController.java

private boolean findOrphanFKFromDB(List<ForeignKey> orphanKeyList, StringBuffer orphanSearch, Mart mart)
        throws Exception {
    List<SourceSchema> sss = mart.getIncludedSchemas();
    // assuming that only one for now
    if (McUtils.isCollectionEmpty(sss))
        return false;
    SourceSchema ss = sss.get(0);//  ww w. j a v a 2 s .  c o m

    String catalog = ss.getConnection().getCatalog();
    Map<String, Collection<Relation>> orphanFK = new HashMap<String, Collection<Relation>>();

    List<String> dbcols;
    boolean foundOrphanFK = false;
    StringBuffer result = orphanSearch;

    // List missTableList = new ArrayList();

    Map<String, Map<String, List<String>>> dbTableColMap = this.getDBTableColsMap(ss.getConnection());

    // ResultSet dbTableSet = getTablesFromDB();
    // Map<String,Set<String>> tableColMap = getDBTableColumnCollection(dbTableSet);
    // dbTableSet.close();

    // String missingTable = "Missing Table";

    // Loop through each foreign key in the GUI model tables
    for (final Table t : ss.getTables()) {
        // Find the hashset of columns in corresponding DB table
        // check only the first schema for now, assume that they are all the same
        dbcols = dbTableColMap.get(catalog).get(t.getName());
        // Tables dropped or renamed is handled inside sync process
        if (dbcols == null) {
            // missTableList.add(t.getName());

            boolean foundRel = addTableKeysToOrphanList(t, orphanFK);
            if (foundRel) {
                foundOrphanFK = true;
            }
            continue;

        }

        for (final ForeignKey k : t.getForeignKeys()) {
            for (int kcl = 0; kcl < k.getColumns().size(); kcl++)

                // If there is no matching column in the DB table, the
                // key is orphan
                if (!dbcols.contains(k.getColumns().get(kcl).getName())) {

                    foundOrphanFK = true;
                    orphanKeyList.add(k);

                    orphanFK.put(k.getColumns().get(kcl).getName(), k.getRelations());
                    Log.debug("found orphan foreign key" + k.toString() + " in table " + t.toString());
                }
        }

    }
    result.append("Orphan Relation: ");
    if (foundOrphanFK) {

        // Output missingt table
        // result.append("Missing Table: " + missTableList.toString());
        result.append(orphanFK.toString());
    }

    return foundOrphanFK;

}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Add templates to the cloud./* w w w .  j  av a 2s.  c  o m*/
 *
 * @param templatesFolder
 *            The templates zip file.
 * @return a map containing the added templates and a success status if succeeded, else returns an error status.
 * @throws RestErrorException
 *             in case of failing to add the template to the space.
 * @throws IOException
 *             in case of reading error.
 * @throws DSLException
 *             in case of failing to read a DSL object.
 */
@JsonRequestExample(requestBody = "{\"templatesFolder\" : \"templates folder\"}")
@JsonResponseExample(status = "success", responseBody = "[\"template1\", \"template2\", \"template3\"]", comments = "In case of failure a RestErrorException will be thrown and its args will contain two maps: "
        + "a map of hosts and foreach host its failed to add templates with their error reasons "
        + "(which is a map of template name and error description) "
        + "and a map of hosts and for each host its list of successfuly added templates.")
@PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "Failed to add all the templates to all the REST instances.") })
@PreAuthorize("isFullyAuthenticated() and hasAnyRole('ROLE_CLOUDADMINS')")
@RequestMapping(value = "templates", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> addTemplates(
        @RequestParam(value = TEMPLATES_DIR_PARAM_NAME, required = true) final MultipartFile templatesFolder)
        throws IOException, DSLException, RestErrorException {
    if (cloud == null) {
        throw new RestErrorException("local_cloud_not_support_templates_operations", "add-templates");
    }
    logger.log(Level.INFO, "[addTemplates] - starting add templates.");
    File loaclTemplatesZipFile = null;
    File unzippedTemplatesFolder = null;
    try {
        loaclTemplatesZipFile = copyMultipartFileToLocalFile(templatesFolder);
        unzippedTemplatesFolder = new ComputeTemplatesReader().unzipCloudTemplatesFolder(loaclTemplatesZipFile);
        final List<String> expectedTemplates = readCloudTemplatesNames(unzippedTemplatesFolder);

        final Map<String, Map<String, String>> failedToAddTemplatesByHost = new HashMap<String, Map<String, String>>();
        final Map<String, List<String>> addedTemplatesByHost = new HashMap<String, List<String>>();
        // add the templates to the remote PUs, update addedTemplatesByHost
        // and missingTemplatesByHost.
        sendAddTemplatesToRestInstances(loaclTemplatesZipFile, expectedTemplates, addedTemplatesByHost,
                failedToAddTemplatesByHost);

        // If some templates failed to be added, throw an exception
        if (!failedToAddTemplatesByHost.isEmpty()) {
            if (addedTemplatesByHost.isEmpty()) {
                logger.log(Level.WARNING, "[addTemplates] - Failed to add the following templates (by host): "
                        + failedToAddTemplatesByHost);
                throw new RestErrorException(CloudifyErrorMessages.FAILED_TO_ADD_TEMPLATES.getName(),
                        failedToAddTemplatesByHost);

            } else {
                logger.log(Level.WARNING,
                        "[addTemplates] - Failed to add the following templates (by host): "
                                + failedToAddTemplatesByHost + ".\nSuccessfully added templates (by host): "
                                + addedTemplatesByHost);
                throw new RestErrorException(CloudifyErrorMessages.PARTLY_FAILED_TO_ADD_TEMPLATES.getName(),
                        failedToAddTemplatesByHost, addedTemplatesByHost);
            }
        }

        logger.log(Level.INFO,
                "[addTemplates] - Successfully added templates: " + addedTemplatesByHost.toString());
        return successStatus(expectedTemplates);

    } finally {
        FileUtils.deleteQuietly(unzippedTemplatesFolder);
        FileUtils.deleteQuietly(loaclTemplatesZipFile);
    }
}

From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java

@Override
protected String encodeJSONExtraData(Integer dashboardID, Map<String, Object> session,
        Map<String, String> parameters, Integer projectID, Integer releaseID, Map<String, String> ajaxParams)
        throws TooManyItemsToLoadException {
    TPersonBean user = (TPersonBean) session.get(Constants.USER_KEY);
    Locale locale = user.getLocale();

    DashboardDescriptor dashboardDescriptor = getDescriptor();
    String bundleName = dashboardDescriptor.getBundleName();

    StringBuilder sb = new StringBuilder();
    String sessionPrefix = "dashboard" + "." + dashboardID;

    //the name where the ImageProvider implementation is stored in the session
    String theProvider = sessionPrefix;
    //the name where configParameters are stored
    String theParams = sessionPrefix + "Params";

    //to avoid caching if IE
    Long actualTime = new Long(new Date().getTime());

    Integer selectedCalculationMode = parseInteger(parameters,
            CONFIGURATION_PARAMETERS.SELECTED_CALCULATION_MODE, CALCULATION_MODE.NEW);
    //for ftl//w  w w  . j  a v  a2 s.co m
    String userEnteredTitle = parameters.get("title");
    if (userEnteredTitle == null || "".equals(userEnteredTitle.trim())) {
        //title="statusOverTime.title." + getCalculationModeSuffix(selectedCalculationMode));
    }

    //      int width=BasePluginDashboardBL.parseIntegerValue(parameters, CONFIGURATION_PARAMETERS.X_AXE, DEFAULT_WIDTH);
    int height = parseInteger(parameters, CONFIGURATION_PARAMETERS.Y_AXE, DEFAULT_HEIGHT);

    Map<String, Object> configParameters = new HashMap<String, Object>();
    Iterator<String> it = parameters.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        configParameters.put(key, parameters.get(key));
    }
    //used in preparing the locale specific chart
    configParameters.put("locale", locale);
    configParameters.put("personBean", user);
    configParameters.put("projectID", projectID);
    configParameters.put("releaseID", releaseID);
    configParameters.put(SESSION_PARAMETERS.PROVIDER_LINK, theProvider);
    configParameters.put(SESSION_PARAMETERS.PROVIDER_PARAMS, theParams);

    //to avoid caching if IE
    configParameters.put("actualTime", new Long(new Date().getTime()));

    //      configParameters.put("width",width);
    configParameters.put("height", height);

    //save the theProvider ImageProvider and the configParameters map into the session
    //they will be used in the .ftl to call the corresponding image provider action
    session.put(theProvider, this);
    session.put(theParams, configParameters);

    String url = "imageServerAction!loadJSON.action?imageProviderKey=" + theProvider + "&imageProviderParams="
            + theParams + "&date=" + actualTime;

    JSONUtility.appendStringValue(sb, "url", url);
    //      JSONUtility.appendIntegerValue(sb, "width",width);
    JSONUtility.appendIntegerValue(sb, "height", height);
    if ((configParameters.get("dateTo") != null && configParameters.get("dateTo") != null
            && !configParameters.get("dateTo").equals("null")
            && !configParameters.get("dateFrom").equals("null"))
            || (configParameters.get("daysBefore") != null)) {
        JSONUtility.appendBooleanValue(sb, "empty", false);
        String JSONResponse = generateJSONResponse(configParameters);
        JSONUtility.appendJSONValue(sb, "chartData", JSONResponse);

        if (configParameters.get("daysBefore") != null) {
            SimpleDateFormat dateFormat;
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            int daysBefore = BasePluginDashboardBL.parseIntegerValue(configParameters,
                    TIMEPERIOD_PARAMETERS.DAYS_BEFORE, 0);
            Date dateTo = calendar.getTime();
            Date dateFrom = calendar.getTime();
            if (daysBefore != 0) {
                calendar.add(Calendar.DATE, -daysBefore);
                dateFrom = calendar.getTime();
            }
            JSONUtility.appendStringValue(sb, "dateTo", dateFormat.format(dateTo).toString());
            JSONUtility.appendStringValue(sb, "dateFrom", dateFormat.format(dateFrom).toString());
        } else {
            JSONUtility.appendStringValue(sb, "dateTo", configParameters.get("dateTo").toString());
            JSONUtility.appendStringValue(sb, "dateFrom", configParameters.get("dateFrom").toString());
        }

        String xAxesLabel = "";
        if (configParameters.get("selectedTimeInterval").toString().equals("2")) {
            xAxesLabel = LocalizeUtil.getLocalizedText("statusOverTime.xAxesLabelMonthly", locale, bundleName);
        } else {
            xAxesLabel = LocalizeUtil.getLocalizedText("statusOverTime.xAxesLabel", locale, bundleName);
        }
        String yAxesLabel = LocalizeUtil.getLocalizedText(
                "statusOverTime.yAxesLabel." + getCalculationModeSuffix(selectedCalculationMode), locale,
                bundleName);

        JSONUtility.appendStringValue(sb, "xAxesLabel", xAxesLabel);
        JSONUtility.appendStringValue(sb, "yAxesLabel", yAxesLabel);
        JSONUtility.appendStringValue(sb, "selectedTimeInterval",
                configParameters.get("selectedTimeInterval").toString());
        JSONUtility.appendStringValue(sb, "locale", locale.toString());

        if (configParameters.get("selectedStatus") != null) {
            JSONUtility.appendStringValue(sb, "selectedStatus",
                    configParameters.get("selectedStatus").toString());
        }

        if (configParameters.get("selectedStatusSecond") != null) {
            JSONUtility.appendStringValue(sb, "selectedStatusSecond",
                    configParameters.get("selectedStatusSecond").toString());
        }

        if (configParameters.get("selectedStatusThird") != null) {
            JSONUtility.appendStringValue(sb, "selectedStatusThird",
                    configParameters.get("selectedStatusThird").toString());
        }
        JSONUtility.appendILabelBeanList(sb, CONFIGURATION_PARAMETERS.STATUSES, StatusBL.loadAll(locale));
        LOGGER.debug(("Status over time config parameters: " + configParameters.toString()));
        LOGGER.debug(("Status over time  JSON Response: " + JSONResponse));
    } else {
        JSONUtility.appendBooleanValue(sb, "empty", true);
        LOGGER.debug("Status over time chart not configured yet!");
    }
    JSONUtility.appendIntegerValue(sb, CONFIGURATION_PARAMETERS.SELECTED_CHART_TYPE,
            parseInteger(parameters, CONFIGURATION_PARAMETERS.SELECTED_CHART_TYPE, CHART_TYPE.LINE));

    if (parameters.get(CONFIGURATION_PARAMETERS.FILLED) != null) {
        JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.FILLED, true);
    } else {
        JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.FILLED, false);
    }

    if (parameters.get(CONFIGURATION_PARAMETERS.GROUPING) != null) {
        JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.GROUPING, true);
    } else {
        JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.GROUPING, false);
    }

    if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME) != null) {
        JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME,
                configParameters.get(CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME).toString());
    }

    if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME) != null) {
        JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME,
                configParameters.get(CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME).toString());
    }

    if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME) != null) {
        JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME,
                configParameters.get(CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME).toString());
    }

    return sb.toString();
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Adds templates to cloud's templates. Adds templates' files to cloud configuration directory.
 *
 * @param templatesFolder//from ww w. j  a va  2s.c o  m
 *            .
 * @return a map contains the added templates list and the failed to add templates list.
 * @throws RestErrorException
 *             If failed to add templates. If failed to copy templates' files to a new directory under the cloud
 *             configuration directory.
 * @throws DSLException
 *             If failed to read templates files.
 */
private Map<String, Object> addTemplatesToCloud(final File templatesFolder)
        throws RestErrorException, DSLException {

    logger.log(Level.FINE, "[addTemplatesToCloud] - Adding templates to cloud.");

    // read cloud templates from templates folder
    final List<ComputeTemplateHolder> cloudTemplatesHolders = readCloudTemplates(templatesFolder);

    logger.log(Level.INFO, "[addTemplatesToCloud] - Successfully read " + cloudTemplatesHolders.size()
            + " templates from folder - " + templatesFolder);

    // adds the templates to the cloud's templates list, deletes the failed to added templates from the folder.
    final Map<String, String> failedToAddTemplates = new HashMap<String, String>();
    final List<String> addedTemplates = new LinkedList<String>();
    addTemplatesToCloudList(templatesFolder, cloudTemplatesHolders, addedTemplates, failedToAddTemplates);
    // if no templates were added, throw an exception
    if (addedTemplates.isEmpty()) {
        logger.log(Level.WARNING, "[addTemplatesToCloud] - Failed to add templates files from "
                + templatesFolder.getAbsolutePath());
    } else {
        // at least one template was added, copy files from template folder to cloudTemplateFolder
        logger.log(Level.INFO, "[addTemplatesToCloud] - Coping templates files from "
                + templatesFolder.getAbsolutePath() + " to " + cloudConfigurationDir.getAbsolutePath());
        try {
            final File localTemplatesDir = copyTemplateFilesToCloudConfigDir(templatesFolder);
            updateCloudTemplatesUploadPath(addedTemplates, localTemplatesDir);
        } catch (final IOException e) {
            // failed to copy files - remove all added templates from cloud and them to the failed map.
            logger.log(Level.WARNING,
                    "[addTemplatesToCloud] - Failed to copy templates files, error: " + e.getMessage(), e);
            for (final String templateName : addedTemplates) {
                cloud.getCloudCompute().getTemplates().remove(templateName);
                failedToAddTemplates.put(templateName, e.getMessage());
            }

        }
    }

    // return the added templates and the failed to add templates lists.
    final Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put(FAILED_TO_ADD_TEMPLATES_KEY, failedToAddTemplates);
    resultMap.put(SUCCESSFULLY_ADDED_TEMPLATES_KEY, addedTemplates);
    if (!failedToAddTemplates.isEmpty()) {
        logger.log(Level.INFO, "[addTemplatesToCloud] - Failed to add the following templates: "
                + failedToAddTemplates.toString());
    }
    return resultMap;
}

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.MtGoxExchangeEventListener.java

@Override
public void handleEvent(ExchangeEvent exchangeEvent) {

    // System.out.println("Msg from server: " + exchangeEvent.getEventType());
    // System.out.println("Msg from server: " + exchangeEvent.getData());

    switch (exchangeEvent.getEventType()) {
    case CONNECT:
        log.debug("MtGox connected");
        addToEventQueue(exchangeEvent);//from ww w.  ja va  2 s  .c o  m
        break;
    case DISCONNECT:
        log.debug("MtGox disconnected");
        addToEventQueue(exchangeEvent);
        break;
    case MESSAGE:

        try {
            // Get raw JSON
            // Map<String, Object> rawJSON = JSONUtils.getJsonGenericMap(exchangeEvent.getData(), streamObjectMapper);
            Map<String, Object> rawJSON;
            rawJSON = streamObjectMapper.readValue(exchangeEvent.getData(),
                    new TypeReference<Map<String, Object>>() {
                    });

            String operation = (String) rawJSON.get("op");
            if ("private".equals(operation)) {
                String priv = (String) rawJSON.get("private");
                if ("user_order".equals(priv)) {
                    // MtGoxOpenOrder order = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("user_order"), streamObjectMapper), MtGoxOpenOrder.class, streamObjectMapper);
                    MtGoxOpenOrder order = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("user_order")),
                            MtGoxOpenOrder.class);
                    ExchangeEvent userOrderEvent = new DefaultExchangeEvent(ExchangeEventType.USER_ORDER,
                            exchangeEvent.getData(), order);
                    addToEventQueue(userOrderEvent);
                    break;
                } else if ("lag".equals(priv)) {
                    // MtGoxTradeLag lag = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("lag"), streamObjectMapper), MtGoxTradeLag.class, streamObjectMapper);
                    MtGoxTradeLag lag = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("lag")), MtGoxTradeLag.class);
                    ExchangeEvent lagEvent = new DefaultExchangeEvent(ExchangeEventType.TRADE_LAG,
                            exchangeEvent.getData(), lag);
                    addToEventQueue(lagEvent);
                    break;
                } else if ("wallet".equals(priv)) {
                    // MtGoxWalletUpdate walletUpdate = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("wallet"), streamObjectMapper), MtGoxWalletUpdate.class, streamObjectMapper);
                    MtGoxWalletUpdate walletUpdate = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("wallet")),
                            MtGoxWalletUpdate.class);
                    ExchangeEvent walletUpdateEvent = new DefaultExchangeEvent(
                            ExchangeEventType.USER_WALLET_UPDATE, exchangeEvent.getData(), walletUpdate);
                    addToEventQueue(walletUpdateEvent);
                    break;
                }

            } else if ("result".equals(operation)) {

                String id = (String) rawJSON.get("id");

                if ("idkey".equals(id)) {
                    ExchangeEvent idEvent = new DefaultExchangeEvent(ExchangeEventType.PRIVATE_ID_KEY, null,
                            rawJSON.get("result"));
                    addToEventQueue(idEvent);
                    break;
                } else if ("orders".equals(id)) {
                    MtGoxOpenOrder[] orders = null;

                    if (rawJSON.get("result") != null) {
                        // orders = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("result"), streamObjectMapper), MtGoxOpenOrder[].class, streamObjectMapper);
                        orders = streamObjectMapper.readValue(
                                streamObjectMapper.writeValueAsString(rawJSON.get("result")),
                                MtGoxOpenOrder[].class);
                    }

                    ExchangeEvent ordersEvent = new DefaultExchangeEvent(ExchangeEventType.USER_ORDERS_LIST,
                            exchangeEvent.getData(), orders);
                    addToEventQueue(ordersEvent);
                    break;

                } else if ("info".equals(id)) {
                    // MtGoxAccountInfo accountInfo = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("result"), streamObjectMapper), MtGoxAccountInfo.class, streamObjectMapper);
                    MtGoxAccountInfo accountInfo = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("result")),
                            MtGoxAccountInfo.class);
                    ExchangeEvent accountInfoEvent = new DefaultExchangeEvent(ExchangeEventType.ACCOUNT_INFO,
                            exchangeEvent.getData(), accountInfo);
                    addToEventQueue(accountInfoEvent);
                    break;

                } else if (id.startsWith("order_add")) {
                    ExchangeEvent userOrderAddedEvent = new DefaultExchangeEvent(
                            ExchangeEventType.USER_ORDER_ADDED, exchangeEvent.getData(), rawJSON.get("result"));
                    addToEventQueue(userOrderAddedEvent);
                    break;

                } else if (id.startsWith("order_cancel")) {

                    // TODO implement the case when the following message comes in from MtGox
                    // {id=order_cancel:c8fa912b-d929-4cc5-98e6-3ea23667cfa5, message=Order not found, op=remark, success=false}

                    // if (((String) rawJSON.get("message")).equals("Order not found")) {
                    // ExchangeEvent userOrderCanceledEvent = new DefaultExchangeEvent(ExchangeEventType.USER_ORDER_NOT_FOUND, exchangeEvent.getData(), rawJSON.get("message"));
                    // addToEventQueue(userOrderCanceledEvent);
                    // }
                    // else {
                    // MtGoxOrderCanceled orderCanceled = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("result"), streamObjectMapper), MtGoxOrderCanceled.class, streamObjectMapper);
                    MtGoxOrderCanceled orderCanceled = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("result")),
                            MtGoxOrderCanceled.class);
                    ExchangeEvent userOrderCanceledEvent = new DefaultExchangeEvent(
                            ExchangeEventType.USER_ORDER_CANCELED, exchangeEvent.getData(), orderCanceled);
                    addToEventQueue(userOrderCanceledEvent);
                    // }

                    break;
                }

            } else if ("remark".equals(operation)) {
                System.out.println("Msg from server: " + rawJSON.toString());
                break;
            }

            // Determine what has been sent
            if (rawJSON.containsKey("ticker")) {

                // Get MtGoxTicker from JSON String
                // MtGoxTicker mtGoxTicker = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("ticker"), streamObjectMapper), MtGoxTicker.class, streamObjectMapper);
                MtGoxTicker mtGoxTicker = streamObjectMapper.readValue(
                        streamObjectMapper.writeValueAsString(rawJSON.get("ticker")), MtGoxTicker.class);

                // Adapt to XChange DTOs
                Ticker ticker = MtGoxAdapters.adaptTicker(mtGoxTicker);

                // Create a ticker event
                ExchangeEvent tickerEvent = new DefaultExchangeEvent(ExchangeEventType.TICKER,
                        exchangeEvent.getData(), ticker);
                addToEventQueue(tickerEvent);
                break;
            } else {
                if (rawJSON.containsKey("trade")) {

                    // log.debug("exchangeEvent: " + exchangeEvent.getEventType());

                    // Get MtGoxTradeStream from JSON String
                    // MtGoxTrade mtGoxTradeStream = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("trade"), streamObjectMapper), MtGoxTrade.class, streamObjectMapper);
                    MtGoxTrade mtGoxTradeStream = streamObjectMapper.readValue(
                            streamObjectMapper.writeValueAsString(rawJSON.get("trade")), MtGoxTrade.class);

                    // Adapt to XChange DTOs
                    Trade trade = MtGoxAdapters.adaptTrade(mtGoxTradeStream);

                    // Create a trade event
                    ExchangeEvent tradeEvent = new DefaultExchangeEvent(ExchangeEventType.TRADE,
                            exchangeEvent.getData(), trade);
                    addToEventQueue(tradeEvent);
                    break;
                } else {
                    if (rawJSON.containsKey("depth")) {

                        // Get MtGoxDepthStream from JSON String
                        // MtGoxDepthUpdate mtGoxDepthStream = JSONUtils.getJsonObject(JSONUtils.getJSONString(rawJSON.get("depth"), streamObjectMapper), MtGoxDepthUpdate.class, streamObjectMapper);
                        MtGoxDepthUpdate mtGoxDepthStream = streamObjectMapper.readValue(
                                streamObjectMapper.writeValueAsString(rawJSON.get("depth")),
                                MtGoxDepthUpdate.class);

                        // Adapt to XChange DTOs
                        OrderBookUpdate orderBookUpdate = MtGoxAdapters.adaptDepthUpdate(mtGoxDepthStream);

                        // Create a depth event
                        ExchangeEvent depthEvent = new DefaultExchangeEvent(ExchangeEventType.DEPTH,
                                exchangeEvent.getData(), orderBookUpdate);
                        addToEventQueue(depthEvent);
                        break;
                    } else {

                        log.debug("MtGox operational message");
                        System.out.println("msg: " + rawJSON.toString());
                        addToEventQueue(exchangeEvent);
                    }
                }
            }
        } catch (JsonParseException e) {
            log.error("Error parsing returned JSON", e);
        } catch (JsonMappingException e) {
            log.error("Error parsing returned JSON", e);
        } catch (IOException e) {
            log.error("Error parsing returned JSON", e);
        }
        break;
    case ERROR:
        log.error("Error message: " + exchangeEvent.getPayload());
        addToEventQueue(exchangeEvent);
        break;
    default:
        throw new IllegalStateException("Unknown ExchangeEventType " + exchangeEvent.getEventType().name());
    }

}

From source file:org.nuxeo.ecm.directory.sql.SQLSession.java

@Override
public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext,
        Map<String, String> orderBy, boolean fetchReferences, int limit, int offset) throws DirectoryException {
    if (!hasPermission(SecurityConstants.READ)) {
        return new DocumentModelListImpl();
    }//from   w w  w.  j a va 2  s  .co m
    acquireConnection();
    Map<String, Object> filterMap = new LinkedHashMap<>(filter);

    if (isMultiTenant()) {
        // filter entries on the tenantId field also
        String tenantId = getCurrentTenantId();
        if (!StringUtils.isBlank(tenantId)) {
            filterMap.put(TENANT_ID_FIELD, tenantId);
        }
    }

    try {
        // build count query statement
        StringBuilder whereClause = new StringBuilder();
        String separator = "";
        List<Column> orderedColumns = new LinkedList<>();
        for (String columnName : filterMap.keySet()) {

            if (getDirectory().isReference(columnName)) {
                log.warn(columnName + " is a reference and will be ignored" + " as a query criterion");
                continue;
            }

            Object value = filterMap.get(columnName);
            Column column = table.getColumn(columnName);
            if (null == column) {
                // this might happen if we have a case like a chain
                // selection and a directory without parent column
                throw new DirectoryException("cannot find column '" + columnName + "' for table: " + table);
            }
            String leftSide = column.getQuotedName();
            String rightSide = "?";
            String operator;
            boolean substring = fulltext != null && fulltext.contains(columnName);
            if ("".equals(value) && dialect.hasNullEmptyString() && !substring) {
                // see NXP-6172, empty values are Null in Oracle
                value = null;
            }
            if (value != null) {
                if (value instanceof SQLComplexFilter) {
                    SQLComplexFilter complexFilter = (SQLComplexFilter) value;
                    operator = complexFilter.getOperator();
                    rightSide = complexFilter.getRightSide();
                } else if (substring) {
                    // NB : remove double % in like query NXGED-833
                    String searchedValue = null;
                    switch (substringMatchType) {
                    case subany:
                        searchedValue = '%' + String.valueOf(value).toLowerCase() + '%';
                        break;
                    case subinitial:
                        searchedValue = String.valueOf(value).toLowerCase() + '%';
                        break;
                    case subfinal:
                        searchedValue = '%' + String.valueOf(value).toLowerCase();
                        break;
                    }
                    filterMap.put(columnName, searchedValue);
                    if (dialect.supportsIlike()) {
                        operator = " ILIKE "; // postgresql rules
                    } else {
                        leftSide = "LOWER(" + leftSide + ')';
                        operator = " LIKE ";
                    }
                } else {
                    operator = " = ";
                }
            } else {
                operator = " IS NULL";
            }
            whereClause.append(separator).append(leftSide).append(operator);
            if (value != null) {
                whereClause.append(rightSide);
                orderedColumns.add(column);
            }
            separator = " AND ";
        }

        int queryLimitSize = getDirectory().getDescriptor().getQuerySizeLimit();
        boolean trucatedResults = false;
        if (queryLimitSize != 0 && (limit <= 0 || limit > queryLimitSize)) {
            PreparedStatement ps = null;
            try {
                // create a preparedStatement for counting and bind the
                // values
                // String countQuery = new StringBuilder("SELECT count(*)
                // FROM ")
                // .append(table.getQuotedName(dialect)).append(whereClause).toString();
                Select select = new Select(table);
                select.setWhat("count(*)");
                select.setFrom(table.getQuotedName());

                String where = whereClause.toString();
                where = addFilterWhereClause(where);
                select.setWhere(where);

                String countQuery = select.getStatement();
                ps = sqlConnection.prepareStatement(countQuery);
                fillPreparedStatementFields(filterMap, orderedColumns, ps);

                ResultSet rs = ps.executeQuery();
                rs.next();
                int count = rs.getInt(1);
                rs.close();
                if (count > queryLimitSize) {
                    trucatedResults = true;
                    limit = queryLimitSize;
                    log.error("Displayed results will be truncated because too many rows in result: " + count);
                    // throw new SizeLimitExceededException("too many rows in result: " + count);
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        }

        // create a preparedStatement and bind the values
        // String query = new StringBuilder("SELECT * FROM
        // ").append(tableName).append(
        // whereClause).toString();

        Select select = new Select(table);
        select.setWhat("*");
        select.setFrom(table.getQuotedName());

        String where = whereClause.toString();
        where = addFilterWhereClause(where);
        select.setWhere(where);

        StringBuilder orderby = new StringBuilder(128);
        if (orderBy != null) {
            for (Iterator<Map.Entry<String, String>> it = orderBy.entrySet().iterator(); it.hasNext();) {
                Entry<String, String> entry = it.next();
                orderby.append(dialect.openQuote()).append(entry.getKey()).append(dialect.closeQuote())
                        .append(' ').append(entry.getValue());
                if (it.hasNext()) {
                    orderby.append(',');
                }
            }
        }
        select.setOrderBy(orderby.toString());
        String query = select.getStatement();
        boolean manualLimitOffset;
        if (limit <= 0) {
            manualLimitOffset = false;
        } else {
            if (offset < 0) {
                offset = 0;
            }
            if (dialect.supportsPaging()) {
                query = dialect.addPagingClause(query, limit, offset);
                manualLimitOffset = false;
            } else {
                manualLimitOffset = true;
            }
        }

        if (logger.isLogEnabled()) {
            List<Serializable> values = new ArrayList<>(orderedColumns.size());
            for (Column column : orderedColumns) {
                Object value = filterMap.get(column.getKey());
                values.add((Serializable) value);
            }
            addFilterValuesForLog(values);
            logger.logSQL(query, values);
        }

        PreparedStatement ps = null;
        try {
            ps = sqlConnection.prepareStatement(query);
            fillPreparedStatementFields(filterMap, orderedColumns, ps);

            // execute the query and create a documentModel list
            ResultSet rs = ps.executeQuery();
            DocumentModelList list = new DocumentModelListImpl();
            while (rs.next()) {

                // fetch values for stored fields
                Map<String, Object> map = new HashMap<>();
                for (String fieldName : storedFieldNames) {
                    Object o = getFieldValue(rs, fieldName);
                    map.put(fieldName, o);
                }

                DocumentModel docModel = fieldMapToDocumentModel(map);

                // fetch the reference fields
                if (fetchReferences) {
                    Map<String, List<String>> targetIdsMap = new HashMap<>();
                    for (Reference reference : directory.getReferences()) {
                        List<String> targetIds = reference.getTargetIdsForSource(docModel.getId());
                        String fieldName = reference.getFieldName();
                        if (targetIdsMap.containsKey(fieldName)) {
                            targetIdsMap.get(fieldName).addAll(targetIds);
                        } else {
                            targetIdsMap.put(fieldName, targetIds);
                        }
                    }
                    for (Entry<String, List<String>> en : targetIdsMap.entrySet()) {
                        String fieldName = en.getKey();
                        List<String> targetIds = en.getValue();
                        docModel.setProperty(schemaName, fieldName, targetIds);
                    }
                }
                list.add(docModel);
            }
            rs.close();
            if (manualLimitOffset) {
                int totalSize = list.size();
                if (offset > 0) {
                    if (offset >= totalSize) {
                        list = new DocumentModelListImpl();
                    } else {
                        list = new DocumentModelListImpl(list.subList(offset, totalSize));
                    }
                }
                if (list.size() > limit) { // list.size() not totalSize, we may have an offset already
                    list = new DocumentModelListImpl(list.subList(0, limit));
                }
                ((DocumentModelListImpl) list).setTotalSize(totalSize);
            }
            if (trucatedResults) {
                ((DocumentModelListImpl) list).setTotalSize(-2);
            }
            return list;
        } finally {
            if (ps != null) {
                ps.close();
            }
        }

    } catch (SQLException e) {
        try {
            sqlConnection.close();
        } catch (SQLException e1) {
        }
        throw new DirectoryException("query failed", e);
    }
}

From source file:com.redsqirl.workflow.server.Workflow.java

public String expand(String superActionId) throws RemoteException {
    String error = null;/* w  w w. ja  va2s.co m*/
    Workflow copy = null;

    if (getElement(superActionId) == null) {
        return "Element " + superActionId + " does not exist.";
    } else if (!getElement(superActionId).getName().contains(">")) {
        return "Element " + superActionId + " is not a super action (" + getElement(superActionId).getName()
                + ").";
    }

    SubWorkflow sw = new SubWorkflow(getElement(superActionId).getName());
    sw.readFromLocal(sw.getInstalledMainFile());
    if (sw.getPrivilege() != null) {
        error = "This action cannot be expanded due to its privilege setting.";
        logger.error(error);
        return error;
    }

    try {
        copy = (Workflow) clone();
    } catch (Exception e) {
        error = "Fail to clone the workflow";
        logger.error(error, e);
        return error;
    }

    // List inputs and outputs element
    logger.debug("List inputs and outputs element");
    DataFlowElement elementToExpand = copy.getElement(superActionId);
    Map<String, Map<String, String>> componentWithNamePerInputs = new LinkedHashMap<String, Map<String, String>>();
    Iterator<DataFlowElement> it = elementToExpand.getAllInputComponent().iterator();
    while (it.hasNext()) {
        DataFlowElement curEl = it.next();
        logger.debug(curEl.getComponentId());
        Map<String, Map<String, String>> cur = curEl.getInputNamePerOutput();
        boolean found = false;
        Iterator<String> itCur = cur.keySet().iterator();
        while (!found && itCur.hasNext()) {
            String outputCur = itCur.next();
            Map<String, String> outputMap = cur.get(outputCur);
            if (outputMap.containsKey(superActionId)) {
                found = true;
                String input = outputMap.get(superActionId);
                if (!componentWithNamePerInputs.containsKey(input)) {
                    componentWithNamePerInputs.put(input, new LinkedHashMap<String, String>());
                }
                componentWithNamePerInputs.get(input).put(curEl.getComponentId(), outputCur);
            }
        }
    }
    Map<String, Map<String, String>> componentWithNamePerOutputs = copy.getElement(superActionId)
            .getInputNamePerOutput();
    logger.debug(componentWithNamePerOutputs);
    Map<String, String> replaceAliases = new LinkedHashMap<String, String>();

    // Remove element SuperAction
    String superActioncoordinatorName = elementToExpand.getCoordinatorName();
    logger.debug("Remove Super Action: " + superActionId);
    try {
        removeElement(superActionId);
    } catch (Exception e) {
        error = "Fail to remove element";
        logger.error(error, e);
        return error;
    }

    Map<String, String> replaceInternalActions = new LinkedHashMap<String, String>();

    //Get the average position so that we can repositionned relatively in the canvas.
    int pos_x = 0;
    int pos_y = 0;
    for (String id : sw.getComponentIds()) {
        DataFlowElement df = sw.getElement(id);
        pos_x += df.getX();
        pos_y += df.getY();
    }
    pos_x /= sw.getComponentIds().size();
    pos_y /= sw.getComponentIds().size();

    // Change Name?
    logger.debug("Change SubWorkflow ids and link");
    for (String id : sw.getComponentIds()) {
        DataFlowElement df = sw.getElement(id);
        logger.debug(id);
        if (!(new SubWorkflowInput().getName()).equals(df.getName())
                && !(new SubWorkflowOutput().getName()).equals(df.getName())) {

            boolean exist = getElement(df.getComponentId()) != null;
            // Change Action Name
            if (exist) {
                String newId = generateNewId();
                replaceInternalActions.put(df.getComponentId(), newId);
                df.setComponentId(newId);
                logger.debug("Id exist, new id: " + newId);
            }

            // If the element is link to input or output link it to the
            // workflow output/input
            logger.debug("link input");
            Iterator<String> itIn = df.getInputComponent().keySet().iterator();
            while (itIn.hasNext()) {
                // Iterate through all the input components
                String inputName = itIn.next();
                logger.debug("input name: " + inputName);
                List<DataFlowElement> lInCur = new LinkedList<DataFlowElement>();
                lInCur.addAll(df.getInputComponent().get(inputName));
                Iterator<DataFlowElement> itInCur = lInCur.iterator();
                while (itInCur.hasNext()) {
                    DataFlowElement elCur = itInCur.next();
                    if ((new SubWorkflowInput().getName()).equals(elCur.getName())) {
                        // Link to a workflow source
                        try {
                            Iterator<String> itOrigInput = componentWithNamePerInputs
                                    .get(elCur.getComponentId()).keySet().iterator();
                            while (itOrigInput.hasNext()) {
                                String elInput = itOrigInput.next();
                                df.addInputComponent(inputName, getElement(elInput));
                                logger.debug("Add input: " + inputName + " " + elInput);
                                getElement(elInput).addOutputComponent(
                                        componentWithNamePerInputs.get(elCur.getComponentId()).get(elInput),
                                        df);
                                logger.debug("Add output: "
                                        + componentWithNamePerInputs.get(elCur.getComponentId()).get(elInput)
                                        + " " + df.getComponentId());
                                // Add alias to replace
                                replaceAliases.put(
                                        df.getAliasesPerComponentInput().get(elCur.getComponentId()).getKey(),
                                        df.getAliasesPerComponentInput().get(elInput).getKey());
                            }
                            df.getInputComponent().get(inputName).remove(elCur);
                        } catch (Exception e) {
                            //Probably some inputs are missing from the workflow
                        }
                    }
                }
            }
            Iterator<String> itOut = df.getOutputComponent().keySet().iterator();
            logger.debug("link output");
            while (itOut.hasNext()) {
                // Iterate through all the input components
                String outputName = itOut.next();
                logger.debug("output name: " + outputName);
                List<DataFlowElement> lOutCur = new LinkedList<DataFlowElement>();
                lOutCur.addAll(df.getOutputComponent().get(outputName));
                Iterator<DataFlowElement> itOutCur = lOutCur.iterator();
                while (itOutCur.hasNext()) {
                    DataFlowElement elCur = itOutCur.next();
                    if ((new SubWorkflowOutput().getName()).equals(elCur.getName())) {
                        // Create new output link
                        logger.debug("Create the new output link");
                        try {
                            Iterator<String> itOrigOutput = componentWithNamePerOutputs
                                    .get(elCur.getComponentId()).keySet().iterator();
                            while (itOrigOutput.hasNext()) {
                                String elOutput = itOrigOutput.next();
                                logger.debug("Add output: " + outputName + " " + elOutput);
                                df.addOutputComponent(outputName, getElement(elOutput));
                                logger.debug("Add input: "
                                        + componentWithNamePerOutputs.get(elCur.getComponentId()).get(elOutput)
                                        + " " + df.getComponentId());
                                getElement(elOutput).addInputComponent(
                                        componentWithNamePerOutputs.get(elCur.getComponentId()).get(elOutput),
                                        df);
                                // Add alias to replace
                                replaceAliases.put(
                                        copy.getElement(elOutput).getAliasesPerComponentInput()
                                                .get(elementToExpand.getComponentId()).getKey(),
                                        getElement(elOutput).getAliasesPerComponentInput()
                                                .get(df.getComponentId()).getKey());
                            }
                        } catch (Exception e) {
                            // Expected if the output is not used in another
                            // element
                        }
                        df.getOutputComponent().get(outputName).remove(elCur);
                    }
                }
            }

            // Replace in the interactions id changes we have seen so far...
            logger.debug("Replace inside the interaction " + df.getComponentId() + ": "
                    + replaceInternalActions.toString());
            Iterator<String> itReplace = replaceInternalActions.keySet().iterator();
            while (itReplace.hasNext()) {
                String key = itReplace.next();
                df.replaceInAllInteraction("([_ \\W]|^)(" + Pattern.quote(key) + ")([_ \\W]|$)",
                        "$1" + replaceInternalActions.get(key) + "$3", true);
            }
            df.setPosition(Math.max(10, df.getX() - pos_x + elementToExpand.getX()),
                    Math.max(10, df.getY() - pos_y + elementToExpand.getY()));

            addElement(df, superActioncoordinatorName);
        }
    }

    // Replace the superaction aliases
    logger.debug("Replace the superaction aliases: " + replaceAliases.toString());
    Iterator<String> itReplaceAliases = replaceAliases.keySet().iterator();
    while (itReplaceAliases.hasNext()) {
        String key = itReplaceAliases.next();
        replaceInAllElements(getComponentIds(), "([_ \\W]|^)(" + Pattern.quote(key) + ")([_ \\W]|$)",
                "$1" + replaceAliases.get(key) + "$3", true);
    }

    return error;
}

From source file:gda.data.metadata.NXMetaDataProvider.java

public INexusTree createChildNodeForScannableMetaEntry(Scannable scn, INexusTree parentNode,
        Map<String, Object> scannableMap) {
    INexusTree node = null;/*www .ja va 2s  .  c  om*/

    List<String> fieldNames = ScannableUtils.getScannableFieldNames(Arrays.asList(new Scannable[] { scn }));
    List<String> inputNames = new Vector<String>();
    inputNames = getScannableInputNames(scn);

    List<String> extraNames = new Vector<String>();
    extraNames = getScannableExtraNames(scn);

    int inputSize = inputNames.size();
    int extraSize = extraNames.size();
    int fieldSize = fieldNames.size();

    if (inputSize + extraSize != fieldSize) {
        String msg = "input names + extra names != field names (" + Integer.toString(inputSize) + " + "
                + Integer.toString(extraSize) + " != " + Integer.toString(fieldSize);

        System.out.println(msg);
        //throw new DeviceException("input names + extra names != field names ("inputNames.size());
    }

    if (scn instanceof ScannableGroup) {

        node = new NexusTreeNode(scn.getName(), NexusExtractor.NXCollectionClassName, parentNode);
        node.addChildNode(new NexusTreeNode(ATTRIBUTE_KEY_FOR_METADATA_TYPE, NexusExtractor.AttrClassName, node,
                new NexusGroupData(ATTRIBUTE_VALUE_FOR_METADATA_TYPE_SCANNABLE_GROUP)));

        for (Scannable s : ((ScannableGroup) scn).getGroupMembers()) {
            INexusTree sNode = createChildNodeForScannableMetaEntry(s, node, scannableMap);
            if (sNode != null) {
                node.addChildNode(sNode);
            }
        }
    } else if (hasGenuineMultipleFieldNames(scn)) {
        node = new NexusTreeNode(scn.getName(), NexusExtractor.NXCollectionClassName, parentNode);

        node.addChildNode(new NexusTreeNode(ATTRIBUTE_KEY_FOR_METADATA_TYPE, NexusExtractor.AttrClassName, node,
                new NexusGroupData(ATTRIBUTE_VALUE_FOR_METADATA_TYPE_SCANNABLE)));

        String[] outputFormat = null;
        outputFormat = scn.getOutputFormat();

        int fieldIdx = 0;
        for (String field : inputNames) {
            String key = field;
            Object posObj = scannableMap.get(key);
            String units = null;

            if (posObj != null) {
                try {
                    units = getScannableUnit(scn);
                } catch (DeviceException e1) {
                    logger.error("Error getting scannable unit", e1);
                }

                NexusGroupData groupData = null;
                groupData = createNexusGroupData(posObj);
                if (groupData != null) {
                    NexusTreeNode fieldNode = new NexusTreeNode(field, NexusExtractor.SDSClassName, node,
                            groupData);
                    fieldNode.addChildNode(
                            new NexusTreeNode(ATTRIBUTE_KEY_FOR_FIELD_TYPE, NexusExtractor.AttrClassName,
                                    fieldNode, new NexusGroupData(ATTRIBUTE_VALUE_FOR_FIELD_TYPE_INPUT)));

                    if (units != null) {
                        fieldNode.addChildNode(new NexusTreeNode(ATTRIBUTE_KEY_FOR_UNITS,
                                NexusExtractor.AttrClassName, fieldNode, new NexusGroupData(units)));
                    }
                    if (outputFormat != null && outputFormat[fieldIdx] != null) {
                        fieldNode.addChildNode(
                                new NexusTreeNode(ATTRIBUTE_KEY_FOR_FORMAT, NexusExtractor.AttrClassName,
                                        fieldNode, new NexusGroupData(outputFormat[fieldIdx])));
                    }
                    node.addChildNode(fieldNode);
                } else {
                    logger.warn("GroupData is null!");
                }
            }
            fieldIdx += 1;
        }

        for (String field : extraNames) {
            String key = field;
            Object posObj = scannableMap.get(key);
            String units = null;

            if (posObj != null) {
                try {
                    units = getScannableUnit(scn);
                } catch (DeviceException e1) {
                    // TODO Auto-generated catch block
                    logger.error("TODO put description of error here", e1);
                }

                NexusGroupData groupData = null;
                groupData = createNexusGroupData(posObj);
                if (groupData != null) {
                    NexusTreeNode fieldNode = new NexusTreeNode(field, NexusExtractor.SDSClassName, node,
                            groupData);
                    fieldNode.addChildNode(
                            new NexusTreeNode(ATTRIBUTE_KEY_FOR_FIELD_TYPE, NexusExtractor.AttrClassName,
                                    fieldNode, new NexusGroupData(ATTRIBUTE_VALUE_FOR_FIELD_TYPE_EXTRA)));
                    if (units != null) {
                        fieldNode.addChildNode(new NexusTreeNode(ATTRIBUTE_KEY_FOR_UNITS,
                                NexusExtractor.AttrClassName, fieldNode, new NexusGroupData(units)));
                    }
                    if (outputFormat != null && outputFormat[fieldIdx] != null) {
                        fieldNode.addChildNode(
                                new NexusTreeNode(ATTRIBUTE_KEY_FOR_FORMAT, NexusExtractor.AttrClassName,
                                        fieldNode, new NexusGroupData(outputFormat[fieldIdx])));
                    }
                    node.addChildNode(fieldNode);
                } else {
                    logger.warn("GroupData is null!");
                }
            }
            fieldIdx += 1;
        }

    } else {
        String key = null;
        int fieldIdx = 0;
        String whoami = "";
        if (inputSize == 1) {
            key = inputNames.get(fieldIdx);
            whoami = "input";
        } else if (extraSize == 1) {
            key = extraNames.get(fieldIdx);
            whoami = "extra";
        } else {
            key = scn.getName();
        }

        String[] outputFormat = null;
        outputFormat = scn.getOutputFormat();

        Object posObj = scannableMap.get(key);
        String units = null;

        if (posObj != null) {
            try {
                units = getScannableUnit(scn);
            } catch (DeviceException e1) {
                logger.error("TODO put description of error here", e1);
            }

            NexusGroupData groupData = null;
            groupData = createNexusGroupData(posObj);
            if (groupData != null) {
                node = new NexusTreeNode(key, NexusExtractor.SDSClassName, parentNode, groupData);

                if (parentNode.getAttribute(ATTRIBUTE_KEY_FOR_METADATA_TYPE) == null) {
                    node.addChildNode(
                            new NexusTreeNode(ATTRIBUTE_KEY_FOR_METADATA_TYPE, NexusExtractor.AttrClassName,
                                    node, new NexusGroupData(ATTRIBUTE_VALUE_FOR_METADATA_TYPE_SCANNABLE)));
                } else {
                    System.out.println("Metadata type already set on the parent");
                }

                if (whoami.equals("input")) {
                    node.addChildNode(
                            new NexusTreeNode(ATTRIBUTE_KEY_FOR_FIELD_TYPE, NexusExtractor.AttrClassName, node,
                                    new NexusGroupData(ATTRIBUTE_VALUE_FOR_FIELD_TYPE_INPUT)));
                } else if (whoami.equals("extra")) {
                    node.addChildNode(
                            new NexusTreeNode(ATTRIBUTE_KEY_FOR_FIELD_TYPE, NexusExtractor.AttrClassName, node,
                                    new NexusGroupData(ATTRIBUTE_VALUE_FOR_FIELD_TYPE_EXTRA)));
                }

                if (units != null && units.length() > 0) {
                    node.addChildNode(new NexusTreeNode(ATTRIBUTE_KEY_FOR_UNITS, NexusExtractor.AttrClassName,
                            node, new NexusGroupData(units)));

                    if (outputFormat != null && outputFormat[fieldIdx] != null) {
                        //System.out.println("\t\t output format = " + outputFormat[fieldIdx]);
                        node.addChildNode(
                                new NexusTreeNode(ATTRIBUTE_KEY_FOR_FORMAT, NexusExtractor.AttrClassName, node,
                                        new NexusGroupData(outputFormat[fieldIdx])));
                    }

                }
            } else {
                System.out.println("***NEW goupData is null!");
            }
        } else {
            System.out.println("NOT FOUND!!! key = " + key);
            System.out.println("\t scannableMap = " + scannableMap.toString());
        }
    }
    return node;
}