List of usage examples for java.util SortedMap get
V get(Object key);
From source file:com.konakart.actions.gateways.CyberSourceSAResponseAction.java
public String execute() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String transactionId = null;//from ww w. jav a 2 s. co m String merchantReference = null; String reasonCode = null; String authAmount = null; String decision = null; String referenceNumber = null; String customerEmail = null; String signature = null; String orderAmount = null; String authCode = null; String responseEnvironment = null; String authResponse = null; String message = null; String signedFields = null; KKAppEng kkAppEng = null; if (log.isDebugEnabled()) { log.debug(CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE + " Response Action"); } SortedMap<String, String> responseHash = new TreeMap<String, String>(); int maxParamNameSize = 0; try { // Process the parameters sent in the callback StringBuffer sb = new StringBuffer(); if (request != null) { Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String paramName = en.nextElement(); String paramValue = request.getParameter(paramName); if (sb.length() > 0) { sb.append("\n"); } sb.append(paramName); sb.append(" = "); sb.append(paramValue); // Capture important variables so that we can determine whether the transaction // was successful if (paramName != null) { responseHash.put(paramName, paramValue); if (paramName.equalsIgnoreCase("kkret")) { if (paramValue.equalsIgnoreCase("true")) { return "Approved"; } return "CheckoutError"; } if (paramName.length() > maxParamNameSize) { maxParamNameSize = paramName.length(); } } } } // Dump the Hashtable if (log.isDebugEnabled()) { String str = "Response fields:"; for (Map.Entry<String, String> entry : responseHash.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); str += "\n " + Utils.padRight(key, maxParamNameSize) + " = " + value; } log.debug(str); } // Pick out values of interest decision = responseHash.get("decision"); transactionId = responseHash.get("transaction_id"); merchantReference = responseHash.get("req_merchant_defined_data1"); responseEnvironment = responseHash.get("req_merchant_defined_data2"); authCode = responseHash.get("auth_code"); reasonCode = responseHash.get("reason_code"); authAmount = responseHash.get("auth_amount"); authResponse = responseHash.get("auth_response"); referenceNumber = responseHash.get("req_reference_number"); orderAmount = responseHash.get("req_amount"); signature = responseHash.get("signature"); message = responseHash.get("message"); signedFields = responseHash.get("signed_field_names"); String fullGatewayResponse = sb.toString(); if (log.isDebugEnabled()) { //log.debug(CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE + " Raw Response data:\n" // + fullGatewayResponse); log.debug("\n decision = " + decision + "\n message = " + message + "\n transactionId = " + transactionId + "\n merchantReference = " + merchantReference + "\n authCode = " + authCode + "\n reasonCode = " + reasonCode + "\n authAmount = " + authAmount + "\n authResponse = " + authResponse + "\n orderAmount = " + orderAmount + "\n referenceNumber = " + referenceNumber + "\n signature = " + signature + "\n responseEnvironment = " + responseEnvironment); } // Pick out the values from the merchantReference // Split the merchantReference into orderId, orderNumber and store information if (merchantReference == null) { throw new Exception("A merchant reference wasn't received from CyberSource"); } StringTokenizer st = new StringTokenizer(merchantReference, "~"); String orderIdStr = null; int orderId = -1; String orderNumberStr = null; String storeId = null; int engineMode = -1; boolean customersShared = false; boolean productsShared = false; boolean categoriesShared = false; String countryCode = null; if (st.hasMoreTokens()) { orderIdStr = st.nextToken(); orderId = Integer.parseInt(orderIdStr); } if (st.hasMoreTokens()) { orderNumberStr = st.nextToken(); } if (st.hasMoreTokens()) { storeId = st.nextToken(); } if (st.hasMoreTokens()) { engineMode = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { customersShared = Boolean.getBoolean(st.nextToken()); } if (st.hasMoreTokens()) { productsShared = Boolean.getBoolean(st.nextToken()); } if (st.hasMoreTokens()) { categoriesShared = Boolean.getBoolean(st.nextToken()); } if (st.hasMoreTokens()) { countryCode = st.nextToken(); } if (log.isDebugEnabled()) { log.debug("Derived from merchantReference: \n" + " OrderId = " + orderId + "\n" + " OrderNumber = " + orderNumberStr + "\n" + " StoreId = " + storeId + "\n" + " EngineMode = " + engineMode + "\n" + " CustomersShared = " + customersShared + "\n" + " ProductsShared = " + productsShared + "\n" + " CategoriesShared = " + categoriesShared + "\n" + " CountryCode = " + countryCode); } // Get an instance of the KonaKart engine // kkAppEng = this.getKKAppEng(request); // v3.2 code kkAppEng = this.getKKAppEng(request, response); // v4.1 code int custId = this.loggedIn(request, response, kkAppEng, "Checkout", false, null); // Check to see whether the user is logged in if (custId < 0) { if (log.isInfoEnabled()) { log.info("Customer is not logged in"); } return KKLOGIN; } // If we didn't receive a decision, we log a warning and return if (decision == null) { String msg = "No decision returned for the " + CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE + " module"; saveIPNrecord(kkAppEng, orderId, CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE, fullGatewayResponse, decision, transactionId, RET1_DESC + msg, RET1); throw new Exception(msg); } String sharedSecret = kkAppEng.getCustomConfig(orderIdStr + "-CUSTOM1", true); boolean validateSignature = false; if (sharedSecret == null) { if (log.isWarnEnabled()) { log.warn("CyberSource shared secret is null"); } validateSignature = false; } else { if (log.isDebugEnabled()) { log.debug("Shared Secret found on session for order " + orderIdStr); } // Check the authenticity of the message by checking the signature String data = null; String dataStr = "Data to Sign:"; for (String field : signedFields.split(",")) { if (data == null) { data = field + "=" + responseHash.get(field); } else { data += "," + field + "=" + responseHash.get(field); } dataStr += "\n " + Utils.padRight(field, maxParamNameSize) + " = " + responseHash.get(field); } if (log.isDebugEnabled()) { log.debug("Validate Signed Fields : " + data); log.debug(dataStr); } validateSignature = CyberSourceSAHMACTools.verifyBase64EncodedSignature(sharedSecret, signature, data); } if (log.isDebugEnabled()) { log.debug("Signature Validation Result: " + validateSignature); } // If the signature on the amount doesn't validate we log a warning and return if (!validateSignature) { String msg = "Signature Validation Failed for the " + CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE + " module - orderId " + orderId; saveIPNrecord(kkAppEng, orderId, CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE, fullGatewayResponse, decision, transactionId, RET1_DESC + msg, RET1); throw new Exception(msg); } // Validate we are in the correct environment boolean validateEnvironment = true; String sessionEnvironment = kkAppEng.getCustomConfig(orderIdStr + "-CUSTOM2", true); if (sessionEnvironment == null) { if (log.isWarnEnabled()) { log.warn("CyberSource Operating Environment is null on the session"); } validateEnvironment = false; } else if (illegalEnvironmentValue(sessionEnvironment)) { if (log.isWarnEnabled()) { log.warn("CyberSource Operating Environment on the session is illegal"); } validateEnvironment = false; } else if (illegalEnvironmentValue(responseEnvironment)) { if (log.isWarnEnabled()) { log.warn("CyberSource Operating Environment in the session is illegal"); } validateEnvironment = false; } else if (!sessionEnvironment.equals(responseEnvironment)) { if (log.isWarnEnabled()) { log.warn("CyberSource Operating Environment in the session (" + sessionEnvironment + ") does not match that in the response (" + responseEnvironment + ")"); } validateEnvironment = false; } // If the signature on the amount doesn't validate we log a warning and return if (!validateEnvironment) { String msg = "Environment Validation Failed for the " + CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE + " module - orderId " + orderId; saveIPNrecord(kkAppEng, orderId, CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE, fullGatewayResponse, decision, transactionId, RET1_DESC + msg, RET1); throw new Exception(msg); } // See if we need to send an email, by looking at the configuration String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS); boolean sendEmail = false; if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) { sendEmail = true; } // If we didn't receive an ACCEPT decision, we let the user Try Again OrderUpdateIf updateOrder = new OrderUpdate(); updateOrder.setUpdatedById(kkAppEng.getActiveCustId()); if (!decision.equals("ACCEPT")) { if (log.isDebugEnabled()) { log.debug("Payment Not Approved for orderId: " + orderId + " for customer: " + customerEmail + " reason: " + getReasonDescription(reasonCode)); } saveIPNrecord(kkAppEng, orderId, CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE, fullGatewayResponse, decision, transactionId, RET2_DESC + decision + " : " + getReasonDescription(reasonCode), RET2); String comment = ORDER_HISTORY_COMMENT_KO + decision; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), orderId, com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, sendEmail, comment, updateOrder); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, orderId, /* success */false); } String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { comment }); addActionError(msg); /* * Add a parameter that is sent back to this action when trying to break out of the * frame */ if (request != null) { StringBuffer retUrl = request.getRequestURL(); retUrl.append("?kkret=false"); this.url = retUrl.toString(); return "redirect"; } throw new KKException("The HttpServletRequest is null"); } // If successful, we forward to "Approved" if (log.isDebugEnabled()) { log.debug("Payment Approved for orderId " + orderId + " for customer " + customerEmail); } saveIPNrecord(kkAppEng, orderId, CyberSourceSA.CYBERSOURCESA_GATEWAY_CODE, fullGatewayResponse, decision, transactionId, RET0_DESC, RET0); String comment = ORDER_HISTORY_COMMENT_OK + transactionId; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), orderId, com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, sendEmail, comment, updateOrder); // If the order payment was approved we update the inventory kkAppEng.getEng().updateInventory(kkAppEng.getSessionId(), orderId); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, orderId, /* success */true); } // If we received no exceptions, delete the basket kkAppEng.getBasketMgr().emptyBasket(); /* * Add a parameter that is sent back to this action when trying to break out of the * frame */ if (request != null) { StringBuffer retUrl = request.getRequestURL(); retUrl.append("?kkret=true"); this.url = retUrl.toString(); return "redirect"; } throw new KKException("The HttpServletRequest is null"); } catch (Exception e) { e.printStackTrace(); return super.handleException(request, e); } }
From source file:org.opencms.workplace.commons.CmsPreferences.java
/** * Builds the html for the preferred editors select boxes of the editor settings.<p> * /*from w w w .j a v a2 s .c om*/ * @param htmlAttributes optional html attributes for the &lgt;select> tag * @return the html for the preferred editors select boxes */ public String buildSelectPreferredEditors(String htmlAttributes) { StringBuffer result = new StringBuffer(1024); HttpServletRequest request = getJsp().getRequest(); if (htmlAttributes != null) { htmlAttributes += " name=\"" + PARAM_PREFERREDEDITOR_PREFIX; } Map resourceEditors = OpenCms.getWorkplaceManager().getWorkplaceEditorManager().getConfigurableEditors(); if (resourceEditors != null) { // first: iterate over the resource types and consider order from configuration Iterator i = resourceEditors.keySet().iterator(); SortedMap rankResources = new TreeMap(); while (i.hasNext()) { String currentResourceType = (String) i.next(); CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager() .getExplorerTypeSetting(currentResourceType); rankResources.put(new Float(settings.getNewResourceOrder()), currentResourceType); } while (rankResources.size() > 0) { // get editor configuration with lowest order Float keyVal = (Float) rankResources.firstKey(); String currentResourceType = (String) rankResources.get(keyVal); SortedMap availableEditors = (TreeMap) resourceEditors.get(currentResourceType); if ((availableEditors != null) && (availableEditors.size() > 0)) { String preSelection = computeEditorPreselection(request, currentResourceType); List options = new ArrayList(availableEditors.size() + 1); List values = new ArrayList(availableEditors.size() + 1); options.add(key(Messages.GUI_PREF_EDITOR_BEST_0)); values.add(INPUT_DEFAULT); // second: iteration over the available editors for the resource type int selectedIndex = 0; int counter = 1; while (availableEditors.size() > 0) { Float key = (Float) availableEditors.lastKey(); CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) availableEditors .get(key); options.add(keyDefault(conf.getEditorLabel(), conf.getEditorLabel())); values.add(conf.getEditorUri()); if (conf.getEditorUri().equals(preSelection)) { selectedIndex = counter; } counter++; availableEditors.remove(key); } // create the table row for the current resource type result.append("<tr>\n\t<td style=\"white-space: nowrap;\">"); String localizedName = keyDefault("label.editor.preferred." + currentResourceType, ""); if (CmsStringUtil.isEmpty(localizedName)) { localizedName = CmsWorkplaceMessages.getResourceTypeName(this, currentResourceType); } result.append(localizedName); result.append("</td>\n\t<td>"); result.append(buildSelect(htmlAttributes + currentResourceType + "\"", options, values, selectedIndex)); result.append("</td>\n</tr>\n"); } rankResources.remove(keyVal); } } return result.toString(); }
From source file:org.apache.hadoop.hbase.tool.LoadIncrementalHFiles.java
/** * If the table is created for the first time, then "completebulkload" reads the files twice. More * modifications necessary if we want to avoid doing it. *//*from w w w . j a va2 s .c o m*/ private void createTable(TableName tableName, Path hfofDir, Admin admin) throws IOException { final FileSystem fs = hfofDir.getFileSystem(getConf()); // Add column families // Build a set of keys List<ColumnFamilyDescriptorBuilder> familyBuilders = new ArrayList<>(); SortedMap<byte[], Integer> map = new TreeMap<>(Bytes.BYTES_COMPARATOR); visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<ColumnFamilyDescriptorBuilder>() { @Override public ColumnFamilyDescriptorBuilder bulkFamily(byte[] familyName) { ColumnFamilyDescriptorBuilder builder = ColumnFamilyDescriptorBuilder.newBuilder(familyName); familyBuilders.add(builder); return builder; } @Override public void bulkHFile(ColumnFamilyDescriptorBuilder builder, FileStatus hfileStatus) throws IOException { Path hfile = hfileStatus.getPath(); try (HFile.Reader reader = HFile.createReader(fs, hfile, CacheConfig.DISABLED, true, getConf())) { if (builder.getCompressionType() != reader.getFileContext().getCompression()) { builder.setCompressionType(reader.getFileContext().getCompression()); LOG.info("Setting compression " + reader.getFileContext().getCompression().name() + " for family " + builder.getNameAsString()); } reader.loadFileInfo(); byte[] first = reader.getFirstRowKey().get(); byte[] last = reader.getLastRowKey().get(); LOG.info("Trying to figure out region boundaries hfile=" + hfile + " first=" + Bytes.toStringBinary(first) + " last=" + Bytes.toStringBinary(last)); // To eventually infer start key-end key boundaries Integer value = map.containsKey(first) ? map.get(first) : 0; map.put(first, value + 1); value = map.containsKey(last) ? map.get(last) : 0; map.put(last, value - 1); } } }); byte[][] keys = inferBoundaries(map); TableDescriptorBuilder tdBuilder = TableDescriptorBuilder.newBuilder(tableName); familyBuilders.stream().map(ColumnFamilyDescriptorBuilder::build) .forEachOrdered(tdBuilder::setColumnFamily); admin.createTable(tdBuilder.build(), keys); LOG.info("Table " + tableName + " is available!!"); }
From source file:org.kuali.kra.proposaldevelopment.web.struts.action.ProposalDevelopmentAction.java
public ActionForward customData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {//from www .j a v a 2 s . co m SortedMap<String, List<CustomAttributeDocument>> customAttributeGroups = new TreeMap<String, List<CustomAttributeDocument>>(); ProposalDevelopmentForm proposalDevelopmentForm = (ProposalDevelopmentForm) form; ProposalDevelopmentDocument doc = proposalDevelopmentForm.getDocument(); Map<String, CustomAttributeDocument> customAttributeDocuments = doc.getCustomAttributeDocuments(); String documentNumber = doc.getDocumentNumber(); for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry : customAttributeDocuments .entrySet()) { CustomAttributeDocument customAttributeDocument = customAttributeDocumentEntry.getValue(); Map<String, Object> primaryKeys = new HashMap<String, Object>(); primaryKeys.put(KNSPropertyConstants.DOCUMENT_NUMBER, documentNumber); primaryKeys.put(Constants.CUSTOM_ATTRIBUTE_ID, customAttributeDocument.getCustomAttributeId()); CustomAttributeDocValue customAttributeDocValue = (CustomAttributeDocValue) KraServiceLocator .getService(BusinessObjectService.class) .findByPrimaryKey(CustomAttributeDocValue.class, primaryKeys); if (customAttributeDocValue != null) { customAttributeDocument.getCustomAttribute().setValue(customAttributeDocValue.getValue()); proposalDevelopmentForm.getCustomAttributeValues().put( "id" + customAttributeDocument.getCustomAttributeId().toString(), new String[] { customAttributeDocValue.getValue() }); } String groupName = customAttributeDocument.getCustomAttribute().getGroupName(); List<CustomAttributeDocument> customAttributeDocumentList = customAttributeGroups.get(groupName); if (customAttributeDocumentList == null) { customAttributeDocumentList = new ArrayList<CustomAttributeDocument>(); customAttributeGroups.put(groupName, customAttributeDocumentList); } customAttributeDocumentList.add(customAttributeDocument); Collections.sort(customAttributeDocumentList, new LabelComparator()); } ((ProposalDevelopmentForm) form).setCustomAttributeGroups(customAttributeGroups); return mapping.findForward(Constants.CUSTOM_ATTRIBUTES_PAGE); }
From source file:org.neo4j.gis.spatial.OsmAnalysisTest.java
private SortedMap<String, Layer> exportPoints(String layerPrefix, SpatialDatabaseService spatialService, Set<User> users) {/*from ww w . jav a 2s.co m*/ SortedMap<String, Layer> layers = new TreeMap<String, Layer>(); int startYear = 2009; int endYear = 2011; for (int y = startYear; y <= endYear; y++) { for (int w = 1; w <= 52; w++) { if (y == 2011 && w == 36) { break; } String name = layerPrefix + "-" + y + "_"; if (w >= 10) name += w; else name += "0" + w; EditableLayerImpl layer = (EditableLayerImpl) spatialService.createLayer(name, WKBGeometryEncoder.class, EditableLayerImpl.class); layer.setExtraPropertyNames( new String[] { "user_id", "user_name", "year", "month", "dayOfMonth", "weekOfYear" }); // EditableLayerImpl layer = (EditableLayerImpl) // spatialService.getLayer(name); layers.put(name, layer); } } for (User user : users) { Node userNode = graphDb().getNodeById(user.id); System.out.println("analyzing user: " + userNode.getProperty("name")); for (Relationship r : userNode.getRelationships(Direction.INCOMING, OSMRelation.USER)) { Node changeset = r.getStartNode(); if (changeset.hasProperty("changeset")) { System.out.println("analyzing changeset: " + changeset.getProperty("changeset")); try (Transaction tx = graphDb().beginTx()) { for (Relationship nr : changeset.getRelationships(Direction.INCOMING, OSMRelation.CHANGESET)) { Node changedNode = nr.getStartNode(); if (changedNode.hasProperty("node_osm_id") && changedNode.hasProperty("timestamp")) { long timestamp = (Long) changedNode.getProperty("timestamp"); Calendar c = Calendar.getInstance(); c.setTimeInMillis(timestamp); int nodeYear = c.get(Calendar.YEAR); int nodeWeek = c.get(Calendar.WEEK_OF_YEAR); if (layers.containsKey(layerPrefix + "-" + nodeYear + "_" + nodeWeek)) { EditableLayer l = (EditableLayer) layers .get(layerPrefix + "-" + nodeYear + "_" + nodeWeek); l.add(l.getGeometryFactory() .createPoint(new Coordinate((Double) changedNode.getProperty("lon"), (Double) changedNode.getProperty("lat"))), new String[] { "user_id", "user_name", "year", "month", "dayOfMonth", "weekOfYear" }, new Object[] { user.internalId, user.name, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.WEEK_OF_YEAR) }); } } } tx.success(); } } } } return layers; }
From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java
/** * Algorithm for getting the start key for a filter * step 1: Iterate through each dimension and verify whether its not an exclude filter. * step 2: Initialize start key with the first filter member value present in each filter model * for the respective dimensions./* ww w . j av a 2s.com*/ * step 3: since its a no dictionary start key there will only actual value so compare * the first filter model value with respect to the dimension data type. * step 4: The least value will be considered as the start key of dimension by comparing all * its filter model. * step 5: create a byte array of start key which comprises of least filter member value of * all dimension and the indexes which will help to read the respective filter value. * * @param dimColResolvedFilterInfo * @param setOfStartKeyByteArray * @return */ public static void getStartKeyForNoDictionaryDimension(DimColumnResolvedFilterInfo dimColResolvedFilterInfo, SegmentProperties segmentProperties, SortedMap<Integer, byte[]> setOfStartKeyByteArray) { Map<CarbonDimension, List<ColumnFilterInfo>> dimensionFilter = dimColResolvedFilterInfo .getDimensionResolvedFilterInstance(); // step 1 for (Map.Entry<CarbonDimension, List<ColumnFilterInfo>> entry : dimensionFilter.entrySet()) { if (!entry.getKey().hasEncoding(Encoding.DICTIONARY)) { List<ColumnFilterInfo> listOfDimColFilterInfo = entry.getValue(); if (null == listOfDimColFilterInfo) { continue; } boolean isExcludePresent = false; for (ColumnFilterInfo info : listOfDimColFilterInfo) { if (!info.isIncludeFilter()) { isExcludePresent = true; } } if (isExcludePresent) { continue; } // in case of restructure scenarios it can happen that the filter dimension is not // present in the current block. In those cases no need to determine the key CarbonDimension dimensionFromCurrentBlock = CarbonUtil .getDimensionFromCurrentBlock(segmentProperties.getDimensions(), entry.getKey()); if (null == dimensionFromCurrentBlock) { continue; } // step 2 byte[] noDictionaryStartKey = listOfDimColFilterInfo.get(0).getNoDictionaryFilterValuesList() .get(0); if (setOfStartKeyByteArray.isEmpty()) { setOfStartKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryStartKey); } else if (null == setOfStartKeyByteArray.get(dimensionFromCurrentBlock.getOrdinal())) { setOfStartKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryStartKey); } else if (ByteUtil.UnsafeComparer.INSTANCE.compareTo( setOfStartKeyByteArray.get(dimensionFromCurrentBlock.getOrdinal()), noDictionaryStartKey) > 0) { setOfStartKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryStartKey); } } } }
From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java
/** * Algorithm for getting the end key for a filter * step 1: Iterate through each dimension and verify whether its not an exclude filter. * step 2: Initialize end key with the last filter member value present in each filter model * for the respective dimensions.(Already filter models are sorted) * step 3: since its a no dictionary end key there will only actual value so compare * the last filter model value with respect to the dimension data type. * step 4: The highest value will be considered as the end key of dimension by comparing all * its filter model.// w ww.jav a 2s . com * step 5: create a byte array of end key which comprises of highest filter member value of * all dimension and the indexes which will help to read the respective filter value. * * @param dimColResolvedFilterInfo * @param setOfEndKeyByteArray * @return end key array */ public static void getEndKeyForNoDictionaryDimension(DimColumnResolvedFilterInfo dimColResolvedFilterInfo, SegmentProperties segmentProperties, SortedMap<Integer, byte[]> setOfEndKeyByteArray) { Map<CarbonDimension, List<ColumnFilterInfo>> dimensionFilter = dimColResolvedFilterInfo .getDimensionResolvedFilterInstance(); // step 1 for (Map.Entry<CarbonDimension, List<ColumnFilterInfo>> entry : dimensionFilter.entrySet()) { if (!entry.getKey().hasEncoding(Encoding.DICTIONARY)) { List<ColumnFilterInfo> listOfDimColFilterInfo = entry.getValue(); if (null == listOfDimColFilterInfo) { continue; } boolean isExcludePresent = false; for (ColumnFilterInfo info : listOfDimColFilterInfo) { if (!info.isIncludeFilter()) { isExcludePresent = true; } } if (isExcludePresent) { continue; } // in case of restructure scenarios it can happen that the filter dimension is not // present in the current block. In those cases no need to determine the key CarbonDimension dimensionFromCurrentBlock = CarbonUtil .getDimensionFromCurrentBlock(segmentProperties.getDimensions(), entry.getKey()); if (null == dimensionFromCurrentBlock) { continue; } // step 2 byte[] noDictionaryEndKey = listOfDimColFilterInfo.get(0).getNoDictionaryFilterValuesList() .get(listOfDimColFilterInfo.get(0).getNoDictionaryFilterValuesList().size() - 1); if (setOfEndKeyByteArray.isEmpty()) { setOfEndKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryEndKey); } else if (null == setOfEndKeyByteArray.get(dimensionFromCurrentBlock.getOrdinal())) { setOfEndKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryEndKey); } else if (ByteUtil.UnsafeComparer.INSTANCE.compareTo( setOfEndKeyByteArray.get(dimensionFromCurrentBlock.getOrdinal()), noDictionaryEndKey) < 0) { setOfEndKeyByteArray.put(dimensionFromCurrentBlock.getOrdinal(), noDictionaryEndKey); } } } }
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
/** * IME??/*from w w w . j ava 2s .c o m*/ * * @param name "area" / "corp" * @param suffix "" / "c" */ void storeIme(String name, String suffix) { long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); SortedMap<String, Pref> prefs = getPrefMap(); Collection<City> cities = getCities(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); ZipEntry entry = new ZipEntry( FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_ime_dic.txt"); entry.setTime(timestamp); int cnt = 0; try { byte[] tab = "\t".getBytes("MS932"); byte[] sonota = "\t?????".getBytes("MS932"); byte[] crlf = CRLF.getBytes("MS932"); zos.putNextEntry(entry); for (City city : cities) { ParentChild pc = getParentChildDao().get(city.getCode() + suffix); if (pc == null) { continue; } String prefName = prefs.get(city.getCode().substring(0, 2)).getName(); String cityName = city.getName(); for (String json : pc.getChildren()) { Zip zip = Zip.fromJson(json); zos.write(ZenHanHelper.convertZipHankakuZenkaku(zip.getCode()).getBytes("MS932")); zos.write(tab); zos.write(prefName.getBytes("MS932")); zos.write(cityName.getBytes("MS932")); zos.write(zip.getAdd1().getBytes("MS932")); zos.write(zip.getAdd2().getBytes("MS932")); zos.write(zip.getCorp().getBytes("MS932")); zos.write(sonota); zos.write(crlf); ++cnt; } } zos.closeEntry(); zos.finish(); getRawDao().store(baos.toByteArray(), name + "_ime_dic.zip"); log.info("count: " + cnt); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
From source file:edu.stanford.epad.common.pixelmed.SegmentationObjectsFileWriter.java
private int[] sort_frames_by_position(AttributeList geometry, double[][] positions, int frame_num) throws DicomException { int[] index = new int[frame_num]; double[] distances = new double[frame_num]; class DoubleArrayComparator implements Comparator<List<Double>> { public int compare(List<Double> o1, List<Double> o2) { int val; if (o1.get(0) > o2.get(0)) val = 1; else if (o1.get(0) < o2.get(0)) val = -1; else { if (o1.get(1) > o2.get(1)) val = 1; else if (o1.get(1) < o2.get(1)) val = -1; else val = 0; }/*from www .j a v a 2s .c o m*/ return val; } } SortedMap<ArrayList<Double>, Integer> sorting = new TreeMap<ArrayList<Double>, Integer>( new DoubleArrayComparator()); GeometryOfSlice slice_geometry; AttributeList geometry_list = (AttributeList) geometry.clone(); ArrayList<Double> key; for (int i = 0; i < frame_num; i++) { Attribute a = new DecimalStringAttribute(TagFromName.ImagePositionPatient); if (positions != null) { a.addValue(positions[i][0]); a.addValue(positions[i][1]); a.addValue(positions[i][2]); } else { a.addValue(0); a.addValue(0); a.addValue(0); } geometry_list.put(a); slice_geometry = new GeometryOfSliceFromAttributeList(geometry_list); distances[i] = slice_geometry.getDistanceAlongNormalFromOrigin(); key = new ArrayList<Double>(2); key.add(0, distances[i]); key.add(1, (double) i); sorting.put(key, 0); } // k will be the index of sorted keys. int k = 1; for (Map.Entry<ArrayList<Double>, Integer> entry : sorting.entrySet()) { sorting.put(entry.getKey(), k++); } for (int i = 0; i < frame_num; i++) { key = new ArrayList<Double>(2); key.add(0, distances[i]); key.add(1, (double) i); index[i] = sorting.get(key); } return index; }