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.fusesource.restygwt.client.codec.EncoderDecoderTestGwt.java

public void testTypeMapWithListValueDecode() {
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    map.put("key", new ArrayList<String>(Arrays.asList("me and the corner")));
    AbstractJsonEncoderDecoder<List<String>> valueEncoder = AbstractNestedJsonEncoderDecoder
            .listEncoderDecoder(AbstractJsonEncoderDecoder.STRING);

    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder//  w w  w.  j ava2  s.c  om
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, valueEncoder, Json.Style.DEFAULT),
                            valueEncoder, Json.Style.DEFAULT)
                    .toString());
    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, valueEncoder, Json.Style.JETTISON_NATURAL),
                            valueEncoder, Json.Style.JETTISON_NATURAL)
                    .toString());
}

From source file:org.opendaylight.controller.yang2sources.plugin.YangToSourcesMojo.java

private void generateResources() throws MojoExecutionException, MojoFailureException {
    if (resourceProviders.length == 0) {
        getLog().warn(Util.message("No resource provider classes provided", LOG_PREFIX));
        return;// w w  w.  j a  va2  s .  c o  m
    }

    Resource res = new Resource();
    String baseDirName = project.getBasedir().getAbsolutePath();
    res.setDirectory(baseDirName + OUTPUT_RESOURCE_DIR);
    res.setTargetPath(INPUT_RESOURCE_DIR);
    project.addResource(res);

    Map<String, String> thrown = Maps.newHashMap();

    Collection<File> yangFiles = new ArrayList<File>();

    // load files from yang root
    yangFiles.addAll(getFilesFromYangRoot());

    // load files from dependencies
    Collection<File> filesFromDependencies = getFilesFromDependencies();
    yangFiles.addAll(filesFromDependencies);

    for (ResourceProviderArg resourceProvider : resourceProviders) {
        try {
            provideResourcesWithOneProvider(yangFiles, resourceProvider);
        } catch (Exception e) {
            // try other generators, exception will be thrown after
            getLog().error(Util.message("Unable to provide resources with %s resource provider", LOG_PREFIX,
                    resourceProvider.getResourceProviderClass()), e);
            thrown.put(resourceProvider.getResourceProviderClass(), e.getClass().getCanonicalName());
        }
    }

    if (!thrown.isEmpty()) {
        String message = Util.message(
                "One or more code resource provider failed, including failed list(resourceProviderClass=exception) %s",
                LOG_PREFIX, thrown.toString());
        getLog().error(message);
        throw new MojoFailureException(message);
    }
}

From source file:com.baasbox.service.push.providers.APNServer.java

