I have the following java code that violets the checkstyle saying that "Cyclomatic Complexity is 11 ( max allowed is 10 )"
public boolean validate(final BindingResult bindingResult) {
boolean validate = true;
for (String channel : getConfiguredChannels()) {
switch (channel) {
case "SMS":
// do nothing
break;
case "Email":
// do nothing
break;
case "Facebook":
// do nothing
break;
case "Voice":
final SpelExpressionParser parser = new SpelExpressionParser();
if (parser
.parseExpression(
"!voiceMessageForm.audioForms.?[audioId == '' || audioId == null].isEmpty()")
.getValue(this, Boolean.class)) {
bindingResult.rejectValue("voiceMessageForm.audioForms",
"message.voice.provide.all.audios");
validate = false;
}
boolean voiceContentErrorSet = false;
boolean voiceDescriptionErrorSet = false;
for (AudioForm audioForm : (List<AudioForm>) parser
.parseExpression(
"voiceMessageForm.audioForms.?[description.length() > 8000]")
.getValue(this)) {
if (audioForm.getAddAudioBy().equals(
AudioForm.AddBy.TTS)
&& !voiceContentErrorSet) {
voiceContentErrorSet = true;
bindingResult.rejectValue(
"voiceMessageForm.audioForms",
"message.voice.content.exceed.limit");
} else {
if (!voiceDescriptionErrorSet) {
voiceDescriptionErrorSet = false;
bindingResult
.rejectValue(
"voiceMessageForm.audioForms",
"message.describe.voice.content.exceed.limit");
}
}
validate = false;
}
break;
default:
throw new IllegalStateException("Unsupported channel: "
+ channel);
}
}
return validate;
}
}
Please suggest a suitable way to avoid this checkstyle issue
I'd go ahead and extract your code of the "Voice" case to another method. After that your validate method will look like:
(You can use the refactoring tools of your IDE to do so.)
public boolean validate(final BindingResult bindingResult) {
boolean validate = true;
for (String channel : getConfiguredChannels()) {
switch (channel) {
case "SMS":
// do nothing
break;
case "Email":
// do nothing
break;
case "Facebook":
// do nothing
break;
case "Voice":
validate = validateVoice(bindingResult);
default:
throw new IllegalStateException("Unsupported channel: "
+ channel);
}
}
return validate;
}
Edit: (Added extracted method, although I did not really look into it.)
private boolean validateVoice(final BindingResult bindingResult) {
boolean validate = true;
final SpelExpressionParser parser = new SpelExpressionParser();
if (parser.parseExpression("!voiceMessageForm.audioForms.?[audioId == '' || audioId == null].isEmpty()").getValue(this, Boolean.class)) {
bindingResult.rejectValue("voiceMessageForm.audioForms", "message.voice.provide.all.audios");
validate = false;
}
boolean voiceContentErrorSet = false;
boolean voiceDescriptionErrorSet = false;
for (AudioForm audioForm : (List<AudioForm>) parser.parseExpression("voiceMessageForm.audioForms.?[description.length() > 8000]").getValue(this)) {
if (audioForm.getAddAudioBy().equals(AudioForm.AddBy.TTS) && !voiceContentErrorSet) {
voiceContentErrorSet = true;
bindingResult.rejectValue("voiceMessageForm.audioForms", "message.voice.content.exceed.limit");
} else {
if (!voiceDescriptionErrorSet) {
voiceDescriptionErrorSet = false;
bindingResult.rejectValue("voiceMessageForm.audioForms", "message.describe.voice.content.exceed.limit");
}
}
validate = false;
}
return validate;
}
Related
I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts
Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);
I'm in a paser of a Webservice. With it, I picked up the dice and already gave Set In each of them (is working agreement). However, in time to insert the same in the database it displays the following error (null):
Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
The db needs a Context, but I can not in class because there extends an Activity or otherwise to the use of getBaseContext, getAplication among others ..
*parser:
public class WSParserSetValoresBD {
private String text;
public BDProgramacaoGetterSetter programacaoGetterSetter;
boolean tabela = false;
int contadorLinhas = 0;
private Context ctx;
public WSParserSetValoresBD(Context contextP){
this.ctx=contextP; // I've checked here and not be null, it's all right
}
BDProgramacaoBancoDao inserir = new BDProgramacaoBancoDao(ctx);
public void parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT ) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("Table")){
tabela = true;
programacaoGetterSetter = new BDProgramacaoGetterSetter();
contadorLinhas++;
}
else if (tagname.equalsIgnoreCase("DATA") || tagname.equalsIgnoreCase("ROTA") || tagname.equalsIgnoreCase("IWERK")
|| tagname.equalsIgnoreCase("AUFNR")|| tagname.equalsIgnoreCase("VORNR")|| tagname.equalsIgnoreCase("POINT")
|| tagname.equalsIgnoreCase("SEQUENCIA")|| tagname.equalsIgnoreCase("STATUS_PONTO")|| tagname.equalsIgnoreCase("FREQUENCIA")
|| tagname.equalsIgnoreCase("PSORT")|| tagname.equalsIgnoreCase("PTTXT")|| tagname.equalsIgnoreCase("EQUNR")
|| tagname.equalsIgnoreCase("EQKTX")|| tagname.equalsIgnoreCase("TPLNR")|| tagname.equalsIgnoreCase("PLTXT")
|| tagname.equalsIgnoreCase("SIST_LUBRIFIC")|| tagname.equalsIgnoreCase("REF_LUBRIFIC")|| tagname.equalsIgnoreCase("COD_LUBRIFIC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFICCL")|| tagname.equalsIgnoreCase("QTD_CONSUMO")|| tagname.equalsIgnoreCase("DESCR_ROTA")
|| tagname.equalsIgnoreCase("ID_PROGRAMACAO")|| tagname.equalsIgnoreCase("GRUPO")|| tagname.equalsIgnoreCase("OBSERVACAO")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("ARBPL")|| tagname.equalsIgnoreCase("ITEM_INSPEC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFCKG")|| tagname.equalsIgnoreCase("NRO_BOMBADAS")|| tagname.equalsIgnoreCase("LIMITE_INF")
|| tagname.equalsIgnoreCase("LIMITE_SUP")|| tagname.equalsIgnoreCase("IDATE_ITIME")|| tagname.equalsIgnoreCase("VLR_MED")
|| tagname.equalsIgnoreCase("COD_VALOR")|| tagname.equalsIgnoreCase("TEXTO_OBS")|| tagname.equalsIgnoreCase("MATRIC")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("STATUS_PROC")|| tagname.equalsIgnoreCase("MENSAGEM")
|| tagname.equalsIgnoreCase("COL_NUMERIC")){
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("DATA")) {
programacaoGetterSetter.setData(text);
} else if(tagname.equalsIgnoreCase("ROTA")){
programacaoGetterSetter.setRota(text);
} else if (tagname.equalsIgnoreCase("IWERK")) {
programacaoGetterSetter.setIwerk(text);
} else if (tagname.equalsIgnoreCase("AUFNR")) {
programacaoGetterSetter.setAufnr(text);
} else if (tagname.equalsIgnoreCase("VORNR")) {
programacaoGetterSetter.setVornr(text);
} else if (tagname.equalsIgnoreCase("POINT")) {
programacaoGetterSetter.setPoint(text);
} else if (tagname.equalsIgnoreCase("SEQUENCIA")) {
programacaoGetterSetter.setSequencia(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("STATUS_PONTO")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("FREQUENCIA")) {
programacaoGetterSetter.setFrequencia(text);
} else if (tagname.equalsIgnoreCase("PSORT")) {
programacaoGetterSetter.setPsort(text);
} else if (tagname.equalsIgnoreCase("PTTXT")) {
programacaoGetterSetter.setPttxt(text);
} else if (tagname.equalsIgnoreCase("EQUNR")) {
programacaoGetterSetter.setEqunr(text);
} else if (tagname.equalsIgnoreCase("EQKTX")) {
programacaoGetterSetter.setEqktx(text);
} else if (tagname.equalsIgnoreCase("TPLNR")) {
programacaoGetterSetter.setTplnr(text);
} else if (tagname.equalsIgnoreCase("PLTXT")) {
programacaoGetterSetter.setPltxt(text);
} else if (tagname.equalsIgnoreCase("SIST_LUBRIFIC")) {
programacaoGetterSetter.setSist_lubrific(text);
} else if (tagname.equalsIgnoreCase("REF_LUBRIFIC")) {
programacaoGetterSetter.setRef_lubrific(text);
} else if (tagname.equalsIgnoreCase("COD_LUBRIFIC")) {
programacaoGetterSetter.setCod_lubrific(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFICCL")) {
programacaoGetterSetter.setVol_lubrificcl(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("QTD_CONSUMO")) {
programacaoGetterSetter.setQtd_consumo(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("DESCR_ROTA")) {
programacaoGetterSetter.setDescr_rota(text);
} else if (tagname.equalsIgnoreCase("ID_PROGRAMACAO")) {
programacaoGetterSetter.setId_programacao(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("GRUPO")) {
programacaoGetterSetter.setGrupo(text);
} else if (tagname.equalsIgnoreCase("OBSERVACAO")) {
programacaoGetterSetter.setObservacao(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("ARBPL")) {
programacaoGetterSetter.setArbpl(text);
} else if (tagname.equalsIgnoreCase("ITEM_INSPEC")) {
programacaoGetterSetter.setItem_inspec(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFCKG")) {
programacaoGetterSetter.setVol_lubrifickg(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("NRO_BOMBADAS")) {
programacaoGetterSetter.setNro_bombadas(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_INF")) {
programacaoGetterSetter.setLimite_inf(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_SUP")) {
programacaoGetterSetter.setlimite_sup(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("IDATE_ITIME")) {
programacaoGetterSetter.setIdate_itime(text);
} else if (tagname.equalsIgnoreCase("VLR_MED")) {
programacaoGetterSetter.setVlr_med(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("COD_VALOR")) {
programacaoGetterSetter.setCod_valor(text);
} else if (tagname.equalsIgnoreCase("TEXTO_OBS")) {
programacaoGetterSetter.setTexto_obs(text);
} else if (tagname.equalsIgnoreCase("MATRIC")) {
programacaoGetterSetter.setMatric(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("STATUS_PROC")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("MENSAGEM")) {
programacaoGetterSetter.setMensagem(text);
} else if (tagname.equalsIgnoreCase("COL_NUMERIC")) {
programacaoGetterSetter.setCol_numeric(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("Table")){
if (programacaoGetterSetter != null && inserir != null){
inserir.open(); // HERE IS THE ERROR; database_prog is null
inserir.inserirDados(programacaoGetterSetter);
}
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*database
public class BDProgramacaoBancoDao {
private SQLiteDatabase database_prog;
public void open () throws SQLDataException{
database_prog = sqliteOpenHelper_prog.getWritableDatabase();
}
private BDProgramacaoCustomSQLiteOpenHelper sqliteOpenHelper_prog;
public BDProgramacaoBancoDao(Context context) {
sqliteOpenHelper_prog = new BDProgramacaoCustomSQLiteOpenHelper(context);
}
public String insertDados(BDProgramacaoGetterSetter dadosProg) {
ContentValues valores = new ContentValues();
long resultado;
//valores.put(sqliteOpenHelper_prog.COLUMN_ID,dadosProg.getId()); ID eh auto increment
valores.put(sqliteOpenHelper_prog.COLUMN_ARBPL, dadosProg.getArbpl());
valores.put(sqliteOpenHelper_prog.COLUMN_ATIVI, dadosProg.getAtivi());
valores.put(sqliteOpenHelper_prog.COLUMN_AUFNR, dadosProg.getAufnr());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_LUBRIFIC, dadosProg.getCod_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_VALOR, dadosProg.getCod_valor());
valores.put(sqliteOpenHelper_prog.COLUMN_DATA, dadosProg.getData()); // no banco esta como integer
valores.put(sqliteOpenHelper_prog.COLUMN_COL_NUMERIC, dadosProg.getCol_numeric());
valores.put(sqliteOpenHelper_prog.COLUMN_DESCR_ROTA, dadosProg.getDescr_rota());
valores.put(sqliteOpenHelper_prog.COLUMN_EQKTX, dadosProg.getEqktx());
valores.put(sqliteOpenHelper_prog.COLUMN_EQUNR, dadosProg.getEqunr());
valores.put(sqliteOpenHelper_prog.COLUMN_FREQUENCIA, dadosProg.getFrequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_GRUPO, dadosProg.getGrupo());
valores.put(sqliteOpenHelper_prog.COLUMN_IDATE_ITIME, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_ITEM_INSPEC, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_IWERK, dadosProg.getIwerk());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_SUP, dadosProg.getlimite_sup());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_INF, dadosProg.getLimite_inf());
valores.put(sqliteOpenHelper_prog.COLUMN_MATRIC, dadosProg.getMatric());
valores.put(sqliteOpenHelper_prog.COLUMN_MENSAGEM, dadosProg.getMensagem());
valores.put(sqliteOpenHelper_prog.COLUMN_NRO_BOMBADAS, dadosProg.getNro_bombadas());
valores.put(sqliteOpenHelper_prog.COLUMN_OBSERVACAO, dadosProg.getObservacao());
valores.put(sqliteOpenHelper_prog.COLUMN_PLTXT, dadosProg.getPltxt());
valores.put(sqliteOpenHelper_prog.COLUMN_POINT, dadosProg.getPoint());
valores.put(sqliteOpenHelper_prog.COLUMN_PSORT, dadosProg.getPsort());
valores.put(sqliteOpenHelper_prog.COLUMN_PTTXT, dadosProg.getPttxt());
valores.put(sqliteOpenHelper_prog.COLUMN_QTD_CONSUMO, dadosProg.getQtd_consumo());
valores.put(sqliteOpenHelper_prog.COLUMN_TEXTO_OBS, dadosProg.getTexto_obs());
valores.put(sqliteOpenHelper_prog.COLUMN_TPLNR, dadosProg.getTplnr());
valores.put(sqliteOpenHelper_prog.COLUMN_VLR_MED, dadosProg.getVlr_med());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCCL, dadosProg.getVol_lubrificcl());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCKG, dadosProg.getVol_lubrifickg());
valores.put(sqliteOpenHelper_prog.COLUMN_VORNR, dadosProg.getVornr());
valores.put(sqliteOpenHelper_prog.COLUMN_REF_LUBRIFIC, dadosProg.getRef_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_ROTA, dadosProg.getRota());
valores.put(sqliteOpenHelper_prog.COLUMN_SEQUENCIA, dadosProg.getSequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_SIST_LUBRIFIC, dadosProg.getSist_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PONTO, dadosProg.getStatus_ponto());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PROC, dadosProg.getStatus_proc());
valores.put(sqliteOpenHelper_prog.COLUMN_ID_PROGRAMACAO, dadosProg.getId_programacao());
resultado = database_prog.insert(BDProgramacaoCustomSQLiteOpenHelper.TABLE_PROGRAMACAO, null, valores);
database_prog.close();
if (resultado ==-1) return "Erro ao inserir registro";
else return "Registro Inserido com sucesso";
}
}
For some reason, the database_prog is null
*WSParserSetValoresBD in activity Opcoes_BaixarRotas (button "Yes" do AlertDialog):
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// nova query para o novo WS com as variaveis
final Runnable gravandoDados = new Runnable() {
public void run() {
getTodosDados(rota, atividade, responsavel, dataSelecionada);
if (WSResultadoTodosDados != null) {
InputStream isTodosDados = new ByteArrayInputStream(WSResultadoTodosDados.getBytes());
// call class
WSParserSetValoresBD parserTodosDados = new WSParserSetValoresBD(Opcoes_BaixarRotas.this.getApplicationContext());
parserTodosDados.parse(isTodosDados);
}
};
Thread queryTodosDados = new Thread(gravandoDados);
queryTodosDados.start();
}
Member variables are initialized before the constructor is invoked. Move the new BDProgramacaoBancoDao(ctx) initialization to your constructor where ctx is non-null.
I'm currently doing a port from Apache OJB to Hibernate. The application I'm working with requires me to build the Hibernate class mappings at runtime. To accomplish this I'm using our proprietary metadata, and mapping the fields of each Model class to the new Hibernate classes, as we did successfully with Apache OJB. Below I will include the relevant classes. After mapping the classes I'm getting a check column duplication error from hibernate: It's a null pointer, which leads me to believe that the columns aren't mapping well.
The error is thrown when the call to buildSessionFactory is initiated.
Thank you for any thoughts!
The Error:
java.lang.NullPointerException at
org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:723)
The Classes:
public class HibernateMetadataConverter implements MetadataConverter
{
public static Configuration cfg =
HibernateConfigurator.getInstance()
.setProperty("default_entity_mode", "dynamic- map");
public int count = 0;
Mappings mappings = cfg.createMappings();
public void convert(Table table, Map<Class<?>, Table> tables)
{
// First setup the table
org.hibernate.mapping.Table hibTable =
mappings.addTable("montecarlo", null, table.getObjectType().getName(),
null, false);
hibTable.setName(table.getObjectType().getName());
hibTable.setSchema("montecarlo");
mappings.addTableBinding(hibTable.getSchema(), null,
hibTable.getName(), hibTable.getName(), null);
Property property;
SimpleValue value;
// Create PersistentClass with rootClass, sub of PersistentClass
RootClass clazz = new RootClass();
clazz.setEntityName(hibTable.getName());
clazz.setJpaEntityName(table.getObjectType().getName());
clazz.setLazy(true);
clazz.setTable(hibTable);
clazz.setNodeName(hibTable.getName());
//Iterate metadata columns and create hibernate objects
for (Column f : table.getColumns())
{
// System.out.println("ojb table name is " + table.getName() + "\n");
/* String tableFields = table.toString();
if (tableFields.contains("stored")) {
System.out.println("skipping table stored in other table");
}
else
{
*/
if (table.getObjectType().getName().equals("gov.lanl.ldrd.montecarlo.model.Worker")
&& count == 0) {
System.out.println(table.toString());
count = 1;
}
org.hibernate.mapping.Column col =
new org.hibernate.mapping.Column();
col.setName(f.getColumnName());
org.hibernate.mapping.Column typeCol = processColumn(col, f);
col.setSqlType(typeCol.getSqlType());
col.setSqlTypeCode(typeCol.getSqlTypeCode());
value = new SimpleValue(mappings, hibTable);
Class<?> javaType;
if (col.getSqlTypeCode() != null)
{
javaType = setDefaultJavaType(col.getSqlTypeCode());
}
else
{
System.out.println("sqlCodeType is null!");
javaType = null;
}
String typeName;
if (javaType != null)
{
typeName = setHibernateType(javaType, col.getSqlTypeCode());
}
else
{
col.setNullable(true);
System.out.println( " Column is " + col.getName());
typeName = null;
}
value.setTypeName(typeName);
value.setTable(hibTable);
value.addColumn(col);
if (f.isPrimaryKey())
{
PrimaryKey pk = new PrimaryKey();
pk.setName(f.getColumnName());
pk.setTable(hibTable);
pk.addColumn(col);
hibTable.setIdentifierValue(value);
hibTable.setPrimaryKey(pk);
}
property = new Property();
property.setName(col.getName());
property.setValue(value);
property.setPersistentClass(clazz);
property.setNodeName(table.getObjectType().getName());
clazz.addProperty(property);
mappings.addColumnBinding(property.getName(),
col, hibTable);
}
System.out.println("PersistentClass is " +
clazz.getEntityName());
mappings.addClass(clazz);
mappings.addImport(clazz.getEntityName(),
clazz.getEntityName());
cfg.addAnnotatedClass(clazz.getClass());
cfg.buildMapping();
}
public org.hibernate.mapping.Column processColumn
(org.hibernate.mapping.Column col,
Column ojbColumn) {
if (ojbColumn.getJDBCType().equals("VARCHAR"))
{
col.setSqlType(ojbColumn.getJDBCType());
col.setSqlTypeCode(Types.VARCHAR);
}
else if (ojbColumn.getJDBCType().equals("BIGINT"))
{
col.setSqlType(ojbColumn.getJDBCType());
col.setSqlTypeCode(Types.BIGINT);
}
else if (ojbColumn.getJDBCType().equals("INTEGER"))
{
col.setSqlType(ojbColumn.getJDBCType());
col.setSqlTypeCode(Types.INTEGER);
}
else if (ojbColumn.getJDBCType().equals("DOUBLE"))
{
col.setSqlType(ojbColumn.getJDBCType());
col.setSqlTypeCode(Types.DOUBLE);
}
else if (ojbColumn.getJDBCType().equals("BIT"))
{
col.setSqlType(ojbColumn.getJDBCType());
col.setSqlTypeCode(Types.BOOLEAN);
}
return col;
}
public static Class<?> setDefaultJavaType(int jdbcType) {
switch (jdbcType) {
case Types.BIGINT:
return Long.class;
case Types.BIT:
return Boolean.class;
case Types.BOOLEAN:
return Boolean.class;
case Types.CHAR:
return String.class;
case Types.VARCHAR:
return String.class;
case Types.DATE:
return Date.class;
case Types.TIME:
return Time.class;
case Types.TIMESTAMP:
return Timestamp.class;
case Types.DECIMAL:
return BigDecimal.class;
case Types.NUMERIC:
return BigDecimal.class;
case Types.DOUBLE:
return Double.class;
case Types.REAL:
return Double.class;
case Types.FLOAT:
return Float.class;
case Types.INTEGER:
return Integer.class;
case Types.SMALLINT:
return Short.class;
case Types.TINYINT:
return Byte.class;
case Types.BINARY:
return byte[].class;
case Types.BLOB:
return java.sql.Blob.class;
case Types.CLOB:
return java.sql.Blob.class;
case Types.LONGVARBINARY:
return byte[].class;
case Types.LONGVARCHAR:
return java.lang.String.class;
case Types.VARBINARY:
return byte[].class;
case Types.ARRAY:
return java.sql.Array.class;
case Types.DATALINK:
return java.net.URL.class;
case Types.DISTINCT:
case Types.JAVA_OBJECT:
return String.class;
case Types.NULL:
case Types.OTHER:
case Types.REF:
return java.sql.Ref.class;
case Types.STRUCT:
return java.sql.Struct.class;
default:
System.out.println("Unsupported jdbc
type: {} " + jdbcType);
return null;
}
}
public static String setHibernateType(Class<?> javaType, int
sqlTypeCode) {
String typeName;
int jdbcTypeCode;
jdbcTypeCode = sqlTypeCode;
if (javaType == null) {
typeName = "TypeName Error";
return typeName;
}
if (javaType == Long.class) {
return typeName = LongType.INSTANCE.getName();
} else if (javaType == Short.class) {
return typeName = ShortType.INSTANCE.getName();
} else if (javaType == Integer.class) {
return typeName =
IntegerType.INSTANCE.getName();
} else if (javaType == Byte.class) {
return typeName = ByteType.INSTANCE.getName();
} else if (javaType == Float.class) {
return typeName = FloatType.INSTANCE.getName();
} else if (javaType == Double.class) {
return typeName = DoubleType.INSTANCE.getName();
} else if (javaType == Character.class) {
return typeName =
CharacterType.INSTANCE.getName();
} else if (javaType == String.class) {
return typeName = StringType.INSTANCE.getName();
} else if
(java.util.Date.class.isAssignableFrom(javaType)) {
switch (jdbcTypeCode) {
case Types.DATE:
typeName = DateType.INSTANCE.getName();
break;
case Types.TIME:
typeName = TimeType.INSTANCE.getName();
break;
case Types.TIMESTAMP:
typeName =
TimestampType.INSTANCE.getName();
break;
default:
typeName = null;
}
return typeName;
} else if (javaType == Boolean.class) {
if (jdbcTypeCode == Types.BIT || jdbcTypeCode ==
Types.BOOLEAN) {
return typeName =
BooleanType.INSTANCE.getName();
} else if (jdbcTypeCode == Types.NUMERIC ||
jdbcTypeCode == Types.DECIMAL) {
return typeName =
NumericBooleanType.INSTANCE.getName();
} else if (jdbcTypeCode == Types.CHAR ||
jdbcTypeCode == Types.VARCHAR) {
return typeName =
StringType.INSTANCE.getName();
} else {
return typeName = null;
}
} else if (javaType == BigDecimal.class) {
return typeName =
BigDecimalType.INSTANCE.getName();
} else if (javaType == BigInteger.class) {
return typeName =
BigIntegerType.INSTANCE.getName();
} else if (javaType == byte[].class) {
return typeName = BlobType.INSTANCE.getName();
}
return typeName = null;
}
}
--------------------------------------------
public class HibernateConfigurator {
private static Configuration hibConfig;
protected HibernateConfigurator() {}
public static Configuration getInstance()
{
if (hibConfig == null)
{
hibConfig = new Configuration();
hibConfig.configure();
}
return hibConfig;
}
}
--------------------------------------------
public class SessionFactoryUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory configureSessionFactory()
throws HibernateException
{
try
{
Configuration configuration =
HibernateConfigurator.getInstance();
configuration.configure();
//configuration.buildMappings();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
//new Exception().printStackTrace();
sessionFactory =
configuration.buildSessionFactory(serviceRegistry);
} catch (HibernateException e){ e.printStackTrace();}
return sessionFactory;
}
public static SessionFactory getInstance()
{
return configureSessionFactory();
}
public static void close()
{
if (sessionFactory != null) {
sessionFactory.close();
}
}
}
I've figured out why i'm getting this checkColumnDuplication Error:
In my code we can see that while I was indeed setting an identifier value for the class, I was also setting that identifier value as a property. This in effect was mapping the same column twice. A column can be mapped to a property or an identifier value(primaryKey), it can't be both.
private Object artikanID(String string) {
try {
DAOTerjemah dao = new DAOTerjemah(ConnectionDB.getConnection()) {};
List<Kata> terjemahan1 = new ArrayList<Kata>();
List<Kata> terjemahan2 = new ArrayList<Kata>();
List<Kata> terjemahan3 = new ArrayList<Kata>();
terjemahan1 = dao.getByIndo(string);
terjemahan2 = dao.getByIndo(string.substring(0,string.length()-1));
terjemahan3 = dao.getByIndo(string.substring(0,string.length()-2));
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else {
return terjemahan2.get(0).getDayak();
}
}catch(Exception e){
return string ;
}
}
there are 3 conditions(terjemahan1,terjemahan2 & terjemahan 3),
how to create the conditions to be executed terjemahan3 ?
With an else, but I'm not entirely sure I understand your logic.
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 == null) {
return terjemahan2.get(0).getDayak();
}
else {
return terjemahan3.get(0).getDayak();
}
I think you probably want the opposite though, so you only call this on variables that are not null. In this case you have to decide which one you want to call in preference if they are all not null. Also you have to decide what to do if all of them are null.
if (terjemahan1 != null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 != null) {
return terjemahan2.get(0).getDayak();
}
else if (terjemahan3 != null) {
return terjemahan3.get(0).getDayak();
}
else
{
// decide what to do in this condition
}
Hello
I am not able to get the correct validation.I think there is some error in this code so can anyone please help me solving this problem.
public static boolean validateFee(String value) {
boolean isvalid = true;
try {
int fee = 0;
if (value != null && !value.isEmpty()) {
fee = Integer.parseInt(value);
}
} catch (NumberFormatException ne) {
// ne.printStackTrace();
isvalid = false;
return isvalid;
}
return isvalid;
}
}
I am actaully using this code for validation of fee in which i m using a regex as [0-9]+.
This code i m using it in a common function.Actually validation call is done in the servlet as follows:
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
Boolean isvalid = true;
HashMap hashMap = new LinkedHashMap();
number = ApplicationConstants.FEE_PATTERN;
if (!Validation.validateFee(number)) {
isvalid = false;
hashMap.put("time", props.getText("error.fee.invalid.type"));
}
session.setAttribute("errorMessage", hashMap);
System.out.println("Map size " + hashMap.size());
logger.info("Exit validateTIme"); return isvalid;
}
I think there is no error in that but i have a doubt in this function.I am facing a problem like if i give number to the fee also its taking validation.please help me out
Currently it allows value of null or "" to count as being valid - is that deliberate?
Note that your current code can be rewritten more simply:
public static boolean validateFee(String value) {
try {
if (value != null && !value.isEmpty()) {
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException ne) {
return false;
}
}
Now if you want null/empty to count as invalid, I'd rewrite it as:
public static boolean validateFee(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException ne) {
return false;
}
}
trim your string and then pass it to.
StringUtils.isNumeric(StringUtils.trimToNull(fees));
You can directly use StringUtils.isNumeric()
I recommend you use commons-lang StringUtils class, your validate method is re-written
public static boolean validateFee(String value) {
return StringUtils.isNumeric(StringUtils.trimToNull(value));
}
And you remove ApplicationConstants.FEE_PATTERN completely. The problem you are currently facing is that your servlet overwrites its input value with ApplicationConstants.FEE_PATTERN. Your servlet method is re-written
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
final Boolean valid = Validation.validateFee(number);
if (!valid) {
final HashMap hashMap = new LinkedHashMap();
hashMap.put("time", props.getText("error.fee.invalid.type"));
session.setAttribute("errorMessage", hashMap);
}
}