Java Code Examples for org.pentaho.di.core.row.ValueMetaInterface#getString()

The following examples show how to use org.pentaho.di.core.row.ValueMetaInterface#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RowForumulaContext.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static Object getPrimitive( ValueMetaInterface valueMeta, Object valueData ) throws KettleValueException {
  switch ( valueMeta.getType() ) {
    case ValueMetaInterface.TYPE_BIGNUMBER:
      return valueMeta.getBigNumber( valueData );
    case ValueMetaInterface.TYPE_BINARY:
      return valueMeta.getBinary( valueData );
    case ValueMetaInterface.TYPE_BOOLEAN:
      return valueMeta.getBoolean( valueData );
    case ValueMetaInterface.TYPE_DATE:
      return valueMeta.getDate( valueData );
    case ValueMetaInterface.TYPE_INTEGER:
      return valueMeta.getInteger( valueData );
    case ValueMetaInterface.TYPE_NUMBER:
      return valueMeta.getNumber( valueData );
      // case ValueMetaInterface.TYPE_SERIALIZABLE: return valueMeta.(valueData);
    case ValueMetaInterface.TYPE_STRING:
      return valueMeta.getString( valueData );
    default:
      return null;
  }
}
 
Example 2
Source File: EnterStringsDialog.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Copy information from the meta-data input to the dialog fields.
 */
public void getData() {
  if ( strings != null ) {
    for ( int i = 0; i < strings.getRowMeta().size(); i++ ) {
      ValueMetaInterface valueMeta = strings.getRowMeta().getValueMeta( i );
      Object valueData = strings.getData()[i];
      String string;
      try {
        string = valueMeta.getString( valueData );
      } catch ( KettleValueException e ) {
        string = "";
        // TODO: can this ever be a meaningful exception? We're editing strings almost by definition
      }
      TableItem item = wFields.table.getItem( i );
      item.setText( 1, valueMeta.getName() );
      if ( !Utils.isEmpty( string ) ) {
        item.setText( 2, string );
      }
    }
  }
  wFields.sortTable( 1 );
  wFields.setRowNums();
  wFields.optWidth( true );
}
 
Example 3
Source File: ValueMetaBase.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified data to the data type specified in this object.
 *
 * @param meta2
 *          the metadata of the object to be converted
 * @param data2
 *          the data of the object to be converted
 * @return the object in the data type of this value metadata object
 * @throws KettleValueException
 *           in case there is a data conversion error
 */
@Override
public Object convertData( ValueMetaInterface meta2, Object data2 ) throws KettleValueException {
  switch ( getType() ) {
    case TYPE_NONE:
    case TYPE_STRING:
      return meta2.getString( data2 );
    case TYPE_NUMBER:
      return meta2.getNumber( data2 );
    case TYPE_INTEGER:
      return meta2.getInteger( data2 );
    case TYPE_DATE:
      return meta2.getDate( data2 );
    case TYPE_BIGNUMBER:
      return meta2.getBigNumber( data2 );
    case TYPE_BOOLEAN:
      return meta2.getBoolean( data2 );
    case TYPE_BINARY:
      return meta2.getBinary( data2 );
    default:
      throw new KettleValueException( toString() + " : I can't convert the specified value to data type : "
          + getType() );
  }
}
 
Example 4
Source File: TableAgileMart.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
protected Object[] writeToTable( RowMetaInterface rowMeta, Object[] r ) throws KettleException {
  // see if we need to truncate any string fields
  try {
    int index = 0;
    List<ValueMetaInterface> valueMetas = rowMeta.getValueMetaList();
    for ( ValueMetaInterface valueMeta : valueMetas ) {
      Object valueData = r[index];
      if ( valueData != null ) {
        if ( valueMeta.getType() == ValueMetaInterface.TYPE_STRING ) {
          String str = valueMeta.getString( valueData );
          int len = valueMeta.getLength();
          if ( len < 1 ) {
            len = MonetDBDatabaseMeta.DEFAULT_VARCHAR_LENGTH;
          }
          if ( str.length() > len ) {
            // TODO log this event
            str = str.substring( 0, len );
          }
          r[index] = str;
        }
      }
      index++;
    }
  } catch ( Exception e ) {
    throw new KettleException( "Error serializing rows of data to the psql command", e );
  }
  return super.writeToTable( rowMeta, r );
}
 