@Override
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
    PushLogger pushLogger = PushLogger.getInstance();
    pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
    ApnsService service = null;//from  ww w. j  a v  a2  s  .c  o m
    try {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
        if (!isInit) {
            pushLogger.addMessage("............ APNS is not initialized!");
            return true;
        }

        String payload = null;
        try {
            service = getService();
        } catch (com.notnoop.exceptions.InvalidSSLConfig e) {
            pushLogger.addMessage("Error sending push notification ...");
            pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
            BaasBoxLogger.error("Error sending push notification");
            throw new PushNotInitializedException(
                    "Error decrypting certificate.Verify your password for given certificate");
            //icallbackPush.onError(ExceptionUtils.getMessage(e));
        }

        JsonNode contentAvailableNode = bodyJson.findValue("content-available");
        Integer contentAvailable = null;
        if (!(contentAvailableNode == null)) {
            if (!(contentAvailableNode.isInt()))
                throw new PushContentAvailableFormatException(
                        "Content-available MUST be an Integer (1 for silent notification)");
            contentAvailable = contentAvailableNode.asInt();
        }

        JsonNode categoryNode = bodyJson.findValue("category");
        String category = null;
        if (!(categoryNode == null)) {
            if (!(categoryNode.isTextual()))
                throw new PushCategoryFormatException("Category MUST be a String");
            category = categoryNode.asText();
        }

        JsonNode soundNode = bodyJson.findValue("sound");
        String sound = null;
        if (!(soundNode == null)) {
            if (!(soundNode.isTextual()))
                throw new PushSoundKeyFormatException("Sound value MUST be a String");
            sound = soundNode.asText();
        }

        JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
        String actionLocKey = null;

        if (!(actionLocKeyNode == null)) {
            if (!(actionLocKeyNode.isTextual()))
                throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
            actionLocKey = actionLocKeyNode.asText();
        }

        JsonNode locKeyNode = bodyJson.findValue("localizedKey");
        String locKey = null;

        if (!(locKeyNode == null)) {
            if (!(locKeyNode.isTextual()))
                throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
            locKey = locKeyNode.asText();
        }

        JsonNode locArgsNode = bodyJson.get("localizedArguments");

        List<String> locArgs = new ArrayList<String>();
        if (!(locArgsNode == null)) {
            if (!(locArgsNode.isArray()))
                throw new PushLocalizedArgumentsFormatException(
                        "LocalizedArguments MUST be an Array of String");
            for (JsonNode locArgNode : locArgsNode) {
                if (locArgNode.isNumber())
                    throw new PushLocalizedArgumentsFormatException(
                            "LocalizedArguments MUST be an Array of String");
                locArgs.add(locArgNode.toString());
            }
        }

        JsonNode customDataNodes = bodyJson.get("custom");

        Map<String, JsonNode> customData = new HashMap<String, JsonNode>();

        if (!(customDataNodes == null)) {
            customData.put("custom", customDataNodes);
        }

        JsonNode badgeNode = bodyJson.findValue("badge");
        int badge = 0;
        if (!(badgeNode == null)) {
            if (!(badgeNode.isNumber()))
                throw new PushBadgeFormatException("Badge value MUST be a number");
            else
                badge = badgeNode.asInt();
        }

        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                    + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                    + " with Localized-Key: " + locKey);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Custom Data: " + customData.toString());

        pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                + " with Localized-Key: " + locKey);
        pushLogger.addMessage("Localized arguments: " + locArgs.toString());
        pushLogger.addMessage("Custom Data: " + customData.toString());
        pushLogger.addMessage("Timeout: " + timeout);

        PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound)
                .actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge)
                .customFields(customData).category(category);
        if (contentAvailable != null && contentAvailable.intValue() == 1) {
            payloadBuilder.instantDeliveryOrSilentNotification();
        }
        payload = payloadBuilder.build();

        Collection<? extends ApnsNotification> result = null;
        if (timeout <= 0) {
            try {
                result = service.push(deviceid, payload);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }
        } else {
            try {
                Date expiry = new Date(Long.MAX_VALUE);
                pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout,
                        expiry.toString());
                result = service.push(deviceid, payload, expiry);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending enhanced push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }

        }
        if (result != null) {
            Iterator<? extends ApnsNotification> it = result.iterator();
            while (it.hasNext()) {
                ApnsNotification item = it.next();
                //item.
            }

        }
        //icallbackPush.onSuccess();
        return false;
    } catch (Exception e) {
        pushLogger.addMessage("Error sending push notification (APNS)...");
        pushLogger.addMessage(ExceptionUtils.getMessage(e));
        throw e;
    } finally {
        if (service != null)
            service.stop();
    }
}

From source file:javazoom.jlgui.player.amp.PlayerUI.java

public void opened(Object stream, Map properties) {
    // Not in EDT.
    audioInfo = properties;
    log.debug(properties.toString());
}

From source file:org.fusesource.restygwt.client.codec.EncoderDecoderTestGwt.java

