List of usage examples for java.lang StringBuffer delete
@Override public synchronized StringBuffer delete(int start, int end)
From source file:org.alfresco.extension.bulkfilesystemimport.impl.AbstractBulkFilesystemImporter.java
protected final String mapToString(final Map<?, ?> map) { StringBuffer result = new StringBuffer(); if (map != null) { result.append('['); if (map.size() > 0) { for (Object key : map.keySet()) { result.append(String.valueOf(key)); result.append(" = "); result.append(String.valueOf(map.get(key))); result.append(",\n"); }/*from www . j a va 2s . co m*/ // Delete final dangling ", " value result.delete(result.length() - 2, result.length()); } result.append(']'); } else { result.append("(null)"); } return (result.toString()); }
From source file:dao.DirectoryStreamBlobDaoDb.java
/** * Add a new blob to a directory of blobs * User permissions are checked before the user is allowed to add it. * If the user is the is the author of this directory or diaryadmin, allow this user to add it. * @param fieldsize/* www.j a va 2 s. c o m*/ * @param blobtype * @param mtype * @param btitle * @param blob * @param zoom * @param userid * @param directoryid * @param userLogin * @param usertags * @param caption * @param dirPath * @param dirName * @throws BaseDaoException If we have a problem interpreting the data or * the data is missing or incorrect */ public void addStreamBlob(long bsize, int blobtype, String mtype, String btitle, byte[] blob, int zoom, String userId, String directoryId, String userLogin, String usertags, String caption, String dirPath, String dirName) throws BaseDaoException { if ((bsize <= 0) || RegexStrUtil.isNull(mtype) || RegexStrUtil.isNull(btitle) || (blob == null)) { throw new BaseDaoException("params are null"); } /** * Get scalability datasource for dirblob - partitioned on directoryId */ String sourceName = scalabilityManager.getWriteBlobScalability(directoryId); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException("ds null, addStreamBlob " + sourceName); } //List dResult = null; //Object[] params = {(Object)directoryId, (Object)userId}; // check authority to add //if ( !isAuthor(params, dResult) && !diaryAdmin.isDiaryAdmin(userLogin) ) { if (!isAuthor(directoryId, userId) && !diaryAdmin.isDiaryAdmin(userLogin)) { throw new BaseDaoException("user does not have permission to add streamblobs in directory " + directoryId + " userId " + userId); } Connection conn = null; String entryId = null; if (RegexStrUtil.isNull(caption)) { caption = btitle; } if (WebUtil.isSanEnabled()) { /** * A file gets overwritten in file storage systems if the same * filename is used that is already exists. * If it is only in the database, we can support same file names * as they have unique ids * If samename exists, give an error */ if (isFileNameExists(btitle, directoryId)) { throw new BaseDaoException( "File already exists with the same name " + btitle + " directoryId = " + directoryId); } try { SanUtils sanUtils = new SanUtils(); logger.info("dirPath=" + dirPath + " dirName=" + dirName + " sanPath=" + SanConstants.sanPath); /** dirPath = users|1 * dirName = smitha * SanConstants.sanPath = /home/usr/local/tomcat */ sanUtils.addSanFile(dirPath, dirName, btitle, SanConstants.sanPath, blob); } catch (SanException e) { throw new BaseDaoException("directory addstreamblob, addSanFile() error " + dirName + dirPath + btitle + e.getMessage(), e); } } try { conn = ds.getConnection(); if (WebUtil.isSanEnabled()) { byte[] noBlobData = null; addStreamBlobQuery.run(conn, noBlobData, blobtype, mtype, btitle, bsize, zoom, directoryId, userId, caption); } else { addStreamBlobQuery.run(conn, blob, blobtype, mtype, btitle, bsize, zoom, directoryId, userId, caption); } List entryIdResult = entryIdQuery.run(conn, directoryId, btitle); if (entryIdResult != null && entryIdResult.size() > 0) { if ((Photo) entryIdResult.get(0) != null) { entryId = ((Photo) entryIdResult.get(0)).getValue(DbConstants.ENTRYID); } } } catch (Exception e) { try { if (conn != null) { conn.close(); } } catch (Exception e2) { throw new BaseDaoException("addBlob error " + e2.getMessage(), e2); } throw new BaseDaoException("addBlob error(e) " + e.getMessage(), e); } try { if (conn != null) { conn.close(); } } catch (Exception e) { throw new BaseDaoException("addBlob error " + e.getMessage(), e); } /* add this entry even if the usertags is null */ if (!RegexStrUtil.isNull(entryId)) { addImagesAndTags(directoryId, usertags, entryId, blobtype, mtype, btitle, bsize, zoom, userId, caption); } /** * lucenesearch */ if (WebUtil.isSanEnabled()) { if (WebUtil.isLuceneSearchEnabled()) { StringBuffer filePath = new StringBuffer( RegexStrUtil.sanFilePath(dirPath, SanConstants.sanPath, dirName)); logger.info("filePath = " + filePath.toString()); if (filePath != null) { filePath.append(File.separator); filePath.append(btitle); } logger.info("filePath = " + filePath.toString()); try { luceneManager.indexDoc(filePath.toString()); } catch (Exception e) { throw new BaseDaoException("Exception in LuceneManager, luceneManager.indexDoc(), file=" + filePath.toString() + " errorMsg=" + e.getMessage()); } } } /** * get stream blobs for a directory from cache, if it exists */ Fqn fqn = cacheUtil.fqn(DbConstants.DIRECTORY_STREAM_BLOBS); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } fqn = cacheUtil.fqn(DbConstants.RECENT_DIR_IMAGES); if (treeCache.exists(fqn, DbConstants.RECENT_DIR_IMAGES)) { treeCache.remove(fqn, DbConstants.RECENT_DIR_IMAGES); } fqn = cacheUtil.fqn(DbConstants.DIR_CAT); StringBuffer sb = new StringBuffer(directoryId); sb.append("-"); sb.append(DbConstants.PHOTO_CATEGORY); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } sb.delete(0, sb.length()); sb.append(directoryId); sb.append("-"); sb.append(DbConstants.FILE_CATEGORY); fqn = cacheUtil.fqn(DbConstants.DIR_CAT); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } fqn = cacheUtil.fqn(DbConstants.DIRECTORY); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } }
From source file:my.home.model.datasource.AutoCompleteItemDataSourceImpl.java
public void markCurrentInput(Context context, String inputString) { Log.d(TAG, "mark: " + inputString); StringBuffer inputBuffer = new StringBuffer(inputString); StringBuffer msgBuffer = new StringBuffer(); boolean in_if_state = false; boolean in_if_then_state = false; boolean in_while_state = false; boolean in_msg_or_time_ind_state = false; String lastString = null;/* w ww. j a va2 s . c o m*/ String preMsgString = null; String curState = mInitState; while (inputBuffer.length() > 0) { if (in_msg_or_time_ind_state) { if (inputBuffer.toString().startsWith(mMessageSeq) || inputBuffer.toString().startsWith(mTimeSeq)) { in_msg_or_time_ind_state = false; MsgHistoryItem msgHistoryItem = new MsgHistoryItem(); msgHistoryItem.setFrom(preMsgString); msgHistoryItem.setMsg(msgBuffer.toString()); DBStaticManager.addMsgHistoryItem(context, msgHistoryItem); msgBuffer.delete(0, msgBuffer.length()); preMsgString = null; } else { msgBuffer.append(inputBuffer.charAt(0)); } inputBuffer.deleteCharAt(0); continue; } boolean found = false; String tempInput = inputBuffer.toString(); if (!mLinks.containsKey(curState)) { return; } for (String nextState : mLinks.get(curState)) { if (!in_if_state && !in_while_state) { if (nextState.equals("then") || nextState.equals("compare") || nextState.equals("logical")) continue; } if (!in_if_then_state) { if (nextState.equals("else")) continue; } for (String val : mNodes.get(nextState)) { if (tempInput.startsWith(val)) { if (lastString != null) { addNewHistoryItem(context, lastString, val); } inputBuffer.delete(0, val.length()); found = true; if (nextState.equals("message") || nextState.equals("time")) { in_msg_or_time_ind_state = true; preMsgString = lastString; } else if (nextState.equals("if")) { in_if_state = true; } else if (nextState.equals("while")) { in_while_state = true; } else if (nextState.equals("then")) { if (in_if_state) in_if_then_state = true; in_if_state = false; in_while_state = false; } else if (in_if_then_state && nextState.equals("else")) { in_if_then_state = false; } lastString = val; curState = nextState; break; } } if (found || inputBuffer.length() == 0) break; } if (inputBuffer.length() == 0) { break; } if (found) { if (msgBuffer.length() != 0) { MsgHistoryItem msgHistoryItem = new MsgHistoryItem(); msgHistoryItem.setFrom(preMsgString); msgHistoryItem.setMsg(msgBuffer.toString()); DBStaticManager.addMsgHistoryItem(context, msgHistoryItem); msgBuffer.delete(0, msgBuffer.length()); preMsgString = null; } continue; } if (curState.equals("message") || mLinks.get(curState).contains("message")) { found = true; curState = "message"; preMsgString = lastString; msgBuffer.append(inputBuffer.charAt(0)); inputBuffer.deleteCharAt(0); } else if (curState.equals("time") || mLinks.get(curState).contains("time")) { found = true; curState = "time"; preMsgString = lastString; msgBuffer.append(inputBuffer.charAt(0)); inputBuffer.deleteCharAt(0); } if (!found) break; } if (msgBuffer.length() != 0) { MsgHistoryItem msgHistoryItem = new MsgHistoryItem(); msgHistoryItem.setFrom(preMsgString); msgHistoryItem.setMsg(msgBuffer.toString()); DBStaticManager.addMsgHistoryItem(context, msgHistoryItem); } }
From source file:org.blackdog.lyrics.type.LeoLyrics.java
/** return an html String representing the lyrics content of the page with the given uri * @param uri the uri of the page containing the song lyrics * @return a String or null if failed//from w ww . ja v a 2 s. c o m */ private String getLyricsContent(String uri) throws HttpException, IOException { String content = null; if (uri != null) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(uri); // method.addRequestHeader(Header.) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(5, false)); try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { String response = method.getResponseBodyAsString(); if (response != null) { /* search first occurrence of 'This song is on the following albums' * * if not found, search <font face="Trebuchet MS, Verdana, Arial" size=-1> * take to next </font> */ String headerString = "This song is on the following albums"; String headerString2 = "<font face=\"Trebuchet MS, Verdana, Arial\" size=-1>"; String paragraphString = "<p>"; String paragraphEndString = "</p>"; StringBuffer bufferContent = new StringBuffer(800); StringBuffer bufferHeaderTmp = new StringBuffer(headerString.length()); StringBuffer bufferParagraphTmp = new StringBuffer(paragraphString.length()); StringBuffer bufferParagraphEndTmp = new StringBuffer(paragraphEndString.length()); boolean headerFound = false; boolean paragraphFound = false; boolean contentFound = false; // for (int i = 0; i < response.length() && !contentFound; i++) { char b = response.charAt(i); /** header found */ if (headerFound) { if (paragraphFound) { bufferContent.append((char) b); if (b == paragraphEndString.charAt(bufferParagraphEndTmp.length())) { bufferParagraphEndTmp.append((char) b); } else if (bufferParagraphEndTmp.length() > 0) { bufferParagraphEndTmp.delete(0, bufferParagraphEndTmp.length() - 1); } /* did we find the end of the paragraph ? */ if (bufferParagraphEndTmp.length() >= paragraphEndString.length()) { contentFound = true; } } else { // System.out.println(" <<"); if (b == paragraphString.charAt(bufferParagraphTmp.length())) { bufferParagraphTmp.append((char) b); } else if (bufferParagraphTmp.length() > 0) { bufferParagraphTmp.delete(0, bufferParagraphTmp.length() - 1); } if (bufferParagraphTmp.length() >= paragraphString.length()) { paragraphFound = true; bufferHeaderTmp.append(headerString); } } } else { // System.out.println(" <<"); if (b == headerString.charAt(bufferHeaderTmp.length())) { bufferHeaderTmp.append((char) b); } else if (bufferHeaderTmp.length() > 0) { bufferHeaderTmp.delete(0, bufferHeaderTmp.length() - 1); } if (bufferHeaderTmp.length() >= headerString.length()) { headerFound = true; } } } if (!contentFound) { int headerString2Index = response.indexOf(headerString2); if (headerString2Index > -1) { String truncatedResponse = response.substring(headerString2Index); int lastEndfont = truncatedResponse.indexOf("</font>"); if (lastEndfont > -1) { bufferContent.append(truncatedResponse.substring(0, lastEndfont)); contentFound = true; } } } if (bufferContent.length() > 0) { bufferContent.insert(0, "<html>"); bufferContent.append("</html>"); try { content = new String(bufferContent.toString().getBytes(), method.getResponseCharSet()); // "UTF-8" } catch (UnsupportedEncodingException e) { logger.warn("unable to encode lyrics content in UTF-8"); content = bufferContent.toString(); } } } } else { logger.error("getting error while trying to connect to : " + uri + " (error code=" + statusCode + ")"); } } finally { method.releaseConnection(); } } return content; }
From source file:org.ourbeehive.mbp.util.StringHelper.java
public static void breakLine(StringBuffer paragraph, List<String> patternList, String indent, int countOfIndent, int maxWidth) { StringBuffer breakedParagraph = new StringBuffer(); // To detect the last new line symbol. String currentStr = paragraph.toString(); int idxOfLineSep = lastIndexOf(currentStr, GlobalConst.LINE_SEPARATOR); // If found, compute from the last new line symbol. if (idxOfLineSep != -1) { breakedParagraph.append(currentStr.substring(0, idxOfLineSep + 1)); currentStr = currentStr.substring(idxOfLineSep + 1); }/*from w w w .ja v a 2s. c om*/ // If current string has exceed the maximum width. String line = null; String pattern = null; int lastPosOfPat = 0; int currPosOfPat = 0; if (currentStr.length() > maxWidth) { // Narrow down to the potential line. line = currentStr.substring(0, maxWidth); // Identify the rightmost of the given pattern in line. for (int i = 0; i < patternList.size(); i++) { pattern = patternList.get(i); currPosOfPat = line.lastIndexOf(pattern); if (currPosOfPat > lastPosOfPat) { lastPosOfPat = currPosOfPat; } } // Insert line separator before the identified pattern. breakedParagraph.append(line.substring(0, lastPosOfPat)); breakedParagraph.append(GlobalConst.LINE_SEPARATOR); for (int i = 0; i < countOfIndent; i++) { breakedParagraph.append(indent); } breakedParagraph.append(currentStr.substring(lastPosOfPat)); // Replace the given paragraph with the breaked one. paragraph.delete(0, paragraph.length()); paragraph.append(breakedParagraph); // Invoke recursively. breakLine(paragraph, patternList, indent, countOfIndent, maxWidth); } }
From source file:edu.umd.cfar.lamp.viper.util.StringHelp.java
/** * Split using a separator, but allow for the separator to occur * in nested parentheses without splitting. * <PRE>/* ww w .j a v a 2 s.com*/ * E.g. "1", 2*("2,3"), "4" * would split into * -- "1" * -- 2*("2,3") * -- "4" * </PRE> * If the data has an odd number of "s, it will append a " character * to the end. In order to include a quote character without delimiting * a string, use the \". For a \, use \\. * @param line the string to split * @param sep the seperator character, e.g. a comma * @return the split string */ public static String[] splitBySeparatorQuoteAndParen(String line, char sep) { boolean withinQuotes = false; String newLine = new String(line); Vector temp = new Vector(); StringBuffer nextString = new StringBuffer(); int nesting = 0; for (int i = 0; i < newLine.length(); i++) { char c = newLine.charAt(i); if (c == '\\') { if ((++i >= newLine.length()) && (nextString.length() > 0)) { temp.addElement(nextString.toString()); break; } else { switch (newLine.charAt(i)) { case 'n': nextString.append('\n'); break; case '"': nextString.append('"'); break; default: nextString.append(newLine.charAt(i)); } } } else if (c == '"') { withinQuotes = !withinQuotes; nextString.append('"'); } else if (!withinQuotes) { if (c == '(') { nesting++; nextString.append('('); } else if (c == ')') { nesting--; nextString.append(')'); } else { if ((nesting == 0) && (c == sep)) { temp.addElement(nextString.toString()); nextString.delete(0, nextString.length()); } else { nextString.append(newLine.charAt(i)); } } } else { nextString.append(newLine.charAt(i)); } } if (withinQuotes) { nextString.append('"'); } temp.addElement(nextString.toString()); String[] result = new String[temp.size()]; for (int i = 0; i < result.length; i++) { result[i] = (String) temp.elementAt(i); } return (result); }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.BiospecimenMetaDataProcessor.java
/** * Extracts biospecimen meta-data from a clinical XML file and returns a list of {@link BiospecimenMetaData} * objects. Each object represents a single XML meta-data element. * * @param xmlFile - the XML file to extract biospecimen meta-data from * @param qcContext - qcContext/* w ww . ja va 2s .c om*/ * @return a list of {@link BiospecimenMetaData} objects, with each object representing a single meta-data element * @throws UUIDException if an error occurs while attempting to generate a UUID for a specific meta-data * element when not provided in the XML * @throws ProcessorException if errors occur while attempting extract meta-data */ protected List<BiospecimenMetaData> handleBiospecimenMetaData(final File xmlFile, final QcContext qcContext) throws UUIDException, ProcessorException { logger.debug("starting handleBiospecimenMetadata"); final Archive archive = qcContext.getArchive(); // Unmarshal the XML file into a JAXB generated object TcgaBcr tcgaBcr; UnmarshalResult unmarshalResult; JAXBIntrospector jaxbIntrospector; try { unmarshalResult = JAXBUtil.unmarshal(xmlFile, TcgaBcr.class, true, false); tcgaBcr = (TcgaBcr) unmarshalResult.getJaxbObject(); jaxbIntrospector = JAXBUtil.getJAXBIntrospector(TcgaBcr.class); logger.debug("JAXB Unmarshalling of BiospecimenMetadata done"); } catch (Exception e) { logger.info(e); throw new ProcessorException(e.getMessage()); } Map<String, BiospecimenMetaData> biospecimenMetaDataByUUIDORBarcode; List<BiospecimenMetaData> biospecimenMetaData = null; if (tcgaBcr != null) { final Patient patient = tcgaBcr.getPatient(); if (patient != null) { biospecimenMetaDataByUUIDORBarcode = new LinkedHashMap<String, BiospecimenMetaData>(); final BiospecimenMetaData patientMetaData = new BiospecimenMetaData(); final String uuid = JAXBUtil.getJAXBObjectValue(patient.getBcrPatientUuid()); patientMetaData.setBarcode(patient.getBcrPatientBarcode().getValue()); setUUID(patientMetaData, uuid, archive); patientMetaData.setUuidType(jaxbIntrospector.getElementName(patient).getLocalPart()); patientMetaData.setBcr(archive.getTheCenter().getCenterId().toString()); patientMetaData.setBatch(archive.getSerialIndex()); patientMetaData.setDisease(archive.getTheTumor().getTumorName()); patientMetaData.setParticipantId(patient.getPatientId().getValue()); patientMetaData.setTissueSourceSite(patient.getTissueSourceSite().getValue()); biospecimenMetaDataByUUIDORBarcode.put( (uuid == null || uuid.isEmpty()) ? patientMetaData.getBarcode() : patientMetaData.getUuid(), patientMetaData); logger.debug("Patient metadata done"); // Get the transform of JAXB object into a list of meta-data entity objects getSampleMetaData(patient, patientMetaData, biospecimenMetaDataByUUIDORBarcode, jaxbIntrospector, archive); logger.debug("Sample metadata done"); getDrugMetaData(patient, patientMetaData, biospecimenMetaDataByUUIDORBarcode, jaxbIntrospector, archive); logger.debug("Drug metadata done"); getRadiationMetaData(patient, patientMetaData, biospecimenMetaDataByUUIDORBarcode, jaxbIntrospector, archive); logger.debug("Radiation metadata done"); getExaminationMetaData(patient, patientMetaData, biospecimenMetaDataByUUIDORBarcode, jaxbIntrospector, archive); logger.debug("Examination metadata done"); getSurgeryMetaData(patient, patientMetaData, biospecimenMetaDataByUUIDORBarcode, jaxbIntrospector, archive); logger.debug("Surgery metadata done"); biospecimenMetaData = new ArrayList<BiospecimenMetaData>( biospecimenMetaDataByUUIDORBarcode.values()); // Persist the meta-data if (!biospecimenMetaDataByUUIDORBarcode.isEmpty()) { // Get the existing meta data from the data base and warn the user if the meta data is changed. final Map<String, BiospecimenMetaData> existingBiospecimenMetaData = uuidHierarchyQueries .getMetaData(new ArrayList<String>(biospecimenMetaDataByUUIDORBarcode.keySet())); logger.debug("Get existing metadata: " + existingBiospecimenMetaData); logger.debug("Persisting metadata starting"); uuidHierarchyQueries.persistUUIDHierarchy(biospecimenMetaData); logger.debug("Persisting metadata done"); final List<BiospecimenMetaData> updatedMetaData = new ArrayList<BiospecimenMetaData>(); // get the updatedMetadata for (final String existingUUIDOrBarcode : existingBiospecimenMetaData.keySet()) { updatedMetaData.add(biospecimenMetaDataByUUIDORBarcode.get(existingUUIDOrBarcode)); } // remove the metadata that are not changed updatedMetaData.removeAll(existingBiospecimenMetaData.values()); if (updatedMetaData.size() > 0) { final StringBuffer warning = new StringBuffer(); for (final BiospecimenMetaData metaData : updatedMetaData) { warning.append("Meta data was updated: "); // get the existing meta data. Key can be either uuid or barcode BiospecimenMetaData existingMetaData = existingBiospecimenMetaData .get(metaData.getUuid()); existingMetaData = (existingMetaData == null) ? existingBiospecimenMetaData.get(metaData.getBarcode()) : existingMetaData; warning.append(existingMetaData.getMetaDataString()).append("-->") .append(metaData.getMetaDataString()); qcContext.addWarning(warning.toString()); warning.delete(0, warning.length()); } } } } processControls(tcgaBcr); } return biospecimenMetaData; }
From source file:com.gst.organisation.staff.service.StaffReadPlatformServiceImpl.java
private String getStaffCriteria(final String sqlSearch, final Long officeId, final boolean loanOfficersOnly, final String status) { final StringBuffer extraCriteria = new StringBuffer(200); if (sqlSearch != null) { extraCriteria.append(" and (").append(sqlSearch).append(")"); }// w w w . j a va 2 s.c o m if (officeId != null) { extraCriteria.append(" and office_id = ").append(officeId).append(" "); } if (loanOfficersOnly) { extraCriteria.append(" and s.is_loan_officer is true "); } // Passing status parameter to get ACTIVE (By Default), INACTIVE or ALL // (Both active and Inactive) employees if (status.equalsIgnoreCase("active")) { extraCriteria.append(" and is_active = 1 "); } else if (status.equalsIgnoreCase("inActive")) { extraCriteria.append(" and is_active = 0 "); } else if (status.equalsIgnoreCase("all")) { } else { throw new UnrecognizedQueryParamException("status", status, new Object[] { "all", "active", "inactive" }); } //adding the Authorization criteria so that a user cannot see an employee who does not belong to his office or a sub office for his office. final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy(); extraCriteria.append(" and o.hierarchy like '" + hierarchy + "%' "); if (StringUtils.isNotBlank(extraCriteria.toString())) { extraCriteria.delete(0, 4); } // remove begin four letter including a space from the string. return extraCriteria.toString(); }
From source file:com.glaf.core.service.impl.MxTableDataServiceImpl.java
@Transactional public Collection<TableModel> saveAll(TableDefinition tableDefinition, String seqNo, Collection<TableModel> rows) { logger.debug("tableDefinition=" + tableDefinition); logger.debug("idColumn=" + tableDefinition.getIdColumn().toString()); if (tableDefinition.getTableName() != null) { tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase()); }//from w w w. j av a 2s .c o m if (tableDefinition.isInsertOnly()) { return this.insertAll(tableDefinition, seqNo, rows); } Collection<String> aggregationKeys = new HashSet<String>(); Map<String, Object> colMap = new java.util.HashMap<String, Object>(); Map<String, Object> keyMap = new java.util.HashMap<String, Object>(); Map<String, String> exprMap = new java.util.HashMap<String, String>(); List<ColumnDefinition> exprColumns = new java.util.ArrayList<ColumnDefinition>(); ColumnModel idColumn = new ColumnModel(); ColumnDefinition idCol = tableDefinition.getIdColumn(); if (idCol != null && idCol.getColumnName() != null) { idColumn.setColumnName(idCol.getColumnName()); idColumn.setJavaType(idCol.getJavaType()); idColumn.setValueExpression(idCol.getValueExpression()); } Iterator<ColumnDefinition> iter = tableDefinition.getColumns().iterator(); while (iter.hasNext()) { ColumnDefinition cell = iter.next(); if (StringUtils.isNotEmpty(cell.getValueExpression())) { exprMap.put(cell.getColumnName(), cell.getValueExpression()); exprColumns.add(cell); } } logger.debug(exprMap); String keyCloumns = tableDefinition.getAggregationKeys(); if (StringUtils.isNotEmpty(keyCloumns)) { List<String> cols = StringTools.split(keyCloumns); if (cols != null && !cols.isEmpty()) { StringBuffer buffer = new StringBuffer(500); Iterator<TableModel> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel tableData = iterator.next(); /** * ?? */ colMap.clear(); buffer.delete(0, buffer.length()); for (ColumnModel cell : tableData.getColumns()) { colMap.put(cell.getColumnName().toLowerCase(), cell.getValue()); } Iterator<String> it = cols.iterator(); while (it.hasNext()) { Object val = colMap.get(it.next().toLowerCase()); if (val != null) { buffer.append(val.toString()); } else { buffer.append(""); } if (it.hasNext()) { buffer.append("_"); } } String aggregationKey = buffer.toString(); aggregationKeys.add(aggregationKey); tableData.setAggregationKey(aggregationKey);// ?? } if (aggregationKeys.size() > 0 && (aggregationKeys.size() % 200 == 0)) { TableModel model = new TableModel(); model.setTableName(tableDefinition.getTableName()); model.setIdColumn(idColumn); model.setAggregationKeys(aggregationKeys); List<Map<String, Object>> list = tableDataMapper.getTableKeyMap(model); if (list != null && !list.isEmpty()) { for (Map<String, Object> dataMap : list) { Object id = ParamUtils.getObject(dataMap, "id"); if (id == null) { id = ParamUtils.getObject(dataMap, "ID"); } String aggregationKey = ParamUtils.getString(dataMap, "aggregationKey"); keyMap.put(aggregationKey, id); } } } } if (aggregationKeys.size() > 0) { TableModel model = new TableModel(); model.setTableName(tableDefinition.getTableName()); model.setIdColumn(idColumn); model.setAggregationKeys(aggregationKeys); List<Map<String, Object>> list = tableDataMapper.getTableKeyMap(model); if (list != null && !list.isEmpty()) { for (Map<String, Object> dataMap : list) { Object id = ParamUtils.getObject(dataMap, "id"); if (id == null) { id = ParamUtils.getObject(dataMap, "ID"); } String aggregationKey = ParamUtils.getString(dataMap, "aggregationKey"); keyMap.put(aggregationKey, id); } } } List<TableModel> inertRows = new java.util.ArrayList<TableModel>(); List<TableModel> updateRows = new java.util.ArrayList<TableModel>(); logger.debug(" rows size = " + rows.size()); Iterator<TableModel> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel tableData = iterator.next(); ColumnModel myPK = tableData.getIdColumn(); ColumnModel pkColumn = new ColumnModel(); pkColumn.setColumnName(idColumn.getColumnName()); pkColumn.setJavaType(idColumn.getJavaType()); for (ColumnModel column : tableData.getColumns()) { colMap.put(column.getColumnName(), column.getValue()); } if (keyMap.containsKey(tableData.getAggregationKey())) { Object id = keyMap.get(tableData.getAggregationKey()); pkColumn.setValue(id); tableData.setIdColumn(pkColumn); tableData.removeColumn(pkColumn); updateRows.add(tableData); } else { ColumnModel col = new ColumnModel(); col.setColumnName("AGGREGATIONKEY"); col.setJavaType("String"); col.setValue(tableData.getAggregationKey()); tableData.removeColumn(col); tableData.addColumn(col); for (ColumnDefinition c : exprColumns) { ColumnModel x = new ColumnModel(); x.setColumnName(c.getColumnName()); x.setJavaType(c.getJavaType()); x.setValueExpression(c.getValueExpression()); tableData.addColumn(x); } for (ColumnModel cell : tableData.getColumns()) { String expr = exprMap.get(cell.getColumnName()); if (StringUtils.isNotEmpty(expr)) { if (ExpressionConstants.NOW_EXPRESSION.equals(expr) || ExpressionConstants.CURRENT_YYYYMMDD_EXPRESSION.equals(expr)) { if (cell.getDateValue() == null) { cell.setDateValue(new Date()); cell.setValue(cell.getDateValue()); } } if (ExpressionConstants.ID_EXPRESSION.equals(expr)) { if (cell.getValue() == null) { if (StringUtils.equals(cell.getJavaType(), "Integer")) { cell.setValue(idGenerator.nextId().intValue()); } else if (StringUtils.equals(cell.getJavaType(), "Long")) { cell.setValue(idGenerator.nextId()); } else { cell.setValue(idGenerator.getNextId()); } } } if (ExpressionConstants.SEQNO_EXPRESSION.equals(expr)) { cell.setValue(seqNo); } if (ExpressionConstants.UUID_EXPRESSION.equals(expr)) { cell.setValue(UUID32.getUUID()); } } } if (myPK != null && myPK.getValue() != null) { pkColumn.setValue(myPK.getValue()); } else { if (StringUtils.equals(pkColumn.getJavaType(), "Integer")) { pkColumn.setValue(idGenerator.nextId().intValue()); } else if (StringUtils.equals(pkColumn.getJavaType(), "Long")) { pkColumn.setValue(idGenerator.nextId()); } else { pkColumn.setValue(idGenerator.getNextId()); } } tableData.removeColumn(pkColumn); tableData.addColumn(pkColumn); tableData.setIdColumn(pkColumn); inertRows.add(tableData); } } if (!inertRows.isEmpty()) { logger.debug("inert rows size:" + inertRows.size()); for (TableModel tableData : inertRows) { tableData.setTableName(tableDefinition.getTableName()); logger.debug(tableData.toString()); tableDataMapper.insertTableData(tableData); } } if (!updateRows.isEmpty()) { logger.debug("update rows size:" + updateRows.size()); for (TableModel tableData : updateRows) { tableData.setTableName(tableDefinition.getTableName()); tableDataMapper.updateTableDataByPrimaryKey(tableData); } } return rows; } else { throw new RuntimeException("aggregationKeys is required."); } }
From source file:org.ourbeehive.mbp.util.JavaFormatter.java
public static String getJavaStyle(String dbPhrase, boolean isLargeCamel) { // If 'dbPhrase' contain schema name, then remove it. int idx = dbPhrase.indexOf(MapperElm.DOT); if (idx != -1) { dbPhrase = dbPhrase.substring(idx + 1, dbPhrase.length()); }//from w w w.j a v a 2 s. co m // If table name begin with defined prefix, then remove it. if (dbPhrase.startsWith(MapperElm.SQL_TABLE_NAME_PREFIX) == true) { dbPhrase = dbPhrase.substring(MapperElm.SQL_TABLE_NAME_PREFIX.length(), dbPhrase.length()); } // Prepare the return value. StringBuffer dbWord = new StringBuffer(); StringBuffer javaPhrase = new StringBuffer(); String javaWord = null; // Get 'abbrToFullNameCache' from SrcGenContext. // Hashtable<String, String> abbrToFullNameCache = CtxCacheFacade.getAbbrToFullNameCache(); int len = dbPhrase.length(); char c = 0; // Separate 'dbPhrase' into 'dbWord', and transform to corresponding 'javaWord'. for (int i = 0; i < len; i++) { c = dbPhrase.charAt(i); // Append any characters not equals underline at the end of current dbWord. if (String.valueOf(c).equals(MapperElm.UNDER_LINE) == false) { dbWord.append(c); if (i < len - 1) { continue; } } if (dbWord.length() != 0) { // Find corresponding 'javaWord' with previous 'dbWord'. // if (changeToFullName == true) { // javaWord = abbrToFullNameCache.get(dbWord.toString()); // } else { javaWord = dbWord.toString().toLowerCase(); // } // If 'javaWord' was found, then append it into 'javaPhrase'. // if (javaWord != null) { if (isLargeCamel == true || javaPhrase.length() != 0) { javaWord = StringHelper.toUpperCase(javaWord, 0); } javaPhrase.append(javaWord); // } // else { // // If no 'javaWord' was found, then no need to look up others. // logger.warn("NO JAVA PHRASE: Fail to find corresponding Java phrase " + "for the given DB phrase: " + dbPhrase // + ", because no corresponding Java word found for DB word: " + dbWord); // return null; // } // Refresh current 'dbWord' and begin with new finding. dbWord.delete(0, dbWord.length()); } } // Processing the situation where no 'DB_WORD_SEPARATOR' was occurred. // if (dbWord.length() != 0) { // // // Find corresponding 'javaWord' with previous 'dbWord'. // // if (changeToFullName == true) { // // javaWord = abbrToFullNameCache.get(dbWord.toString()); // // } else { // javaWord = dbWord.toString().toLowerCase(); // // } // // // If 'javaWord' was found, then append it into 'javaPhrase'. // if (javaWord != null) { // if (javaPhrase.length() != 0) { // javaWord = StringHelper.toUpperCase(javaWord, 0); // } // javaPhrase.append(javaWord); // } // // // else { // // // If no 'javaWord' was found, then no need to look up others. // // logger.warn("NO JAVA PHRASE: Fail to find corresponding Java phrase " + "for the given DB phrase: " + dbPhrase // // + ", because no corresponding Java word found for DB word: " + dbWord); // // return null; // // } // // } return javaPhrase.toString(); }