Example 5
Source File: TextFileOutput.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private byte[] formatField( ValueMetaInterface v, Object valueData ) throws KettleValueException {
  if ( v.isString() ) {
    if ( v.isStorageBinaryString() && v.getTrimType() == ValueMetaInterface.TRIM_TYPE_NONE && v.getLength() < 0
        && Utils.isEmpty( v.getStringEncoding() ) ) {
      return (byte[]) valueData;
    } else {
      String svalue = ( valueData instanceof String ) ? (String) valueData : v.getString( valueData );
      return convertStringToBinaryString( v, Const.trimToType( svalue, v.getTrimType() ) );
    }
  } else {
    return v.getBinaryString( valueData );
  }
}
 
Example 6
Source File: SelectRowDialog.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Copy information from the input buffer to the dialog fields.
 */
private void getData() {
  for ( int i = 0; i < buffer.size(); i++ ) {
    RowMetaAndData rowMetaAndData = buffer.get( i );
    RowMetaInterface rowMeta = rowMetaAndData.getRowMeta();
    Object[] rowData = rowMetaAndData.getData();

    for ( int c = 0; c < rowMeta.size(); c++ ) {
      ValueMetaInterface v = rowMeta.getValueMeta( c );
      String show;

      try {
        if ( v.isNumeric() ) {
          show = v.getString( rowData[c] );
        } else {
          show = v.getString( rowData[c] );
        }
      } catch ( KettleValueException e ) {
        show = "<conversion error>";
      }
      if ( show != null ) {
        wFields.table.getItem( i ).setText( c + 1, show );
      }
    }
  }
  wFields.optWidth( true );
}
 
Example 7
Source File: XMLOutput.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void writeField( ValueMetaInterface valueMeta, Object valueData, String element ) throws KettleStepException {
  try {
    String value = valueMeta.getString( valueData );
    if ( value != null ) {
      data.writer.writeStartElement( element );
      data.writer.writeCharacters( value );
      data.writer.writeEndElement();
    } else {
      data.writer.writeEmptyElement( element );
    }
  } catch ( Exception e ) {
    throw new KettleStepException( "Error writing line :", e );
  }
}
 
Example 8
Source File: ServerUtils.java    From pentaho-cpython-plugin with Apache License 2.0 4 votes vote down vote up
protected static List<Object> rowsToCSVNew( RowMetaInterface meta, List<Object[]> rows ) throws KettleException {
  List<Object> results = new ArrayList<>( 2 );
  boolean needsBase64;
  CharsetEncoder encoder = Charset.forName( "US-ASCII" ).newEncoder();
  Charset utf8 = Charset.forName( "UTF-8" );

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  BufferedOutputStream buf = new BufferedOutputStream( bos );

  // header row
  StringBuilder builder = new StringBuilder();
  int i = 0;
  for ( ValueMetaInterface v : meta.getValueMetaList() ) {
    String name = quote( v.getName() );
    builder.append( i > 0 ? "," : "" ).append( name );
    i++;
  }
  builder.append( "\n" );

  // We look for non-ascii characters and, if found, encode to ascii base64 first. For some reason,
  // encoding directly to utf-8 on the Java side (Mac OS X; Java 8) causes the python utf-8 decoder to hang
  // when there are non-ascii characters (such as in Mayagüez) present. Encoding to base64 first, then decoding
  // this on the python side seems to fix the issue.
  needsBase64 = !encoder.canEncode( builder.toString() );
  try {
    buf.write( builder.toString().getBytes( utf8 ) );

    for ( Object[] row : rows ) {
      builder.setLength( 0 );
      for ( i = 0; i < meta.size(); i++ ) {
        String value;
        ValueMetaInterface vm = meta.getValueMeta( i );
        if ( row[i] == null || Const.isEmpty( vm.getString( row[i] ) ) ) {
          value = "?";
        } else {
          //switch ( meta.getValueMetaList().get( i ).getType() ) {
          switch ( vm.getType() ) {
            case ValueMetaInterface.TYPE_NUMBER:
            case ValueMetaInterface.TYPE_INTEGER:
            case ValueMetaInterface.TYPE_BIGNUMBER:
              value = vm.getString( row[i] );
              break;
            case ValueMetaInterface.TYPE_DATE:
              int offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
              value = "" + ( vm.getDate( row[i] ).getTime() + offset );
              break;
            case ValueMetaInterface.TYPE_TIMESTAMP:
              offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
              value = "" + ( vm.getDate( row[i] ).getTime() + offset );
              break;
            case ValueMetaInterface.TYPE_BOOLEAN:
              value = "" + ( vm.getBoolean( row[i] ) ? "1" : "0" );
              break;
            // TODO throw an exception for Serializable/Binary
            default:
              value = quote( vm.getString( row[i] ) );
          }
        }
        builder.append( i > 0 ? "," : "" ).append( value );
      }
      builder.append( "\n" );

      if ( !needsBase64 ) {
        needsBase64 = !encoder.canEncode( builder.toString() );
      }
      buf.write( builder.toString().getBytes( utf8 ) );
    }

    buf.flush();
    buf.close();
  } catch ( IOException e ) {
    throw new KettleException( e );
  }

  byte[] bytes = bos.toByteArray();
  if ( needsBase64 ) {
    bytes = Base64.encodeBase64( bytes );
  }
  results.add( bytes );
  results.add( needsBase64 );

  return results;
}
 
