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 testTypeMapWithMapValueDecode() {
    Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
    Map<String, String> nested = new HashMap<String, String>();
    nested.put("name", "me");
    map.put("key", nested);

    AbstractJsonEncoderDecoder<Map<String, String>> valueEncoder = AbstractNestedJsonEncoderDecoder
            .mapEncoderDecoder(AbstractJsonEncoderDecoder.STRING, AbstractJsonEncoderDecoder.STRING,
                    Json.Style.DEFAULT);

    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder//from   w w  w.ja v a  2 s  . co  m
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, valueEncoder, Json.Style.DEFAULT),
                            valueEncoder, Json.Style.DEFAULT)
                    .toString());

    // the JETTISON enoding it is important to use the special encoder with String keys
    valueEncoder = AbstractNestedJsonEncoderDecoder.mapEncoderDecoder(AbstractJsonEncoderDecoder.STRING,
            Json.Style.JETTISON_NATURAL);

    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder
                    .toMap(AbstractJsonEncoderDecoder.toJSON(map, valueEncoder, Json.Style.JETTISON_NATURAL),
                            valueEncoder, Json.Style.JETTISON_NATURAL)
                    .toString());
}

From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java

private void queryPageInfo(String lang, String pageId, PageInfo page) {
    Map<String, Object> params = new HashMap<>();
    params.put("format", "json");
    params.put("action", "query");
    params.put("pageids", pageId);
    params.put("prop", "info");
    try {//from w  w  w . j a  v a2s  .  c o m
        String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?"
                + StringUtils.mapToURLParameters(params);
        URL url = new URL(urlString);

        JSONObject response = queryForJSONResponse(url);
        try {
            JSONObject pageInfo = response.getJSONObject("query").getJSONObject("pages").getJSONObject(pageId);
            page.setTitle(pageInfo.getString("title"));
            page.setSize(pageInfo.getLong("length"));
            page.setLastRevisionId(Long.toString(pageInfo.getLong("lastrevid")));

        } catch (JSONException ex) {
            LogHandler.log(this, LogLevel.WARN,
                    "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage());
        }

    } catch (UnsupportedEncodingException ex) {
        LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage());
    } catch (MalformedURLException ex) {
        LogHandler.log(this, LogLevel.ERROR, ex);
    } catch (IOException ex) {
        LogHandler.log(this, LogLevel.ERROR, ex);
    }
}

From source file:com.redsqirl.workflow.server.connect.HDFSInterface.java

/**
 * Get the properties of a path/*w w  w  .  ja  v a2 s  .  c  o  m*/
 * 
 * @param path
 * @return Map of properties
 * @throws RemoteException
 */
@Override
public Map<String, String> getProperties(String path) throws RemoteException {

    logger.debug("getProperties");

    Map<String, String> prop = new LinkedHashMap<String, String>();
    try {
        logger.debug(0);
        logger.debug("sys_namenode PathHDFS: " + NameNodeVar.get());
        FileSystem fs = NameNodeVar.getFS();
        FileStatus stat = fs.getFileStatus(new Path(path));
        prop = getProperties(path, stat);
        logger.debug(1);
    } catch (IOException e) {
        logger.error("Error in filesystem");
        logger.error(e, e);
    } catch (Exception e) {
        logger.error("Not expected exception: " + e);
        logger.error(e.getMessage(), e);
    }
    logger.debug("Properties of " + path + ": " + prop.toString());
    return prop;
}

From source file:org.wso2.carbon.apimgt.impl.workflow.APIStateChangeWSWorkflowExecutor.java

/**
 * Read the user provided lifecycle states for the approval task. These are provided in the workflow-extension.xml
 *///from www. j a  v  a 2 s  .c  o  m
private Map<String, List<String>> getSelectedStatesToApprove() {
    Map<String, List<String>> stateAction = new HashMap<String, List<String>>();
    // exract selected states from stateList and populate the map
    if (stateList != null) {
        // list will be something like ' Created:Publish,Created:Deploy as a Prototype,Published:Block ' String
        // It will have State:action pairs
        String[] statelistArray = stateList.split(",");
        for (int i = 0; i < statelistArray.length; i++) {
            String[] stateActionArray = statelistArray[i].split(":");
            if (stateAction.containsKey(stateActionArray[0].toUpperCase())) {
                ArrayList<String> actionList = (ArrayList<String>) stateAction
                        .get(stateActionArray[0].toUpperCase());
                actionList.add(stateActionArray[1]);
            } else {
                ArrayList<String> actionList = new ArrayList<String>();
                actionList.add(stateActionArray[1]);
                stateAction.put(stateActionArray[0].toUpperCase(), actionList);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("selected states: " + stateAction.toString());
    }
    return stateAction;
}

From source file:com.prey.net.PreyRestHttpClient.java

public PreyHttpResponse postAutentication(String url, Map<String, String> params, PreyConfig preyConfig,
        List<EntityFile> entityFiles) throws IOException {
    HttpPost method = new HttpPost(url);
    method.setHeader("Accept", "*/*");
    method.addHeader("Authorization", "Basic " + getCredentials(preyConfig.getApiKey(), "X"));

    SimpleMultipartEntity entity = new SimpleMultipartEntity();
    for (Iterator<Map.Entry<String, String>> it = params.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> entry = it.next();
        String key = entry.getKey();
        String value = entry.getValue();
        entity.addPart(key, value);// w w w .jav a 2  s  .  c om
    }
    for (int i = 0; i < entityFiles.size(); i++) {
        EntityFile entityFile = entityFiles.get(i);
        boolean isLast = ((i + 1) == entityFiles.size() ? true : false);
        //         PreyLogger.d("["+i+"]type:"+entityFile.getType()+" name:"+entityFile.getName()+ " File:" + entityFile.getFile() + " MimeType:" + entityFile.getMimeType()+" isLast:"+isLast);
        entity.addPart(entityFile.getType(), entityFile.getName(), entityFile.getFile(),
                entityFile.getMimeType(), isLast);
    }

    method.setEntity(entity);
    PreyLogger.d("Sending using 'POST' - URI: " + url + " - parameters: " + params.toString());
    httpclient.setRedirectHandler(new NotRedirectHandler());
    HttpResponse httpResponse = httpclient.execute(method);
    PreyHttpResponse response = new PreyHttpResponse(httpResponse);
    //PreyLogger.d("Response from server: " + response.toString());
    return response;
}

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

public void testTypeMapWithListValueDecodeAndComplexKey() {
    Map<Email, List<String>> map = new HashMap<Email, List<String>>();
    Email email = new Email();
    email.email = "me@example.com";
    email.name = "me";
    map.put(email, new ArrayList<String>(Arrays.asList("me and the corner")));
    AbstractJsonEncoderDecoder<Email> keyEncoder = GWT.create(EmailCodec.class);
    AbstractJsonEncoderDecoder<List<String>> valueEncoder = AbstractNestedJsonEncoderDecoder
            .listEncoderDecoder(AbstractJsonEncoderDecoder.STRING);

    assertEquals(map.toString(),
            AbstractJsonEncoderDecoder//from w  w w .j  a  v a  2s  .co m
                    .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:jeeves.server.JeevesEngine.java

/** Setup resources from the resource element (config.xml)
  *//*from ww  w  .  ja v  a  2  s.  c  o  m*/

@SuppressWarnings("unchecked")
private void initResources(Element resources, String file) {
    boolean resourceFound = false;
    info("Initializing resources...");

    List<Element> resList = resources.getChildren(ConfigFile.Resources.Child.RESOURCE);

    for (int i = 0; i < resList.size(); i++) {
        Element res = resList.get(i);

        String name = res.getChildText(ConfigFile.Resource.Child.NAME);
        String provider = res.getChildText(ConfigFile.Resource.Child.PROVIDER);
        Element config = res.getChild(ConfigFile.Resource.Child.CONFIG);
        Element activator = res.getChild(ConfigFile.Resource.Child.ACTIVATOR);

        String enabled = res.getAttributeValue(ConfigFile.Resource.Attr.ENABLED);

        if ((enabled == null) || enabled.equals("true")) {
            info("   Adding resource : " + name);

            resourceFound = true;
            try {
                if (activator != null) {
                    String clas = activator.getAttributeValue(ConfigFile.Activator.Attr.CLASS);

                    info("      Loading activator  : " + clas);
                    Activator activ = (Activator) Class.forName(clas).newInstance();

                    info("      Starting activator : " + clas);
                    activ.startup(appPath, activator);

                    vActivators.add(activ);
                }

                providerMan.register(provider, name, config);

                // Try and open a resource from the provider
                providerMan.getProvider(name).open();

                if (name.equals(dbResourceProviderName)) {
                    Dbms dbms = null;
                    try {
                        dbms = (Dbms) providerMan.getProvider(name).open();
                    } finally {
                        if (dbms != null)
                            providerMan.getProvider(name).close(dbms);
                    }
                }
            } catch (Exception e) {
                Map<String, String> errors = new HashMap<String, String>();
                String eS = "Raised exception while initializing resource " + name + " in " + file
                        + ". Skipped.";
                error(eS);
                errors.put("Error", eS);
                error("   Resource  : " + name);
                errors.put("Resource", name);
                error("   Provider  : " + provider);
                errors.put("Provider", provider);
                error("   Exception : " + e);
                errors.put("Exception", e.toString());
                error("   Message   : " + e.getMessage());
                errors.put("Message", e.getMessage());
                error("   Stack     : " + Util.getStackTrace(e));
                errors.put("Stack", Util.getStackTrace(e));
                error(errors.toString());
                serviceMan.setStartupErrors(errors);
            }
        }
    }

    if (!resourceFound) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("Error", "No database resources found to initialize - check " + file);
        error(errors.toString());
        serviceMan.setStartupErrors(errors);
    }
}

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

private void handleRemoveTemplateResponse(final RemoveTemplatesResponse resposne, final String templateName)
        throws RestErrorException {
    final Map<String, String> failedToRemoveFromHosts = resposne.getFailedToRemoveFromHosts();
    final List<String> successfullyRemovedFromHosts = resposne.getSuccessfullyRemovedFromHosts();

    // check if some REST instances failed to remove the template
    if (!failedToRemoveFromHosts.isEmpty()) {
        String message = "[removeTemplate] - failed to remove template [" + templateName + "] from: "
                + failedToRemoveFromHosts;
        if (!successfullyRemovedFromHosts.isEmpty()) {
            message += ". Succeeded to remove the template from: " + successfullyRemovedFromHosts;
        }//from   ww w  .  java2s .c o  m
        log(Level.WARNING, message);
        throw new RestErrorException(CloudifyErrorMessages.FAILED_REMOVE_TEMPLATE.getName(), templateName,
                failedToRemoveFromHosts.toString());
    }
}

From source file:org.mmadsen.sim.transmissionlab.analysis.ClusterTraitFrequencyFileSnapshot.java

public void process() {
    this.log.debug("Entering ClusterTraitFrequencyFileSnapshot.process()");
    IAgentPopulation population = this.model.getPopulation();
    // return immediately if the population isn't clustered, because we can't do anything.
    if (population.isPopulationClustered() == false) {
        return;//from   w w  w  .j  a  va 2  s  . co  m
    }

    /** nothing below here is executed if the population isn't structured into discrete clusters **/

    // manual hack to ensure that we only record files every N ticks
    if (this.intervalCount != 1) {
        this.intervalCount--;
        return;
    }

    int modelTick = (int) Math.round(this.model.getTickCount());
    int numClusters = population.getNumClusters();
    this.curSortedTraitCounts.clear();
    Map<Integer, Integer> totalTraitsAcrossClusters = new TreeMap<Integer, Integer>();

    for (int c = 0; c < numClusters; c++) {
        this.log.debug("Processing cluster #" + c);

        List<IAgent> agentList = population.getAgentListForCluster(c);

        this.freqMap.clear();
        this.curSortedTraitCounts.add(new ArrayList<TraitCount>());

        // fill up the frequency map
        CollectionUtils.forAllDo(agentList, this.freqCounter);

        // At this point, we've got all the counts, so let's prepare a sorted List
        // of TraitCounts for further processing
        ArrayList<TraitCount> refClusterCount = this.curSortedTraitCounts.get(c);
        refClusterCount.addAll(this.freqMap.values());

        // now we count traits ACROSS all cluster - we'll be interested in whether some
        // traits spread to more than 1 cluster.
        for (TraitCount tc : refClusterCount) {
            this.log.debug("analyzing refClusterCount for: " + tc.getTrait());
            int trait = tc.getTrait();
            if (totalTraitsAcrossClusters.containsKey(trait)) {
                int cnt = totalTraitsAcrossClusters.get(trait);
                cnt++;
                totalTraitsAcrossClusters.put(trait, cnt);
            } else {
                totalTraitsAcrossClusters.put(trait, 1);
            }
        }
        this.log.debug("totalTraitsAcrossClusters: " + totalTraitsAcrossClusters.toString());

    }

    this.sharedClusterTraitCountsByTick.put(modelTick, totalTraitsAcrossClusters);
    this.model.storeSharedObject(TRAITS_SHARED_ACROSS_CLUSTER_COUNTS, this.sharedClusterTraitCountsByTick);

    this.log.debug("recording file snapshot at " + this.model.getTickCount());

    this.recordStats(this.curSortedTraitCounts);

    this.intervalCount = this.recordingInterval;
    this.log.debug("Leaving TraitFrequencyFileSnapshot.process()");
}

From source file:org.apache.sqoop.connector.idf.TestCSVIntermediateDataFormat.java

@Test
public void testMapWithComplexMapValueWithObjectArrayInObjectArrayOut() {
    Schema schema = new Schema("test");
    schema.addColumn(//from  w w  w.j av a  2s. c o m
            new org.apache.sqoop.schema.type.Map("1", new Text("key"), new Array("value", new Text("text"))));
    schema.addColumn(new org.apache.sqoop.schema.type.Text("2"));
    dataFormat = new CSVIntermediateDataFormat(schema);
    Map<Object, Object> givenMap = new HashMap<Object, Object>();
    List<String> stringList = new ArrayList<String>();
    stringList.add("A");
    stringList.add("A");
    Map<String, List<String>> anotherMap = new HashMap<String, List<String>>();
    anotherMap.put("anotherKey", stringList);
    givenMap.put("testKey", anotherMap);
    // create an array inside the object array
    Object[] data = new Object[2];
    data[0] = givenMap;
    data[1] = "text";
    dataFormat.setObjectData(data);
    @SuppressWarnings("unchecked")
    Map<Object, Object> expectedMap = (Map<Object, Object>) dataFormat.getObjectData()[0];
    assertEquals(givenMap.toString(), expectedMap.toString());
    assertEquals("text", dataFormat.getObjectData()[1]);
}