public void testTypeMapWithComplexDecode() {
    Map<Email, String> map = new HashMap<Email, String>();
    Email email = new Email();
    email.email = "me@example.com";
    email.name = "me";
    map.put(email, "done");
    AbstractJsonEncoderDecoder<Email> keyEncoder = GWT.create(EmailCodec.class);
    AbstractJsonEncoderDecoder<String> valueEncoder = AbstractJsonEncoderDecoder.STRING;

    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder//  w  w  w.j  ava 2  s.c om
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, keyEncoder, valueEncoder, Json.Style.DEFAULT),
                            keyEncoder, valueEncoder, Json.Style.DEFAULT)
                    .toString());
    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, keyEncoder, valueEncoder,
                            Json.Style.JETTISON_NATURAL), keyEncoder, valueEncoder, Json.Style.JETTISON_NATURAL)
                    .toString());
}

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

@Override
public void handleEvent(ExchangeEvent exchangeEvent) {

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

    switch (exchangeEvent.getEventType()) {
    case CONNECT:
        log.debug("MtGox connected");
        addToEventQueue(exchangeEvent);//  w w  w .ja  v  a2s.  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)) {

            } 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 (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")) {

                    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:me.piebridge.prevent.framework.SystemReceiver.java

private boolean handleCheckLicense(Context context, Intent intent) {
    String user = intent.getStringExtra(Intent.EXTRA_USER);
    Map<String, Set<String>> users = new LinkedHashMap<String, Set<String>>();
    for (Account account : ActivityManagerServiceHook.getAccountWatcher().getEnabledAccounts()) {
        Set<String> accounts = users.get(account.type);
        if (accounts == null) {
            accounts = new LinkedHashSet<String>();
            users.put(account.type, accounts);
        }/*from  w  ww.ja  v a2 s. c  om*/
        accounts.add(account.name);
        if (PackageUtils.equals(account.name, user)) {
            setResultCode(0x1);
            return true;
        }
    }
    String number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
    if (number != null) {
        number = number.replace("-", "");
        number = number.replace(" ", "");
        Set<String> numbers = users.get("");
        if (numbers == null) {
            numbers = new LinkedHashSet<String>();
            users.put("", numbers);
        }
        numbers.add(number);
        if (PackageUtils.equals(number, user)) {
            setResultCode(0x1);
            return true;
        }
    }
    setResultCode(0x0);
    setResultData(users.toString());
    return false;
}

From source file:net.itransformers.postDiscoverer.core.ReportManager.java

public StringBuffer reportExecutor(File postDiscoveryPath, Map<String, Object> params)
        throws ParserConfigurationException, SAXException, IOException {

    List<ReportEntryType> reportEnties = reportGenerator.getReportEntry();
    StringBuffer sb = new StringBuffer();
    String deviceType = (String) params.get("deviceType");
    String deviceName = (String) params.get("deviceName");
    File postDiscoveryNodeFolder = new File(postDiscoveryPath, (String) params.get("deviceName"));
    if (!postDiscoveryNodeFolder.exists()) {
        postDiscoveryNodeFolder.mkdir();
    }/*from   ww w .  j a v  a  2s  .c  om*/

    if (params.get("port") instanceof String) {
        params.put("port", Integer.parseInt((String) params.get("port")));
    }
    if (params.get("retries") instanceof String) {
        params.put("retries", Integer.parseInt((String) params.get("retries")));

    }

    for (ReportEntryType reportEntry : reportEnties) {
        String reportName = reportEntry.getName();
        File postDiscoveryReportOutput = new File(
                postDiscoveryNodeFolder + File.separator + reportName + ".xml");

        logger.debug("Report id: " + reportName + " " + reportEntry.getDeviceType() + " "
                + reportEntry.getDeviceName() + "with params" + params.toString());
        if (reportEntry.getDeviceType().equals(deviceType)) {

            sb.append("<?xml version=\"1.0\"?>\n");

            // sb.append("<report name=\""+reportEntry.getName()+"\" " + "deviceType=\""+deviceType+"\" "+ "deviceName=\""+deviceName+"\">");
            sb.append("<report>\n");
            List<CommandType> commands = reportEntry.getCommand();
            List<CommandDescriptorType> commandDescriptors = reportGenerator.getCommandDescriptor();

            for (CommandDescriptorType commandDescriptor : commandDescriptors) {

                if (commandDescriptor.getDeviceType().equals(deviceType)) {
                    LoginScriptType loginScript = commandDescriptor.getLoginScript();
                    LogoutScriptType logoutScript = commandDescriptor.getLogoutScript();
                    SendCommandScriptType sendCommandScript = commandDescriptor.getSendCommandScript();

                    try {
                        Expect4GroovyScriptLauncher launcher = new Expect4GroovyScriptLauncher();
                        logger.debug(
                                "Launch connection to :" + deviceName + " with params " + params.toString());
                        logger.debug(
                                "Script path = " + scriptPath + " |login script " + loginScript.getValue());

                        Map<String, Object> loginResult = launcher.open(
                                new String[] { scriptPath + File.separator }, loginScript.getValue(), params);

                        int loginresult = (Integer) loginResult.get("status");

                        if (loginresult == 2) {
                            logger.debug(loginResult);
                            return null;
                        }

                        List<CommandType> commandDescriptorCommands = commandDescriptor.getCommand();

                        for (CommandType descriptorCommand : commandDescriptorCommands) {

                            for (CommandType command : commands) {

                                if (descriptorCommand.getName().equals(command.getName())) {
                                    String evalScriptName = descriptorCommand.getEvalScript();
                                    String commandString = descriptorCommand.getSendCommand();
                                    File script = null;
                                    Map<String, Object> result = null;

                                    if (evalScriptName != null) {
                                        script = new File(scriptPath, evalScriptName);
                                        HashMap<String, Object> scriptParams = new HashMap<>();
                                        scriptParams.put("command", commandString);
                                        scriptParams.put("evalScript", evalScriptName);
                                        result = launcher.sendCommand(sendCommandScript.getValue(),
                                                scriptParams);

                                        Map<String, Object> evalData = (Map<String, Object>) result
                                                .get("reportResult");
                                        if (evalData != null) {
                                            for (String key : evalData.keySet()) {
                                                sb.append("\n\t<entry>\n");
                                                sb.append("\t\t<AuditRule>" + key + "</AuditRule>" + "\n");
                                                Map<String, Map<String, Integer>> keyMap = (Map<String, Map<String, Integer>>) evalData
                                                        .get(key);
                                                if (keyMap.get("message") != null) {
                                                    sb.append("\t\t<Statement><![CDATA[" + keyMap.get("message")
                                                            + "]]></Statement>" + "\n");
                                                }

                                                if (keyMap.get("score") != null) {

                                                    sb.append("\t\t<Score>" + keyMap.get("score") + "</Score>"
                                                            + "\n");
                                                }
                                                sb.append("\t</entry>");
                                                logger.debug(key + " " + evalData.get(key));
                                            }

                                        }
                                        // result = launcher.sendCommand(sendCommandScript.getValue(), commandString, null);
                                        if (result.get("commandResult") != null) {
                                            File postDiscoveryCommandOutput = new File(postDiscoveryNodeFolder
                                                    + File.separator + command.getName() + ".txt");
                                            try {
                                                FileUtils.writeStringToFile(postDiscoveryCommandOutput,
                                                        result.get("commandResult").toString());
                                            } catch (IOException e) {
                                                logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                                            }
                                        }
                                    } else {
                                        HashMap<String, Object> scriptParams = new HashMap<>();
                                        scriptParams.put("command", commandString);
                                        result = launcher.sendCommand(sendCommandScript.getValue(),
                                                scriptParams);

                                        if (result.get("commandResult") != null) {
                                            File postDiscoveryCommandOutput = new File(postDiscoveryNodeFolder
                                                    + File.separator + command.getName() + ".txt");
                                            try {
                                                FileUtils.writeStringToFile(postDiscoveryCommandOutput,
                                                        result.get("commandResult").toString());
                                            } catch (IOException e) {
                                                logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                                            }
                                        }

                                    }

                                }

                            }
                        }

                        launcher.close(logoutScript.getValue());
                    } catch (ResourceException e) {
                        logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                    } catch (ScriptException e) {
                        logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                        //To change body of catch statement use File | Settings | File Templates.
                    }
                }

            }
            sb.append("\n</report>");
            try {
                String report = new XmlFormatter().format(sb.toString());

                ByteArrayOutputStream finalReport = generateTableReport(
                        new ByteArrayInputStream(report.getBytes()));
                FileUtils.writeStringToFile(postDiscoveryReportOutput, finalReport.toString());
            } catch (IOException e) {
                logger.info(e); //To change body of catch statement use File | Settings | File Templates.
            }

        }
    }

    return sb;
}

From source file:org.matsim.integration.weekly.fundamentaldiagram.CreateAutomatedFDTest.java

private void run(final boolean isUsingFastCapacityUpdate) {

    MatsimRandom.reset();//from   w w  w. ja  v  a2s.  co m

    final Config config = ConfigUtils.createConfig();
    config.qsim().setMainModes(Arrays.asList(travelModes));
    config.qsim().setEndTime(14 * 3600);
    config.qsim().setLinkDynamics(linkDynamics);

    if (linkDynamics.equals(LinkDynamics.SeepageQ)) {
        config.qsim().setSeepModes(Arrays.asList("bike"));
        config.qsim().setSeepModeStorageFree(false);
        config.qsim().setRestrictingSeepage(true);
    }

    config.vspExperimental().setVspDefaultsCheckingLevel(VspDefaultsCheckingLevel.abort);
    config.qsim().setTrafficDynamics(trafficDynamics);

    config.qsim().setUsingFastCapacityUpdate(isUsingFastCapacityUpdate);

    // ---

    Scenario scenario = ScenarioUtils.loadScenario(config);
    createNetwork(scenario);

    storeVehicleTypeInfo();

    double networkDensity = 3. * (1000. / 7.5);

    double sumOfPCUInEachStep = 0.;

    //equal modal split run
    for (String mode : travelModes) {
        sumOfPCUInEachStep += modeVehicleTypes.get(mode).getPcuEquivalents() * getMinNumberOfAgentAtStart(mode);
    }
    ;

    int reduceNoOfDataPointsInPlot = 4; // 1--> will generate all possible data points;
    if (sumOfPCUInEachStep >= 3)
        reduceNoOfDataPointsInPlot = 1;

    int numberOfPoints = (int) Math.ceil(networkDensity / (reduceNoOfDataPointsInPlot * sumOfPCUInEachStep))
            + 5;

    List<Map<String, Integer>> points2Run = new ArrayList<>();

    for (int m = 1; m < numberOfPoints; m++) {
        Map<String, Integer> pointToRun = new HashMap<>();
        for (String mode : travelModes) {
            pointToRun.put(mode, getMinNumberOfAgentAtStart(mode) * m * reduceNoOfDataPointsInPlot);
        }

        double density = 0;
        for (String mode : pointToRun.keySet()) {
            double pcu = this.modeVehicleTypes.get(mode).getPcuEquivalents();
            density += pcu * pointToRun.get(mode);
        }

        if (density <= networkDensity + 10) {
            System.out.println("Number of Agents - \t" + pointToRun.toString());
            points2Run.add(pointToRun);
        }
    }

    Map<Double, Map<String, Tuple<Double, Double>>> outData = new HashMap<>();

    for (Map<String, Integer> point2run : points2Run) {

        System.out.println("\n \n \t \t Running points " + point2run.toString() + "\n \n");

        int count = 0;
        person2Mode.clear();

        for (String mode : point2run.keySet()) {
            for (int ii = 0; ii < point2run.get(mode); ii++) {
                person2Mode.put(Id.createPersonId(count++), mode);
            }
            this.mode2FlowData.get(modeVehicleTypes.get(mode).getId()).setnumberOfAgents(point2run.get(mode));
        }

        EventsManager events = EventsUtils.createEventsManager();
        globalFlowDynamicsUpdator = new GlobalFlowDynamicsUpdator(mode2FlowData);
        events.addHandler(globalFlowDynamicsUpdator);

        final QSim qSim = new QSim(scenario, events);
        ActivityEngine activityEngine = new ActivityEngine(events, qSim.getAgentCounter());
        qSim.addMobsimEngine(activityEngine);
        qSim.addActivityHandler(activityEngine);
        QNetsimEngine netsimEngine;
        //         if ( config.qsim().getTrafficDynamics()==TrafficDynamics.assignmentEmulating ) {
        //            QNetworkFactory networkFactory = new AssignmentEmulatingQLaneNetworkFactory(scenario,events) ;
        //            netsimEngine = new QNetsimEngine( qSim, networkFactory ) ;
        //         } else {
        netsimEngine = new QNetsimEngine(qSim);
        //         }
        qSim.addMobsimEngine(netsimEngine);
        qSim.addDepartureHandler(netsimEngine.getDepartureHandler());

        final Map<String, VehicleType> travelModesTypes = new HashMap<>();

        for (String mode : travelModes) {
            travelModesTypes.put(mode, modeVehicleTypes.get(mode));
        }

        AgentSource agentSource = new AgentSource() {
            @Override
            public void insertAgentsIntoMobsim() {
                for (Id<Person> personId : person2Mode.keySet()) {
                    String travelMode = person2Mode.get(personId);
                    double actEndTime = (MatsimRandom.getRandom().nextDouble()) * 900;

                    MobsimAgent agent = new MySimplifiedRoundAndRoundAgent(personId, actEndTime, travelMode);
                    qSim.insertAgentIntoMobsim(agent);

                    final Vehicle vehicle = VehicleUtils.getFactory().createVehicle(
                            Id.create(agent.getId(), Vehicle.class), travelModesTypes.get(travelMode));
                    final Id<Link> linkId4VehicleInsertion = Id.createLinkId("home");
                    qSim.createAndParkVehicleOnLink(vehicle, linkId4VehicleInsertion);
                }
            }
        };

        qSim.addAgentSource(agentSource);

        qSim.run();

        Map<String, Tuple<Double, Double>> mode2FlowSpeed = new HashMap<>();
        for (int i = 0; i < travelModes.length; i++) {

            Tuple<Double, Double> flowSpeed = new Tuple<>(
                    this.mode2FlowData.get(Id.create(travelModes[i], VehicleType.class)).getPermanentFlow(),
                    this.mode2FlowData.get(Id.create(travelModes[i], VehicleType.class))
                            .getPermanentAverageVelocity());
            mode2FlowSpeed.put(travelModes[i], flowSpeed);
            outData.put(globalFlowDynamicsUpdator.getGlobalData().getPermanentDensity(), mode2FlowSpeed);
        }
    }

    /*
     *   Basically overriding the helper.getOutputDirectory() method, such that,
     *   if file directory does not exists or same file already exists, remove and re-creates the whole dir hierarchy so that
     *   all existing files are re-written 
     *   else, just keep adding files in the directory.   
     *   This is necessary in order to allow writing different tests results from JUnit parameterization.
     */

    String outDir = "test/output/" + CreateAutomatedFDTest.class.getCanonicalName().replace('.', '/') + "/"
            + helper.getMethodName() + "/";
    String fileName = linkDynamics + "_" + trafficDynamics + ".png";

    String outFile;
    //TODO : what if, there exists some different directory (or files with old filename) => changing method name will keep collecting the old data.
    if (!new File(outDir).exists() || new File(outDir + fileName).exists()) {
        outFile = helper.getOutputDirectory() + fileName;
    } else {
        outFile = outDir + fileName;
    }

    //plotting data
    scatterPlot(outData, outFile);
}