Example 9
Source File: ServerUtils.java    From pentaho-cpython-plugin with Apache License 2.0 4 votes vote down vote up
protected static StringBuilder rowsToCSV( RowMetaInterface meta, List<Object[]> rows ) throws KettleValueException {
  StringBuilder builder = new StringBuilder();
  // header row
  int i = 0;
  for ( ValueMetaInterface v : meta.getValueMetaList() ) {
    String name = quote( v.getName() );
    builder.append( i > 0 ? "," : "" ).append( name );
    i++;
  }
  builder.append( "\n" );
  for ( Object[] row : rows ) {
    for ( i = 0; i < meta.size(); i++ ) {
      String value;
      ValueMetaInterface vm = meta.getValueMeta( i );
      if ( row[i] == null || Const.isEmpty( vm.getString( row[i] ) ) ) {
        value = "?";
      } else {
        //switch ( meta.getValueMetaList().get( i ).getType() ) {
        switch ( vm.getType() ) {
          case ValueMetaInterface.TYPE_NUMBER:
          case ValueMetaInterface.TYPE_INTEGER:
          case ValueMetaInterface.TYPE_BIGNUMBER:
            value = vm.getString( row[i] );
            break;
          case ValueMetaInterface.TYPE_DATE:
            int offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
            value = "" + ( vm.getDate( row[i] ).getTime() + offset );
            break;
          case ValueMetaInterface.TYPE_TIMESTAMP:
            offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
            value = "" + ( vm.getDate( row[i] ).getTime() + offset );
            break;
          case ValueMetaInterface.TYPE_BOOLEAN:
            value = "" + ( vm.getBoolean( row[i] ) ? "1" : "0" );
            break;
          // TODO throw an exception for Serializable/Binary
          default:
            value = quote( vm.getString( row[i] ) );
        }
      }
      builder.append( i > 0 ? "," : "" ).append( value );
    }
    builder.append( "\n" );
  }

  return builder;
}
 
Example 10
Source File: HBaseValueMeta.java    From pentaho-hadoop-shims with Apache License 2.0 4 votes vote down vote up
/**
 * Encode a keyValue (with associated meta data) to an array of bytes with respect to the key type specified in a
 * mapping.
 *
 * @param keyValue the key value (object) to encode
 * @param keyMeta  meta data about the key value
 * @param keyType  the target type of the encoded key value
 * @return the key encoded as an array of bytes
 * @throws KettleException if something goes wrong
 */
