List of usage examples for java.util Map.Entry get
V get(Object key);
From source file:com.datatorrent.contrib.hdht.HDHTWriter.java
/** * Lookup in write cache (data not flushed/committed to files). * @param bucketKey//from ww w . ja v a 2 s . com * @param key * @return uncommitted. */ @Override public byte[] getUncommitted(long bucketKey, Slice key) { Bucket bucket = this.buckets.get(bucketKey); if (bucket != null) { byte[] v = bucket.writeCache.get(key); if (v != null) { return v != DELETED ? v : null; } for (Map.Entry<Long, WriteCache> entry : bucket.checkpointedWriteCache.entrySet()) { byte[] v2 = entry.getValue().get(key); // find most recent entry if (v2 != null) { v = v2; } } if (v != null) { return v != DELETED ? v : null; } v = bucket.committedWriteCache.get(key); if (v != null) { return v != DELETED ? v : null; } v = bucket.frozenWriteCache.get(key); return v != null && v != DELETED ? v : null; } return null; }
From source file:org.apache.lens.cube.parse.CandidateTableResolver.java
private void resolveCandidateDimTablesForJoinsAndDenorms(CubeQueryContext cubeql) throws LensException { if (cubeql.getAutoJoinCtx() == null) { return;/*from www. j av a2s . co m*/ } Set<Aliased<Dimension>> allDims = new HashSet<>(); for (Dimension dim : cubeql.getDimensions()) { allDims.add(Aliased.create(dim)); } allDims.addAll(cubeql.getOptionalDimensions()); for (Aliased<Dimension> aliasedDim : allDims) { Dimension dim = aliasedDim.getObject(); if (cubeql.getCandidateDimTables().get(dim) != null && !cubeql.getCandidateDimTables().get(dim).isEmpty()) { for (Iterator<CandidateDim> i = cubeql.getCandidateDimTables().get(dim).iterator(); i.hasNext();) { CandidateDim cdim = i.next(); CubeDimensionTable dimtable = cdim.dimtable; // go over the join columns accessed in the query and find out which tables // can participate in join // for each join path check for columns involved in path boolean removed = false; for (Map.Entry<Aliased<Dimension>, Map<AbstractCubeTable, List<String>>> joincolumnsEntry : cubeql .getAutoJoinCtx().getJoinPathFromColumns().entrySet()) { Aliased<Dimension> reachableDim = joincolumnsEntry.getKey(); OptionalDimCtx optdim = cubeql.getOptionalDimensionMap().get(reachableDim); Collection<String> colSet = joincolumnsEntry.getValue().get(dim); if (!checkForFactColumnExistsAndValidForRange(cdim, colSet, cubeql)) { if (optdim == null || optdim.isRequiredInJoinChain || optdim.requiredForCandidates.contains(cdim)) { i.remove(); removed = true; log.info( "Not considering dimtable:{} as its columns are not part of any join paths. Join columns:{}", dimtable, colSet); cubeql.addDimPruningMsgs(dim, dimtable, CandidateTablePruneCause.noColumnPartOfAJoinPath(colSet)); break; } } } if (!removed) { // check for to columns for (Map.Entry<Aliased<Dimension>, Map<AbstractCubeTable, List<String>>> joincolumnsEntry : cubeql .getAutoJoinCtx().getJoinPathToColumns().entrySet()) { Aliased<Dimension> reachableDim = joincolumnsEntry.getKey(); OptionalDimCtx optdim = cubeql.getOptionalDimensionMap().get(reachableDim); Collection<String> colSet = joincolumnsEntry.getValue().get(dim); if (!checkForFactColumnExistsAndValidForRange(cdim, colSet, cubeql)) { if (optdim == null || optdim.isRequiredInJoinChain || optdim.requiredForCandidates.contains(cdim)) { i.remove(); removed = true; log.info( "Not considering dimtable:{} as its columns are not part of any join paths. Join columns:{}", dimtable, colSet); cubeql.addDimPruningMsgs(dim, dimtable, CandidateTablePruneCause.noColumnPartOfAJoinPath(colSet)); break; } } } } if (!removed) { // go over the referenced columns accessed in the query and find out which tables can participate if (cubeql.getOptionalDimensionMap().get(aliasedDim) != null && !checkForFactColumnExistsAndValidForRange(cdim, cubeql.getOptionalDimensionMap().get(aliasedDim).colQueried, cubeql)) { i.remove(); log.info( "Not considering optional dimtable:{} as its denorm fields do not exist. Denorm fields:{}", dimtable, cubeql.getOptionalDimensionMap().get(aliasedDim).colQueried); cubeql.addDimPruningMsgs(dim, dimtable, CandidateTablePruneCause.noColumnPartOfAJoinPath( cubeql.getOptionalDimensionMap().get(aliasedDim).colQueried)); } } } if (cubeql.getCandidateDimTables().get(dim).size() == 0) { OptionalDimCtx optdim = cubeql.getOptionalDimensionMap().get(aliasedDim); if ((cubeql.getDimensions() != null && cubeql.getDimensions().contains(dim)) || (optdim != null && optdim.isRequiredInJoinChain)) { throw new LensException(LensCubeErrorCode.NO_DIM_HAS_COLUMN.getLensErrorInfo(), dim.getName(), cubeql.getAutoJoinCtx().getAllJoinPathColumnsOfTable(dim).toString()); } else { // remove it from optional tables log.info( "Not considering optional dimension {} as, No dimension table has the queried columns:{}" + " Clearing the required for candidates:{}", dim, optdim.colQueried, optdim.requiredForCandidates); removeOptionalDim(cubeql, aliasedDim); } } } } }
From source file:org.silverpeas.migration.jcr.wysiwyg.purge.WysiwygDocumentPurger.java
/** * Removes all wysiwyg duplication between all languages. * Method//w w w . java2 s .c o m * {@link #removeDuplicatesForEachLanguage(String, WysiwygDocumentPurger.ForeignIdProcessContext)} * must be called before. * @param context the context. */ private void removeDuplicatesBetweenAllLanguages(String commonLogPart, ForeignIdProcessContext context) { long start = System.currentTimeMillis(); commonLogPart += " - duplicates between all languages"; if (context.getWysiwygIndexedByLangs().size() > 1) { WysiwygContent defaultWysiwygContent = null; WysiwygContent firstContent = null; List<WysiwygContent> wysiwygContentsToRemove = new ArrayList<WysiwygContent>( context.getWysiwygIndexedByLangs().size()); for (Map.Entry<String, List<WysiwygContent>> languageWysiwygContents : context .getWysiwygIndexedByLangs().entrySet()) { if (!languageWysiwygContents.getValue().isEmpty()) { // It must exist at most one SimpleDocument per language, otherwise treatments stops here. if (languageWysiwygContents.getValue().size() > 1) { console.printWarning(commonLogPart + " - contains several JCR master nodes with different language contents, ..."); return; } WysiwygContent currentWysiwygContent = languageWysiwygContents.getValue().get(0); if (defaultWysiwygContent == null || !defaultWysiwygContent.getLanguage().equals(ConverterUtil.defaultLanguage) && currentWysiwygContent.getLanguage().equals(ConverterUtil.defaultLanguage)) { defaultWysiwygContent = currentWysiwygContent; if (firstContent == null) { firstContent = defaultWysiwygContent; } } if (firstContent.isContentEqualTo(commonLogPart, currentWysiwygContent)) { wysiwygContentsToRemove.add(currentWysiwygContent); } else { // Contents between languages are differents, stopping the treatment of this method. return; } } } removeWysiwygContents(commonLogPart, context, defaultWysiwygContent, wysiwygContentsToRemove); } console.printMessage(commonLogPart + " - duration of " + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start)); }
From source file:com.compomics.colims.core.io.mztab.MzTabExporter.java
/** * This method parses the JSON root node and returns a list of MzTabParam * instances.//from w w w .ja v a 2 s . c o m * * @param jsonNode the root JsonNode * @return the list of MzTabParam instances * @throws IOException thrown in case of an I/O related problem */ private List<MzTabParam> parseJsonNode(JsonNode jsonNode) throws IOException { List<MzTabParam> mzTabParamList = new ArrayList<>(); Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); MzTabParam mzTabParam = new MzTabParam(entry.getKey()); JsonNode nameNode = entry.getValue().get("name"); mzTabParam.setUserFriendlyName(nameNode.get(JSON_NAME).asText()); Iterator<JsonNode> optionElements = entry.getValue().get("values").elements(); while (optionElements.hasNext()) { MzTabParamOption mzTabParamOption = mapper.treeToValue(optionElements.next(), MzTabParamOption.class); mzTabParam.addOption(mzTabParamOption); } mzTabParamList.add(mzTabParam); } return mzTabParamList; }
From source file:com.healthcit.cacure.businessdelegates.GeneratedModuleDataManager.java
/** * Generates a random unique key for a given module. * Returns whether or not this key is actually a duplicate * within the appropriate scope (per-module, per-entity or per-entitymodule). */// w ww. java 2 s . c om private void buildNewKey(Map<String, JSONObject> uniqueKey, Map<String, JSONObject> lastUniqueKey, List<Map<String, Object>> keyQuestions, Map<Object, List<Object>> keyQuestionCombinations, Object uniqueGroupId) { for (int i = 0; i < keyQuestions.size(); ++i) { // Get the unique key question Map<String, Object> uniquePerEntityOrModuleQuestion = keyQuestions.get(i); // Get the question UUID String questionUUID = (String) uniquePerEntityOrModuleQuestion.get(UUID_VALUE); // Generate a random answer value for this question JSONObject randomAnswerValue = generateRandomAnswerValueForUniqueKey(uniquePerEntityOrModuleQuestion, uniqueKey, lastUniqueKey, keyQuestionCombinations, uniqueGroupId); uniqueKey.put(questionUUID, randomAnswerValue); // Track the newly generated key in the questionCombinations collection if (i == keyQuestions.size() - 1) { for (Map.Entry<String, JSONObject> entry : uniqueKey.entrySet()) { String key = GeneratedModuleDataDetail.getTwoPartMapKey(entry.getKey(), entry.getValue().get(ANSWERVALUE_VALUE).toString()); List<Object> list = keyQuestionCombinations.get(key); if (list == null) { list = Collections.synchronizedList(new ArrayList<Object>()); } if (!list.contains(uniqueGroupId)) list.add(uniqueGroupId); keyQuestionCombinations.put(key, list); } } } }
From source file:org.opencms.workplace.tools.modules.CmsCloneModuleThread.java
/** * Changes the resource types and the schema locations of existing content.<p> * * @param resTypeMap a map containing the source types as keys and the target types as values * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding *///from w w w. j a v a2s . co m private void changeResourceTypes(Map<I_CmsResourceType, I_CmsResourceType> resTypeMap) throws CmsException, UnsupportedEncodingException { CmsObject cms = getCms(); CmsObject cloneCms = OpenCms.initCmsObject(cms); if (isTrue(m_cloneInfo.getApplyChangesEverywhere())) { cloneCms.getRequestContext().setSiteRoot("/"); } for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) { CmsResourceFilter filter = CmsResourceFilter.requireType(mapping.getKey()); List<CmsResource> resources = cloneCms.readResources("/", filter); String sourceSchemaPath = mapping.getKey().getConfiguration().get("schema"); String targetSchemaPath = mapping.getValue().getConfiguration().get("schema"); for (CmsResource res : resources) { if (lockResource(cms, res)) { CmsFile file = cms.readFile(res); if (CmsResourceTypeXmlContent.isXmlContent(file)) { CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file); xmlContent.setAutoCorrectionEnabled(true); file = xmlContent.correctXmlStructure(getCms()); } String encoding = CmsLocaleManager.getResourceEncoding(cms, file); String content = new String(file.getContents(), encoding); content = content.replaceAll(sourceSchemaPath, targetSchemaPath); file.setContents(content.getBytes(encoding)); try { cms.writeFile(file); } catch (CmsXmlException e) { LOG.error(e.getMessage(), e); } res.setType(mapping.getValue().getTypeId()); cms.writeResource(res); } } } }
From source file:com.jaspersoft.jasperserver.war.action.DataSourceAction.java
public Map<String, Map<String, Object>> getAvailableJdbcDrivers() { Map<String, Map<String, Object>> availableDrivers = new LinkedHashMap<String, Map<String, Object>>(); for (Map.Entry<String, Map<String, Object>> entry : jdbcConnectionMap.entrySet()) { Map<String, Object> driverData = new HashMap<String, Object>(); driverData.putAll(entry.getValue()); driverData.put("available", jdbcDriverService.isRegistered(String.valueOf(entry.getValue().get("jdbcDriverClass")))); availableDrivers.put(entry.getKey(), driverData); }//from w ww . java 2 s. com for (String registeredDriverClassName : jdbcDriverService.getRegisteredDriverClassNames()) { boolean defined = false; for (Map.Entry<String, Map<String, Object>> entry : jdbcConnectionMap.entrySet()) { if (registeredDriverClassName.equals(entry.getValue().get("jdbcDriverClass"))) { defined = true; break; } } if (!defined) { availableDrivers.put(registeredDriverClassName, null); } } return availableDrivers; }
From source file:com.healthcit.cacure.businessdelegates.GeneratedModuleDataManager.java
/** * Updates the GeneratedFormDataDetail object with * randomly generated unique key field values. */// w ww . j av a 2 s . co m private Map<String, JSONObject> generateUniqueKey(GeneratedModuleDataDetail form, Map<String, JSONObject> lastUniqueKey, String entityId, int moduleId, int entityModuleId) { log.debug("Generating unique key.............."); log.debug("=========================="); // Get the list of "unique-per-entity" fields List<Map<String, Object>> uniquePerEntityQuestions = form.retrieveUniquePerEntityQuestions(); // Get the list of "unique-per-all-modules" fields List<Map<String, Object>> uniquePerAllModulesQuestions = form.retrieveUniquePerAllModulesQuestions(); // Get the list of "unique-per-entity-modules" fields List<Map<String, Object>> uniquePerEntityModulesQuestions = form.retrieveUniquePerEntityModulesQuestions(); // Generate the answer values: first for "unique-per-entity", then "unique-per-entity-modules", then "unique-per-all-modules" Map<String, JSONObject> uniqueKey = new HashMap<String, JSONObject>(); // Get the map of answer-value to "unique-per-entity" question fields Map<Object, List<Object>> uniquePerEntityCombinations = form.getUniquePerEntityQuestionCombinations(); // Get the map of answer-value to "unique-per-all-modules" question fields Map<Object, List<Object>> uniquePerAllModulesCombinations = form .getUniquePerAllModuleQuestionCombinations(); // Get the map of answer-value to "unique-per-entity-modules" question fields Map<Object, List<Object>> uniquePerEntityModulesCombinations = form .getUniquePerEntityModuleQuestionCombinations(); // Generate the answer values: first for "unique-per-entity", then "unique-per-entity-modules", then "unique-per-all-modules" uniqueKey.clear(); // First, generate the unique answer values for "unique-per-entity" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerEntityQuestions, uniquePerEntityCombinations, entityId); // Then, generate the unique answer values for "unique-per-entity-modules" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerEntityModulesQuestions, uniquePerEntityModulesCombinations, entityModuleId); // Then, generate the unique answer values for "unique-per-all-modules" fields buildNewKey(uniqueKey, lastUniqueKey, uniquePerAllModulesQuestions, uniquePerAllModulesCombinations, moduleId); // Debugging log.debug("Generated unique key fields: " + (uniqueKey.isEmpty() ? "NONE" : "")); for (Map.Entry<String, JSONObject> entry : uniqueKey.entrySet()) { log.debug("==========Key: " + entry.getKey()); log.debug("==========Text:" + StringUtils.defaultIfEmpty((String) entry.getValue().get(ANSWERVALUE_TEXT), "") + "==========Value:" + entry.getValue().get(ANSWERVALUE_VALUE).toString()); } return uniqueKey; }
From source file:com.espertech.esper.core.context.mgr.ContextManagerNested.java
private AgentInstance[] getAgentInstancesForStmt(String statementId, ContextPartitionSelector selector) { Collection<Integer> agentInstanceIds = getAgentInstancesForSelector(selector); if (agentInstanceIds == null || agentInstanceIds.isEmpty()) { return new AgentInstance[0]; }//w ww. j ava 2 s .com List<AgentInstance> instances = new ArrayList<AgentInstance>(agentInstanceIds.size()); for (Map.Entry<ContextController, ContextControllerTreeEntry> subcontext : subcontexts.entrySet()) { if (subcontext.getKey().getFactory().getFactoryContext() .getNestingLevel() != nestedContextFactories.length) { continue; } if (subcontext.getValue().getAgentInstances() == null || subcontext.getValue().getAgentInstances().isEmpty()) { continue; } for (Integer agentInstanceId : agentInstanceIds) { ContextControllerTreeAgentInstanceList instancesList = subcontext.getValue().getAgentInstances() .get(agentInstanceId); if (instancesList != null) { Iterator<AgentInstance> instanceIt = instancesList.getAgentInstances().iterator(); for (; instanceIt.hasNext();) { AgentInstance instance = instanceIt.next(); if (instance.getAgentInstanceContext().getStatementContext().getStatementId() .equals(statementId)) { instances.add(instance); } } } } } return instances.toArray(new AgentInstance[instances.size()]); }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java
protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers, final Output writer, final BindingSession session, BigInteger offset, BigInteger length) { int respCode = -1; try {// w ww. j a va2s. c om // log before connect if (LOG.isDebugEnabled()) { LOG.debug("Session {}: {} {}", session.getSessionId(), method, url); } // get HTTP client object from session DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { session.writeLock(); try { httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { httpclient = createHttpClient(url, session); session.put(HTTP_CLIENT, httpclient, true); } } finally { session.writeUnlock(); } } HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(url.toString()); } else if ("POST".equals(method)) { request = new HttpPost(url.toString()); } else if ("PUT".equals(method)) { request = new HttpPut(url.toString()); } else if ("DELETE".equals(method)) { request = new HttpDelete(url.toString()); } else { throw new CmisRuntimeException("Invalid HTTP method!"); } // set content type if (contentType != null) { request.setHeader("Content-Type", contentType); } // set other headers if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } // authenticate AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); if (authProvider != null) { Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString()); if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getKey() != null && isNotEmpty(header.getValue())) { String key = header.getKey(); if (key.equalsIgnoreCase("user-agent")) { request.setHeader("User-Agent", header.getValue().get(0)); } else { for (String value : header.getValue()) { if (value != null) { request.addHeader(key, value); } } } } } } } // range if ((offset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((offset == null) || (offset.signum() == -1)) { offset = BigInteger.ZERO; } sb.append(offset.toString()); sb.append('-'); if ((length != null) && (length.signum() == 1)) { sb.append(offset.add(length.subtract(BigInteger.ONE)).toString()); } request.setHeader("Range", sb.toString()); } // compression Object compression = session.get(SessionParameter.COMPRESSION); if ((compression != null) && Boolean.parseBoolean(compression.toString())) { request.setHeader("Accept-Encoding", "gzip,deflate"); } // locale if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) { request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString()); } // send data if (writer != null) { Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION); final boolean clientCompressionFlag = (clientCompression != null) && Boolean.parseBoolean(clientCompression.toString()); if (clientCompressionFlag) { request.setHeader("Content-Encoding", "gzip"); } AbstractHttpEntity streamEntity = new AbstractHttpEntity() { @Override public boolean isChunked() { return true; } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() throws IOException { throw new UnsupportedOperationException(); } @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStream connOut = null; if (clientCompressionFlag) { connOut = new GZIPOutputStream(outstream, 4096); } else { connOut = outstream; } OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); try { writer.write(out); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } out.flush(); if (connOut instanceof GZIPOutputStream) { ((GZIPOutputStream) connOut).finish(); } } }; ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity); } // connect HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); // get stream, if present respCode = response.getStatusLine().getStatusCode(); InputStream inputStream = null; InputStream errorStream = null; if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) { if (entity != null) { inputStream = entity.getContent(); } else { inputStream = new ByteArrayInputStream(new byte[0]); } } else { if (entity != null) { errorStream = entity.getContent(); } else { errorStream = new ByteArrayInputStream(new byte[0]); } } // collect headers Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>(); for (Header header : response.getAllHeaders()) { List<String> values = responseHeaders.get(header.getName()); if (values == null) { values = new ArrayList<String>(); responseHeaders.put(header.getName(), values); } values.add(header.getValue()); } // log after connect if (LOG.isTraceEnabled()) { LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url, responseHeaders.toString()); } // forward response HTTP headers if (authProvider != null) { authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders); } // get the response return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream, errorStream); } catch (Exception e) { String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : ""); throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e); } }