List of usage examples for java.lang StringBuffer insert
@Override public StringBuffer insert(int offset, double d)
From source file:fr.paris.lutece.plugins.directory.web.action.ExportDirectoryAction.java
/** * Append partial export result to temporary file if need * @param strBufferListRecordXml The partial XML content * @param bufferedWriter The bufferedWriter used to append content to * temporary file//from w w w. j a v a2 s. c om * @param physicalFile The XSL physical File * @param bIsCsvExport is CSV export * @param strXslId The XSL unique ID * @param nXmlHeaderLength XML header length * @param xmlTransformerService he XmlTransformer service * @return The string buffer containing the partial export */ private StringBuffer appendPartialContent(StringBuffer strBufferListRecordXml, BufferedWriter bufferedWriter, PhysicalFile physicalFile, boolean bIsCsvExport, String strXslId, int nXmlHeaderLength, XmlTransformerService xmlTransformerService) { if (strBufferListRecordXml.length() > EXPORT_STRINGBUFFER_MAX_CONTENT_SIZE) { strBufferListRecordXml.insert(0, EXPORT_XSL_BEGIN_PARTIAL_EXPORT); strBufferListRecordXml.insert(0, XmlUtil.getXmlHeader()); strBufferListRecordXml.append(EXPORT_XSL_END_PARTIAL_EXPORT); String strFileOutPut = xmlTransformerService.transformBySourceWithXslCache( strBufferListRecordXml.toString(), physicalFile.getValue(), strXslId, null, null); try { if (bIsCsvExport) { bufferedWriter.write(strFileOutPut); } else { bufferedWriter.write(strFileOutPut.substring(nXmlHeaderLength)); } } catch (IOException e) { AppLogService.error(e); } finally { strBufferListRecordXml = new StringBuffer(EXPORT_STRINGBUFFER_INITIAL_SIZE); } } return strBufferListRecordXml; }
From source file:org.dspace.eperson.EPerson.java
/** * Find the epeople that match the search query across firstname, lastname or email. * This method also allows offsets and limits for pagination purposes. * /* ww w .j ava2 s . c o m*/ * @param context * DSpace context * @param query * The search string * @param offset * Inclusive offset * @param limit * Maximum number of matches returned * * @return array of EPerson objects */ public static EPerson[] search(Context context, String query, int offset, int limit) throws SQLException { String params = "%" + query.toLowerCase() + "%"; StringBuffer queryBuf = new StringBuffer(); queryBuf.append("SELECT * FROM eperson WHERE eperson_id = ? OR "); queryBuf.append( "LOWER(firstname) LIKE LOWER(?) OR LOWER(lastname) LIKE LOWER(?) OR LOWER(email) LIKE LOWER(?) ORDER BY lastname, firstname ASC "); // Add offset and limit restrictions - Oracle requires special code if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { // First prepare the query to generate row numbers if (limit > 0 || offset > 0) { queryBuf.insert(0, "SELECT /*+ FIRST_ROWS(n) */ rec.*, ROWNUM rnum FROM ("); queryBuf.append(") "); } // Restrict the number of rows returned based on the limit if (limit > 0) { queryBuf.append("rec WHERE rownum<=? "); // If we also have an offset, then convert the limit into the maximum row number if (offset > 0) { limit += offset; } } // Return only the records after the specified offset (row number) if (offset > 0) { queryBuf.insert(0, "SELECT * FROM ("); queryBuf.append(") WHERE rnum>?"); } } else { if (limit > 0) { queryBuf.append(" LIMIT ? "); } if (offset > 0) { queryBuf.append(" OFFSET ? "); } } String dbquery = queryBuf.toString(); // When checking against the eperson-id, make sure the query can be made into a number Integer int_param; try { int_param = Integer.valueOf(query); } catch (NumberFormatException e) { int_param = Integer.valueOf(-1); } // Create the parameter array, including limit and offset if part of the query Object[] paramArr = new Object[] { int_param, params, params, params }; if (limit > 0 && offset > 0) { paramArr = new Object[] { int_param, params, params, params, limit, offset }; } else if (limit > 0) { paramArr = new Object[] { int_param, params, params, params, limit }; } else if (offset > 0) { paramArr = new Object[] { int_param, params, params, params, offset }; } // Get all the epeople that match the query TableRowIterator rows = DatabaseManager.query(context, dbquery, paramArr); try { List<TableRow> epeopleRows = rows.toList(); EPerson[] epeople = new EPerson[epeopleRows.size()]; for (int i = 0; i < epeopleRows.size(); i++) { TableRow row = (TableRow) epeopleRows.get(i); // First check the cache EPerson fromCache = (EPerson) context.fromCache(EPerson.class, row.getIntColumn("eperson_id")); if (fromCache != null) { epeople[i] = fromCache; } else { epeople[i] = new EPerson(context, row); } } return epeople; } finally { if (rows != null) { rows.close(); } } }
From source file:info.magnolia.cms.taglibs.util.SearchResultSnippetTag.java
/** * Extract a collection of snippets from any paragraph in the given page. * @return a collection of Strings.// w w w . ja v a 2 s. c o m * @todo avoid overlapping snippets (use regexp insted of simple indexOfs) * @todo only extract snippets from user-configured properties * @todo abbreviate on whitespace and puntuation, detect start of sentences * @todo replace ampersand in regexp * @todo break methods and write junits */ public Collection getSnippets() { if (log.isDebugEnabled()) { log.debug("collecting snippets"); //$NON-NLS-1$ } Collection snippets = new ArrayList(); String[] searchTerms = StringUtils.split(this.query); Collection paragraphCollections = this.page.getChildren(ItemType.CONTENTNODE); Iterator iterator = paragraphCollections.iterator(); outer: while (iterator.hasNext()) { Content paragraphCollection = (Content) iterator.next(); Collection paragraphs = paragraphCollection.getChildren(); Iterator parIterator = paragraphs.iterator(); while (parIterator.hasNext()) { Content paragraph = (Content) parIterator.next(); if (log.isDebugEnabled()) { log.debug("Iterating on paragraph " + paragraph); //$NON-NLS-1$ } Collection properties = paragraph.getNodeDataCollection(); Iterator dataIterator = properties.iterator(); while (dataIterator.hasNext()) { NodeData property = (NodeData) dataIterator.next(); if (property.getType() != PropertyType.BINARY) { String resultString = property.getString(); if (log.isDebugEnabled()) { log.debug("Iterating on property " + property.getName()); //$NON-NLS-1$ log.debug("Property value is " + resultString); //$NON-NLS-1$ } // a quick and buggy way to avoid configuration properties, we should allow the user to // configure a list of nodeData to search for... if (resultString.length() < 20) { continue; } for (int j = 0; j < searchTerms.length; j++) { String searchTerm = StringUtils.lowerCase(searchTerms[j]); // exclude keywords and words with less than 2 chars if (!ArrayUtils.contains(SimpleSearchTag.KEYWORDS, searchTerm) && searchTerm.length() > 2) { if (log.isDebugEnabled()) { log.debug("Looking for search term [" + searchTerm + "] in [" + resultString //$NON-NLS-1$//$NON-NLS-2$ + "]"); //$NON-NLS-1$ } // first check, avoid using heavy string replaceAll operations if the search term is not // there if (!StringUtils.contains(resultString.toLowerCase(), searchTerm)) { continue; } // strips out html tags using a regexp resultString = resultString.replaceAll("\\<.*?\\>", ""); //$NON-NLS-1$ //$NON-NLS-2$ // only get first matching keyword int pos = resultString.toLowerCase().indexOf(searchTerm); if (pos > -1) { int posEnd = pos + searchTerm.length(); int from = (pos - chars / 2); if (from < 0) { from = 0; } int to = from + chars; if (to > resultString.length()) { to = resultString.length(); } StringBuffer snippet = new StringBuffer(); snippet.append(StringUtils.substring(resultString, from, pos)); snippet.append("<strong>"); //$NON-NLS-1$ snippet.append(StringUtils.substring(resultString, pos, posEnd)); snippet.append("</strong>"); //$NON-NLS-1$ snippet.append(StringUtils.substring(resultString, posEnd, to)); if (from > 0) { snippet.insert(0, "... "); //$NON-NLS-1$ } if (to < resultString.length()) { snippet.append("... "); //$NON-NLS-1$ } if (log.isDebugEnabled()) { log.debug("Search term found, adding snippet " + snippet); //$NON-NLS-1$ } snippets.add(snippet); if (snippets.size() >= this.maxSnippets) { if (log.isDebugEnabled()) { log.debug("Maximum number of snippets (" //$NON-NLS-1$ + this.maxSnippets + ") reached, exiting"); //$NON-NLS-1$ } break outer; } } } } } } } } return snippets; }
From source file:org.opennms.netmgt.xmlrpcd.XmlrpcAnticipator.java
public synchronized void verifyAnticipated() { StringBuffer problems = new StringBuffer(); if (m_anticipated.size() > 0) { problems.append(m_anticipated.size() + " expected calls still outstanding:\n"); problems.append(listCalls("\t", m_anticipated)); }/*from www. ja v a 2 s.co m*/ if (m_unanticipated.size() > 0) { problems.append(m_unanticipated.size() + " unanticipated calls received:\n"); problems.append(listCalls("\t", m_unanticipated)); } if (problems.length() > 0) { problems.deleteCharAt(problems.length() - 1); problems.insert(0, "XML-RPC Anticipator listening at port " + m_port + " has:\n"); throw new AssertionFailedError(problems.toString()); } }
From source file:org.j2free.util.ServletUtils.java
/** * Redirects the user to the current url over HTTP * * @param request a HttpServletRequest//from ww w . ja va 2 s. c o m * @param response a HttpServletResponse * @param nonSslPort the port Non-SSL requests should be forwarded to * @throws ServletException * @throws IOException */ public static void redirectOverNonSSL(HttpServletRequest request, HttpServletResponse response, int nonSslPort) throws ServletException, IOException { StringBuffer url = request.getRequestURL(); // Make sure we're on http if (url.charAt(4) == 's') url.deleteCharAt(4); // If there is a non-ssl port, make sure we're on it, // otherwise assume we're already on the right port if (nonSslPort > 0) { int portStart = url.indexOf(":", 8) + 1; int portEnd = url.indexOf("/", 8); if (portEnd == -1) // If their isn't a trailing slash, then the end is the last char portEnd = url.length() - 1; if (portStart > 0 && portStart < portEnd) { // If we detected a : before the trailing slash or end of url, delete the port url.delete(portStart, portEnd); } else { url.insert(portEnd, ':'); // If the url didn't have a port, add in the : portStart = portEnd; } url.insert(portStart, nonSslPort); // Insert the right port where it should be } LogFactory.getLog(ServletUtils.class).debug("redirectOverSSL sending 301: " + url.toString()); sendPermanentRedirect(response, url.toString()); }
From source file:org.j2free.util.ServletUtils.java
/** * Redirects the user to the current url over HTTPS * * @param request a HttpServletRequest/*from ww w. j a va 2 s . c o m*/ * @param response a HttpServletResponse * @param urlStr * @param nonSslPort the port Non-SSL requests should be forwarded to * @throws ServletException * @throws IOException */ public static void redirectOverNonSSL(HttpServletRequest request, HttpServletResponse response, String urlStr, int nonSslPort) throws ServletException, IOException { StringBuffer url = new StringBuffer(urlStr); // Make sure we're on http if (url.charAt(4) == 's') url.deleteCharAt(4); // If there is a non-ssl port, make sure we're on it, // otherwise assume we're already on the right port if (nonSslPort > 0) { int portStart = url.indexOf(":", 8) + 1; int portEnd = url.indexOf("/", 8); if (portEnd == -1) // If their isn't a trailing slash, then the end is the last char portEnd = url.length() - 1; if (portStart > 0 && portStart < portEnd) { // If we detected a : before the trailing slash or end of url, delete the port url.delete(portStart, portEnd); } else { url.insert(portEnd, ':'); // If the url didn't have a port, add in the : portStart = portEnd; } url.insert(portStart, nonSslPort); // Insert the right port where it should be } LogFactory.getLog(ServletUtils.class).debug("redirectOverSSL sending 301: " + url.toString()); sendPermanentRedirect(response, url.toString()); }
From source file:info.magnolia.templating.jsp.taglib.SearchResultSnippetTag.java
/** * Extract a collection of snippets from any paragraph in the given page. * @return a collection of Strings.// w ww .j av a2 s. c o m * @todo avoid overlapping snippets (use regexp insted of simple indexOfs) * @todo only extract snippets from user-configured properties * @todo abbreviate on whitespace and puntuation, detect start of sentences * @todo replace ampersand in regexp * @todo break methods and write junits */ public Collection getSnippets() { log.debug("collecting snippets"); Collection snippets = new ArrayList(); String[] searchTerms = StringUtils.split(this.query); try { Iterator<Node> iterator = NodeUtil.getNodes(this.page, NodeTypes.ContentNode.NAME).iterator(); outer: while (iterator.hasNext()) { Node paragraphCollection = iterator.next(); Iterator<Node> parIterator = NodeUtil.getNodes(paragraphCollection, NodeTypes.ContentNode.NAME) .iterator(); while (parIterator.hasNext()) { Node paragraph = parIterator.next(); log.debug("Iterating on paragraph {}", paragraph); Iterator dataIterator = paragraph.getProperties(); while (dataIterator.hasNext()) { Property property = (Property) dataIterator.next(); if (property.getType() != PropertyType.BINARY) { String resultString = property.getString(); log.debug("Iterating on property {}", property.getName()); log.debug("Property value is {}", resultString); // a quick and buggy way to avoid configuration properties, we should allow the user to // configure a list of nodeData to search for... if (resultString.length() < 20) { continue; } for (int j = 0; j < searchTerms.length; j++) { String searchTerm = StringUtils.lowerCase(searchTerms[j]); // exclude keywords and words with less than 2 chars if (!ArrayUtils.contains(new String[] { "and", "or" }, searchTerm) && searchTerm.length() > 2) { log.debug("Looking for search term [{}] in [{}]", searchTerm, resultString); // first check, avoid using heavy string replaceAll operations if the search term is not // there if (!StringUtils.contains(resultString.toLowerCase(), searchTerm)) { continue; } // strips out html tags using a regexp resultString = stripHtmlTags(resultString); // only get first matching keyword int pos = resultString.toLowerCase().indexOf(searchTerm); if (pos > -1) { int posEnd = pos + searchTerm.length(); int from = (pos - chars / 2); if (from < 0) { from = 0; } int to = from + chars; if (to > resultString.length()) { to = resultString.length(); } StringBuffer snippet = new StringBuffer(); snippet.append(StringUtils.substring(resultString, from, pos)); snippet.append("<strong>"); snippet.append(StringUtils.substring(resultString, pos, posEnd)); snippet.append("</strong>"); snippet.append(StringUtils.substring(resultString, posEnd, to)); if (from > 0) { snippet.insert(0, "... "); } if (to < resultString.length()) { snippet.append("... "); } log.debug("Search term found, adding snippet {}", snippet); snippets.add(snippet); if (snippets.size() >= this.maxSnippets) { log.debug("Maximum number of snippets ({}) reached, exiting", Integer.toString(this.maxSnippets)); break outer; } } } } } } } } return snippets; } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
From source file:ExposedFloat.java
void updateNumberFields() { int intBits = Float.floatToIntBits(value); if (Float.isNaN(value)) { base10Field.setText(notANumberString); } else if (Float.isInfinite(value)) { if ((intBits >>> 31) == 1) { // This is a negative infinity base10Field.setText(negativeInfinityString); } else {// w w w . j a va 2 s. c om // This is a positive infinity base10Field.setText(positiveInfinityString); } } else if (intBits == (int) 0x80000000) { base10Field.setText("-0"); } else { base10Field.setText(Float.toString(value)); } int v = intBits; StringBuffer buf = new StringBuffer(); for (int i = 0; i < 8; ++i) { // Get lowest bit int remainder = v & 0xf; // Convert bit to a character and insert it into the beginning of the string switch (remainder) { case 0: buf.insert(0, "0"); break; case 1: buf.insert(0, "1"); break; case 2: buf.insert(0, "2"); break; case 3: buf.insert(0, "3"); break; case 4: buf.insert(0, "4"); break; case 5: buf.insert(0, "5"); break; case 6: buf.insert(0, "6"); break; case 7: buf.insert(0, "7"); break; case 8: buf.insert(0, "8"); break; case 9: buf.insert(0, "9"); break; case 10: buf.insert(0, "a"); break; case 11: buf.insert(0, "b"); break; case 12: buf.insert(0, "c"); break; case 13: buf.insert(0, "d"); break; case 14: buf.insert(0, "e"); break; case 15: buf.insert(0, "f"); break; } // Shift the int to the right one bit v >>>= 4; } hexField.setText(buf.toString()); v = intBits; buf.setLength(0); for (int i = 0; i < 32; ++i) { // Get lowest bit int remainder = v & 0x1; // Convert bit to a character and insert it into the beginning of the string if (remainder == 0) { buf.insert(0, "0"); } else { buf.insert(0, "1"); } // Shift the int to the right one bit v >>>= 1; } binaryField.setText(buf.toString()); if (intBits < 0) { signField.setText("1"); } else { signField.setText("0"); } v = intBits >> 23; buf.setLength(0); for (int i = 0; i < 8; ++i) { // Get lowest bit int remainder = v & 0x1; // Convert bit to a character and insert it into the beginning of the string if (remainder == 0) { buf.insert(0, "0"); } else { buf.insert(0, "1"); } // Shift the int to the right one bit v >>>= 1; } exponentField.setText(buf.toString()); // Do the mantissa v = intBits; buf.setLength(0); for (int i = 0; i < 23; ++i) { // Get lowest bit int remainder = v & 0x1; // Convert bit to a character and insert it into the beginning of the string if (remainder == 0) { buf.insert(0, "0"); } else { buf.insert(0, "1"); } // Shift the int to the right one bit v >>>= 1; } if (((intBits >> 23) & 0xff) == 0) { // This is a denormalized number, first bit is 0 buf.insert(0, "0"); } else { // This is a normalized number, first bit is 1 buf.insert(0, "1"); } mantissaField.setText(buf.toString()); // Print out a denormalized base 2 version. buf.setLength(0); if (Float.isNaN(value)) { buf.append(notANumberString); } else if (Float.isInfinite(value)) { if ((intBits >>> 31) == 1) { // This is a negative infinity buf.append(negativeInfinityString); } else { // This is a positive infinity buf.append(positiveInfinityString); } } else { if ((intBits >>> 31) == 1) { // This is a negative number buf.append("-"); } // Convert mantissa to int. v = (intBits & 0x007fffff); if (((intBits >> 23) & 0xff) != 0) { // Set bit 23 if the number is normalized v |= 0x00800000; } buf.append(v); // print out the exponent v = (intBits >> 23) & 0xff; if (v != 150 && intBits != 0 && intBits != (int) 0x80000000) { if (v != 0) { // regular normalized number buf.append("e" + (v - 150)); } else { // denormalized number buf.append("e-149"); } } } base2Field.setText(buf.toString()); }
From source file:eu.citadel.converter.transform.CitadelJsonTransform.java
/** * CSV to Citadel JSON with validation// w ww.j a v a2s .co m * @param dataset * @param metadata * @param datatype * @param transformationConfig * @return a new Data * @throws IOException * @throws TransformException */ protected Data<?, ?> getTarget(CsvDataset dataset, BasicMetadata metadata, BasicDatatype datatype, BasicTransformationConfig transformationConfig) throws IOException, TransformException { Logger logger = LoggerFactory.getLogger(CitadelJsonTransform.class.getName() + ".getTarget.CsvDataset"); logger.trace("getTarget(CsvDataset, BasicMetadata, BasicDatatype, BasicTransformationConfig) - start"); Map<Object, BasicSchemaObjAbstractValue<?>> datatypeIdAbstractValueMap = getDatatypeIdAndBasicSchemaObjAbstractValueMap( datatype, transformationConfig, true); Map<Object, BasicSchemaObjAttributes> datatypeIdAttributeMap = Maps.newHashMap(); for (int i = 0; i < datatype.getValues().size() - 1; i++) { datatypeIdAttributeMap.put(i, datatype.getValuesById(i)); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") { private static final long serialVersionUID = 1L; public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) { StringBuffer toFix = super.format(date, toAppendTo, pos); StringBuffer returnStringBuffer = toFix.insert(toFix.length() - 2, ':'); return returnStringBuffer; }; }; String json = new String(); BasicSchemaObjAttributes metadataAttributes = metadata.getValuesById(null); try (ICsvListReader listReader = dataset.getStream();) { if (listReader != null) { String datatypeName = datatype.getName(); if (datatypeName == null) { datatypeName = "the selected Datatype"; } List<String> columnStringList = null; boolean firstRow = true; boolean firstCall = true; while ((columnStringList = listReader.read()) != null) { if (!firstRow || (firstRow && "data".equalsIgnoreCase( metadataAttributes.get(BasicMetadataUtils.FIRST_ROW).getValue().toString()))) { List<Object> columnList = new ArrayList<Object>(columnStringList); json = json + getLoopContent(firstCall, dateFormat, datatypeIdAbstractValueMap, datatypeIdAttributeMap, columnList, datatypeName); firstCall = false; } firstRow = false; } } } json = json + "]}}"; validateJson(json); Data<?, ?> returnData = new Data<JsonDataset, BasicMetadata>(new JsonDataset(json), null); logger.trace("getTarget(CsvDataset, BasicMetadata, BasicDatatype, BasicTransformationConfig) - end"); return returnData; }
From source file:eu.citadel.converter.transform.CitadelJsonTransform.java
/** * Excel to Citadel JSON//from w ww.j a v a 2 s . c om * @param dataset * @param metadata * @param datatype * @param transformationConfig * @return a new Data * @throws TransformException * @throws IOException * @throws InvalidFormatException */ protected Data<?, ?> getTarget(ExcelDataset dataset, BasicMetadata metadata, BasicDatatype datatype, BasicTransformationConfig transformationConfig) throws TransformException, IOException { Logger logger = LoggerFactory.getLogger(CitadelJsonTransform.class.getName() + ".getTarget.ExcelDataset"); logger.trace("getTarget(ExcelDataset, BasicMetadata, BasicDatatype, BasicTransformationConfig) - start"); Map<Object, BasicSchemaObjAbstractValue<?>> datatypeIdAbstractValueMap = getDatatypeIdAndBasicSchemaObjAbstractValueMap( datatype, transformationConfig, true); Map<Object, BasicSchemaObjAttributes> datatypeIdAttributeMap = Maps.newHashMap(); for (int i = 0; i < datatype.getValues().size() - 1; i++) { datatypeIdAttributeMap.put(i, datatype.getValuesById(i)); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") { private static final long serialVersionUID = 1L; public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) { StringBuffer toFix = super.format(date, toAppendTo, pos); StringBuffer returnStringBuffer = toFix.insert(toFix.length() - 2, ':'); return returnStringBuffer; }; }; String json = new String(); BasicSchemaObjAttributes metadataAttributes = metadata.getValuesById(null); boolean firstRow = true; boolean firstCall = true; try { dataset.buildContent(); } catch (ExcelDatasetException e) { throw new TransformException(e.getMessage()); } List<List<Object>> content = dataset.getContent(); if (content == null) { logger.error( "getTarget(ExcelDataset, BasicMetadata, BasicDatatype, BasicTransformationConfig) - no content for the Dataset"); throw new TransformException(MessageKey.EXCEPTION_CANNOT_GET_CONTENT); } String datatypeName = datatype.getName(); if (datatypeName == null) { datatypeName = "the selected Datatype"; } for (List<Object> columnList : dataset.getContent()) { if (!firstRow || (firstRow && "data".equalsIgnoreCase( metadataAttributes.get(BasicMetadataUtils.FIRST_ROW).getValue().toString()))) { json = json + getLoopContent(firstCall, dateFormat, datatypeIdAbstractValueMap, datatypeIdAttributeMap, columnList, datatypeName); firstCall = false; } firstRow = false; } json = json + "]}}"; validateJson(json); Data<?, ?> returnData = new Data<JsonDataset, BasicMetadata>(new JsonDataset(json), null); logger.trace("getTarget(ExcelDataset, BasicMetadata, BasicDatatype, BasicTransformationConfig) - end"); return returnData; }