public static byte[] encodeKeyValue( Object keyValue,
                                     ValueMetaInterface keyMeta, Mapping.KeyType keyType,
                                     HBaseBytesUtilShim bytesUtil ) throws KettleException {

  byte[] result = null;

  switch ( keyType ) {
    case STRING:
      String stringKey = keyMeta.getString( keyValue );
      result = encodeKeyValue( stringKey, keyType, bytesUtil );
      break;
    case DATE:
    case UNSIGNED_DATE:
      Date dateKey = keyMeta.getDate( keyValue );
      if ( keyType == Mapping.KeyType.UNSIGNED_DATE && dateKey.getTime() < 0 ) {
        throw new KettleException( BaseMessages.getString( PKG,
          "HBaseValueMeta.Error.UnsignedDate" ) );
      }
      result = encodeKeyValue( dateKey, keyType, bytesUtil );
      break;
    case INTEGER:
    case UNSIGNED_INTEGER:
      int keyInt = keyMeta.getInteger( keyValue ).intValue();
      if ( keyType == Mapping.KeyType.UNSIGNED_INTEGER && keyInt < 0 ) {
        throw new KettleException( BaseMessages.getString( PKG,
          "HBaseValueMeta.Error.UnsignedIngteger" ) );
      }
      result = encodeKeyValue( new Integer( keyInt ), keyType, bytesUtil );
      break;
    case LONG:
    case UNSIGNED_LONG:
      long keyLong = keyMeta.getInteger( keyValue ).longValue();
      if ( keyType == Mapping.KeyType.UNSIGNED_LONG && keyLong < 0 ) {
        throw new KettleException( BaseMessages.getString( PKG,
          "HBaseValueMeta.Error.UnsignedLong" ) );
      }
      result = encodeKeyValue( new Long( keyLong ), keyType, bytesUtil );
      break;

    case BINARY:
      byte[] keyBinary = keyMeta.getBinary( keyValue );
      result = encodeKeyValue( keyBinary, keyType, bytesUtil );
  }

  if ( result == null ) {
    throw new KettleException( BaseMessages.getString( PKG,
      "HBaseValueMeta.Error.UnknownTableKeyType" ) );
  }

  return result;
}
 
Example 11
Source File: HBaseValueMeta.java    From pentaho-hadoop-shims with Apache License 2.0 4 votes vote down vote up
public static byte[] encodeColumnValue( Object columnValue,
                                        ValueMetaInterface colMeta, HBaseValueMeta mappingColMeta,
                                        HBaseBytesUtilShim bytesUtil ) throws KettleException {

  byte[] encoded = null;
  switch ( mappingColMeta.getType() ) {
    case TYPE_STRING:
      String toEncode = colMeta.getString( columnValue );
      encoded = bytesUtil.toBytes( toEncode );
      break;
    case TYPE_INTEGER:
      Long l = colMeta.getInteger( columnValue );
      if ( mappingColMeta.getIsLongOrDouble() ) {
        encoded = bytesUtil.toBytes( l.longValue() );
      } else {
        encoded = bytesUtil.toBytes( l.intValue() );
      }
      break;
    case TYPE_NUMBER:
      Double d = colMeta.getNumber( columnValue );
      if ( mappingColMeta.getIsLongOrDouble() ) {
        encoded = bytesUtil.toBytes( d.doubleValue() );
      } else {
        encoded = bytesUtil.toBytes( d.floatValue() );
      }
      break;
    case TYPE_DATE:
      Date date = colMeta.getDate( columnValue );
      encoded = bytesUtil.toBytes( date.getTime() );
      break;
    case TYPE_BOOLEAN:
      Boolean b = colMeta.getBoolean( columnValue );
      String boolString = ( b.booleanValue() ) ? "Y" : "N";
      encoded = bytesUtil.toBytes( boolString );
      break;
    case TYPE_BIGNUMBER:
      BigDecimal bd = colMeta.getBigNumber( columnValue );
      String bds = bd.toString();
      encoded = bytesUtil.toBytes( bds );
      break;
    case TYPE_SERIALIZABLE:
      try {
        encoded = encodeObject( columnValue );
      } catch ( IOException e ) {
        throw new KettleException( BaseMessages.getString( PKG,
          "HBaseValueMeta.Error.UnableToSerialize", colMeta.getName() ), e );
      }
      break;
    case TYPE_BINARY:
      encoded = colMeta.getBinary( columnValue );
      break;
  }

  if ( encoded == null ) {
    throw new KettleException( BaseMessages.getString( PKG,
      "HBaseValueMeta.Error.UnknownTypeForColumn" ) );
  }

  return encoded;
}
 
