List of usage examples for java.util Map.Entry get
V get(Object key);
From source file:anhttpclient.AnhttpclientTest.java
@Test public void testRequestMethodsAndDefaultHeadersAndHostAndResponseText() throws Exception { final String methodParamName = "method"; final String responseText = "Hello from SimpleHttperver"; server.addHandler("/index", new ByteArrayHandlerAdapter() { public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) throws IOException { URI requestURI = httpRequestContext.getRequestURI(); assertEquals(methodParamName, requestURI.getQuery().split("=")[0]); String method = requestURI.getQuery().split("=")[1]; assertEquals("Method should be " + method, method, httpRequestContext.getRequestMethod()); //In PUT and POST methods Content-length headers should be added int headersSize = method.equals(RequestMethod.POST.toString()) || method.equals(RequestMethod.PUT.toString()) ? defaultHeaders.size() + 1 : defaultHeaders.size(); assertEquals("Count of request headers is incorrect", headersSize, httpRequestContext.getRequestHeaders().size() - 1); assertEquals("Host request header is unexpected", httpRequestContext.getRequestHeaders().get("Host").get(0), DefaultHttpServer.DEFAULT_HOST + ":" + server.getPort()); for (Map.Entry<String, List<String>> entry : httpRequestContext.getRequestHeaders().entrySet()) { if ("Content-length".equalsIgnoreCase(entry.getKey())) { //assertEquals(httpRequestContext.getRequestBody().length, // Integer.valueOf(entry.getValue().get(0)).intValue()); continue; } else if ("Host".equalsIgnoreCase(entry.getKey())) { continue; }//from w w w . j a v a 2 s . c o m //Test default headers assertEquals(String.format("sent header [%s] not equals to received one", entry.getKey()), defaultHeaders.get(entry.getKey()), entry.getValue().get(0)); } return responseText.getBytes(); } }); for (Map.Entry<RequestMethod, Class<? extends WebRequest>> entry : allRequests.entrySet()) { WebRequest req = entry.getValue().newInstance(); req.setUrl(server.getBaseUrl() + "/index"); req.addParam(methodParamName, entry.getKey().toString()); WebResponse resp = wb.getResponse(req); if (!entry.getKey().equals(RequestMethod.HEAD)) { assertEquals("Response from server is incorrect", responseText, resp.getText()); } else { assertNull(resp.getBytes()); } } }
From source file:org.apache.syncope.core.rest.cxf.ExtendedSwagger2Serializers.java
@Override public void writeTo(final Swagger data, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream out) throws IOException { if (dynamicBasePath) { MessageContext ctx = JAXRSUtils.createContextValue(JAXRSUtils.getCurrentMessage(), null, MessageContext.class); data.setBasePath(StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/")); }//from ww w .j a v a 2s . c o m if (replaceTags || javadocProvider != null) { Map<String, ClassResourceInfo> operations = new HashMap<>(); Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>(); for (ClassResourceInfo cri : cris) { for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) { String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue()); operations.put(normalizedPath, cri); methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori); } } if (replaceTags && data.getTags() != null) { data.getTags().clear(); } for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) { Tag tag = null; if (replaceTags && operations.containsKey(entry.getKey())) { ClassResourceInfo cri = operations.get(entry.getKey()); tag = new Tag(); tag.setName(cri.getURITemplate().getValue()); if (javadocProvider != null) { tag.setDescription(javadocProvider.getClassDoc(cri)); } data.addTag(tag); } for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) { if (replaceTags && tag != null) { subentry.getValue().setTags(Collections.singletonList(tag.getName())); } Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey()); if (methods.containsKey(key) && javadocProvider != null) { OperationResourceInfo ori = methods.get(key); subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori)); boolean domainHeaderParameterFound = false; for (int i = 0; i < subentry.getValue().getParameters().size(); i++) { subentry.getValue().getParameters().get(i) .setDescription(javadocProvider.getMethodParameterDoc(ori, i)); if (subentry.getValue().getParameters().get(i) instanceof HeaderParameter && RESTHeaders.DOMAIN .equals(subentry.getValue().getParameters().get(i).getName())) { domainHeaderParameterFound = true; } } if (!domainHeaderParameterFound) { HeaderParameter domainHeaderParameter = new HeaderParameter(); domainHeaderParameter.setName(RESTHeaders.DOMAIN); domainHeaderParameter.setRequired(true); domainHeaderParameter.setType("string"); domainHeaderParameter.setEnum(domains); domainHeaderParameter.setDefault(SyncopeConstants.MASTER_DOMAIN); subentry.getValue().getParameters().add(domainHeaderParameter); } if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) { subentry.getValue().getResponses().entrySet().iterator().next().getValue() .setDescription(javadocProvider.getMethodResponseDoc(ori)); } } } } } if (replaceTags && data.getTags() != null) { Collections.sort(data.getTags(), new Comparator<Tag>() { @Override public int compare(final Tag tag1, final Tag tag2) { return ComparatorUtils.<String>naturalComparator().compare(tag1.getName(), tag2.getName()); } }); } super.writeTo(data, type, genericType, annotations, mediaType, headers, out); }
From source file:org.openecomp.sdc.validation.impl.validators.EcompGuideLineValidator.java
private void validateNovaServerAvailabilityZoneName(String fileName, Map.Entry<String, Resource> resourceEntry, GlobalValidationContext globalContext) { String[] regexList = new String[] { "availability_zone_(\\d+)" }; if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { return;/*from ww w. jav a 2 s . co m*/ } Object availabilityZoneMap = resourceEntry.getValue().getProperties().containsKey("availability_zone") ? resourceEntry.getValue().getProperties().get("availability_zone") : null; if (Objects.nonNull(availabilityZoneMap)) { if (availabilityZoneMap instanceof Map) { String availabilityZoneName = getWantedNameFromPropertyValueGetParam(availabilityZoneMap); if (availabilityZoneName != null) { if (!evalPattern(availabilityZoneName, regexList)) { globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( Messages.AVAILABILITY_ZONE_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), resourceEntry.getKey())); } } } else { globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( Messages.MISSING_GET_PARAM.getErrorMessage(), "availability_zone", resourceEntry.getKey())); } } }
From source file:org.apache.lens.cube.parse.CandidateTableResolver.java
private void resolveCandidateFactTablesForJoins(CubeQueryContext cubeql) throws LensException { if (cubeql.getAutoJoinCtx() == null) { return;//w w w .j a v a2 s . c om } Collection<String> colSet = null; if (cubeql.getCube() != null && !cubeql.getCandidates().isEmpty()) { for (Iterator<StorageCandidate> i = CandidateUtil.getStorageCandidates(cubeql.getCandidates()) .iterator(); i.hasNext();) { StorageCandidate sc = i.next(); // for each join path check for columns involved in path 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); colSet = joincolumnsEntry.getValue().get(cubeql.getCube()); if (!checkForFactColumnExistsAndValidForRange(sc, colSet, cubeql)) { if (optdim == null || optdim.isRequiredInJoinChain || optdim.requiredForCandidates.contains(sc)) { i.remove(); log.info( "Not considering storage candidate :{} as it does not have columns in any of the join paths." + " Join columns:{}", sc, colSet); cubeql.addStoragePruningMsg(sc, CandidateTablePruneCause.noColumnPartOfAJoinPath(colSet)); break; } } } } if (cubeql.getCandidates().size() == 0) { throw new LensException(LensCubeErrorCode.NO_FACT_HAS_COLUMN.getLensErrorInfo(), colSet == null ? "NULL" : colSet.toString()); } } }
From source file:org.kiji.rest.resources.RowsResource.java
/** * Extracts map of freshening parameters out of REST query. * * @param queryParameters of request from which to extract the freshening parameters. * @return a map of strings to strings of freshening parameters. */// www .ja va2s. co m private Map<String, String> getFresheningParameters(final MultivaluedMap<String, String> queryParameters) { final Map<String, String> fresheningParameters = Maps.newHashMap(); for (final Map.Entry<String, List<String>> query : queryParameters.entrySet()) { final String queryKey = query.getKey(); if (queryKey.startsWith(FRESH_PARAMETER_PREFIX)) { // Make sure the parameter was constructed acceptably, i.e.: fresh.key=value Preconditions.checkNotNull(query.getValue()); Preconditions.checkArgument(1 == query.getValue().size()); final String queryValue = query.getValue().get(0); fresheningParameters.put(queryKey.substring(FRESH_PARAMETER_PREFIX.length()), queryValue); } } return fresheningParameters; }
From source file:it.unibas.spicy.persistence.csv.DAOCsv.java
@SuppressWarnings("unchecked") public void loadInstance(int scenarioNo, IDataSourceProxy dataSource, boolean source) throws DAOException, SQLException { IConnectionFactory connectionFactory = null; Connection connection = null; AccessConfiguration accessConfiguration = new AccessConfiguration(); accessConfiguration.setDriver(SpicyEngineConstants.ACCESS_CONFIGURATION_DRIVER); accessConfiguration/* ww w . ja va2 s . c om*/ .setUri(SpicyEngineConstants.ACCESS_CONFIGURATION_URI + SpicyEngineConstants.MAPPING_TASK_DB_NAME); accessConfiguration.setLogin(SpicyEngineConstants.ACCESS_CONFIGURATION_LOGIN); accessConfiguration.setPassword(SpicyEngineConstants.ACCESS_CONFIGURATION_PASS); try { connectionFactory = new SimpleDbConnectionFactory(); connection = connectionFactory.getConnection(accessConfiguration); Statement statement = connection.createStatement(); HashMap<String, ArrayList<Object>> strfullPath = (HashMap<String, ArrayList<Object>>) dataSource .getAnnotation(SpicyEngineConstants.INSTANCE_PATH_LIST); for (Map.Entry<String, ArrayList<Object>> entry : strfullPath.entrySet()) { String filePath = entry.getKey(); //the list entry.getValue() contains a)the table name //b)a boolean that contains the info if the instance file includes column names //and c) a boolean that contains the info if the instance file has been already loaded boolean loaded = (Boolean) entry.getValue().get(2); if (!loaded) { String tableName = (String) entry.getValue().get(0); if (source) { tableName = SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ".\"" + tableName + "\""; } else { tableName = SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo + ".\"" + tableName + "\""; } boolean colNames = (Boolean) entry.getValue().get(1); //avenet //CSVReader reader = new CSVReader(new FileReader(filePath)); Reader r = new FileReader(filePath); CSVReader reader = new com.opencsv.CSVReaderBuilder(r) .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS).build(); try { //ignore the first line if file includes column names if (colNames) { reader.readNext(); } String[] nextLine; String values; ArrayList<String> stmnt_list = new ArrayList<String>(); String sql_insert_stmnt = ""; int line = 0; while ((nextLine = reader.readNext()) != null) {//for each line in the file line++; //skip empty lines at the end of the csv file if (nextLine.length != 1 || !nextLine[0].isEmpty()) { //insert into batches (of 500 rows) if (line % BATCH_SIZE == 0) { //take out the last ',' character sql_insert_stmnt = sql_insert_stmnt.substring(0, sql_insert_stmnt.length() - 1); stmnt_list.add(sql_insert_stmnt); sql_insert_stmnt = ""; } values = ""; for (int i = 0; i < nextLine.length; i++) { //avenet 20/7 if (nextLine[i] != null) { // if (!nextLine[i].equalsIgnoreCase("null")){ // //replace double quotes with single quotes // //while first escape the character ' for SQL (the "replaceAll" method call) values += "'" + nextLine[i].trim().replaceAll("'", "''") + "',"; // } // //do not put quotes if value is the string null // else{ // values += nextLine[i].trim().replaceAll("'", "''") + ","; // } } else { values += "null,"; } } //take out the last ',' character values = values.substring(0, values.length() - 1); sql_insert_stmnt += "(" + values + "),"; } } reader.close(); if (sql_insert_stmnt != "") { //take out the last ',' character sql_insert_stmnt = sql_insert_stmnt.substring(0, sql_insert_stmnt.length() - 1); stmnt_list.add(sql_insert_stmnt); for (String stmnmt : stmnt_list) { statement.executeUpdate("insert into " + tableName + " values " + stmnmt + ";"); } } //change the "loaded" value of the entry by replacing it in the hashmap ArrayList<Object> valSet = new ArrayList<Object>(); valSet.add(tableName); valSet.add(colNames); valSet.add(true); strfullPath.put(filePath, valSet); } catch (IOException ex) { Logger.getLogger(DAOCsv.class.getName()).log(Level.SEVERE, null, ex); throw new DAOException(ex); } dataSource.addAnnotation(SpicyEngineConstants.LOADED_INSTANCES_FLAG, true); } } } catch (FileNotFoundException ex) { Logger.getLogger(DAOCsv.class.getName()).log(Level.SEVERE, null, ex); throw new DAOException(ex); } finally { if (connection != null) connection.close(); } }
From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java
private String createCriterionJsonPayload(HashMap<String, String> formPostParameters, Resource<ToolItemRubricAssociation> association) throws Exception { Map<String, Map<String, String>> criterionDataMap = extractCriterionDataFromParams(formPostParameters); String criterionJsonData = ""; int index = 0; boolean pointsAdjusted = false; String points = null;/* ww w . j a v a 2 s. c om*/ String selectedRatingId = null; String inlineRubricUri = String.format("%s?%s", association.getLink("rubric").getHref(), "projection=inlineRubric"); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", String.format("Bearer %s", generateJsonWebToken(association.getContent().getToolId()))); HttpEntity<?> requestEntity = new HttpEntity<>(headers); ResponseEntity<Rubric> rubricEntity = restTemplate.exchange(inlineRubricUri, HttpMethod.GET, requestEntity, Rubric.class); Map<String, Criterion> criterions = new HashMap<>(); for (Criterion criterion : rubricEntity.getBody().getCriterions()) { criterions.put(String.valueOf(criterion.getId()), criterion); } for (Map.Entry<String, Map<String, String>> criterionData : criterionDataMap.entrySet()) { if (index > 0) { criterionJsonData += ", "; } index++; final String selectedRatingPoints = criterionData.getValue().get("rbcs-criterion"); if (StringUtils.isNotBlank(criterionData.getValue().get("rbcs-criterion-override"))) { pointsAdjusted = true; points = criterionData.getValue().get("rbcs-criterion-override"); } else { pointsAdjusted = false; points = selectedRatingPoints; } Criterion criterion = criterions.get(criterionData.getKey()); Optional<Rating> rating = criterion.getRatings().stream() .filter(c -> String.valueOf(c.getPoints()).equals(selectedRatingPoints)).findFirst(); if (rating.isPresent()) { selectedRatingId = String.valueOf(rating.get().getId()); } if (StringUtils.isEmpty(points)) { points = "0"; } criterionJsonData += String.format( "{ \"criterionId\" : \"%s\", \"points\" : \"%s\", " + "\"comments\" : \"%s\", \"pointsAdjusted\" : %b, \"selectedRatingId\" : \"%s\" }", criterionData.getKey(), points, StringEscapeUtils.escapeJson(criterionData.getValue().get("rbcs-criterion-comment")), pointsAdjusted, selectedRatingId); } return criterionJsonData; }
From source file:org.commoncrawl.service.listcrawler.ProxyServlet.java
private static void sendCrawlURLResponse(final HttpServletRequest req, final HttpServletResponse response, CrawlURL url, String renderAs, AsyncResponse responseObject, long requestStartTime) throws IOException { if (url.getLastAttemptResult() == CrawlURL.CrawlResult.SUCCESS) { // remove default headers ... response.setHeader("Date", null); response.setHeader("Server", null); // set the result code ... response.setStatus(200);/*from w ww .ja v a2 s .co m*/ if (renderAs.equals(PROXY_RENDER_TYPE_TEXT)) { response.setHeader("content-type", "text/plain"); // parse headers ... NIOHttpHeaders headers = NIOHttpHeaders.parseHttpHeaders(url.getHeaders()); PrintWriter writer = response.getWriter(); writer.write(PROXY_HEADER_SOURCE + ":origin\n"); writer.write(PROXY_HEADER_ORIG_STATUS + ":" + headers.getValue(0) + "\n"); writer.write(PROXY_HEADER_TIMER + ":" + (System.currentTimeMillis() - requestStartTime) + "MS\n"); writer.write(PROXY_HEADER_FINALURL + ":" + (((url.getFlags() & CrawlURL.Flags.IsRedirected) != 0) ? url.getRedirectURL() : url.getUrl()) + "\n"); // and put then in a map ... Map<String, List<String>> headerItems = NIOHttpHeaders.parseHttpHeaders(url.getHeaders()) .getHeaders(); writer.write("content-length:" + Integer.toString(url.getContentRaw().getCount()) + "\n"); // pull out content encoding if it is set ... String contentEncoding = headers.findValue("content-encoding"); if (contentEncoding != null) { writer.write("content-encoding:" + contentEncoding + "\n"); } String truncationFlags = ""; if ((url.getFlags() & CrawlURL.Flags.TruncatedDuringDownload) != 0) { truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload); } if (truncationFlags.length() != 0) { writer.write(PROXY_HEADER_TRUNCATION + ":" + truncationFlags + "\n"); } // now walk remaining headers ... for (Map.Entry<String, List<String>> entry : headerItems.entrySet()) { // if not in exclusion list ... if (entry.getKey() != null && entry.getKey().length() != 0) { if (!dontProxyHeaders.contains(entry.getKey().toLowerCase())) { // and it has values ... if (entry.getValue() != null) { for (String value : entry.getValue()) { writer.write(entry.getKey() + ":" + value + "\n"); } } } else { if (entry.getKey().equalsIgnoreCase("content-length") && entry.getValue() != null) { writer.write( PROXY_HEADER_ORIGINAL_CONTENT_LEN + ":" + entry.getValue().get(0) + "\n"); } } } } writer.write("\n"); int contentLength = url.getContentRaw().getCount(); byte contentData[] = url.getContentRaw().getReadOnlyBytes(); if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { UnzipResult result = GZIPUtils.unzipBestEffort(contentData, CrawlEnvironment.CONTENT_SIZE_LIMIT); if (result != null) { contentData = result.data.get(); contentLength = result.data.getCount(); } } BufferedReader bufferedReader = readerForCharset(headers, contentData, contentLength, writer); try { String line = null; while ((line = bufferedReader.readLine()) != null) { writer.println(line); } } finally { bufferedReader.close(); } writer.flush(); } else { response.setHeader(PROXY_HEADER_SOURCE, "origin"); response.setHeader(PROXY_HEADER_TIMER, (System.currentTimeMillis() - requestStartTime) + "MS"); response.setHeader(PROXY_HEADER_FINALURL, (((url.getFlags() & CrawlURL.Flags.IsRedirected) != 0) ? url.getRedirectURL() : url.getUrl())); // parse headers ... NIOHttpHeaders headers = NIOHttpHeaders.parseHttpHeaders(url.getHeaders()); // and put then in a map ... Map<String, List<String>> headerItems = NIOHttpHeaders.parseHttpHeaders(url.getHeaders()) .getHeaders(); // set the content length ... response.setHeader("content-length", Integer.toString(url.getContentRaw().getCount())); String truncationFlags = ""; if ((url.getFlags() & CrawlURL.Flags.TruncatedDuringDownload) != 0) { truncationFlags += ArcFileItem.Flags.toString(ArcFileItem.Flags.TruncatedInDownload); } if (truncationFlags.length() != 0) { response.setHeader(PROXY_HEADER_TRUNCATION, truncationFlags); } // pull out content encoding if it is set ... String contentEncoding = headers.findValue("content-encoding"); if (contentEncoding != null) { response.setHeader("content-encoding", contentEncoding); } // now walk remaining headers ... for (Map.Entry<String, List<String>> entry : headerItems.entrySet()) { // if not in exclusion list ... if (entry.getKey() != null && entry.getKey().length() != 0) { if (!dontProxyHeaders.contains(entry.getKey().toLowerCase())) { // and it has values ... if (entry.getValue() != null) { for (String value : entry.getValue()) { response.setHeader(entry.getKey(), value); } } } else { if (entry.getKey().equalsIgnoreCase("content-length") && entry.getValue() != null) { response.setHeader(PROXY_HEADER_ORIGINAL_CONTENT_LEN, entry.getValue().get(0)); } } } } ServletOutputStream responseOutputStream = response.getOutputStream(); // write out content bytes responseOutputStream.write(url.getContentRaw().getReadOnlyBytes(), 0, url.getContentRaw().getCount()); } } // otherwise failed for some other reason ... else { /* ProxyServer.getSingleton().logProxyFailure(500, CrawlURL.FailureReason.toString(url.getLastAttemptFailureReason()) + " - " + url.getLastAttemptFailureDetail(), url.getUrl(), url.getRedirectURL(), requestStartTime); */ // report the reason ... response.sendError(500, CrawlURL.FailureReason.toString(url.getLastAttemptFailureReason()) + " - " + url.getLastAttemptFailureDetail()); } }
From source file:org.egov.ptis.actions.edit.EditDemandAction.java
@SuppressWarnings("unchecked") @ValidationErrorPage(value = RESULT_NEW) @Action(value = "/editDemand-update") public String update() { if (LOGGER.isDebugEnabled()) LOGGER.info("Entered into update, basicProperty=" + basicProperty); final List<EgDemandDetails> demandDetailsFromDB = getPersistenceService() .findAllBy(QUERY_NONZERO_DEMAND_DETAILS, basicProperty); final Installment currentInstallment = propertyTaxCommonUtils.getCurrentInstallment(); final Map<Installment, List<EgDemandDetails>> demandDetails = new TreeMap<>(); final String queryZeroDemandDetails = QUERY_DEMAND_DETAILS + " AND dd.amount = 0"; final List<EgDemandDetails> dmdDtlsWithZeroAmt = getPersistenceService().findAllBy(queryZeroDemandDetails, basicProperty);/*from w w w . java 2s .c om*/ final Set<Installment> zeroInstallments = new TreeSet<>(); BigDecimal totalDmd = BigDecimal.ZERO; EgDemandDetails egDemandDtls = null; demandAudit.setBasicproperty(basicProperty.getUpicNo()); demandAudit.setTransaction(EDIT_DEMAND); demandAudit.setRemarks(remarks); demandAudit.setLastModifiedDate(new Date()); for (final DemandDetail dmdDetail : demandDetailBeanList) if (dmdDetail.getIsNew() != null && dmdDetail.getIsNew() && dmdDetail.getActualAmount() != null) { final EgDemandReason egDmdRsn = propertyTaxUtil.getDemandReasonByCodeAndInstallment( demandReasonMap.get(dmdDetail.getReasonMaster()), dmdDetail.getInstallment()); /** * Checking whether already EgDemandDetails exists for this, if yes updating the same. this may be when taxes * updated to 0 and then later adding the installment taxes. */ for (final EgDemandDetails details : dmdDtlsWithZeroAmt) if (details.getEgDemandReason().equals(egDmdRsn)) { zeroInstallments.add(details.getEgDemandReason().getEgInstallmentMaster()); details.setAmount(dmdDetail.getActualAmount()); details.setAmtCollected(dmdDetail.getActualCollection() == null ? BigDecimal.ZERO : dmdDetail.getActualCollection()); egDemandDtls = details; } else { egDemandDtls = propService.createDemandDetails(dmdDetail.getActualAmount(), dmdDetail.getActualCollection(), egDmdRsn, dmdDetail.getInstallment()); totalDmd = totalDmd.add(egDemandDtls.getAmount()); } if (dmdDtlsWithZeroAmt.isEmpty()) { egDemandDtls = propService.createDemandDetails(dmdDetail.getActualAmount(), dmdDetail.getActualCollection(), egDmdRsn, dmdDetail.getInstallment()); totalDmd = totalDmd.add(egDemandDtls.getAmount()); } logAudit(dmdDetail); final List<EgDemandDetails> dmdDtl = new ArrayList<>(); if (demandDetails.get(dmdDetail.getInstallment()) == null) { dmdDtl.add(egDemandDtls); demandDetails.put(dmdDetail.getInstallment(), dmdDtl); } else demandDetails.get(dmdDetail.getInstallment()).add(egDemandDtls); } for (final EgDemandDetails ddFromDB : demandDetailsFromDB) for (final DemandDetail dmdDetail : demandDetailBeanList) if (dmdDetail.getIsNew() != null && !dmdDetail.getIsNew()) { Boolean isUpdateAmount = false; Boolean isUpdateCollection = false; if (dmdDetail.getRevisedAmount() != null && dmdDetail.getInstallment() .equals(ddFromDB.getEgDemandReason().getEgInstallmentMaster()) && ddFromDB.getEgDemandReason().getEgDemandReasonMaster().getCode() .equalsIgnoreCase(demandReasonMap.get(dmdDetail.getReasonMaster()))) isUpdateAmount = true; if (dmdDetail.getRevisedCollection() != null && ddFromDB.getEgDemand().getEgInstallmentMaster().equals(currentInstallment) && ddFromDB.getEgDemandReason().getEgDemandReasonMaster().getCode() .equalsIgnoreCase(demandReasonMap.get(dmdDetail.getReasonMaster()))) { final Installment inst = installmentDAO.findById(dmdDetail.getInstallment().getId(), false); if (ddFromDB.getEgDemandReason().getEgInstallmentMaster().equals(inst)) isUpdateCollection = true; } if (isUpdateAmount) ddFromDB.setAmount(dmdDetail.getRevisedAmount() != null ? dmdDetail.getRevisedAmount() : BigDecimal.ZERO); if (isUpdateCollection) ddFromDB.setAmtCollected( dmdDetail.getRevisedCollection() != null ? dmdDetail.getRevisedCollection() : BigDecimal.ZERO); if (isUpdateAmount || isUpdateCollection) { ddFromDB.setModifiedDate(new Date()); logAudit(dmdDetail); demandDetailsDao.update(ddFromDB); break; } } if (!demandAudit.getDemandAuditDetails().isEmpty()) demandAuditService.saveDetails(demandAudit); final List<EgDemandDetails> currentInstdemandDetailsFromDB = getPersistenceService().findAllBy(QUERYINSTDD, basicProperty, propertyTaxCommonUtils.getCurrentInstallment()); final Map<Installment, Set<EgDemandDetails>> demandDetailsSetByInstallment = getEgDemandDetailsSetByInstallment( currentInstdemandDetailsFromDB); final List<Installment> installments = new ArrayList<>(demandDetailsSetByInstallment.keySet()); Collections.sort(installments); for (final Installment inst : installments) { final Map<String, BigDecimal> dmdRsnAmt = new LinkedHashMap<>(); for (final String rsn : DEMAND_RSNS_LIST) { final EgDemandDetails newDmndDtls = propService .getEgDemandDetailsForReason(demandDetailsSetByInstallment.get(inst), rsn); if (newDmndDtls != null && newDmndDtls.getAmtCollected() != null) { final BigDecimal extraCollAmt = newDmndDtls.getAmtCollected().subtract(newDmndDtls.getAmount()); // If there is extraColl then add to map if (extraCollAmt.compareTo(BigDecimal.ZERO) > 0) { dmdRsnAmt.put(newDmndDtls.getEgDemandReason().getEgDemandReasonMaster().getCode(), extraCollAmt); newDmndDtls.setAmtCollected(newDmndDtls.getAmtCollected().subtract(extraCollAmt)); newDmndDtls.setModifiedDate(new Date()); demandDetailsDao.update(newDmndDtls); } } } propService.getExcessCollAmtMap().put(inst, dmdRsnAmt); } LOGGER.info("Excess Collection - " + propService.getExcessCollAmtMap()); final Set<EgDemandDetails> demandDetailsToBeSaved = new HashSet<>(); for (final Map.Entry<Installment, List<EgDemandDetails>> entry : demandDetails.entrySet()) if (!entry.getValue().get(0).getEgDemandReason().getEgDemandReasonMaster().getReasonMaster() .equalsIgnoreCase(DEMANDRSN_STR_CHQ_BOUNCE_PENALTY)) demandDetailsToBeSaved.addAll(new HashSet<EgDemandDetails>(entry.getValue())); final List<Ptdemand> currPtdemand = getPersistenceService().findAllBy(QUERYINSTPTDEMAND, basicProperty, propertyTaxCommonUtils.getCurrentInstallment()); if (currPtdemand != null && currPtdemand.isEmpty()) { final Ptdemand ptDemand = new Ptdemand(); final PTDemandCalculations ptDmdCalc = new PTDemandCalculations(); ptDemand.setEgInstallmentMaster(propertyTaxCommonUtils.getCurrentInstallment()); ptDemand.setEgDemandDetails(demandDetailsToBeSaved); ptDemand.setBaseDemand(totalDmd); ptDemand.setCreateDate(new Date()); ptDemand.setModifiedDate(new Date()); ptDemand.setIsHistory("N"); ptDemand.setEgptProperty((PropertyImpl) basicProperty.getProperty()); ptDmdCalc.setPtDemand(ptDemand); ptDemand.setDmdCalculations(ptDmdCalc); getPersistenceService().applyAuditing(ptDmdCalc); basicProperty.getProperty().getPtDemandSet().add(ptDemand); } else if (currPtdemand != null) { final Ptdemand ptdemand = currPtdemand.get(0); ptdemand.getBaseDemand().add(totalDmd); ptdemand.getEgDemandDetails().addAll(demandDetailsToBeSaved); getPersistenceService().applyAuditing(ptdemand.getDmdCalculations()); basicProperty.getProperty().getPtDemandSet().add(ptdemand); } propertyImplService.update(basicProperty.getProperty()); LOGGER.info("Exiting from update"); return RESULT_ACK; }
From source file:edu.vt.vbi.patric.portlets.TranscriptomicsGeneExp.java
private JSONObject processSummary(ResourceRequest request) { JSONObject jsonResult = new JSONObject(); String paramFeatureId = request.getParameter("featureId"); String paramSampleId = request.getParameter("sampleId"); String paramKeyword = request.getParameter("keyword"); String paramLogRatio = request.getParameter("log_ratio"); String paramZScore = request.getParameter("zscore"); try {/* ww w. ja v a2s. c om*/ DataApiHandler dataApi = new DataApiHandler(request); //select?q=feature_id:PATRIC.83332.12.NC_000962.CDS.34.1524.fwd&rows=0&facet=true&facet.range.other=before&facet.range.other=after // &facet.range.start=-2&facet.range.end=2&facet.range.gap=0.5&facet.range=z_score&facet.range=log_ratio //select?q=feature_id:PATRIC.83332.12.NC_000962.CDS.34.1524.fwd&rows=0&facet=true&facet.mincount=1&facet.field=strain&facet.field=mutant&facet.field=condition SolrQuery query = new SolrQuery(); if (paramKeyword != null && !paramKeyword.equals("")) { query.setQuery(paramKeyword + " AND feature_id:" + paramFeatureId); } else { query.setQuery("feature_id:" + paramFeatureId); } if (paramSampleId != null && !paramSampleId.equals("")) { String[] pids = paramSampleId.split(","); query.addFilterQuery("pid:(" + StringUtils.join(pids, " OR ") + ")"); } if (paramLogRatio != null && !paramLogRatio.equals("") && !paramLogRatio.equals("0")) { query.addFilterQuery( "log_ratio:[* TO -" + paramLogRatio + "] OR log_ratio:[" + paramLogRatio + " TO *]"); } if (paramZScore != null && !paramZScore.equals("") && !paramZScore.equals("0")) { query.addFilterQuery("z_score:[* TO -" + paramZScore + "] OR z_score:[" + paramZScore + " TO *]"); } query.setRows(dataApi.MAX_ROWS); query.setFacet(true).setFacetMinCount(1).set("json.nl", "map"); query.set("facet.range.other", "before").add("facet.range.other", "after"); query.addNumericRangeFacet("log_ratio", -2, 2, 0.5).addNumericRangeFacet("z_score", -2, 2, 0.5); query.addFacetField("strain").addFacetField("mutant").addFacetField("condition"); LOGGER.debug("[{}] {}", SolrCore.TRANSCRIPTOMICS_GENE.getSolrCoreName(), query.toString()); String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_GENE, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); // features JSONArray features = new JSONArray(); for (Map doc : sdl) { JSONObject feature = new JSONObject(); feature.put("exp_accession", doc.get("accession")); // feature.put("exp_channels", doc.get("")); feature.put("exp_condition", doc.get("condition")); feature.put("exp_id", doc.get("eid")); feature.put("exp_locustag", doc.get("refseq_locus_tag")); feature.put("exp_mutant", doc.get("mutant")); feature.put("exp_name", doc.get("expname")); feature.put("exp_organism", doc.get("organism")); feature.put("exp_pavg", doc.get("avg_intensity")); feature.put("exp_platform", doc.get("")); // ?? feature.put("exp_pratio", doc.get("log_ratio")); feature.put("exp_samples", doc.get("")); // ?? feature.put("exp_strain", doc.get("")); // ?? feature.put("exp_timepoint", doc.get("timepoint")); feature.put("exp_zscore", doc.get("z_score")); // feature.put("figfam_id", doc.get("")); // ?? feature.put("locus_tag", doc.get("alt_locus_tag")); feature.put("feature_id", doc.get("feature_id")); feature.put("pid", doc.get("pid")); feature.put("pmid", doc.get("pmid")); features.add(feature); } jsonResult.put("features", features); Map facets = (Map) resp.get("facet_counts"); Map facetRanges = (Map) facets.get("facet_ranges"); if (facetRanges.containsKey("log_ratio")) { Map facetLogRatio = (Map) facetRanges.get("log_ratio"); final int before = (Integer) facetLogRatio.get("before"); final int after = (Integer) facetLogRatio.get("after"); Map facetRangeLogRatio = (Map) facetLogRatio.get("counts"); List<JSONObject> list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) facetRangeLogRatio.entrySet()) { JSONObject json = new JSONObject(); json.put("category", entry.getKey()); json.put("count", entry.getValue()); list.add(json); } boolean hasMinBucket = false; boolean hasMaxBucket = false; for (JSONObject entry : list) { if (entry.get("category").equals("-2.0")) { entry.put("count", ((Integer) entry.get("count") + before)); hasMinBucket = true; } else if (entry.get("category").equals("2.0")) { entry.put("count", ((Integer) entry.get("count") + after)); hasMaxBucket = true; } } if (!hasMinBucket) { JSONObject json = new JSONObject(); json.put("category", "-2.0"); json.put("count", before); list.add(json); } if (!hasMaxBucket) { JSONObject json = new JSONObject(); json.put("category", "2.0"); json.put("count", after); list.add(json); } jsonResult.put("log_ratio", list); } if (facetRanges.containsKey("z_score")) { Map facetZscore = (Map) facetRanges.get("z_score"); final int before = (Integer) facetZscore.get("before"); final int after = (Integer) facetZscore.get("after"); Map facetRangeZscore = (Map) facetZscore.get("counts"); List<JSONObject> list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) facetRangeZscore.entrySet()) { JSONObject json = new JSONObject(); json.put("category", entry.getKey()); json.put("count", entry.getValue()); list.add(json); } boolean hasMinBucket = false; boolean hasMaxBucket = false; for (JSONObject entry : list) { if (entry.get("category").equals("-2.0")) { entry.put("count", ((Integer) entry.get("count") + before)); hasMinBucket = true; } else if (entry.get("category").equals("2.0")) { entry.put("count", ((Integer) entry.get("count") + after)); hasMaxBucket = true; } } if (!hasMinBucket) { JSONObject json = new JSONObject(); json.put("category", "-2.0"); json.put("count", before); list.add(json); } if (!hasMaxBucket) { JSONObject json = new JSONObject(); json.put("category", "2.0"); json.put("count", after); list.add(json); } jsonResult.put("z_score", list); } Map facetFields = (Map) facets.get("facet_fields"); // strain if (facetFields.containsKey("strain")) { Map facetStrain = (Map) facetFields.get("strain"); List<JSONObject> list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) facetStrain.entrySet()) { JSONObject json = new JSONObject(); json.put("category", entry.getKey()); json.put("count", entry.getValue()); list.add(json); } jsonResult.put("strain", list); } // mutant if (facetFields.containsKey("mutant")) { Map facetMutant = (Map) facetFields.get("mutant"); List<JSONObject> list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) facetMutant.entrySet()) { JSONObject json = new JSONObject(); json.put("category", entry.getKey()); json.put("count", entry.getValue()); list.add(json); } jsonResult.put("mutant", list); } // condition if (facetFields.containsKey("condition")) { Map facetCondition = (Map) facetFields.get("condition"); List<JSONObject> list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) facetCondition.entrySet()) { JSONObject json = new JSONObject(); json.put("category", entry.getKey()); json.put("count", entry.getValue()); list.add(json); } jsonResult.put("condition", list); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return jsonResult; }