List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:com.vuze.plugin.azVPN_PIA.Checker.java
public String portBindingCheck() { synchronized (this) { if (checkingPortBinding) { return lastPortCheckStatus; }// w w w. j a va2 s . c o m checkingPortBinding = true; } CheckerListener[] triggers = listeners.toArray(new CheckerListener[0]); for (CheckerListener l : triggers) { try { l.portCheckStart(); } catch (Exception e) { e.printStackTrace(); } } StringBuilder sReply = new StringBuilder(); String pathPIAManager = config.getPluginStringParameter(PluginPIA.CONFIG_PIA_MANAGER_DIR); File pathPIAManagerData = new File(pathPIAManager, "data"); try { int newStatusID = findBindingAddress(pathPIAManagerData, sReply); boolean rpcCalled = false; if (newStatusID != STATUS_ID_BAD && vpnIP != null) { rpcCalled = callRPCforPort(pathPIAManagerData, vpnIP, sReply); } if (!rpcCalled) { boolean gotPort = checkStatusFileForPort(pathPIAManagerData, sReply); if (!gotPort) { if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; addReply(sReply, CHAR_WARN, "pia.port.forwarding.get.failed"); } } } if (newStatusID != -1) { currentStatusID = newStatusID; } String msgID = null; if (newStatusID == STATUS_ID_BAD) { msgID = "pia.topline.bad"; } else if (newStatusID == STATUS_ID_OK) { msgID = "pia.topline.ok"; } else if (newStatusID == STATUS_ID_WARN) { msgID = "pia.topline.warn"; } if (msgID != null) { sReply.insert(0, texts.getLocalisedMessageText(msgID) + "\n"); } } catch (Throwable t) { t.printStackTrace(); PluginPIA.log(t.toString()); } lastPortCheckStatus = sReply.toString(); triggers = listeners.toArray(new CheckerListener[0]); for (CheckerListener l : triggers) { try { l.portCheckStatusChanged(lastPortCheckStatus); } catch (Exception e) { e.printStackTrace(); } } synchronized (this) { checkingPortBinding = false; } return lastPortCheckStatus; }
From source file:de.aschoerk.javaconv.RustDumpVisitor.java
private String getArrayDeclaration(String typeOrDefaultValue, List<String> dims) { StringBuilder sb = new StringBuilder(); sb.append(typeOrDefaultValue);//from w ww .j a v a 2 s . c o m reverse(dims); for (String s : dims) { sb.insert(0, "["); sb.append("; ").append(s).append("]"); } reverse(dims); return sb.toString(); }
From source file:au.org.ala.delta.util.Utils.java
/** * The main job of this method is to terminate RTF control words with {} * instead of a space./*from w w w. j a va 2 s .c o m*/ */ // Not all cases are handled correctly in the current code. // For example, text with \bin might not always give correct results // A few other things, such as \'xx, should perhaps also be given // explicit treatment, but should not substantially affect the outcome. public static String despaceRtf(String text, boolean quoteDelims) { if (StringUtils.isEmpty(text)) { return ""; } int srcPos; boolean inRTF = false; boolean inParam = false; boolean inUnicode = false; boolean bracketed = text.charAt(0) == '<' && text.charAt(text.length() - 1) == '>'; StringBuilder outputText = new StringBuilder(text); if (bracketed) // If a "comment", temporarily chop off the terminating // bracket outputText.setLength(outputText.length() - 1); for (srcPos = 0; srcPos < outputText.length(); ++srcPos) { char ch = outputText.charAt(srcPos); // Always convert a tab character into a \tab control word if (ch == '\t') { outputText.replace(srcPos, srcPos + 1, "\\tab{}"); ch = '\\'; } if (inRTF) { if (Character.isDigit(ch) || (!inParam && ch == '-')) { if (!inParam && outputText.charAt(srcPos - 1) == 'u' && outputText.charAt(srcPos - 2) == '\\') inUnicode = true; inParam = true; } else if (inParam || !Character.isLetter(ch)) { boolean wasInUnicode = inUnicode; inUnicode = inParam = inRTF = false; if (Character.isSpaceChar(ch)) { // Check for the absence of a control; when this // happens, // the terminating character IS the control word! if (srcPos > 0 && outputText.charAt(srcPos - 1) == '\\') { // \<NEWLINE> is treated as a \par control. We make // this // change here explicitly, to make it more apparent. // But should we keep the <NEWLINE> character around // as well, // as a clue for breaking lines during output? if (ch == '\n' || ch == '\r') { // text.replace(--srcPos, 2, "\\par{}"); outputText.insert(srcPos, "par{}"); srcPos += 5; } // (Note that if we don't catch this here, replacing // "\ " could yield // "\{}" which is WRONG. But rather than just get // rid of this, it // is probably better to replace with {} to ensure // that any preceding // RTF is terminated) else if (ch == ' ') { outputText.replace(srcPos - 1, 2, "{}"); } } // This is the chief condition we are trying to fix. // Terminate the RTF // control phrase with {} instead of white space... // But if the terminator is a new line, we keep it // around // for assistance in wrapping output lines. // else if (ch == '\n') // { // text.insert(srcPos, "{}"); // srcPos += 2; // } else if (ch != '\n') { outputText.setCharAt(srcPos, '{'); outputText.insert(++srcPos, '}'); } } // No reason to do the following. Probably better to leave // the // character quoted. // Reinstated 8 December 1999 because we need to be sure // all text is in a consistent state when linking characters // One exception - if the quoted character is a Unicode // "replacement" // character, we'd better leave it quoted. else if (ch == '\'' && !wasInUnicode && srcPos + 2 < outputText.length()) { char[] buff = new char[3]; buff[0] = outputText.charAt(srcPos + 1); buff[1] = outputText.charAt(srcPos + 2); buff[2] = 0; int[] endPos = new int[1]; int value = strtol(new String(buff), endPos, 16); if ((endPos[0] == 2) && value > 127 && outputText.charAt(srcPos - 1) == '\\') { srcPos--; outputText.replace(srcPos, srcPos + 4, new String(new char[] { (char) value })); } } else if (ch == '\\' && outputText.charAt(srcPos - 1) != '\\') // Terminates // RTF, // but // starts // new // RTF { inRTF = true; if (wasInUnicode && srcPos + 1 < outputText.length() && outputText.charAt(srcPos + 1) == '\'') inUnicode = true; } else if (ch == '>') { // Append a space after the RTF (it was probably // stripped by the attribute parsing) outputText.insert(srcPos, "{}"); } } } else if (ch == '\\') inRTF = true; // TEST - to allow outputting of a "*" or "#" character in arbitrary // text... else if (quoteDelims && (ch == '*' || ch == '#') && (srcPos == 0 || Character.isSpaceChar(outputText.charAt(srcPos - 1)))) { // //char buffer[5]; // Always build a 4-character replacement string, like: // \'20 // //sprintf(buffer, "\\\'%2.2x", (int)ch); // //text.replace(srcPos, buffer, 4); // //srcPos += 3; outputText.insert(srcPos, "{}"); srcPos += 2; } } if (inRTF) outputText.append("{}"); if (bracketed) outputText.append('>'); return outputText.toString(); }
From source file:de.aschoerk.javaconv.RustDumpVisitor.java
@Override public void visit(final ArrayInitializerExpr n, final Object arg) { Type t = arg instanceof Type ? (Type) arg : null; printJavaComment(n.getComment(), arg); if (!isNullOrEmpty(n.getValues())) { if (t != null) { List<Integer> dims = getDimensions(n, t); StringBuilder sb = new StringBuilder(); sb.append(acceptAndCut(t, arg)); reverse(dims);/* w w w . j av a2 s .com*/ for (Integer i : dims) { sb.insert(0, "vec!["); sb.append("; ").append(i).append("]"); } printer.print(": "); printer.print(sb.toString()); printer.print(" = "); } printer.print("vec!["); for (Expression val : n.getValues()) { val.accept(this, null); printer.print(", "); } printer.printLn("]"); } }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
/** * Sign a JAR file outputting the signed JAR to a different file. * * @param jarFile/*from ww w.j ava2 s. c o m*/ * JAR file to sign * @param signedJarFile * Output file for signed JAR * @param privateKey * Private key to sign with * @param certificateChain * Certificate chain for private key * @param signatureType * Signature type * @param signatureName * Signature name * @param signer * Signer * @param digestType * Digest type * @param tsaUrl * TSA URL * @throws IOException * If an I/O problem occurs while signing the JAR file * @throws CryptoException * If a crypto problem occurs while signing the JAR file */ public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer, DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException { JarFile jar = null; JarOutputStream jos = null; try { // Replace illegal characters in signature name signatureName = convertSignatureName(signatureName); // Create Jar File accessor for JAR to be signed jar = new JarFile(jarFile); // Write manifest content to here StringBuilder sbManifest = new StringBuilder(); // Write out main attributes to manifest String manifestMainAttrs = getManifestMainAttrs(jar, signer); sbManifest.append(manifestMainAttrs); // Write out all entries' attributes to manifest String entryManifestAttrs = getManifestEntriesAttrs(jar); if (entryManifestAttrs.length() > 0) { // Only output if there are any sbManifest.append(entryManifestAttrs); sbManifest.append(CRLF); } // Write signature file to here StringBuilder sbSf = new StringBuilder(); // Write out digests to manifest and signature file // Sign each JAR entry... for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) // Ignore directories { if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files) { // Get the digest of the entry as manifest attributes String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType); // Add it to the manifest string buffer sbManifest.append(manifestEntry); // Get the digest of manifest entries created above byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType); byte[] mdSf64 = Base64.encode(mdSf); String mdSf64Str = new String(mdSf64); // Write this digest as entries in signature file sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName())); sbSf.append(CRLF); sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), mdSf64Str)); sbSf.append(CRLF); sbSf.append(CRLF); } } } // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file byte[] manifest = sbManifest.toString().getBytes(); byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType); String digestMfStr = new String(Base64.encode(digestMf)); // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file byte[] mainfestMainAttrs = manifestMainAttrs.getBytes(); byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType); String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs)); // Write out Manifest Digest, Created By and Signature Version to start of signature file sbSf.insert(0, CRLF); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText( MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()), digestMfMainAttrsStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION)); // Signature file complete byte[] sf = sbSf.toString().getBytes(); // Create output stream to write signed JAR jos = new JarOutputStream(new FileOutputStream(signedJarFile)); // Write JAR files from JAR to be signed to signed JAR writeJarEntries(jar, jos, signatureName); // Write manifest to signed JAR writeManifest(manifest, jos); // Write signature file to signed JAR writeSignatureFile(sf, signatureName, jos); // Create signature block and write it out to signed JAR byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl, provider); writeSignatureBlock(sigBlock, signatureType, signatureName, jos); } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(jos); } }
From source file:com.vuze.plugin.azVPN_Air.Checker.java
public String portBindingCheck() { synchronized (this) { if (checkingPortBinding) { return lastPortCheckStatus; }/* w w w .j a v a 2s . c o m*/ checkingPortBinding = true; } CheckerListener[] triggers = listeners.toArray(new CheckerListener[0]); for (CheckerListener l : triggers) { try { l.portCheckStart(); } catch (Exception e) { e.printStackTrace(); } } StringBuilder sReply = new StringBuilder(); try { int newStatusID = findBindingAddress(sReply); boolean doPortForwarding = config.getPluginBooleanParameter(PluginAir.CONFIG_DO_PORT_FORWARDING); if (doPortForwarding) { boolean rpcCalled = false; if (newStatusID != STATUS_ID_BAD && vpnIP != null) { rpcCalled = callRPCforPort(vpnIP, sReply); } if (!rpcCalled) { if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; addReply(sReply, CHAR_WARN, "airvpn.port.forwarding.get.failed"); } } } if (newStatusID != -1) { currentStatusID = newStatusID; } String msgID = null; if (newStatusID == STATUS_ID_BAD) { msgID = "airvpn.topline.bad"; } else if (newStatusID == STATUS_ID_OK) { msgID = "airvpn.topline.ok"; } else if (newStatusID == STATUS_ID_WARN) { msgID = "airvpn.topline.warn"; } if (msgID != null) { sReply.insert(0, texts.getLocalisedMessageText(msgID) + "\n"); } } catch (Throwable t) { t.printStackTrace(); PluginAir.log(t.toString()); } lastPortCheckStatus = sReply.toString(); triggers = listeners.toArray(new CheckerListener[0]); for (CheckerListener l : triggers) { try { l.portCheckStatusChanged(lastPortCheckStatus); } catch (Exception e) { e.printStackTrace(); } } synchronized (this) { checkingPortBinding = false; } return lastPortCheckStatus; }
From source file:org.sakaiproject.component.app.messageforums.ui.PrivateMessageManagerImpl.java
private String buildMessageBody(PrivateMessage message) { User currentUser = UserDirectoryService.getCurrentUser(); StringBuilder body = new StringBuilder(message.getBody()); StringBuilder fromString = new StringBuilder(); fromString.append("<p>"); if (ServerConfigurationService.getBoolean("msg.displayEid", true)) { fromString.append(getResourceBundleString("pvt_email_from_with_eid", new Object[] { currentUser.getDisplayName(), currentUser.getEid(), currentUser.getEmail() })); } else {/*from w w w.j a v a 2 s . co m*/ fromString.append(getResourceBundleString("pvt_email_from", new Object[] { currentUser.getDisplayName(), currentUser.getEmail() })); } fromString.append("</p>"); body.insert(0, fromString.toString()); // need to determine if there are "hidden" recipients to this message. // If so, we need to replace them with "Undisclosed Recipients" // Identifying them is tricky now because hidden users are identified by having their // names in parentheses at the end of the list. At some point, the usernames were also added to // this in parentheses (although this may be overridden via a property). // So to fix this going forward, the hidden users will be indicated by brackets [], // but we still need to handle the old data with hidden users in parens String sendToString = message.getRecipientsAsText(); if (sendToString.indexOf(PrivateMessage.HIDDEN_RECIPIENTS_START) > 0) { sendToString = sendToString.substring(0, sendToString.indexOf(PrivateMessage.HIDDEN_RECIPIENTS_START)); // add "Undisclosed Recipients" in place of the hidden users sendToString = sendToString.trim(); if (sendToString.length() > 0) { sendToString += "; "; } sendToString += getResourceBundleString("pvt_HiddenRecipients"); } else { // we may have parens around a list of names with eid in parens if (ServerConfigurationService.getBoolean("msg.displayEid", true)) { String originalSendTo = sendToString; sendToString = sendToString.replaceAll("\\([^)]+\\(.*", ""); // add "Undisclosed Recipients" in place of the hidden users if (!sendToString.equals(originalSendTo)) { sendToString = sendToString.trim(); if (sendToString.length() > 0) { sendToString += "; "; } sendToString += getResourceBundleString("pvt_HiddenRecipients"); } } else { // the old data just has the hidden users in parens if (sendToString.indexOf("(") > 0) { sendToString = sendToString.substring(0, sendToString.indexOf("(")); // add "Undisclosed Recipients" in place of the hidden users sendToString = sendToString.trim(); if (sendToString.length() > 0) { sendToString += "; "; } sendToString += getResourceBundleString("pvt_HiddenRecipients"); } } } body.insert(0, "<p>" + getResourceBundleString("pvt_email_to", new Object[] { sendToString }) + "<p/>"); if (message.getAttachments() != null && message.getAttachments().size() > 0) { body.append("<br/><br/>"); for (Iterator iter = message.getAttachments().iterator(); iter.hasNext();) { Attachment attachment = (Attachment) iter.next(); //body.append("<a href=\"" + attachment.getAttachmentUrl() + //"\">" + attachment.getAttachmentName() + "</a><br/>"); body.append("<a href=\"" + messageManager.getAttachmentUrl(attachment.getAttachmentId()) + "\">" + attachment.getAttachmentName() + "</a><br/>"); } } String siteTitle = null; try { siteTitle = SiteService.getSite(getContextId()).getTitle(); } catch (IdUnusedException e) { LOG.error(e.getMessage(), e); } String thisPageId = ""; ToolSession ts = sessionManager.getCurrentToolSession(); if (ts != null) { ToolConfiguration tool = SiteService.findTool(ts.getPlacementId()); if (tool != null) { thisPageId = tool.getPageId(); } } String footer = "<p>----------------------<br>" + getResourceBundleString(EMAIL_FOOTER1) + " " + ServerConfigurationService.getString("ui.service", "Sakai") + " " + getResourceBundleString(EMAIL_FOOTER2) + " \"" + siteTitle + "\" " + getResourceBundleString(EMAIL_FOOTER3) + "\n" + getResourceBundleString(EMAIL_FOOTER4) + " <a href=\"" + ServerConfigurationService.getPortalUrl() + "/site/" + ToolManager.getCurrentPlacement().getContext() + "/page/" + thisPageId + "\">"; footer += siteTitle + "</a>.</p>"; body.append(footer); String bodyString = body.toString(); return bodyString; }
From source file:org.openmrs.module.sdmxhdintegration.web.controller.MapIndicatorDialogController.java
/** * Handles submission of indicator mapping dialog *//*from ww w .ja v a2 s . co m*/ @RequestMapping(method = RequestMethod.POST) public String handleDialogSubmit(HttpSession httpSession, @RequestParam("mappedOMRSIndicatorId") Integer mappedOMRSIndicatorId, @RequestParam("messageId") Integer messageId, @RequestParam("sdmxhdIndicator") String sdmxhdIndicator, @RequestParam("keyFamilyId") String keyFamilyId) throws Exception { sdmxhdIndicator = URLDecoder.decode(sdmxhdIndicator); SDMXHDService service = Context.getService(SDMXHDService.class); SDMXHDMessage message = service.getMessage(messageId); DSD sdmxhdDSD = Utils.getDataSetDefinition(message); // get Indicator obj // TODO do this properly with either uuid or create method in service to fetch by id IndicatorService is = Context.getService(IndicatorService.class); CohortIndicator omrsIndicator = null; List<Indicator> allIndicators = is.getAllDefinitions(false); for (Indicator i : allIndicators) { if (i.getId().equals(mappedOMRSIndicatorId)) { omrsIndicator = (CohortIndicator) i; break; } } SDMXHDCohortIndicatorDataSetDefinition omrsDSD = Utils.getDataSetDefinition(message, keyFamilyId); // remove previous column specification if there is one List<String> columnNames = omrsDSD.getIndicatorColumnMapping().get(sdmxhdIndicator); if (columnNames != null) { for (Iterator<String> iterator = columnNames.iterator(); iterator.hasNext();) { String columnName = iterator.next(); omrsDSD.removeColumn(columnName); } } omrsDSD.removeIndicatorColumnMappings(sdmxhdIndicator); // Map Indicator omrsDSD.mapIndicator(sdmxhdIndicator, mappedOMRSIndicatorId); try { // add column specifications for this indicator // find all combinations of dimensions for this indicator List<List<DimensionWrapper>> allCombinationofDimensionsForIndicator = sdmxhdDSD .getAllCombinationofDimensionsForIndicator(sdmxhdIndicator, keyFamilyId); List<String> baseFixedDimensionToBeMapped = new ArrayList<String>(); // if there is no disaggregation hierarchy for this indicator... use all (non-fixed) dimensions for disagregation if (allCombinationofDimensionsForIndicator == null || allCombinationofDimensionsForIndicator.size() < 0) { Set<String> smxhdFixedDimensions = omrsDSD.getFixedDimensionValues().keySet(); List<Dimension> allNonStanadrdDimensions = sdmxhdDSD.getAllNonStanadrdDimensions(keyFamilyId); List<Dimension> listToBeRemoved = new ArrayList<Dimension>(); for (Iterator<Dimension> iterator = allNonStanadrdDimensions.iterator(); iterator.hasNext();) { Dimension dimension = iterator.next(); if (smxhdFixedDimensions.contains(dimension.getConceptRef())) { listToBeRemoved.add(dimension); } } // remove all fixed dimension from being calculated in the combination permutations ... allNonStanadrdDimensions.removeAll(listToBeRemoved); allCombinationofDimensionsForIndicator = sdmxhdDSD.getAllCombinationOfDimensions(keyFamilyId, allNonStanadrdDimensions); // ... but save them for mapping later for (Dimension d : listToBeRemoved) { baseFixedDimensionToBeMapped.add(d.getConceptRef()); } //added by Dave Thomas -- if the indicator is listed in the hierarchy as having no dimensions explicitly, just add indicator with no dimensions, //rather than applying all possible dimension combinations. } else if (allCombinationofDimensionsForIndicator.size() == 0) { String columnName = omrsIndicator.getName(); Mapped<CohortIndicator> mappedOMRSIndicator = new Mapped<CohortIndicator>(omrsIndicator, IndicatorUtil.getDefaultParameterMappings()); omrsDSD.addColumn(columnName, columnName, mappedOMRSIndicator, new HashMap<String, String>()); //empty map = no dimensions omrsDSD.addIndicatorColumnMapping(sdmxhdIndicator, columnName); } for (List<DimensionWrapper> combinationOfDimensions : allCombinationofDimensionsForIndicator) { // construct a dim option mapping for each combination //List<DimensionWrapper> combinationOfDimensions = sdmxhdDSD.getDimensionHierarchy(sdmxhdIndicator); StringBuilder dimOptsString = new StringBuilder(); StringBuilder fixedDimsString = new StringBuilder(); Map<String, String> dimOpts = new HashMap<String, String>(); List<String> fixedDimensionToBeMapped = new ArrayList<String>(); for (DimensionWrapper dw : combinationOfDimensions) { String omrsMappedDimensionOption = omrsDSD.getORMSMappedDimensionOption( dw.getDimension().getConceptRef(), dw.getCode().getDescription().getDefaultStr()); Integer omrsMappedDimensionId = omrsDSD .getOMRSMappedDimension(dw.getDimension().getConceptRef()); if (omrsMappedDimensionOption == null || omrsMappedDimensionId == null) { if (omrsDSD.getFixedDimensionValues(dw.getDimension().getConceptRef()) == null) { throw new DimensionNotMappedException(dw.getDimension()); } else { // Fixed value is set, no need to add this dimension // Just save it for mapping once we know the column name String sdmxhdDimension = dw.getDimension().getConceptRef(); fixedDimensionToBeMapped.add(sdmxhdDimension); if (fixedDimsString.length() > 0) { fixedDimsString.append(", "); } fixedDimsString.append( sdmxhdDimension + "=" + omrsDSD.getFixedDimensionValues(sdmxhdDimension)); continue; } } dimOpts.put(omrsMappedDimensionId + "", omrsMappedDimensionOption); if (dimOptsString.length() > 0) { dimOptsString.append(", "); } dimOptsString.append(omrsMappedDimensionId + "=" + omrsMappedDimensionOption); } dimOptsString.insert(0, " Dims["); dimOptsString.append("]"); // make sure base fixed dimensions are included for (String sdmxhdDimension : baseFixedDimensionToBeMapped) { fixedDimsString .append(sdmxhdDimension + "=" + omrsDSD.getFixedDimensionValues(sdmxhdDimension)); } fixedDimsString.insert(0, " FixedValDims:["); fixedDimsString.append("]"); String columnName = omrsIndicator.getName() + dimOptsString.toString() + fixedDimsString.toString(); Mapped<CohortIndicator> mappedOMRSIndicator = new Mapped<CohortIndicator>(omrsIndicator, IndicatorUtil.getDefaultParameterMappings()); // add column specification for each dimension combination omrsDSD.addColumn(columnName, columnName, mappedOMRSIndicator, dimOpts); omrsDSD.addIndicatorColumnMapping(sdmxhdIndicator, columnName); // add base fixed value dimension (if any) fixedDimensionToBeMapped.addAll(baseFixedDimensionToBeMapped); // map fixed value dimensions Iterator<String> iter = fixedDimensionToBeMapped.iterator(); while (iter.hasNext()) { String sdmxhdDimension = iter.next(); omrsDSD.mapFixedDimension(columnName, sdmxhdDimension); } } // save dataset DataSetDefinitionService dss = Context.getService(DataSetDefinitionService.class); dss.saveDefinition(omrsDSD); } catch (DimensionNotMappedException e) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Indicator could not be mapped as one or more Dimensions that are used by this indicator have not been mapped"); } return "redirect:redirectParent.form?url=keyFamilyMapping.form?messageId=" + messageId + "%26keyFamilyId=" + keyFamilyId; }
From source file:com.dycody.android.idealnote.DetailFragment.java
private void tagNote(List<Tag> tags, Integer[] selectedTags, Note note) { Pair<String, List<Tag>> taggingResult = TagsHelper.addTagToNote(tags, selectedTags, note); StringBuilder sb; if (noteTmp.isChecklist()) { CheckListViewItem mCheckListViewItem = mChecklistManager.getFocusedItemView(); if (mCheckListViewItem != null) { sb = new StringBuilder(mCheckListViewItem.getText()); sb.insert(contentCursorPosition, " " + taggingResult.first + " "); mCheckListViewItem.setText(sb.toString()); mCheckListViewItem.getEditText() .setSelection(contentCursorPosition + taggingResult.first.length() + 1); } else {//from w ww . j a v a 2 s . c o m title.append(" " + taggingResult.first); } } else { sb = new StringBuilder(getNoteContent()); if (content.hasFocus()) { sb.insert(contentCursorPosition, " " + taggingResult.first + " "); content.setText(sb.toString()); content.setSelection(contentCursorPosition + taggingResult.first.length() + 1); } else { if (getNoteContent().trim().length() > 0) { sb.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")); } sb.append(taggingResult.first); content.setText(sb.toString()); } } // Removes unchecked tags if (taggingResult.second.size() > 0) { if (noteTmp.isChecklist()) { toggleChecklist2(true, true); } Pair<String, String> titleAndContent = TagsHelper.removeTag(getNoteTitle(), getNoteContent(), taggingResult.second); title.setText(titleAndContent.first); content.setText(titleAndContent.second); if (noteTmp.isChecklist()) { toggleChecklist2(); } } }
From source file:com.jkoolcloud.tnt4j.core.UsecTimestamp.java
/** * <p>Creates UsecTimestamp from string representation of timestamp in the * specified format.</p>/* w w w.jav a2 s . com*/ * <p>This is based on {@link SimpleDateFormat}, but extends its support to * recognize microsecond fractional seconds. If number of fractional second * characters is greater than 3, then it's assumed to be microseconds. * Otherwise, it's assumed to be milliseconds (as this is the behavior of * {@link SimpleDateFormat}. * * @param timeStampStr timestamp string * @param formatStr format specification for timestamp string * @param timeZone time zone that timeStampStr represents. This is only needed when formatStr does not include * time zone specification and timeStampStr does not represent a string in local time zone. * @param locale locale for date format to use. * @throws NullPointerException if timeStampStr is {@code null} * @throws IllegalArgumentException if timeStampStr is not in the correct format * @throws ParseException if failed to parse string based on specified format * @see java.util.TimeZone */ public UsecTimestamp(String timeStampStr, String formatStr, TimeZone timeZone, String locale) throws ParseException { if (timeStampStr == null) throw new NullPointerException("timeStampStr must be non-null"); int usecs = 0; SimpleDateFormat dateFormat; if (StringUtils.isEmpty(formatStr)) { dateFormat = new SimpleDateFormat(); } else { // Java date formatter cannot deal with usecs, so we need to extract those ourselves int fmtPos = formatStr.indexOf('S'); if (fmtPos > 0) { int endFmtPos = formatStr.lastIndexOf('S'); int fmtFracSecLen = endFmtPos - fmtPos + 1; if (fmtFracSecLen > 6) throw new ParseException( "Date format containing more than 6 significant digits for fractional seconds is not supported", 0); StringBuilder sb = new StringBuilder(); int usecPos = timeStampStr.lastIndexOf('.') + 1; int usecEndPos; if (usecPos > 2) { for (usecEndPos = usecPos; usecEndPos < timeStampStr.length(); usecEndPos++) { if (!StringUtils.containsAny("0123456789", timeStampStr.charAt(usecEndPos))) break; } if (fmtFracSecLen > 3) { // format specification represents more than milliseconds, assume microseconds String usecStr = String.format("%s", timeStampStr.substring(usecPos, usecEndPos)); if (usecStr.length() < fmtFracSecLen) usecStr = StringUtils.rightPad(usecStr, fmtFracSecLen, '0'); else if (usecStr.length() > fmtFracSecLen) usecStr = usecStr.substring(0, fmtFracSecLen); usecs = Integer.parseInt(usecStr); // trim off fractional part < microseconds from both timestamp and format strings sb.append(timeStampStr); sb.delete(usecPos - 1, usecEndPos); timeStampStr = sb.toString(); sb.setLength(0); sb.append(formatStr); sb.delete(fmtPos - 1, endFmtPos + 1); formatStr = sb.toString(); } else if ((usecEndPos - usecPos) < 3) { // pad msec value in date string with 0's so that it is 3 digits long sb.append(timeStampStr); while ((usecEndPos - usecPos) < 3) { sb.insert(usecEndPos, '0'); usecEndPos++; } timeStampStr = sb.toString(); } } } dateFormat = StringUtils.isEmpty(locale) ? new SimpleDateFormat(formatStr) : new SimpleDateFormat(formatStr, Utils.getLocale(locale)); } dateFormat.setLenient(true); if (timeZone != null) dateFormat.setTimeZone(timeZone); Date date = dateFormat.parse(timeStampStr); setTimestampValues(date.getTime(), 0, 0); add(0, usecs); }