Example 12
Source File: KettleDatabaseRepositoryConditionDelegate.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public synchronized ObjectId insertCondition( ObjectId id_condition_parent, Condition condition ) throws KettleException {
  ObjectId id = repository.connectionDelegate.getNextConditionID();

  String tablename = KettleDatabaseRepository.TABLE_R_CONDITION;
  RowMetaAndData table = new RowMetaAndData();
  table.addValue( new ValueMetaInteger(
    KettleDatabaseRepository.FIELD_CONDITION_ID_CONDITION ), id );
  table.addValue(
    new ValueMetaInteger(
      KettleDatabaseRepository.FIELD_CONDITION_ID_CONDITION_PARENT ),
    id_condition_parent );
  table.addValue( new ValueMetaBoolean(
    KettleDatabaseRepository.FIELD_CONDITION_NEGATED ), Boolean
    .valueOf( condition.isNegated() ) );
  table.addValue( new ValueMetaString(
    KettleDatabaseRepository.FIELD_CONDITION_OPERATOR ), condition
    .getOperatorDesc() );
  table.addValue( new ValueMetaString(
    KettleDatabaseRepository.FIELD_CONDITION_LEFT_NAME ), condition
    .getLeftValuename() );
  table.addValue( new ValueMetaString(
    KettleDatabaseRepository.FIELD_CONDITION_CONDITION_FUNCTION ), condition
    .getFunctionDesc() );
  table.addValue( new ValueMetaString(
    KettleDatabaseRepository.FIELD_CONDITION_RIGHT_NAME ), condition
    .getRightValuename() );

  ObjectId id_value = null;
  ValueMetaAndData v = condition.getRightExact();

  if ( v != null ) {

    // We have to make sure that all data is saved irrespective of locale differences.
    // Here is where we force that
    //
    ValueMetaInterface valueMeta = v.getValueMeta();
    valueMeta.setDecimalSymbol( ValueMetaAndData.VALUE_REPOSITORY_DECIMAL_SYMBOL );
    valueMeta.setGroupingSymbol( ValueMetaAndData.VALUE_REPOSITORY_GROUPING_SYMBOL );
    switch ( valueMeta.getType() ) {
      case ValueMetaInterface.TYPE_NUMBER:
        valueMeta.setConversionMask( ValueMetaAndData.VALUE_REPOSITORY_NUMBER_CONVERSION_MASK );
        break;
      case ValueMetaInterface.TYPE_INTEGER:
        valueMeta.setConversionMask( ValueMetaAndData.VALUE_REPOSITORY_INTEGER_CONVERSION_MASK );
        break;
      case ValueMetaInterface.TYPE_DATE:
        valueMeta.setConversionMask( ValueMetaAndData.VALUE_REPOSITORY_DATE_CONVERSION_MASK );
        break;
      default:
        break;
    }
    String stringValue = valueMeta.getString( v.getValueData() );

    id_value =
      insertValue( valueMeta.getName(), valueMeta.getTypeDesc(), stringValue, valueMeta.isNull( v
        .getValueData() ), condition.getRightExactID() );
    condition.setRightExactID( id_value );
  }
  table.addValue( new ValueMetaInteger(
    KettleDatabaseRepository.FIELD_CONDITION_ID_VALUE_RIGHT ), id_value );

  repository.connectionDelegate.getDatabase().prepareInsert( table.getRowMeta(), tablename );
  repository.connectionDelegate.getDatabase().setValuesInsert( table );
  repository.connectionDelegate.getDatabase().insertRow();
  repository.connectionDelegate.getDatabase().closeInsert();

  return id;
}
 
