Java Code Examples for java.util.Map#get()
The following examples show how to use
java.util.Map#get() .
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: NodeMap_first.java From util4j with Apache License 2.0 | 6 votes |
public void testMap(byte[] data) { //map读写测试 Map<Integer,Byte> map=new HashMap<>(); long t=System.currentTimeMillis(); for(int i=0;i<data.length;i++) { map.put(i,data[i]); } long m1=System.currentTimeMillis()-t; t=System.currentTimeMillis(); for(int i=0;i<data.length;i++) { map.get(i); } long m2=System.currentTimeMillis()-t; System.out.println("map写:"+m1+",map读:"+m2); }
Example 2
Source File: FinishScheduleLessonJob.java From lams with GNU General Public License v2.0 | 6 votes |
@Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { IMonitoringFullService monitoringService = getMonitoringService(context); //getting gate id set from scheduler Map properties = context.getJobDetail().getJobDataMap(); long lessonId = ((Long) properties.get(MonitoringConstants.KEY_LESSON_ID)).longValue(); Integer userId = (Integer) properties.get(MonitoringConstants.KEY_USER_ID); if (log.isDebugEnabled()) { log.debug("Lesson [" + lessonId + "] is suspending..."); } monitoringService.suspendLesson(lessonId, userId, false); if (log.isDebugEnabled()) { log.debug("Lesson [" + lessonId + "] suspended"); } }
Example 3
Source File: MessageLocationReplacers.java From zap-extensions with Apache License 2.0 | 6 votes |
private static <T> T getFactory( Map<Class<? extends MessageLocation>, T> factories, Class<?> clazz) { if (!MessageLocation.class.isAssignableFrom(clazz)) { return null; } T factory = factories.get(clazz); if (factory != null) { return factory; } factory = getFactory(factories, clazz.getSuperclass()); if (factory != null) { return factory; } for (Class<?> interfaceClazz : clazz.getInterfaces()) { factory = getFactory(factories, interfaceClazz); if (factory != null) { return factory; } } return null; }
Example 4
Source File: SimulatedFSDataset.java From big-c with Apache License 2.0 | 6 votes |
@Override // FsDatasetSpi public String recoverClose(ExtendedBlock b, long newGS, long expectedBlockLen) throws IOException { final Map<Block, BInfo> map = getMap(b.getBlockPoolId()); BInfo binfo = map.get(b.getLocalBlock()); if (binfo == null) { throw new ReplicaNotFoundException("Block " + b + " is not valid, and cannot be appended to."); } if (!binfo.isFinalized()) { binfo.finalizeBlock(b.getBlockPoolId(), binfo.getNumBytes()); } map.remove(b.getLocalBlock()); binfo.theBlock.setGenerationStamp(newGS); map.put(binfo.theBlock, binfo); return binfo.getStorageUuid(); }
Example 5
Source File: FilterProfile.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** determines whether there is any remaining interest for the given identifier */ public boolean hasInterestFor(Object inputClientID) { Long clientID; if (inputClientID instanceof Long) { clientID = (Long)inputClientID; } else { Map<Object, Long> cids = clientMap.realIDs; // read clientID = cids.get(inputClientID); if (clientID == null) { return false; } } return this.hasAllKeysInterestFor(clientID, true) || this.hasKeysOfInterestFor(clientID, true) || this.hasRegexInterestFor(clientID, true) || this.hasFilterInterestFor(clientID, true) || this.hasKeysOfInterestFor(clientID, false) || this.hasRegexInterestFor(clientID, false) || this.hasAllKeysInterestFor(clientID, false) || this.hasFilterInterestFor(clientID, false); }
Example 6
Source File: UrlBuilder.java From lumongo with Apache License 2.0 | 5 votes |
public static Map<String, List<String>> buildListParamMap(String queryString) { if (queryString != null) { //places don't start with ? and the substring below removes the first char if (!queryString.startsWith("?")) { queryString = "?" + queryString; } Map<String, List<String>> out = new HashMap<String, List<String>>(); if (queryString.length() > 1) { String qs = queryString.substring(1); for (String kvPair : qs.split("&")) { String[] kv = kvPair.split("=", 2); if (kv[0].length() == 0) { continue; } List<String> values = out.get(kv[0]); if (values == null) { values = new ArrayList<String>(); out.put(kv[0], values); } values.add(kv.length > 1 ? URL.decodeQueryString(kv[1]) : ""); } } for (Map.Entry<String, List<String>> entry : out.entrySet()) { entry.setValue(Collections.unmodifiableList(entry.getValue())); } out = Collections.unmodifiableMap(out); return out; } return Collections.emptyMap(); }
Example 7
Source File: SessionDataStore.java From sofa-registry with Apache License 2.0 | 5 votes |
@Override public Publisher queryById(String registerId, String dataInfoId) { Map<String, Publisher> publishers = registry.get(dataInfoId); if (publishers == null) { LOGGER.warn("Publisher is not registered for dataInfoId: {}", dataInfoId); return null; } return publishers.get(registerId); }
Example 8
Source File: ExtraBindingTargetUtil.java From dart with Apache License 2.0 | 5 votes |
public void createBindingTargetTrees(Map<TypeElement, ExtraBindingTarget> targetClassMap) { final Set<TypeElement> targetTypeElements = targetClassMap.keySet(); for (TypeElement typeElement : targetTypeElements) { TypeElement parentTypeElement = compilerUtil.findParent(typeElement, targetTypeElements); if (parentTypeElement != null) { final ExtraBindingTarget target = targetClassMap.get(typeElement); final ExtraBindingTarget parentTarget = targetClassMap.get(parentTypeElement); target.parentPackage = parentTarget.classPackage; target.parentClass = parentTarget.className; parentTarget.addChild(typeElement); } } checkForParentsOutside(targetClassMap); }
Example 9
Source File: ChannelPropertiesFactory.java From pinpoint with Apache License 2.0 | 5 votes |
private Map<Object, Object> copyCustomProperty(Map<Object, Object> properties) { if (ArrayUtils.isEmpty(customKey)) { return Collections.emptyMap(); } final Map<Object, Object> copy = new HashMap<Object, Object>(); for (Object key : customKey) { final Object value = properties.get(key); if (value != null) { copy.put(key, value); } } return copy; }
Example 10
Source File: ReviewResponsibilityMaintainable.java From rice with Educational Community License v2.0 | 5 votes |
@Override public void setupNewFromExisting(MaintenanceDocument document, Map<String, String[]> parameters) { String docTypeName = ""; String routeNodeName = ""; ReviewResponsibilityBo reviewResponsibilityBo = (ReviewResponsibilityBo) document.getNewMaintainableObject().getDataObject(); initializeResponsibilityId(document.getDocumentBusinessObject()); reviewResponsibilityBo.setActive(true); for (String paramName : parameters.keySet()) { String[] parameterValues = parameters.get(paramName); if (paramName.equals(DOCUMENT_TYPE_NAME)) { if (parameterValues.length > 0) { docTypeName = parameterValues[0]; } } if (paramName.equals(ROUTE_NODE_NAME)) { if (parameterValues.length > 0) { routeNodeName = parameterValues[0]; } } } if (StringUtils.isNotEmpty(docTypeName) && StringUtils.isNotEmpty(routeNodeName)) { reviewResponsibilityBo.setDocumentTypeName(docTypeName); reviewResponsibilityBo.setRouteNodeName(routeNodeName); } document.getNewMaintainableObject().setDataObject(reviewResponsibilityBo); }
Example 11
Source File: Engine.java From Jatalog with Apache License 2.0 | 5 votes |
protected static Collection<Rule> getDependentRules(IndexedSet<Expr,String> facts, Map<String, Collection<Rule>> dependents) { Set<Rule> dependantRules = new HashSet<>(); for(String predicate : facts.getIndexes()) { Collection<Rule> rules = dependents.get(predicate); if(rules != null) { dependantRules.addAll(rules); } } return dependantRules; }
Example 12
Source File: MoviePrinter.java From SAX with GNU General Public License v2.0 | 5 votes |
private static double[] toVector(Map<String, Integer> shingledData1) { TreeSet<String> keys = new TreeSet<String>(shingledData1.keySet()); double[] res = new double[shingledData1.size()]; int counter = 0; for (String shingle : keys) { Integer value = shingledData1.get(shingle); res[counter] = value; counter++; } return res; }
Example 13
Source File: SIDCacheImpl.java From jcifs-ng with GNU Lesser General Public License v2.1 | 4 votes |
/** * * {@inheritDoc} * * @see jcifs.SidResolver#getLocalGroupsMap(jcifs.CIFSContext, java.lang.String, int) */ @Override public Map<jcifs.SID, List<jcifs.SID>> getLocalGroupsMap ( CIFSContext tc, String authorityServerName, int flags ) throws CIFSException { SID domSid = getServerSid(tc, authorityServerName); synchronized ( this.sidCache ) { try ( DcerpcHandle handle = DcerpcHandle.getHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]", tc) ) { samr.SamrSamArray sam = new samr.SamrSamArray(); try ( SamrPolicyHandle policyHandle = new SamrPolicyHandle(handle, authorityServerName, 0x02000000); SamrDomainHandle domainHandle = new SamrDomainHandle(handle, policyHandle, 0x02000000, domSid) ) { MsrpcEnumerateAliasesInDomain rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, 0xFFFF, sam); handle.sendrecv(rpc); if ( rpc.retval != 0 ) { throw new SmbException(rpc.retval, false); } Map<jcifs.SID, List<jcifs.SID>> map = new HashMap<>(); for ( int ei = 0; ei < rpc.sam.count; ei++ ) { samr.SamrSamEntry entry = rpc.sam.entries[ ei ]; SID[] mems = getGroupMemberSids(tc, authorityServerName, domSid, entry.idx, flags); SID groupSid = new SID(domSid, entry.idx); groupSid.type = jcifs.SID.SID_TYPE_ALIAS; groupSid.domainName = domSid.getDomainName(); groupSid.acctName = ( new UnicodeString(entry.name, false) ).toString(); for ( int mi = 0; mi < mems.length; mi++ ) { List<jcifs.SID> groups = map.get(mems[ mi ]); if ( groups == null ) { groups = new ArrayList<>(); map.put(mems[ mi ], groups); } if ( !groups.contains(groupSid) ) groups.add(groupSid); } } return map; } } catch ( IOException e ) { throw new CIFSException("Failed to resolve groups", e); } } }
Example 14
Source File: FDWT.java From warp10-platform with Apache License 2.0 | 4 votes |
@Override protected Object gtsOp(Map<String, Object> params, GeoTimeSerie gts) throws WarpScriptException { Wavelet wavelet = (Wavelet) params.get(WAVELET); // // Check GTS type // if (TYPE.DOUBLE != gts.getType() && TYPE.LONG != gts.getType()) { throw new WarpScriptException(getName() + " can only be applied to numeric Geo Time Series."); } // // Check GTS size, MUST be a power of 2 // int len = gts.size(); if (0 != (len & (len - 1))) { throw new WarpScriptException(getName() + " can only operate on Geo Time Series whose length is a power of 2."); } // // Sort GTS // GTSHelper.sort(gts); // // Extract ticks, locations, elevations, values // double[] values = GTSHelper.getValuesAsDouble(gts); double[] hilbert = FWT.forward(wavelet, values); GeoTimeSerie transformed = gts.cloneEmpty(); for (int i = 0; i < len; i++) { GTSHelper.setValue(transformed, GTSHelper.tickAtIndex(gts, i), GTSHelper.locationAtIndex(gts, i), GTSHelper.elevationAtIndex(gts, i), hilbert[i], false); } return transformed; }
Example 15
Source File: ListAttachments.java From cs-actions with Apache License 2.0 | 4 votes |
@Action(name = "Retrieve a list of attachment objects attached to a message.", outputs = { @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC), @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC), @Output(value = DOCUMENT, description = DOCUMENT_DESC), @Output(value = ATTACHMENT_ID, description = ATTACHMENT_ID_DESC), @Output(value = STATUS_CODE, description = STATUS_CODE_DESC) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, description = FAILURE_DESC) }) public Map<String, String> execute(@Param(value = AUTH_TOKEN, required = true, description = AUTH_TOKEN_DESC) String authToken, @Param(value = USER_PRINCIPAL_NAME, description = USER_PRINCIPAL_NAME_DESC) String userPrincipalName, @Param(value = USER_ID, description = USER_ID_DESC) String userId, @Param(value = MESSAGE_ID, required = true, description = MESSAGE_ID_DESC) String messageId, @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost, @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort, @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword, @Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword, @Param(value = CONNECT_TIMEOUT, description = CONNECT_TIMEOUT_DESC) String connectTimeout, @Param(value = SOCKET_TIMEOUT, description = SOCKET_TIMEOUT_DESC) String socketTimeout, @Param(value = KEEP_ALIVE, description = KEEP_ALIVE_DESC) String keepAlive, @Param(value = CONNECTIONS_MAX_PER_ROUTE, description = CONN_MAX_ROUTE_DESC) String connectionsMaxPerRoute, @Param(value = CONNECTIONS_MAX_TOTAL, description = CONN_MAX_TOTAL_DESC) String connectionsMaxTotal, @Param(value = RESPONSE_CHARACTER_SET, description = RESPONSC_CHARACTER_SET_DESC) String responseCharacterSet) { userPrincipalName = defaultIfEmpty(userPrincipalName, EMPTY); userId = defaultIfEmpty(userId, EMPTY); messageId = defaultIfEmpty(messageId, EMPTY); proxyHost = defaultIfEmpty(proxyHost, EMPTY); proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT); proxyUsername = defaultIfEmpty(proxyUsername, EMPTY); proxyPassword = defaultIfEmpty(proxyPassword, EMPTY); trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE); x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT); trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE); trustPassword = defaultIfEmpty(trustPassword, CHANGEIT); connectTimeout = defaultIfEmpty(connectTimeout, ZERO); socketTimeout = defaultIfEmpty(socketTimeout, ZERO); keepAlive = defaultIfEmpty(keepAlive, BOOLEAN_FALSE); connectionsMaxPerRoute = defaultIfEmpty(connectionsMaxPerRoute, CONNECTIONS_MAX_PER_ROUTE_CONST); connectionsMaxTotal = defaultIfEmpty(connectionsMaxTotal, CONNECTIONS_MAX_TOTAL_CONST); responseCharacterSet = defaultIfEmpty(responseCharacterSet, UTF8); final List<String> exceptionMessages = verifyCommonInputs(userPrincipalName, userId, proxyPort, trustAllRoots, connectTimeout, socketTimeout, keepAlive, connectionsMaxPerRoute, connectionsMaxTotal); if (!exceptionMessages.isEmpty()) { return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE)); } try { final Map<String, String> result = listAttachment(ListAttachmentsInputs.builder() .messageId(messageId) .commonInputs(Office365CommonInputs.builder() .authToken(authToken) .connectionsMaxPerRoute(connectionsMaxPerRoute) .connectionsMaxTotal(connectionsMaxTotal) .proxyHost(proxyHost) .proxyPort(proxyPort) .proxyUsername(proxyUsername) .proxyPassword(proxyPassword) .keepAlive(keepAlive) .responseCharacterSet(responseCharacterSet) .connectTimeout(connectTimeout) .trustAllRoots(trustAllRoots) .userId(userId) .userPrincipalName(userPrincipalName) .x509HostnameVerifier(x509HostnameVerifier) .trustKeystore(trustKeystore) .trustPassword(trustPassword) .build()) .build()); final String returnMessage = result.get(RETURN_RESULT); final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage); final Integer statusCode = Integer.parseInt(result.get(STATUS_CODE)); if (statusCode >= 200 && statusCode < 300) { results.put(ATTACHMENT_ID, retrieveAttachmentIdList(returnMessage)); } else { result.put(ATTACHMENT_ID, EMPTY); } return results; } catch (Exception exception) { return getFailureResultsMap(exception); } }
Example 16
Source File: ModuleMetadataUpdateTask.java From oneplatform with Apache License 2.0 | 4 votes |
private void updateModuleApis(ModuleEntity module){ if(module.getMetadata() == null)return; List<ApiInfo> apis = module.getMetadata().getApis(); if(apis == null || apis.isEmpty())return; Map<String, ApiInfo> newApiMap = apis.stream().collect(Collectors.toMap(ApiInfo::getPermCode, e -> e)); QueryResourceParam param = new QueryResourceParam(); param.setModuleId(module.getId()); param.setType(PermissionResourceType.api.name()); Map<String, PermissionResourceEntity> existApiMap = resourceMapper.findListByParam(param) .stream() .collect(Collectors.toMap(PermissionResourceEntity::getPermissionCode, e -> e)); List<String> addUriList; List<String> removeUriList = null; if (!existApiMap.isEmpty()) { addUriList = new ArrayList<>(newApiMap.keySet()); addUriList.removeAll(existApiMap.keySet()); removeUriList = new ArrayList<>(existApiMap.keySet()); removeUriList.removeAll(newApiMap.keySet()); } else { addUriList = new ArrayList<>(newApiMap.keySet()); } if(!addUriList.isEmpty()){ List<PermissionResourceEntity> addList = new ArrayList<>(); PermissionResourceEntity entity; for (String permCode : addUriList) { entity = new PermissionResourceEntity(); entity.setModuleId(module.getId()); entity.setType(PermissionResourceType.api.name()); entity.setName(newApiMap.get(permCode).getName()); entity.setUri(newApiMap.get(permCode).getUrl()); entity.setEnabled(true); entity.setGrantType(newApiMap.get(permCode).getPermissionType().name()); entity.setHttpMethod(newApiMap.get(permCode).getMethod()); entity.buildPermssionCode(module); entity.setCreatedAt(new Date()); addList.add(entity); } resourceMapper.insertList(addList); } if(removeUriList != null){ for (String uri : removeUriList) { PermissionResourceEntity removeEntity = existApiMap.get(uri); removeEntity.setEnabled(false); resourceMapper.updateByPrimaryKey(removeEntity); } } }
Example 17
Source File: Orchid97.java From SEANLP with Apache License 2.0 | 4 votes |
/** * 从句子语料中获取核心词典 * @param sentences * @return */ public static List<String> makeCoreDictionary(List<String> sentences) { Map<String, String> wnmap = new TreeMap<String, String>(); for (String sentence : sentences) { sentence = sentence.trim(); if (!sentence.isEmpty()) { String[] words = sentence.split("###"); int len = words.length; for (int i = 0; i < len; i++) { String[] wn = words[i].split("/"); String word = wn[0].trim(); String nature = wn[1].trim(); if (wnmap.get(word) == null) { wnmap.put(word, nature + "\t" + "1"); } else { String[] nm = wnmap.get(word).split("\t"); boolean catFlag = false; for (String cat : nm) { if (nature.equals(cat)) { catFlag = true; } } if (catFlag) { int nlen = nm.length; for (int j = 0; j < nlen; j += 2) { if (nature.equals(nm[j].trim())) { //System.out.println("key = " + word + "; nature = " + wnmap.get(word)); nm[j + 1] = String.valueOf(Integer.parseInt(nm[j + 1]) + 1); } } String newNature = ""; for (int k = 0; k < nlen; k++) { if (k ==0) { newNature += nm[k]; } else { newNature += "\t" + nm[k]; } } wnmap.put(word, newNature); newNature = ""; } else { wnmap.put(word, wnmap.get(word) + "\t" + nature + "\t" + "1"); } } } } } return Corpus.mapToList(Corpus.NatureSort(wnmap)); }
Example 18
Source File: TestRollLogSegments.java From distributedlog with Apache License 2.0 | 4 votes |
@Test(timeout = 600000) public void testLastDLSNInRollingLogSegments() throws Exception { final Map<Long, DLSN> lastDLSNs = new HashMap<Long, DLSN>(); String name = "distrlog-lastdlsn-in-rolling-log-segments"; DistributedLogConfiguration confLocal = new DistributedLogConfiguration(); confLocal.loadConf(conf); confLocal.setImmediateFlushEnabled(true); confLocal.setOutputBufferSize(0); confLocal.setLogSegmentRollingIntervalMinutes(0); confLocal.setMaxLogSegmentBytes(40); int numEntries = 100; DistributedLogManager dlm = createNewDLM(confLocal, name); BKAsyncLogWriter writer = (BKAsyncLogWriter) dlm.startAsyncLogSegmentNonPartitioned(); final CountDownLatch latch = new CountDownLatch(numEntries); // send requests in parallel to have outstanding requests for (int i = 1; i <= numEntries; i++) { final int entryId = i; Future<DLSN> writeFuture = writer.write(DLMTestUtil.getLogRecordInstance(entryId)).addEventListener(new FutureEventListener<DLSN>() { @Override public void onSuccess(DLSN value) { logger.info("Completed entry {} : {}.", entryId, value); synchronized (lastDLSNs) { DLSN lastDLSN = lastDLSNs.get(value.getLogSegmentSequenceNo()); if (null == lastDLSN || lastDLSN.compareTo(value) < 0) { lastDLSNs.put(value.getLogSegmentSequenceNo(), value); } } latch.countDown(); } @Override public void onFailure(Throwable cause) { } }); if (i == 1) { // wait for first log segment created FutureUtils.result(writeFuture); } } latch.await(); // make sure all ensure blocks were executed. writer.closeAndComplete(); List<LogSegmentMetadata> segments = dlm.getLogSegments(); logger.info("lastDLSNs after writes {} {}", lastDLSNs.size(), lastDLSNs); logger.info("segments after writes {} {}", segments.size(), segments); assertTrue(segments.size() >= 2); assertTrue(lastDLSNs.size() >= 2); assertEquals(lastDLSNs.size(), segments.size()); for (LogSegmentMetadata segment : segments) { DLSN dlsnInMetadata = segment.getLastDLSN(); DLSN dlsnSeen = lastDLSNs.get(segment.getLogSegmentSequenceNumber()); assertNotNull(dlsnInMetadata); assertNotNull(dlsnSeen); if (dlsnInMetadata.compareTo(dlsnSeen) != 0) { logger.error("Last dlsn recorded in log segment {} is different from the one already seen {}.", dlsnInMetadata, dlsnSeen); } assertEquals(0, dlsnInMetadata.compareTo(dlsnSeen)); } dlm.close(); }
Example 19
Source File: MethodConfiguration.java From skywalking with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public static Map<String, String> getTags(Map<String, Object> configuration) { return (Map<String, String>) configuration.get(Constants.CONFIGURATION_ATTRIBUTE_TAGS); }
Example 20
Source File: DynamoDbSigner.java From aws-dynamodb-encryption-java with Apache License 2.0 | 4 votes |
static byte[] calculateStringToSign(Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData) throws NoSuchAlgorithmException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); List<String> attrNames = new ArrayList<>(itemAttributes.keySet()); Collections.sort(attrNames); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); if (associatedData != null) { out.write(sha256.digest(associatedData)); } else { out.write(sha256.digest()); } sha256.reset(); for (String name : attrNames) { Set<EncryptionFlags> set = attributeFlags.get(name); if(set != null && set.contains(EncryptionFlags.SIGN)) { AttributeValue tmp = itemAttributes.get(name); out.write(sha256.digest(name.getBytes(UTF8))); sha256.reset(); if (set.contains(EncryptionFlags.ENCRYPT)) { sha256.update("ENCRYPTED".getBytes(UTF8)); } else { sha256.update("PLAINTEXT".getBytes(UTF8)); } out.write(sha256.digest()); sha256.reset(); sha256.update(AttributeValueMarshaller.marshall(tmp)); out.write(sha256.digest()); sha256.reset(); } } return out.toByteArray(); } catch (IOException ex) { // Due to the objects in use, an IOException is not possible. throw new RuntimeException("Unexpected exception", ex); } }