String to int conversion

One Star

String to int conversion

Hello,
I am trying to convert a String into an int. I am using the expression:
Integer.parseInt(Name.SECURITY_LEVEL)
What I get when I test the expression is:
Exception in component tRowGenerator_1
and
Multiple markers at this line
- Syntax error on token ")", AssignmentOperator expected after
this token
- The left-hand side of an assignment must be a variable
I don't understand. Doesn't this expression return an int?
Thanks for any help,
Jim Long
One Star

Re: String to int conversion

Hi Jim,
where did you entered that code? In a tMap?
Bye
Volker
One Star

Re: String to int conversion

Hello Volker,
Yes, this is in a tMap. Name.SECURITY_LEVEL is a number String (i.e. "1", "3", "9"). The new schema has an integer for this field. The transformation is simple, yet I am mystified by the error message I am getting.
Thanks,
Jim
One Star

Re: String to int conversion

Hello Volker,
I opened my project again and looked at the tMap. I am getting a new error message now. My expression is:
Integer.parseInt(Name.SECURITY_LEVEL)
The message I am getting is:
This method must return a result of type int.
parseInt is a public static int.
Thanks,
Jim Long
Employee

Re: String to int conversion

Hi,
I can see you have this error "Exception in component tRowGenerator_1" so the error might be even before the tMap component.
You're right, this method returns an Integer. The tmap should look like this.
One Star

Re: String to int conversion

Hello Volker,
....hmmm.
This is the transformation I have entered. I will pull the data out into a tLogRow to see what is coming out of the ODBC data source. I will let you know what I discover.
Thanks,
Jim Long
One Star

Re: String to int conversion

Hello Volker,
I pulled the data into into a tLogRow and I am getting the same result. However, even through the expression builder reports an error, the function seems to convert the String to an Integer just fine.
Let me know if you learn anything else.
Thanks,
Jim Long
One Star

Re: String to int conversion

Hi Jim,
a) you code looks correct.
b) the example of nhaumont too. So if you use it the same way it should work.
If the error still exists, please give us the following two information:
- The generated code around the error. You'll have a line number where the error occurs, switch to the code view and copy some line berore and after this line number.
- Give us a screen shot of the actual component where it happens. Search the code upwards to next comment to see the component name
Bye
Volker Brehm
Moderator

Re: String to int conversion

Hello,
as nhaumont suggested, your error is not in the tMap but in the tRowGenerator_1.
Can you post a screenshot of it.
regards,
benjamin
One Star

Re: String to int conversion

Hi benjamin, hi nhaumont,
I think the message "Exception in component tRowGenerator_1" is related to the created class in the code (not the component). So it should happen in every component and to take a look into the code is the only way to be sure.
Bye
Volker
One Star jds
One Star

Re: String to int conversion

Hello,
Was any solution to this problem ever found? I am experiencing the same problem... any advice appreciated. Based on the responses above, I am attaching an image of the tMap and the file with tRowGenerator_1 code.
Thanks,
Jeremy
EDIT: it did not let me attach the code, so pasting it in here. file Expression_builder_RowGenerator2.java:

// ============================================================================
//
// Copyright (c) 2005-2010, Talend Inc.
//
// This source code has been automatically generated by_Talend Open Studio for Data Integration
// / JobDesigner (CodeGenerator version 5.0.2.r78327)
// You can find more information about Talend products at www.talend.com.
// You may distribute this code under the terms of the GNU LGPL license
// http://www.gnu.org/licenses/lgpl.html).
//
// ============================================================================
package phonetest.expression_builder_rowgenerator2;
import routines.Mathematical;
import routines.DataOperation;
import routines.Relational;
import routines.TalendDate;
import routines.TalendDataGenerator;
import routines.Numeric;
import routines.TalendString;
import routines.StringHandling;
import routines.system.*;
import routines.system.api.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.math.BigDecimal;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Comparator;
@SuppressWarnings("unused")
/**
* Job: Expression_builder_RowGenerator2 Purpose: <br>
* Description: <br>
* @author
* @version 5.0.2.r78327
* @status
*/
public class Expression_builder_RowGenerator2 implements TalendJob {
public final Object obj = new Object();
// for transmiting parameters purpose
private Object valueObject = null;
public Object getValueObject() {
return this.valueObject;
}
public void setValueObject(Object valueObject) {
this.valueObject = valueObject;
}
private final static String defaultCharset = java.nio.charset.Charset
.defaultCharset().name();
private final static String utf8Charset = "UTF-8";
// create and load default properties
private java.util.Properties defaultProps = new java.util.Properties();
// create application properties with default
public class ContextProperties extends java.util.Properties {
private static final long serialVersionUID = 1L;
public ContextProperties(java.util.Properties properties) {
super(properties);
}
public ContextProperties() {
super();
}
public void synchronizeContext() {
}
}
private ContextProperties context = new ContextProperties();
public ContextProperties getContext() {
return this.context;
}
private final String jobVersion = "null";
private final String jobName = "Expression_builder_RowGenerator2";
private final String projectName = "PHONETEST";
public Integer errorCode = null;
private String currentComponent = "";
private final java.util.Map<String, Long> start_Hash = new java.util.HashMap<String, Long>();
private final java.util.Map<String, Long> end_Hash = new java.util.HashMap<String, Long>();
private final java.util.Map<String, Boolean> ok_Hash = new java.util.HashMap<String, Boolean>();
private final java.util.Map<String, Object> globalMap = new java.util.HashMap<String, Object>();
public final java.util.List<String[]> globalBuffer = new java.util.ArrayList<String[]>();
public boolean isExportedAsOSGI = false;
private final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
private final java.io.PrintStream errorMessagePS = new java.io.PrintStream(
new java.io.BufferedOutputStream(baos));
public String getExceptionStackTrace() {
if ("failure".equals(this.getStatus())) {
errorMessagePS.flush();
return baos.toString();
}
return null;
}
private Exception exception = null;
public Exception getException() {
if ("failure".equals(this.getStatus())) {
return this.exception;
}
return null;
}
private class TalendException extends Exception {
private static final long serialVersionUID = 1L;
private java.util.Map<String, Object> globalMap = null;
private Exception e = null;
private String currentComponent = null;
private TalendException(Exception e, String errorComponent,
final java.util.Map<String, Object> globalMap) {
this.currentComponent = errorComponent;
this.globalMap = globalMap;
this.e = e;
}
@Override
public void printStackTrace() {
if (!(e instanceof TalendException || e instanceof TDieException)) {
globalMap.put(currentComponent + "_ERROR_MESSAGE", e
.getMessage());
System.err
.println("Exception in component " + currentComponent);
}
if (!(e instanceof TDieException)) {
if (e instanceof TalendException) {
e.printStackTrace();
} else {
e.printStackTrace();
e.printStackTrace(errorMessagePS);
Expression_builder_RowGenerator2.this.exception = e;
}
}
if (!(e instanceof TalendException)) {
try {
for (java.lang.reflect.Method m : this.getClass()
.getEnclosingClass().getMethods()) {
if (m.getName().compareTo(currentComponent + "_error") == 0) {
m.invoke(Expression_builder_RowGenerator2.this,
new Object[] { e, currentComponent,
globalMap });
break;
}
}
if (!(e instanceof TDieException)) {
}
} catch (java.lang.SecurityException e) {
this.e.printStackTrace();
} catch (java.lang.IllegalArgumentException e) {
this.e.printStackTrace();
} catch (java.lang.IllegalAccessException e) {
this.e.printStackTrace();
} catch (java.lang.reflect.InvocationTargetException e) {
this.e.printStackTrace();
}
}
}
}
public void tRowGenerator_1_error(Exception exception,
String errorComponent, final java.util.Map<String, Object> globalMap)
throws TalendException {
end_Hash.put("tRowGenerator_1", System.currentTimeMillis());
tRowGenerator_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tRowGenerator_1_onSubJobError(Exception exception,
String errorComponent, final java.util.Map<String, Object> globalMap)
throws TalendException {
resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", Thread
.currentThread().getId()
+ "", "FATAL", "", exception.getMessage(), ResumeUtil
.getExceptionStackTrace(exception), "");
}
public static class RowStruct implements
routines.system.IPersistableRow<RowStruct> {
final static byte[] commonByteArrayLock = new byte;
static byte[] commonByteArray = new byte;
public String newColumn;
public String getNewColumn() {
return this.newColumn;
}
private String readString(ObjectInputStream dis) throws IOException {
String strReturn = null;
int length = 0;
length = dis.readInt();
if (length == -1) {
strReturn = null;
} else {
if (length > commonByteArray.length) {
if (length < 1024 && commonByteArray.length == 0) {
commonByteArray = new byte;
} else {
commonByteArray = new byte;
}
}
dis.readFully(commonByteArray, 0, length);
strReturn = new String(commonByteArray, 0, length, utf8Charset);
}
return strReturn;
}
private void writeString(String str, ObjectOutputStream dos)
throws IOException {
if (str == null) {
dos.writeInt(-1);
} else {
byte[] byteArray = str.getBytes(utf8Charset);
dos.writeInt(byteArray.length);
dos.write(byteArray);
}
}
public void readData(ObjectInputStream dis) {
synchronized (commonByteArrayLock) {
try {
int length = 0;
this.newColumn = readString(dis);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void writeData(ObjectOutputStream dos) {
try {
// String
writeString(this.newColumn, dos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("");
return sb.toString();
}
/**
* Compare keys
*/
public int compareTo(RowStruct other) {
int returnValue = -1;
return returnValue;
}
private int checkNullsAndCompare(Object object1, Object object2) {
int returnValue = 0;
if (object1 instanceof Comparable && object2 instanceof Comparable) {
returnValue = ((Comparable) object1).compareTo(object2);
} else if (object1 != null && object2 != null) {
returnValue = compareStrings(object1.toString(), object2
.toString());
} else if (object1 == null && object2 != null) {
returnValue = 1;
} else if (object1 != null && object2 == null) {
returnValue = -1;
} else {
returnValue = 0;
}
return returnValue;
}
private int compareStrings(String string1, String string2) {
return string1.compareTo(string2);
}
}
public void tRowGenerator_1Process(
final java.util.Map<String, Object> globalMap)
throws TalendException {
globalMap.put("tRowGenerator_1_SUBPROCESS_STATE", 0);
final boolean execStat = this.execStat;
String iterateId = "";
String currentComponent = "";
try {
String currentMethodName = new Exception().getStackTrace()
.getMethodName();
boolean resumeIt = currentMethodName.equals(resumeEntryMethodName);
if (resumeEntryMethodName == null || resumeIt || globalResumeTicket) {// start
// the
// resume
globalResumeTicket = true;
RowStruct Row = new RowStruct();
/**
* start
*/
ok_Hash.put("tLogRow", false);
start_Hash.put("tLogRow", System.currentTimeMillis());
currentComponent = "tLogRow";
int tos_count_tLogRow = 0;
// /////////////////////
final String OUTPUT_FIELD_SEPARATOR_tLogRow = "|";
java.io.PrintStream consoleOut_tLogRow = null;
StringBuilder strBuffer_tLogRow = null;
int nb_line_tLogRow = 0;
// /////////////////////
/**
* stop
*/
/**
* start
*/
ok_Hash.put("tRowGenerator_1", false);
start_Hash.put("tRowGenerator_1", System.currentTimeMillis());
currentComponent = "tRowGenerator_1";
int tos_count_tRowGenerator_1 = 0;
int nb_line_tRowGenerator_1 = 0;
int nb_max_row_tRowGenerator_1 = 1;
class tRowGenerator_1Randomizer {
public String getRandomnewColumn() {
return "" + (Integer.parseInt("null")) + "";
}
}
tRowGenerator_1Randomizer randtRowGenerator_1 = new tRowGenerator_1Randomizer();
for (int itRowGenerator_1 = 0; itRowGenerator_1 < nb_max_row_tRowGenerator_1; itRowGenerator_1++) {
Row.newColumn = randtRowGenerator_1.getRandomnewColumn();
nb_line_tRowGenerator_1++;
/**
* stop
*/
/**
* start
*/
currentComponent = "tRowGenerator_1";
tos_count_tRowGenerator_1++;
/**
* stop
*/
/**
* start
*/
currentComponent = "tLogRow";
// /////////////////////
strBuffer_tLogRow = new StringBuilder();
if (Row.newColumn != null) { //
strBuffer_tLogRow.append(String.valueOf(Row.newColumn));
} //
if (globalMap.get("tLogRow_CONSOLE") != null) {
consoleOut_tLogRow = (java.io.PrintStream) globalMap
.get("tLogRow_CONSOLE");
} else {
consoleOut_tLogRow = new java.io.PrintStream(
new java.io.BufferedOutputStream(System.out));
globalMap.put("tLogRow_CONSOLE", consoleOut_tLogRow);
}
consoleOut_tLogRow.println(strBuffer_tLogRow.toString());
consoleOut_tLogRow.flush();
nb_line_tLogRow++;
// ////
// ////
// /////////////////////
tos_count_tLogRow++;
/**
* stop
*/
/**
* start
*/
currentComponent = "tRowGenerator_1";
}
globalMap.put("tRowGenerator_1_NB_LINE",
nb_line_tRowGenerator_1);
ok_Hash.put("tRowGenerator_1", true);
end_Hash.put("tRowGenerator_1", System.currentTimeMillis());
/**
* stop
*/
/**
* start
*/
currentComponent = "tLogRow";
// ////
// ////
globalMap.put("tLogRow_NB_LINE", nb_line_tLogRow);
// /////////////////////
ok_Hash.put("tLogRow", true);
end_Hash.put("tLogRow", System.currentTimeMillis());
/**
* stop
*/
}// end the resume
} catch (Exception e) {
throw new TalendException(e, currentComponent, globalMap);
} catch (java.lang.Error error) {
throw new java.lang.Error(error);
}
globalMap.put("tRowGenerator_1_SUBPROCESS_STATE", 1);
}
public String resuming_logs_dir_path = null;
public String resuming_checkpoint_path = null;
public String parent_part_launcher = null;
private String resumeEntryMethodName = null;
private boolean globalResumeTicket = false;
public boolean watch = false;
// portStats is null, it means don't execute the statistics
public Integer portStats = null;
public int portTraces = 4334;
public String clientHost;
public String defaultClientHost = "localhost";
public String contextStr = "Preview";
public boolean isDefaultContext = true;
public String pid = "0";
public String rootPid = null;
public String fatherPid = null;
public String fatherNode = null;
public long startTime = 0;
public boolean isChildJob = false;
private boolean execStat = true;
private ThreadLocal threadLocal = new ThreadLocal();
{
java.util.Map threadRunResultMap = new java.util.HashMap();
threadRunResultMap.put("errorCode", null);
threadRunResultMap.put("status", "");
threadLocal.set(threadRunResultMap);
}
private java.util.Properties context_param = new java.util.Properties();
public java.util.Map<String, Object> parentContextMap = new java.util.HashMap<String, Object>();
public String status = "";
public static void main(String[] args) {
final Expression_builder_RowGenerator2 Expression_builder_RowGenerator2Class = new Expression_builder_RowGenerator2();
int exitCode = Expression_builder_RowGenerator2Class.runJobInTOS(args);
System.exit(exitCode);
}
public String[][] runJob(String[] args) {
int exitCode = runJobInTOS(args);
String[][] bufferValue = new String[][] { { Integer.toString(exitCode) } };
return bufferValue;
}
public int runJobInTOS(String[] args) {
String lastStr = "";
for (String arg : args) {
if (arg.equalsIgnoreCase("--context_param")) {
lastStr = arg;
} else if (lastStr.equals("")) {
evalParam(arg);
} else {
evalParam(lastStr + " " + arg);
lastStr = "";
}
}
if (clientHost == null) {
clientHost = defaultClientHost;
}
if (pid == null || "0".equals(pid)) {
pid = TalendString.getAsciiRandomString(6);
}
if (rootPid == null) {
rootPid = pid;
}
if (fatherPid == null) {
fatherPid = pid;
} else {
isChildJob = true;
}
try {
// call job/subjob with an existing context, like:
// --context=production. if without this parameter, there will use
// the default context instead.
java.io.InputStream inContext = Expression_builder_RowGenerator2.class
.getClassLoader().getResourceAsStream(
"phonetest/expression_builder_rowgenerator2/contexts/"
+ contextStr + ".properties");
if (isDefaultContext && inContext == null) {
} else {
if (inContext != null) {
// defaultProps is in order to keep the original context
// value
defaultProps.load(inContext);
inContext.close();
context = new ContextProperties(defaultProps);
} else {
// print info and job continue to run, for case:
// context_param is not empty.
System.err.println("Could not find the context "
+ contextStr);
}
if (!context_param.isEmpty()) {
context.putAll(context_param);
}
}
} catch (java.io.IOException ie) {
System.err.println("Could not load context " + contextStr);
ie.printStackTrace();
}
// get context value from parent directly
if (parentContextMap != null && !parentContextMap.isEmpty()) {
}
// Resume: init the resumeUtil
resumeEntryMethodName = ResumeUtil
.getResumeEntryMethodName(resuming_checkpoint_path);
resumeUtil = new ResumeUtil(resuming_logs_dir_path, isChildJob, rootPid);
resumeUtil.initCommonInfo(pid, rootPid, fatherPid, projectName,
jobName, contextStr, jobVersion);
// Resume: jobStart
resumeUtil.addLog("JOB_STARTED", "JOB:" + jobName,
parent_part_launcher, Thread.currentThread().getId() + "", "",
"", "", "", resumeUtil.convertToJsonText(context));
long startUsedMemory = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
long endUsedMemory = 0;
long end = 0;
startTime = System.currentTimeMillis();
this.globalResumeTicket = true;// to run tPreJob
this.globalResumeTicket = false;// to run others jobs
try {
errorCode = null;
tRowGenerator_1Process(globalMap);
if (!"failure".equals(status)) {
status = "end";
}
} catch (TalendException e_tRowGenerator_1) {
status = "failure";
e_tRowGenerator_1.printStackTrace();
globalMap.put("tRowGenerator_1_SUBPROCESS_STATE", -1);
} finally {
}
this.globalResumeTicket = true;// to run tPostJob
end = System.currentTimeMillis();
if (watch) {
System.out.println((end - startTime) + " milliseconds");
}
endUsedMemory = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
if (false) {
System.out
.println((endUsedMemory - startUsedMemory)
+ " bytes memory increase when running : Expression_builder_RowGenerator2");
}
int returnCode = 0;
if (errorCode == null) {
returnCode = status != null && status.equals("failure") ? 1 : 0;
} else {
returnCode = errorCode.intValue();
}
resumeUtil.addLog("JOB_ENDED", "JOB:" + jobName, parent_part_launcher,
Thread.currentThread().getId() + "", "", "" + returnCode, "",
"", "");
return returnCode;
}
private void evalParam(String arg) {
if (arg.startsWith("--resuming_logs_dir_path")) {
resuming_logs_dir_path = arg.substring(25);
} else if (arg.startsWith("--resuming_checkpoint_path")) {
resuming_checkpoint_path = arg.substring(27);
} else if (arg.startsWith("--parent_part_launcher")) {
parent_part_launcher = arg.substring(23);
} else if (arg.startsWith("--watch")) {
watch = true;
} else if (arg.startsWith("--stat_port=")) {
String portStatsStr = arg.substring(12);
if (portStatsStr != null && !portStatsStr.equals("null")) {
portStats = Integer.parseInt(portStatsStr);
}
} else if (arg.startsWith("--trace_port=")) {
portTraces = Integer.parseInt(arg.substring(13));
} else if (arg.startsWith("--client_host=")) {
clientHost = arg.substring(14);
} else if (arg.startsWith("--context=")) {
contextStr = arg.substring(10);
isDefaultContext = false;
} else if (arg.startsWith("--father_pid=")) {
fatherPid = arg.substring(13);
} else if (arg.startsWith("--root_pid=")) {
rootPid = arg.substring(11);
} else if (arg.startsWith("--father_node=")) {
fatherNode = arg.substring(14);
} else if (arg.startsWith("--pid=")) {
pid = arg.substring(6);
} else if (arg.startsWith("--context_param")) {
String keyValue = arg.substring(16);
int index = -1;
if (keyValue != null && (index = keyValue.indexOf('=')) > -1) {
context_param.put(keyValue.substring(0, index),
replaceEscapeChars(keyValue.substring(index + 1)));
}
}
}
private final String[][] escapeChars = { { "\\n", "\n" }, { "\\'", "\'" },
{ "\\r", "\r" }, { "\\f", "\f" }, { "\\b", "\b" }, { "\\t", "\t" },
{ "\\\\", "\\" } };
private String replaceEscapeChars(String keyValue) {
if (keyValue == null || ("").equals(keyValue.trim())) {
return keyValue;
}
for (String[] strArray : escapeChars) {
keyValue = keyValue.replace(strArray, strArray);
}
return keyValue;
}
public Integer getErrorCode() {
return errorCode;
}
public String getStatus() {
return status;
}
ResumeUtil resumeUtil = null;
}
/************************************************************************************************
* 21658 characters generated by Talend Open Studio for Data Integration on the
* August 30, 2012 10:46:17 AM EDT
************************************************************************************************/