Example 13
Source File: IngresVectorwiseLoader.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private void writeRowToBulk( RowMetaInterface rowMeta, Object[] r ) throws KettleException {

    try {
      // So, we have this output stream to which we can write CSV data to.
      // Basically, what we need to do is write the binary data (from strings to
      // it as part of this proof of concept)
      //
      // The data format required is essentially "value|value|value|value"
      // new feature implemented
      // "use SSV which requires the format to be '"value";"value","value"'
      byte[] delimiter;
      if ( meta.isUseSSV() ) {
        delimiter = data.semicolon;
      } else {
        delimiter = data.separator;
      }

      for ( int i = 0; i < data.keynrs.length; i++ ) {
        if ( i > 0 ) {
          // Write a separator
          //
          write( delimiter );
        }

        int index = data.keynrs[i];
        ValueMetaInterface valueMeta = rowMeta.getValueMeta( index );
        Object valueData = r[index];

        if ( valueData != null ) {
          if ( valueMeta.isStorageBinaryString() ) {
            byte[] value = valueMeta.getBinaryString( valueData );
            write( value );
          } else {
            // We're using the bulk row metadata so dates and numerics should be in the correct format now...
            //
            String string = valueMeta.getString( valueData );
            if ( string != null ) {

              if ( meta.isEscapingSpecialCharacters() && valueMeta.isString() ) {
                string = replace( string, new String[] { "\n", "\r", }, new String[] { "\\n", "\\r", } );
              }
              // support of SSV feature
              //
              if ( meta.isUseSSV() ) {

                // replace " in string fields
                //
                if ( meta.isEscapingSpecialCharacters() && valueMeta.isString() ) {
                  string = replace( string, new String[] { "\"" }, new String[] { "\\\"" } );
                  log.logRowlevel( "\' \" \' symbol was added for the future processing" );
                }
                write( data.doubleQuote );
                write( data.getBytes( string ) );
                write( data.doubleQuote );
              } else {
                write( data.getBytes( string ) );
              }
            }
          }
        }
      }

      // finally write a newline
      //
      write( data.newline );
    } catch ( Exception e ) {
      // If something went wrong with the import,
      // rather return that error, in stead of "Pipe Broken"
      try {
        data.sqlRunner.checkExcn();
      } catch ( Exception loadEx ) {
        throw new KettleException( "Error serializing rows of data to the fifo file", loadEx );
      }

      throw new KettleException( "Error serializing rows of data to the fifo file", e );
    }

  }
 
Example 14
Source File: BaseDatabaseMeta.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Override
public String getSQLValue( ValueMetaInterface valueMeta, Object valueData, String dateFormat ) throws KettleValueException {

  StringBuilder ins = new StringBuilder();

  if ( valueMeta.isNull( valueData ) ) {
    ins.append( "null" );
  } else {
    // Normal cases...
    //
    switch ( valueMeta.getType() ) {
      case ValueMetaInterface.TYPE_BOOLEAN:
      case ValueMetaInterface.TYPE_STRING:
        String string = valueMeta.getString( valueData );
        // Have the database dialect do the quoting.
        // This also adds the single quotes around the string (thanks to PostgreSQL)
        //
        string = quoteSQLString( string );
        ins.append( string );
        break;
      case ValueMetaInterface.TYPE_DATE:
        Date date = valueMeta.getDate( valueData );

        if ( Utils.isEmpty( dateFormat ) ) {
          ins.append( "'" + valueMeta.getString( valueData ) + "'" );
        } else {
          try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat( dateFormat );
            ins.append( "'" + formatter.format( date ) + "'" );
          } catch ( Exception e ) {
            throw new KettleValueException( "Error : ", e );
          }
        }
        break;
      default:
        ins.append( valueMeta.getString( valueData ) );
        break;
    }
  }

  return ins.toString();
}
 
Example 15
Source File: AccessOutputMeta.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static Object[] createObjectsForRow( RowMetaInterface rowMeta, Object[] rowData ) throws KettleValueException {
  Object[] values = new Object[rowMeta.size()];
  for ( int i = 0; i < rowMeta.size(); i++ ) {
    ValueMetaInterface valueMeta = rowMeta.getValueMeta( i );
    Object valueData = rowData[i];

    // Prevent a NullPointerException below
    if ( valueData == null || valueMeta == null ) {
      values[i] = null;
      continue;
    }

    int length = valueMeta.getLength();

    switch ( valueMeta.getType() ) {
      case ValueMetaInterface.TYPE_INTEGER:
        if ( length < 3 ) {
          values[i] = new Byte( valueMeta.getInteger( valueData ).byteValue() );
        } else {
          if ( length < 5 ) {
            values[i] = new Short( valueMeta.getInteger( valueData ).shortValue() );
          } else {
            values[i] = valueMeta.getInteger( valueData );
          }
        }
        break;
      case ValueMetaInterface.TYPE_NUMBER:
        values[i] = valueMeta.getNumber( valueData );
        break;
      case ValueMetaInterface.TYPE_DATE:
        values[i] = valueMeta.getDate( valueData );
        break;
      case ValueMetaInterface.TYPE_STRING:
        values[i] = valueMeta.getString( valueData );
        break;
      case ValueMetaInterface.TYPE_BINARY:
        values[i] = valueMeta.getBinary( valueData );
        break;
      case ValueMetaInterface.TYPE_BOOLEAN:
        values[i] = valueMeta.getBoolean( valueData );
        break;
      case ValueMetaInterface.TYPE_BIGNUMBER:
        values[i] = valueMeta.getNumber( valueData );
        break;
      default:
        break;
    }
  }
  return values;
}
 
