简体   繁体   中英

UDF for conditional generation of filename

I want to pass the filename dynamically based on the condition. I have written the below code but the filename is not getting passed . I think there might be some issue in the if condition.

DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System","FileName");

//get current timestamp and reformat
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

//define filename
String filename = new String("");
if (orgid == "G"||"ZG"||"S")
{
filename = "N_" + df.format(date) + ".txt"  ;
}
if (orgid == "L")
{
filename = "D_" + df.format(date) + ".txt"  ;
}

if (orgid == "F"||"IV")
{
filename = "F_" + df.format(date) + ".txt"  ;
}


conf.put(key, filename);

return filename;

Please let me know where I am getting wrong.

Several things:

Don't use == to compare strings for equality. Use the equals() method instead. The == checks if both objects point to the same memory location whereas the String#equals() method evaluates to the comparison of values in the objects.

Don't initialize your String variables in this fashion: String filename = new String(""); . This is a String Constructor Invocation. What you should be doing is: String filename = ""; .

You can't check to see if a particular variable contains one of multiple possibilities in this fashion:

if (orgid == "G" || "ZG" || "S") {

As mentioned earlier you need to use the String#equals() method and to compare against other possibilities you need to compare each string to the variable, for example:

if (orgid.equals("G") || orgid.equals("ZG") || orgid.equals("S")) {

It's better to use switch statement instead for something like this, for example:

/* Using the String#toUpperCase() method ensures that 
   we don't need to worry about what letter case happens
   to be in orgid.    */
switch (orgid.toUpperCase()) {
    case "G":
    case "ZG":
    case "S":
        filename = "N_" + df.format(date) + ".txt";
        break;
    case "L":
        filename = "D_" + df.format(date) + ".txt";
        break;
    case "F":
    case "IV":
        filename = "F_" + df.format(date) + ".txt";
        break;
    default:
        System.err.println("Can Not Establish A Proper File Name (missing prefix)!");
        return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM