Java Code Examples for java.util.Map#toString()

The following examples show how to use java.util.Map#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericDynamoDB.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Override
public void create(Entry entry) {
    readWriteLock.writeLock().lock();

    try {
        Map<String, AttributeValue> keys = createKey(entry);
        Map<String, AttributeValueUpdate> attributes = createAttributes(entry);
        Map<String, ExpectedAttributeValue> expected = expectNotExists();

        try {
            executeUpdate(keys, attributes, expected);
        } catch (ConditionalCheckFailedException e) {
            throw new AlreadyExistsException("DynamoDB store entry already exists:" + keys.toString());
        }
    } finally {
        readWriteLock.writeLock().unlock();
    }
}
 
Example 2
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
@Override
public String mediaUpload(String type, File f) {
    if (type == null)
        throw new NullPointerException("media type is NULL");
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("http://file.api.weixin.qq.com/cgi-bin/media/upload?token=%s&type=%s",
                               getAccessToken(),
                               type);
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("media upload file, resp code=" + resp.getStatus());
    Map<String, Object> map = (Map<String, Object>) Json.fromJson(resp.getReader());
    if (map != null
        && map.containsKey("errcode")
        && ((Number) map.get("errcode")).intValue() != 0) {
        throw new IllegalArgumentException(map.toString());
    }
    return map.get("media_id").toString();
}
 
Example 3
Source File: DashboardNodeService.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> deleteNode(Session session, String url, String projectId, String nodeType,
                                    Map<String, Object> requestBody) throws AppJointErrorException{
    Map<String, Object> element;
    try {
        HttpUtils httpUtils = new HttpUtils();
        requestBody.put("projectId", Integer.valueOf(projectId));
        logger.info("DashboardNodeServiceImpl request params is " + requestBody + ",nodeType:" + nodeType);
        logger.info("Dashboard url is " + url);
        String nodeId = requestBody.get("id").toString();
        String resultString = httpUtils.sendHttpDelete(session, url + dashboardUrl + "/" + nodeId, session.getUser());
        element = BDPJettyServerHelper.jacksonJson().readValue(resultString, Map.class);
        Map<String, Object> header = (Map<String, Object>) element.get("header");
        int code = (int) header.get("code");
        if (code != 200) {
            String errorMsg = header.toString();
            throw new AppJointErrorException(code, errorMsg);
        }
    }catch (Exception ex){
        throw new AppJointErrorException(90156,"Update Display AppJointNode Exception",ex);
    }
    return element;
}
 
Example 4
Source File: ParRegUtilVersionHelper.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/** The map that is used for comparing bucket copies (bucketMap) is too big in some runs to log in 
 *  exceptions, causing OOM problems. Return a string that eliminates the contents of the map
 *  but keeps the other information such as the member that hosts this bucket map.
 * @param bucketMap A bucket map from verifyBucketCopies
 * @return A toString() version of the bucket map with entries removed.
 */
private static String getBucketMapStr(Map<Object, Object> bucketMap) {
  String bucketMapStr = bucketMap.toString();
  StringBuilder reducedStr = new StringBuilder();
  int index = bucketMapStr.indexOf("{");
  if (index < 0) {
    return bucketMapStr;
  }
  reducedStr.append(bucketMapStr.substring(0, index));
  index = bucketMapStr.lastIndexOf("}");
  if (index < 0) {
    return bucketMapStr;
  }
  reducedStr.append(bucketMapStr.substring(index+1, bucketMapStr.length()));
  return reducedStr.toString();
}
 
Example 5
Source File: PluginConfig.java    From sylph with Apache License 2.0 6 votes vote down vote up
@Override
public String toString()
{
    Map<String, Object> map = Arrays.stream(this.getClass().getDeclaredFields())
            .collect(Collectors.toMap(Field::getName, field -> {
                field.setAccessible(true);
                try {
                    Object value = field.get(this);
                    return value == null ? "" : value;
                }
                catch (IllegalAccessException e) {
                    throw new RuntimeException("PluginConfig " + this.getClass() + " Serializable failed", e);
                }
            }));
    map.put("otherConfig", otherConfig);
    return map.toString();
}
 
Example 6
Source File: StandardBullhornData.java    From sdk-rest with MIT License 6 votes vote down vote up
/**
 * @param uriVariables
 * @param tryNumber
 * @param error
 * @throws RestApiException if tryNumber >= API_RETRY.
 */
protected boolean handleHttpStatusCodeError(Map<String, String> uriVariables, int tryNumber, HttpStatusCodeException error) {
    boolean isTooManyRequestsError = false;
    if (error.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        resetBhRestToken(uriVariables);
    } else if (error.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
        isTooManyRequestsError = true;
    }
    log.error(
            "HttpStatusCodeError making api call. Try number:" + tryNumber + " out of " + API_RETRY + ". Http status code: "
                    + error.getStatusCode() + ". Response body: " + error.getResponseBodyAsString(), error);
    if (tryNumber >= API_RETRY && !isTooManyRequestsError) {
        throw new RestApiException("HttpStatusCodeError making api call with url variables " + uriVariables.toString()
                + ". Http status code: " + error.getStatusCode().toString() + ". Response body: " + error == null ? ""
                : error.getResponseBodyAsString());
    }
    return isTooManyRequestsError;
}
 
Example 7
Source File: Pre90403Phase1CompatibilityTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testColorings() {
    Set<String> mimeTypes = new HashSet<String>(EditorSettings.getDefault().getMimeTypes());
    mimeTypes.add("");
    Set<String> profiles = EditorSettings.getDefault().getFontColorProfiles();
    
    for(String mimeType : mimeTypes) {
        for(String profile : profiles) {
            Collection<AttributeSet> colorings = EditorSettings.getDefault().getFontColorSettings(mimeType.length() == 0 ? new String[0] : new String [] { mimeType }).getAllFontColors(profile);
            Map<String, Map<String, String>> norm = normalize(colorings);
            
            String current = norm.toString();
            String golden = fromFile("C-" + mimeType.replace("/", "-") + "-" + profile);
            
            assertEquals("Wrong colorings for '" + mimeType + "', profile '" + profile + "'", golden, current);
        }
    }
}
 
Example 8
Source File: AtlasEntityStoreV2.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
@GraphTransaction
public AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships) throws AtlasBaseException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> getByUniqueAttribute({}, {})", entityType.getTypeName(), uniqAttributes);
    }

    AtlasVertex entityVertex = AtlasGraphUtilsV2.getVertexByUniqueAttributes(graph, entityType, uniqAttributes);

    EntityGraphRetriever entityRetriever = new EntityGraphRetriever(graph, typeRegistry, ignoreRelationships);

    AtlasEntityWithExtInfo ret = entityRetriever.toAtlasEntityWithExtInfo(entityVertex, isMinExtInfo);

    if (ret == null) {
        throw new AtlasBaseException(AtlasErrorCode.INSTANCE_BY_UNIQUE_ATTRIBUTE_NOT_FOUND, entityType.getTypeName(),
                uniqAttributes.toString());
    }

    AtlasAuthorizationUtils.verifyAccess(new AtlasEntityAccessRequest(typeRegistry, AtlasPrivilege.ENTITY_READ, new AtlasEntityHeader(ret.getEntity())), "read entity: typeName=", entityType.getTypeName(), ", uniqueAttributes=", uniqAttributes);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== getByUniqueAttribute({}, {}): {}", entityType.getTypeName(), uniqAttributes, ret);
    }

    return ret;
}
 
Example 9
Source File: ViewResolutionResultHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType mediaType, ServerWebExchange exchange) {
	ServerHttpResponse response = exchange.getResponse();
	if (mediaType != null) {
		response.getHeaders().setContentType(mediaType);
	}
	model = new TreeMap<>(model);
	String value = this.name + ": " + model.toString();
	ByteBuffer byteBuffer = ByteBuffer.wrap(value.getBytes(UTF_8));
	DataBuffer dataBuffer = new DefaultDataBufferFactory().wrap(byteBuffer);
	return response.writeWith(Flux.just(dataBuffer));
}
 
Example 10
Source File: GroovyRunnerRegistry.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    Map<String, GroovyRunner> map = getMap();
    readLock.lock();
    try {
        return map.toString();
    } finally {
        readLock.unlock();
    }
}
 
Example 11
Source File: Pre90403Phase1CompatibilityTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testKeybindings() {
    MimeTypesTracker tracker = MimeTypesTracker.get(KeyMapsStorage.ID, "Editors");
    Set<String> mimeTypes = new HashSet<String>(tracker.getMimeTypes());
    Set<String> profiles = EditorSettings.getDefault().getKeyMapProfiles();
    
    for(String profile : profiles) {
        List<MultiKeyBinding> commonKeybindings = EditorSettings.getDefault().getKeyBindingSettings(new String[0]).getKeyBindings(profile);
        Map<String, String> commonNorm = normalize(commonKeybindings);

        String commonCurrent = commonNorm.toString();
        String commonGolden = fromFile("KB--" + profile);

        assertEquals("Wrong keybindings for '', profile '" + profile + "'", commonGolden, commonCurrent);

        for(String mimeType : mimeTypes) {
            List<MultiKeyBinding> keybindings = EditorSettings.getDefault().getKeyBindingSettings(mimeType.length() == 0 ? new String[0] : new String [] { mimeType }).getKeyBindings(profile);

            Map<String, String> mimeTypeNorm = new TreeMap<String, String>();
            Map<String, String> norm = normalize(keybindings);
            
            mimeTypeNorm.putAll(commonNorm);
            mimeTypeNorm.putAll(norm);
            
            String current = mimeTypeNorm.toString();
            String golden = fromFile("KB-" + mimeType.replace("/", "-") + "-" + profile);
            
            assertEquals("Wrong keybindings for '" + mimeType + "', profile '" + profile + "'", golden, current);
        }
    }
}
 
Example 12
Source File: RangerPolicyResourceSignature.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
	// invalid/empty policy gets a deterministic signature as if it had an
	// empty resource string
	if (!isPolicyValidForResourceSignatureComputation()) {
		return "";
	}
	int type = RangerPolicy.POLICY_TYPE_ACCESS;
	if (_policy.getPolicyType() != null) {
		type = _policy.getPolicyType();
	}
	Map<String, ResourceSerializer> resources = new TreeMap<>();
	for (Map.Entry<String, RangerPolicyResource> entry : _policy.getResources().entrySet()) {
		String resourceName = entry.getKey();
		ResourceSerializer resourceView = new ResourceSerializer(entry.getValue());
		resources.put(resourceName, resourceView);
	}
	String resource = resources.toString();
	if (CollectionUtils.isNotEmpty(_policy.getValiditySchedules())) {
		resource += _policy.getValiditySchedules().toString();
	}
	if (_policy.getPolicyPriority() != null && _policy.getPolicyPriority() != RangerPolicy.POLICY_PRIORITY_NORMAL) {
		resource += _policy.getPolicyPriority();
	}
	if (!StringUtils.isEmpty(_policy.getZoneName())) {
	    resource += _policy.getZoneName();
          }

	if (_policy.getConditions() != null) {
		CustomConditionSerialiser customConditionSerialiser = new CustomConditionSerialiser(_policy.getConditions());
		resource += customConditionSerialiser.toString();
	}

	String result = String.format("{version=%d,type=%d,resource=%s}", _SignatureVersion, type, resource);
	return result;
}
 
Example 13
Source File: AtlasGraphUtilsV1.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
public static AtlasVertex getVertexByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> attrValues) throws AtlasBaseException {
    AtlasVertex vertex = findByUniqueAttributes(entityType, attrValues);

    if (vertex == null) {
        throw new AtlasBaseException(AtlasErrorCode.INSTANCE_BY_UNIQUE_ATTRIBUTE_NOT_FOUND, entityType.getTypeName(),
                                     attrValues.toString());
    }

    return vertex;
}
 
Example 14
Source File: AtlasEntityStoreV1.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
@GraphTransaction
public EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes)
        throws AtlasBaseException {

    if (MapUtils.isEmpty(uniqAttributes)) {
        throw new AtlasBaseException(AtlasErrorCode.INSTANCE_BY_UNIQUE_ATTRIBUTE_NOT_FOUND, uniqAttributes.toString());
    }

    final AtlasVertex vertex = AtlasGraphUtilsV1.findByUniqueAttributes(entityType, uniqAttributes);
    Collection<AtlasVertex> deletionCandidates = new ArrayList<>();

    if (vertex != null) {
        deletionCandidates.add(vertex);
    } else {
        if (LOG.isDebugEnabled()) {
            // Entity does not exist - treat as non-error, since the caller
            // wanted to delete the entity and it's already gone.
            LOG.debug("Deletion request ignored for non-existent entity with uniqueAttributes " + uniqAttributes);
        }
    }

    EntityMutationResponse ret = deleteVertices(deletionCandidates);

    // Notify the change listeners
    entityChangeNotifier.onEntitiesMutated(ret, false);

    return ret;
}
 
Example 15
Source File: DefaultActionPrototypeProviderTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
static void assertPrototypes(
		Map<ActionParameterTypes, List<InferredStandardParameter>> elements,
		Object[]... expected) {
	Collection<Object[]> expectedElements = new ArrayList<>();
	for (int i = 0; i < expected.length; ++i) {
		expectedElements.add(expected[i]);
	}
	for (List<InferredStandardParameter> parameters : elements.values()) {
		assertPrototypes(parameters, expectedElements, expected);
	}
	if (!expectedElements.isEmpty()) {
		throw new AssertionFailedError(
				"Not same prototypes", expectedElements.toString(), elements.toString());
	}
}
 
Example 16
Source File: DynamoDBEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureEncryptedAttributesUnmodified() throws GeneralSecurityException {
    Map<String, AttributeValue> encryptedAttributes =
            encryptor.encryptAllFieldsExcept(Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
    String encryptedString = encryptedAttributes.toString();
    encryptor.decryptAllFieldsExcept(Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version");

    assertEquals(encryptedString, encryptedAttributes.toString());
}
 
Example 17
Source File: MetricsRecord.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  // Pack metrics as a map
  Map<String, String> metricsMap = new HashMap<String, String>();
  for (MetricsInfo metricsInfo : getMetrics()) {
    metricsMap.put(metricsInfo.getName(), metricsInfo.getValue());
  }

  // Pack exceptions as a list of map
  LinkedList<Object> exceptionsList = new LinkedList<Object>();
  for (ExceptionInfo exceptionInfo : getExceptions()) {
    Map<String, Object> exception = new HashMap<String, Object>();
    exception.put("firstTime", exceptionInfo.getFirstTime());
    exception.put("lastTime", exceptionInfo.getLastTime());
    exception.put("logging", exceptionInfo.getLogging());
    exception.put("stackTrace", exceptionInfo.getStackTrace());
    exception.put("count", exceptionInfo.getCount());
    exceptionsList.add(exception);
  }

  // Pack the whole MetricsRecord as a map
  Map<String, Object> result = new HashMap<String, Object>();
  result.put("timestamp", getTimestamp());
  result.put("source", getSource());
  result.put("context", getContext());
  result.put("metrics", metricsMap);
  result.put("exceptions", exceptionsList);

  return result.toString();
}
 
Example 18
Source File: WFUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public static String toString(Object bean) {
	Map<String, Object> m = BeanUtil.getProperties(bean);
	m.remove("id");
	m.remove("tableId");
	m.remove("currStepIndex");
	m.remove("PK");
	m.remove("class");
	
	return m.toString();
}
 
Example 19
Source File: ChangedTableDescription.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String toString(TableName oldName, TableName newName, boolean newGroup, ParentChange groupChange, Map<String,String> preservedIndexMap) {
    return oldName + "=" + newName + "[newGroup=" + newGroup + "][parentChange=" + groupChange + "]" + preservedIndexMap.toString();
}
 
Example 20
Source File: XMLFileSystemTestHid.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static String computeToString(Map whatIsYourToString) {
    return whatIsYourToString.toString();
}