List of usage examples for org.apache.commons.lang StringUtils contains
public static boolean contains(String str, String searchStr)
Checks if String contains a search String, handling null
.
From source file:edu.ku.brc.af.ui.forms.FormViewObj.java
/** * This method enables us to loop when there is a duplicate key * @param dataObj the data object to be saved * @return the merged object, or null if there was an error. *//*from w w w .ja v a 2 s .c o m*/ protected SAVE_STATE saveToDB(final Object dataObjArg) { if (dataObjArg == null) { if (saveControl != null) { saveControl.setEnabled(false); } return SAVE_STATE.SaveOK; } SAVE_STATE saveState = SAVE_STATE.Initial; boolean isDuplicateError = false; boolean tryAgain = false; int numTries = 0; Vector<Object> deletedItems = mvParent != null ? mvParent.getDeletedItems() : null; Vector<Object> toBeSavedItems = mvParent != null ? mvParent.getToBeSavedItems() : null; Object dObj = null; do { try { numTries++; Integer dataObjId = ((FormDataObjIFace) dataObjArg).getId(); if (dataObjId != null) { DataProviderSessionIFace session1 = DataProviderFactory.getInstance().createSession(); Integer count = null; try { count = session1.getDataCount(dataObjArg.getClass(), "id", dataObjId, DataProviderSessionIFace.CompareType.Equals); } catch (Exception ex) { ex.printStackTrace(); } finally { if (session1 != null) session1.close(); } if (count == null || count == 0) { UIRegistry.showLocalizedError("FormViewObj.DATA_OBJ_MISSING"); setHasNewData(false); removeObject(true); return SAVE_STATE.Error; } } // First get data so business Rules can be checked this.getDataFromUI(); traverseToGetDataFromForms(mvParent); //log.debug("saveObject checking businessrules for [" + (dataObjArg != null ? dataObjArg.getClass(): "null") + "]"); //if (businessRules != null && businessRules.processBusinessRules(dataObjArg) == BusinessRulesIFace.STATUS.Error) BusinessRulesIFace busRuleInError = recurseProcessBR(mvParent); if (busRuleInError != null) { UIRegistry.showError(busRuleInError.getMessagesAsString()); return null; } // Now update the auto number fields and re-get all the data // we can't update the auto number fields before we run the business rules. mvParent.updateAutoNumbers(); this.getDataFromUI(); traverseToGetDataFromForms(mvParent); // XXX FINAL RELEASE - Need to walk the form tree and set them manually //FormHelper.updateLastEdittedInfo(dataObjArg); traverseToSetModified(getMVParent()); session.beginTransaction(); if (numTries == 1 && deletedItems != null && deletedItems.size() > 0) { //As far as I can tell it is not necessary to delete the items by hand, hibernate will delete them automatically //when the parent object is saved. EXCEPT if constraint violations are present due to user actions: //Say a user deletes Jim Jones from the collector list, and then changes mind and adds Jim Jones, and saves. //Then it is necessary to delete here -- I think because hibernate doesn't work. //If not for the merging done by business rules for embedded collectingevents it would be possible //to only delete manually if numTries was 2, i.e. hibernate failed the first try, but the merging generates //exceptions for duplicate keys that are not thrown up to this method but mess up the session. deleteItemsInDelList(session, deletedItems); try { //need to flush so later actions in the transaction know about the deletes. session.flush(); } catch (org.hibernate.ObjectDeletedException odex) { //for some reason, for authors (apparently ONLY authors, even though the annotations look the same as for collector, groupmember), //hibernate will complain that the object "will be re-saved by cascade rules". If we just ignore the exception hibernate cascade deletes the object later. log.warn(odex.getMessage()); } } if (numTries == 1 && toBeSavedItems != null) { //see remarks above for deletes. //No problems here so far, so just do it the first time around. saveItemsInToBeSavedList(session, toBeSavedItems); } if (businessRules != null) { businessRules.startProcessingBeforeAfterRules(); businessRules.beforeMerge(dataObjArg, session); } dObj = session.merge(dataObjArg); if (businessRules != null) { businessRules.beforeSave(dObj, session); } session.saveOrUpdate(dObj); if (businessRules != null) { if (!businessRules.beforeSaveCommit(dObj, session)) { throw new Exception("Business rules processing failed"); } } session.commit(); session.flush(); if (mvParent != null) { mvParent.clearItemsToBeSaved(); } if (deletedItems != null) { // notify the business rules object that a deletion has occurred for (Object obj : deletedItems) { BusinessRulesIFace delBusRules = DBTableIdMgr.getInstance().getBusinessRule(obj); if (delBusRules != null) { delBusRules.afterDeleteCommit(obj); } } deletedItems.clear(); } tryAgain = false; isNewlyCreatedDataObj = isCreatingNewObject; // shouldn't be needed, but just in case if (rsController != null) { rsController.setNewObj(isNewlyCreatedDataObj); } if (formValidator != null) { formValidator.setNewObj(isNewlyCreatedDataObj); } saveState = SAVE_STATE.SaveOK; dataObj = dObj; for (FVOFieldInfo fi : controlsByName.values()) { if (fi.getComp() instanceof EditViewCompSwitcherPanel) { ((EditViewCompSwitcherPanel) fi.getComp()).putIntoViewMode(); } } } catch (StaleObjectException e) // was StaleObjectStateException { session.rollback(); recoverFromStaleObject("UPDATE_DATA_STALE", null); tryAgain = false; dObj = dataObj; saveState = SAVE_STATE.StaleRecovery; //e.printStackTrace(); } catch (ConstraintViolationException e) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormViewObj.class, e); log.error(e); log.error(e.getSQLException()); log.error(e.getSQLException().getSQLState()); // This check here works for MySQL in English "Duplicate entry" // we can add other Databases as we go // The idea of this code is that if we are certain it failed on a constraint because // of a duplicate key error then we will try a couple of more times. // // The number 5 and 3 below are completely arbitrary, I just choose them // because they seemed right. // String errMsg = e.getSQLException().toString(); if (StringUtils.isNotEmpty(errMsg) && errMsg.indexOf("Duplicate entry") > -1) { isDuplicateError = true; } tryAgain = (isDuplicateError && numTries < 5) || (!isDuplicateError && numTries < 3); isDuplicateError = false; // Ok, we tried a couple of times and have decided to give up. if (!tryAgain) { session.rollback(); recoverFromStaleObject("DUPLICATE_KEY_ERROR", null); dObj = dataObj; saveState = SAVE_STATE.StaleRecovery; } } catch (org.hibernate.ObjectNotFoundException ex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormViewObj.class, ex); String errMsg = null; String msg = ex.toString(); if (StringUtils.contains(msg, "No row with the given identifier exists")) { int sInx = msg.indexOf('['); int eInx = msg.lastIndexOf(']'); if (sInx > -1 && eInx > -1) { msg = msg.substring(sInx + 1, eInx); eInx = msg.lastIndexOf('#'); if (eInx > -1) { msg = msg.substring(0, eInx); DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(msg); if (ti != null) { errMsg = String.format(getResourceString("FormViewObj.FIELD_STALE_TITLE"), ti.getTitle()); } } } } if (errMsg == null) { errMsg = getResourceString("FormViewObj.FIELD_STALE"); } session.rollback(); recoverFromStaleObject("UNRECOVERABLE_DB_ERROR", errMsg); saveState = SAVE_STATE.StaleRecovery; } catch (Exception e) { session.rollback(); // This happens when MySQL doesn't have permissions // to INSERT, UPDATE, OR DELETE if (e instanceof SQLGrammarException) { String msg = e.getCause().getMessage(); if (StringUtils.contains(msg.toLowerCase(), "denied")) { UIRegistry.showLocalizedError("FormViewObj.MISSING_DB_PERMS"); } } else { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormViewObj.class, e); log.error("******* " + e); e.printStackTrace(); } recoverFromStaleObject("UNRECOVERABLE_DB_ERROR", null); saveState = SAVE_STATE.StaleRecovery; } } while (tryAgain); return saveState; }
From source file:com.haulmont.cuba.web.gui.components.WebAbstractTable.java
protected String generateDefaultCellStyle(Object itemId, Object propertyId, MetaPropertyPath propertyPath) { String style = null;//w w w. jav a2s . co m Column column = getColumn(propertyId.toString()); if (column != null) { final String isLink = column.getXmlDescriptor() == null ? null : column.getXmlDescriptor().attributeValue("link"); if (propertyPath.getRange().isClass()) { if (StringUtils.isNotEmpty(isLink) && Boolean.valueOf(isLink)) { style = "c-table-cell-link"; } } else if (propertyPath.getRange().isDatatype()) { if (StringUtils.isNotEmpty(isLink) && Boolean.valueOf(isLink)) { style = "c-table-cell-link"; } else if (column.getMaxTextLength() != null) { Entity item = getDatasource().getItemNN(itemId); Object value = item.getValueEx(propertyId.toString()); String stringValue; if (value instanceof String) { stringValue = item.getValueEx(propertyId.toString()); } else { if (DynamicAttributesUtils.isDynamicAttribute(propertyPath.getMetaProperty())) { stringValue = DynamicAttributesUtils .getDynamicAttributeValueAsString(propertyPath.getMetaProperty(), value); } else { stringValue = value == null ? null : value.toString(); } } if (column.getMaxTextLength() != null) { boolean isMultiLineCell = StringUtils.contains(stringValue, "\n"); if ((stringValue != null && stringValue.length() > column.getMaxTextLength() + MAX_TEXT_LENGTH_GAP) || isMultiLineCell) { style = "c-table-cell-textcut"; } else { // use special marker stylename style = "c-table-clickable-text"; } } } } } if (propertyPath.getRangeJavaClass() == Boolean.class) { Entity item = datasource.getItem(itemId); if (item != null) { Boolean value = item.getValueEx(propertyId.toString()); if (BooleanUtils.isTrue(value)) { style = "boolean-cell boolean-cell-true"; } else { style = "boolean-cell boolean-cell-false"; } } } return style; }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * Fixes the Schema for Database Version 1.2 * @param conn/*w w w .j av a 2 s. c o m*/ * @throws Exception */ private boolean doFixesForDBSchemaVersions(final Connection conn, final String databaseName) throws Exception { ///////////////////////////// // PaleoContext ///////////////////////////// getTableNameAndTitleForFrame(PaleoContext.getClassTableId()); Integer len = getFieldLength(conn, databaseName, "paleocontext", "Text1"); alterFieldLength(conn, databaseName, "paleocontext", "Text1", 32, 64); alterFieldLength(conn, databaseName, "paleocontext", "Text2", 32, 64); len = getFieldLength(conn, databaseName, "paleocontext", "Remarks"); if (len == null) { int count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM paleocontext"); int rv = update(conn, "ALTER TABLE paleocontext ADD Remarks VARCHAR(60)"); if (rv != count) { errMsgList.add("Error updating PaleoContext.Remarks"); return false; } } frame.incOverall(); DBConnection dbc = DBConnection.getInstance(); ///////////////////////////// // FieldNotebookPage ///////////////////////////// getTableNameAndTitleForFrame(FieldNotebookPage.getClassTableId()); len = getFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber"); if (len != null && len == 16) { alterFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber", 16, 32); update(conn, "ALTER TABLE fieldnotebookpage ALTER COLUMN ScanDate DROP DEFAULT"); } frame.incOverall(); ///////////////////////////// // Project Table ///////////////////////////// alterFieldLength(conn, databaseName, "project", "projectname", 50, 128); frame.incOverall(); ///////////////////////////// // AttachmentImageAttribute Table ///////////////////////////// if (doesTableExist(databaseName, "attachmentimageattribute")) { alterFieldLength(conn, databaseName, "attachmentimageattribute", "CreativeCommons", 128, 500); frame.incOverall(); } ///////////////////////////// // LocalityDetail ///////////////////////////// String tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId()); boolean statusOK = true; String sql = String.format( "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'localitydetail' AND COLUMN_NAME = 'UtmScale' AND DATA_TYPE = 'varchar'", dbc.getDatabaseName()); int count = BasicSQLUtils.getCountAsInt(sql); if (count > 0) { Vector<Object[]> values = query("SELECT ld.LocalityDetailID, ld.UtmScale, l.LocalityName " + "FROM localitydetail ld INNER JOIN locality l ON ld.LocalityID = l.LocalityID WHERE ld.UtmScale IS NOT NULL"); update(conn, "ALTER TABLE localitydetail DROP COLUMN UtmScale"); addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude"); addColumn(conn, databaseName, tblName, "MgrsZone", "VARCHAR(4)", "UtmScale"); HashMap<String, String> badLocalitiesHash = new HashMap<String, String>(); try { PreparedStatement pStmt = conn .prepareStatement("UPDATE localitydetail SET UtmScale=? WHERE LocalityDetailID=?"); for (Object[] row : values) { Integer locDetailId = (Integer) row[0]; String scale = (String) row[1]; String locName = (String) row[2]; scale = StringUtils.contains(scale, ',') ? StringUtils.replace(scale, ",", "") : scale; if (!StringUtils.isNumeric(scale)) { badLocalitiesHash.put(locName, scale); continue; } float scaleFloat = 0.0f; try { scaleFloat = Float.parseFloat(scale); } catch (NumberFormatException ex) { badLocalitiesHash.put(locName, scale); continue; } pStmt.setFloat(1, scaleFloat); pStmt.setInt(2, locDetailId); pStmt.execute(); } pStmt.close(); } catch (SQLException ex) { statusOK = false; } if (badLocalitiesHash.size() > 0) { try { File file = new File( UIRegistry.getUserHomeDir() + File.separator + "localitydetailerrors.html"); TableWriter tblWriter = new TableWriter(file.getAbsolutePath(), "Locality Detail Errors"); tblWriter.startTable(); tblWriter.logHdr(new String[] { "Locality Name", "Scale" }); for (String key : badLocalitiesHash.keySet()) { tblWriter.log(key, badLocalitiesHash.get(key)); } tblWriter.endTable(); tblWriter.flush(); tblWriter.close(); UIRegistry.showLocalizedError("LOC_DETAIL_ERRORS", badLocalitiesHash.size(), file.getAbsoluteFile()); badLocalitiesHash.clear(); if (file.exists()) { try { AttachmentUtils.openURI(file.toURI()); } catch (Exception ex) { ex.printStackTrace(); } } } catch (IOException ex) { ex.printStackTrace(); } } } else { addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude"); } frame.incOverall(); ////////////////////////////////////////////// // collectingeventattribute Schema 1.3 ////////////////////////////////////////////// DBMSUserMgr dbmsMgr = DBMSUserMgr.getInstance(); if (dbmsMgr.connectToDBMS(itUserNamePassword.first, itUserNamePassword.second, dbc.getServerName())) { boolean status = true; Connection connection = dbmsMgr.getConnection(); try { // Add New Fields to Determination tblName = getTableNameAndTitleForFrame(Determination.getClassTableId()); addColumn(conn, databaseName, tblName, "VarQualifier", "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER Qualifier"); addColumn(conn, databaseName, tblName, "SubSpQualifier", "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER VarQualifier"); frame.incOverall(); // CollectingEventAttributes sql = String.format( "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collectingeventattribute' AND COLUMN_NAME = 'CollectionMemberID'", dbc.getDatabaseName()); count = BasicSQLUtils.getCountAsInt(sql); connection.setCatalog(dbc.getDatabaseName()); //int numCEAttrs = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute"); if (count > 0) { HashMap<Integer, Integer> collIdToDispIdHash = new HashMap<Integer, Integer>(); sql = "SELECT UserGroupScopeId, DisciplineID FROM collection"; for (Object[] cols : query(sql)) { Integer colId = (Integer) cols[0]; Integer dspId = (Integer) cols[1]; collIdToDispIdHash.put(colId, dspId); } count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute"); IdMapperMgr.getInstance().setDBs(connection, connection); IdTableMapper mapper = new IdTableMapper("ceattrmapper", "id", "SELECT CollectingEventAttributeID, CollectionMemberID FROM collectingeventattribute", true, false); mapper.setFrame(frame); mapper.mapAllIdsNoIncrement(count > 0 ? count : null); Statement stmt = null; try { getTableNameAndTitleForFrame(CollectingEventAttribute.getClassTableId()); stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); update(conn, "DROP INDEX COLEVATSColMemIDX on collectingeventattribute"); update(conn, "ALTER TABLE collectingeventattribute DROP COLUMN CollectionMemberID"); update(conn, "ALTER TABLE collectingeventattribute ADD COLUMN DisciplineID int(11)"); update(conn, "CREATE INDEX COLEVATSDispIDX ON collectingeventattribute(DisciplineID)"); double inc = count > 0 ? (100.0 / (double) count) : 0; double cnt = 0; int percent = 0; frame.setProcess(0, 100); frame.setProcessPercent(true); PreparedStatement pStmt = conn.prepareStatement( "UPDATE collectingeventattribute SET DisciplineID=? WHERE CollectingEventAttributeID=?"); ResultSet rs = stmt .executeQuery("SELECT CollectingEventAttributeID FROM collectingeventattribute"); while (rs.next()) { Integer ceAttrId = rs.getInt(1); Integer oldColId = mapper.get(ceAttrId); if (oldColId != null) { Integer dispId = collIdToDispIdHash.get(oldColId); if (dispId != null) { pStmt.setInt(1, dispId); pStmt.setInt(2, ceAttrId); pStmt.execute(); } else { log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId + "] ceAttrId[" + ceAttrId + "]"); } } else { log.debug("Error getting mapped Collection ID[" + oldColId + "] ceAttrId[" + ceAttrId + "]"); } cnt += inc; if (((int) cnt) > percent) { percent = (int) cnt; frame.setProcess(percent); } } rs.close(); pStmt.close(); frame.setProcess(100); } catch (SQLException ex) { ex.printStackTrace(); } finally { if (stmt != null) stmt.close(); } mapper.cleanup(); } frame.incOverall(); //----------------------------- // Collectors //----------------------------- sql = String.format( "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collector' AND COLUMN_NAME = 'CollectionMemberID'", dbc.getDatabaseName()); count = BasicSQLUtils.getCountAsInt(sql); if (count > 0) { HashMap<Integer, Integer> collIdToDivIdHash = new HashMap<Integer, Integer>(); sql = "SELECT c.UserGroupScopeId, d.DivisionID FROM collection c INNER JOIN discipline d ON c.DisciplineID = d.UserGroupScopeId"; for (Object[] cols : query(sql)) { Integer colId = (Integer) cols[0]; Integer divId = (Integer) cols[1]; collIdToDivIdHash.put(colId, divId); } count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collector"); IdMapperMgr.getInstance().setDBs(connection, connection); IdTableMapper mapper = new IdTableMapper("collectormap", "id", "SELECT CollectorID, CollectionMemberID FROM collector", true, false); mapper.setFrame(frame); mapper.mapAllIdsNoIncrement(count > 0 ? count : null); getTableNameAndTitleForFrame(Collector.getClassTableId()); Statement stmt = null; try { stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); update(conn, "DROP INDEX COLTRColMemIDX on collector"); update(conn, "ALTER TABLE collector DROP COLUMN CollectionMemberID"); update(conn, "ALTER TABLE collector ADD COLUMN DivisionID INT(11)"); update(conn, "CREATE INDEX COLTRDivIDX ON collector(DivisionID)"); double inc = count > 0 ? (100.0 / (double) count) : 0; double cnt = 0; int percent = 0; frame.setProcess(0, 100); frame.setProcessPercent(true); PreparedStatement pStmt = conn .prepareStatement("UPDATE collector SET DivisionID=? WHERE CollectorID=?"); ResultSet rs = stmt.executeQuery("SELECT CollectorID FROM collector"); while (rs.next()) { Integer coltrId = rs.getInt(1); Integer oldColId = mapper.get(coltrId); if (oldColId != null) { Integer divId = collIdToDivIdHash.get(oldColId); if (divId != null) { pStmt.setInt(1, divId); pStmt.setInt(2, coltrId); pStmt.execute(); } else { log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId + "]"); } } else { log.debug("Error getting mapped Collector ID[" + oldColId + "]"); } cnt += inc; if (((int) cnt) > percent) { percent = (int) cnt; frame.setProcess(percent); } } rs.close(); pStmt.close(); frame.setProcess(100); } catch (SQLException ex) { ex.printStackTrace(); } finally { if (stmt != null) stmt.close(); } mapper.cleanup(); frame.incOverall(); } } catch (Exception ex) { ex.printStackTrace(); } finally { frame.getProcessProgress().setIndeterminate(true); frame.setDesc("Loading updated schema..."); if (!status) { //UIRegistry.showLocalizedError("SCHEMA_UPDATE_ERROR", errMsgStr); JTextArea ta = UIHelper.createTextArea(); ta.setText(errMsgStr); CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g")); pb.add(new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), cc.xy(1, 1)); pb.setDefaultDialogBorder(); CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(), getResourceString("SCHEMA_UPDATE_ERROR"), true, pb.getPanel()); UIHelper.centerAndShow(dlg); } dbmsMgr.close(); } } return statusOK; }
From source file:com.ah.ui.actions.config.ImportCsvFileAction.java
/** * For MAC, we support these formats: <br> * 1- 000000000000<br> /*from w w w.j av a2 s .com*/ * 2- 00:00:00:00:00:00<br> * 3- 00-00-00-00-00-00<br> * 4- 000000-000000 <br> * For OUI, we support these formats: <br> * 1- 000000 <br> * 2- 00:00:00 <br> * 3- 00-00-00 * * @param macORoui - * @return value without separator or any format; <p>if the param not in supported format, return <b>null</b> */ private String format2MACOUI(String macORoui) { final int MAC_LENGTH = 12; final int OUI_LENGTH = 6; final String colonSymbols = ":"; final String dashSymbols = "-"; if (StringUtils.isEmpty(macORoui)) { return null; } int length = macORoui.length(); if (MAC_LENGTH == length || OUI_LENGTH == length) { //MAC_1 - 000000000000 //OUI_1 - 000000 if (isHex(macORoui)) return macORoui; //"The MAC/OUI "+macORoui+" should only contains hex value." return null; } else if (OUI_LENGTH < length && length < MAC_LENGTH) { boolean containsColon = StringUtils.contains(macORoui, colonSymbols); boolean containsDash = StringUtils.contains(macORoui, dashSymbols); if (containsColon && containsDash) { //"The MAC "+macORoui+" is invalid format." return null; } String[] arrayStr = macORoui.split(containsColon ? colonSymbols : dashSymbols); if (3 == arrayStr.length) { //OUI_2 - 00:00:00 //OUI_3 - 00-00-00 for (String element : arrayStr) { //if the sub string's length exceed 2 or not a hex value return null if (2 != element.length() || !isHex(element)) { //"The OUI "+macORoui+" is invalid format." return null; } } return StringUtils.join(arrayStr); } else { //"The OUI "+macORoui+" is invalid format." return null; } } else if (MAC_LENGTH < length) { boolean containsColon = StringUtils.contains(macORoui, colonSymbols); boolean containsDash = StringUtils.contains(macORoui, dashSymbols); if (containsColon && containsDash) { //"The MAC "+macORoui+" is invalid format." return null; } String[] arrayStr = macORoui.split(containsColon ? colonSymbols : dashSymbols); if (6 == arrayStr.length) { //MAC_2 - 00:00:00:00:00:00 //MAC_3 - 00-00-00-00-00-00 for (String element : arrayStr) { //if the sub string's length exceed 2 or not a hex value return null if (2 != element.length() || !isHex(element)) { //"The MAC "+macORoui+" is invalid format." return null; } } return StringUtils.join(arrayStr); } else if (2 == arrayStr.length && containsDash) { //MAC_4 - 000000-000000 if (6 != arrayStr[0].length() || 6 != arrayStr[1].length()) { //"The MAC "+macORoui+" is invalid format." return null; } if (isHex(arrayStr[0]) && isHex(arrayStr[1])) { return StringUtils.join(arrayStr); } else { //"The MAC "+macORoui+" is invalid format." return null; } } else { //after split the length isn't equal 6 or 2, return null //"The MAC "+macORoui+" is invalid format." } } else { //"Unknown return...input is:"+macORoui } return null; }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
public static void turnOnHibernateLogging(Level level) { for (Enumeration<?> e = LogManager.getCurrentLoggers(); e.hasMoreElements();) { Logger logger = (Logger) e.nextElement(); if (StringUtils.contains(logger.getName(), "hibernate")) { logger.setLevel(level);// www .j a v a 2 s . c o m } } }
From source file:net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.GenericWikiTableConfigurationBean.java
/** * @see net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.IWikiTableConfiguration#setHeaderCell(java.lang.String) *///from ww w . j a v a 2 s.c o m @Override public void setHeaderCell(String headerCell) { checkReadOnly(); if (StringUtils.contains(headerCell, VALUE_PLACEHOLDER) == false) { throw new IllegalArgumentException( s_stringMgr.getString("GenericWikiTableConfigurationBean.headerCellErrorValueVariableMissing")); //$NON-NLS-1$ } this.headerCell = headerCell; }
From source file:net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.GenericWikiTableConfigurationBean.java
/** * @see net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.IWikiTableConfiguration#setDataCell(java.lang.String) *//*from w w w .ja va2s.c o m*/ @Override public void setDataCell(String dataCell) { checkReadOnly(); if (StringUtils.contains(dataCell, VALUE_PLACEHOLDER) == false) { throw new IllegalArgumentException( s_stringMgr.getString("GenericWikiTableConfigurationBean.dataCellErrorValueVariableMissing")); //$NON-NLS-1$ } this.dataCell = dataCell; }
From source file:net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.GenericWikiTableConfigurationBean.java
/** * @see net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.IWikiTableConfiguration#setNoWikiTag(java.lang.String) *//*from w w w .j av a2s. c om*/ @Override public void setNoWikiTag(String escapeSequence) { checkReadOnly(); if (StringUtils.contains(escapeSequence, VALUE_PLACEHOLDER) == false) { throw new IllegalArgumentException( s_stringMgr.getString("GenericWikiTableConfigurationBean.noWikiErrorValueVariableMissing")); //$NON-NLS-1$ } this.noWikiTag = escapeSequence; }
From source file:net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.GenericWikiTableTransformer.java
/** * Replaces some variables in the token and append's the resulting string to * the buffer. The following place holder would be replaced: * <li>NEW_LINE_PLACEHOLDER</li> * <li>VALUE_PLACEHOLDER</li> * If the configuration contains a <code>noWikiTag</code>, then the value will be embedded into this tag. * @param buff Buffer, where to append/*w ww .jav a 2 s . com*/ * @param token token, where the replacement should be done. * @param value value, which should be replace the {@link IWikiTableConfiguration#VALUE_PLACEHOLDER} * @see #NEW_LINE_PLACEHOLDER * @see #VALUE_PLACEHOLDER * @see IWikiTableConfiguration#getNoWikiTag() * */ public void appendWithReplacement(StringBuilder buff, String token, String value) { if (StringUtils.contains(token, IWikiTableConfiguration.VALUE_PLACEHOLDER) && value == null) { value = ""; //$NON-NLS-1$ } else if (!StringUtils.contains(token, IWikiTableConfiguration.VALUE_PLACEHOLDER) && value != null) { throw new IllegalStateException("there is no place holder for the value, but I should inject a value!"); //$NON-NLS-1$ } if (StringUtils.isNotBlank(token)) { // Escape the value; if (StringUtils.contains(token, IWikiTableConfiguration.VALUE_PLACEHOLDER)) { value = escapeString(value); } value = replacePlaceHolder(token, value); buff.append(value); } }
From source file:net.ymate.framework.commons.ParamUtils.java
private static void __doAppendHiddenElement(StringBuilder stringBuilder, String key, String value, boolean encode, String charset) { if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) { String _splitStr = StringUtils.contains(value, '\"') ? "\'" : "\""; ////from ww w . j av a 2 s . c o m stringBuilder.append("<input type=").append(_splitStr).append("hidden").append(_splitStr) .append(" name=").append(_splitStr).append(key).append(_splitStr); // String _valueStr = value; if (encode) { try { _valueStr = URLEncoder.encode(_valueStr, charset); } catch (UnsupportedEncodingException e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } stringBuilder.append(" value=").append(_splitStr).append(_valueStr).append(_splitStr).append(">"); } }