Example 16
Source File: AddXML.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private String formatField( ValueMetaInterface valueMeta, Object valueData, XMLField field )
  throws KettleValueException {
  String retval = "";
  if ( field == null ) {
    return "";
  }

  if ( valueMeta == null || valueMeta.isNull( valueData ) ) {
    String defaultNullValue = field.getNullString();
    return Utils.isEmpty( defaultNullValue ) ? "" : defaultNullValue;
  }

  if ( valueMeta.isNumeric() ) {
    // Formatting
    if ( !Utils.isEmpty( field.getFormat() ) ) {
      data.df.applyPattern( field.getFormat() );
    } else {
      data.df.applyPattern( data.defaultDecimalFormat.toPattern() );
    }
    // Decimal
    if ( !Utils.isEmpty( field.getDecimalSymbol() ) ) {
      data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt( 0 ) );
    } else {
      data.dfs.setDecimalSeparator( data.defaultDecimalFormatSymbols.getDecimalSeparator() );
    }
    // Grouping
    if ( !Utils.isEmpty( field.getGroupingSymbol() ) ) {
      data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt( 0 ) );
    } else {
      data.dfs.setGroupingSeparator( data.defaultDecimalFormatSymbols.getGroupingSeparator() );
    }
    // Currency symbol
    if ( !Utils.isEmpty( field.getCurrencySymbol() ) ) {
      data.dfs.setCurrencySymbol( field.getCurrencySymbol() );
    } else {
      data.dfs.setCurrencySymbol( data.defaultDecimalFormatSymbols.getCurrencySymbol() );
    }

    data.df.setDecimalFormatSymbols( data.dfs );

    if ( valueMeta.isBigNumber() ) {
      retval = data.df.format( valueMeta.getBigNumber( valueData ) );
    } else if ( valueMeta.isNumber() ) {
      retval = data.df.format( valueMeta.getNumber( valueData ) );
    } else {
      // Integer
      retval = data.df.format( valueMeta.getInteger( valueData ) );
    }
  } else if ( valueMeta.isDate() ) {
    if ( field != null && !Utils.isEmpty( field.getFormat() ) && valueMeta.getDate( valueData ) != null ) {
      if ( !Utils.isEmpty( field.getFormat() ) ) {
        data.daf.applyPattern( field.getFormat() );
      } else {
        data.daf.applyPattern( data.defaultDateFormat.toLocalizedPattern() );
      }
      data.daf.setDateFormatSymbols( data.dafs );
      retval = data.daf.format( valueMeta.getDate( valueData ) );
    } else {
      if ( valueMeta.isNull( valueData ) ) {
        if ( field != null && !Utils.isEmpty( field.getNullString() ) ) {
          retval = field.getNullString();
        }
      } else {
        retval = valueMeta.getString( valueData );
      }
    }
  } else if ( valueMeta.isString() ) {
    retval = valueMeta.getString( valueData );
  } else if ( valueMeta.isBinary() ) {
    if ( valueMeta.isNull( valueData ) ) {
      if ( !Utils.isEmpty( field.getNullString() ) ) {
        retval = field.getNullString();
      } else {
        retval = Const.NULL_BINARY;
      }
    } else {
      try {
        retval = new String( valueMeta.getBinary( valueData ), "UTF-8" );
      } catch ( UnsupportedEncodingException e ) {
        // chances are small we'll get here. UTF-8 is
        // mandatory.
        retval = Const.NULL_BINARY;
      }
    }
  } else {
    // Boolean
    retval = valueMeta.getString( valueData );
  }

  return retval;
}