JavaCompiler API: access functions/variables outside the compiled program while it's running? - java-compiler-api

Adapting this the following code takes a class and function name, a string of Java code, compiles the code and runs the function.
public class Compile {
static void compileAndRun(final String className, final String methodName, final String code) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
JavaFileObject file = new JavaSourceFromString(className, code);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
System.out.println("Success: " + success);
if (success) {
try {
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
Class.forName("HelloWorld", true, classLoader).getDeclaredMethod(methodName, new Class[] { String[].class }).invoke(null, new Object[] { null });
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + e);
} catch (NoSuchMethodException e) {
System.err.println("No such method: " + e);
} catch (IllegalAccessException e) {
System.err.println("Illegal access: " + e);
} catch (InvocationTargetException e) {
System.err.println("Invocation target: " + e);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
You might call this using:
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"Hello World !\");");
out.println(" }");
out.println("}");
out.close();
Compile.compileAndRun("HelloWorld", "main", writer.toString());
Is it possible from inside the compiled program to call external functions and variables? e.g.
class SomeClass {
int x = 123;
void myFunc() {
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" y = foo(x);");
out.println(" }");
out.println("}");
out.close();
Compile.compileAndRun("HelloWorld", "main", writer.toString());
}
void foo(int x) {
}
}
or maybe with the foo and x in another class? Obviously I tried this, but it fails to compile. Is there a way to achieve this?

In the end I was able to use Groovy, which is a superset of the Java language, to achieve my goal, so you can write a script in Java or Groovy. Passing in variables and classes, which can of course contain variables and functions, was straight-forward, e.g.
class MyClass {
int x = 100;
void myFunc(int r) {
System.out.println("value from inside script = " + r + " !");
}
}
void groovy() {
MyClass q = new MyClass();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println(" System.out.println(\"Hello world\" + q.x);");
out.println(" q.x += 100;");
out.println(" q.myFunc(123)");
out.close();
// call groovy expressions from Java code
Binding binding = new Binding();
binding.setVariable("q", q);
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate(writer.toString());
System.out.println("new value = " + q.x);
}

Related

C3P0, rawConnectionOperation() & java.lang.IllegalArgumentException

I am attempting to use a non-standard method, getServerJobIdentifier(), that is part of the IBM Java Tool Box (jt400.jar) and class com.ibm.as400.access.AS400JDBCConnection with C3P0 & rawConnectionOperation(). I am getting "java.lang.IllegalArgumentException: object is not an instance of declaring class". I have tried numerous options but have not stumbled upon the correct parameters to pass. I am using C3P0 0.9.5.4. Code snippet follows:
// The method I want to call.
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
String m_DatabaseConnectionString = "jdbc:db2:*local;naming=sql;extended metadata=true";
Connection m_dbConnection;
ComboPooledDataSource m_cpds;
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
m_dbConnection = m_cpds.getConnection();
String qualifiedName = "";
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
Method m = AS400JDBCConnection.class.getDeclaredMethod("getServerJobIdentifier");
// This does return what I want. getServerJobIdentified() has no parameters.
System.out.println("method=" + m.toString());
Object[] args = new Object[] {};
System.out.println("calling rawConnectionOperation");
qualifiedName = (String) castCon.rawConnectionOperation(m, C3P0ProxyConnection.RAW_CONNECTION, args);
// never gets here
System.out.println("qualifiedName=" + qualifiedName);
I know I'm that close or I think I am. Thanks!
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import com.mchange.v2.c3p0.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCConnection;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.db2.jdbc.app.DB2Connection;
// javac -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main.java
// /QIBM/ProdData/OS400/jt400/lib/jt400Native.jar
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main
// or
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:/QIBM/ProdData/OS400/jt400/lib/jt400Native.jar C3P0Main
// c3p0.acquireRetryAttempts=0
// c3p0.acquireRetryDelay=5000
// c3p0.breakAfterAcquireFailure=false
// c3p0.maxConnectionAge=10800
// c3p0.maxIdleTime=3600
// c3p0.maxIdleTimeExcessConnections=600
// c3p0.automaticTestTable=c3p0test
// c3p0.idleConnectionTestPeriod=600
// c3p0.testConnectionOnCheckout=true
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar -Dc3p0.acquireRetryAttempts=0 -Dc3p0.acquireRetryDelay=5000 -Dc3p0.breakAfterAcquireFailure=false -Dc3p0.maxConnectionAge=10800 -Dc3p0.maxIdleTime=3600 -Dc3p0.maxIdleTimeExcessConnections=600 -Dc3p0.automaticTestTable=c3p0test -Dc3p0.idleConnectionTestPeriod=600 -Dc3p0.testConnectionOnCheckout=true C3P0Main
public class C3P0Main {
private Connection m_dbConnection;
private ComboPooledDataSource m_cpds;
private String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
//private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true;user=beak;password=roatan12";
private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true";
private String m_databaseServerJobID;
public C3P0Main() throws SQLException
{
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
}
public void run(String[] args) throws Exception
{
m_dbConnection = m_cpds.getConnection();
System.out.println("m_dbConnection=" + m_dbConnection.toString());
String qualifiedName = "";
try {
// To use it, first cast the returned Connection to a C3P0ProxyConnection.
// Then call the method rawConnectionOperation, supplying the java.lang.reflect.Method object
// for the non-standard method you wish to call as an argument. The Method you supply will
// be invoked on the target you provide on the second argument (null for static methods),
// and using the arguments you supply in the third argument to that function. For the target,
// and for any of the method arguments, you can supply the special token
// C3P0ProxyConnection.RAW_CONNECTION, which will be replaced with the
// underlying vendor-specific Connection object before the Method is invoked.
//
// C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection();
// Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class});
// Object[] args = new Object[] {C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )};
// CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args);
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
System.out.println("Is a wrapper for DB2Connection=" + m_dbConnection.isWrapperFor(com.ibm.db2.jdbc.app.DB2Connection.class));
System.out.println("Is a wrapper for AS400JDBCConnection=" + m_dbConnection.isWrapperFor(AS400JDBCConnection.class));
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
System.out.println("C3P0ProxyConnection.RAW_CONNECTION=" + C3P0ProxyConnection.RAW_CONNECTION.getClass().getName());
Method method = AS400JDBCConnection.class.getMethod("getServerJobIdentifier");
System.out.println("method=" + method.toString());
Object[] method_args = new Object[] {};
System.out.println("calling rawConnectionOperation");
try {
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #1.");
}
try {
Object[] method_args = new Object[] {};
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #2.");
}
if (castCon instanceof AS400JDBCConnection) {
System.out.println("YES");
qualifiedName = ((AS400JDBCConnection)C3P0ProxyConnection.RAW_CONNECTION).getServerJobIdentifier();
String jobName = qualifiedName.substring(0, 10).trim();
String jobUser = qualifiedName.substring(10, 20).trim();
String jobNumber = qualifiedName.substring(20).trim();
m_databaseServerJobID = jobNumber + '/' + jobUser + '/' + jobName;
System.out.println("SQL Server Job ID: " + m_databaseServerJobID);
}
else {
System.out.println("m_dbConnection is not an instance of DB2Connection.");
}
}
catch (IllegalArgumentException | SQLException | NoSuchMethodException e) {
System.out.println(e);
System.out.println("oh well.");
}
}
public static void main(java.lang.String args[])
{
try {
C3P0Main app = new C3P0Main();
app.run(args);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

How I can link between JADE agent with the OPC

How I can link between Agent and OPC? Because when I add the Agent code, JAVA cannot connect the OPC. Thank you
public class G2P extends Agent{
//Agent initializations
protected void setup() {
// Printout a welcome message
System.out.println("G2-agent "+getAID().getName()+" is ready.");
}
public static void main(String[] args) throws Exception {
// create connection information
final ConnectionInformation ci = new ConnectionInformation();
ci.setHost("");
ci.setDomain("");
ci.setUser("");
ci.setPassword("");
ci.setClsid("F8582CF2-88FB-11D0-B850-00C0F0104305");
final String itemId1 = "....";
// create a new server
final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
try {
// connect to server
server.connect();
// add sync access, poll every 500 ms
final AccessBase access = new SyncAccess(server, 500);
access.addItem(itemId1, new DataCallback() {
#Override
public void changed(Item item, ItemState state) {
// also dump value
try {
if (state.getValue().getType() == JIVariant.VT_UI4) {
System.out.println("<<< " + state + " / value = " + state.getValue().getObjectAsUnsigned().getValue());
} else {
System.out.println("<<< " + state + " / value = " + state.getValue().getObject());
}
} catch (JIException e) {
e.printStackTrace();
}
}
});
// Add a new group
final Group group = server.addGroup("test");
// Add a new item to the group
final Item item = group.addItem(itemId1);
// start reading
access.bind();
// add a thread for writing a value every 3 seconds
ScheduledExecutorService writeThread = Executors.newSingleThreadScheduledExecutor();
final AtomicInteger i = new AtomicInteger(0);
writeThread.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
final JIVariant value = new JIVariant(i.incrementAndGet());
try {
System.out.println(">>> " + "writing value " + i.get());
item.write(value);
} catch (JIException e) {
e.printStackTrace();
}
}
}, 5, 3, TimeUnit.SECONDS);
// wait a little bit
Thread.sleep(20 * 1000);
writeThread.shutdownNow();
// stop reading
access.unbind();
} catch (final JIException e) {
System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
}
}
}

Java initialization question

JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
JRadioButton roundrButton = new JRadioButton("Round", true);
tubtype.add(roundrButton);
JRadioButton ovalrButton = new JRadioButton("Oval", false);
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.valueOf(plength.getText());
sWidth =Double.valueOf(pwidth.getText());
sdepth =Double.valueOf(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.valueOf(hlength.getText());
cWidth = Double.valueOf(hwidth.getText());
cdepth = Double.valueOf(hdepth.getText());
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
class exitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
class FocusHandler implements FocusListener {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
I am getting an error that says my roundrButton may not have been initialized. Please help.
The problem is these lines here:
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
You're declaring a variable called roundrButton, and then attempting to call .isSelected() on it. You never assign anything to roundButton, though, so it is going to be null.
It seems like you might want to be referring to the roundrButton that you declared earlier. Have you considered making it a field of your class?
The error happens here:
try {
AbstractButton roundrButton;
if (roundrButton.isSelected()) {
You declared a variable called roundrButton but did not assign any object to it.
Then you called a method on, well, who knows? There is no object on which to call the method, because the variable roundrButton never received a value.
I guess your problem is in method actionPerformed of class calcButtonHandler2 :
try {
AbstractButton roundrButton;
if(roundrButton.isSelected())
roundrButton is indeed not initialized and it will lead to a NullPointerException at runtime.

can not run multiple jobs with quartz

Hi i m trying to run two jobs using batch framework.
My problem is SimpleJobLauncher is running only one job which is last in the jobs list.
Here what i am doing:
I have two jobs in my database along with the steps for the jobs.
I read the job data from database and process it as following
public class BatchJobScheduler {
private static Log sLog = LogFactory.getLog(BatchJobScheduler.class);
private ApplicationContext ac;
private DataSourceTransactionManager mTransactionManager;
private SimpleJobLauncher mJobLauncher;
private JobRepository mJobRepository;
private SimpleStepFactoryBean stepFactory;
private MapJobRegistry mapJobRegistry;
private JobDetailBean jobDetail;
private CronTriggerBean cronTrigger;
private SimpleJob job;
private SchedulerFactoryBean schedulerFactory;
private static String mDriverClass;
private static String mConnectionUrl;
private static String mUser;
private static String mPassword;
public static JobMetaDataFeeder metadataFeeder;
static {
try {
loadProperties();
metadataFeeder = new JobMetaDataFeeder();
metadataFeeder.configureDataSource(mDriverClass, mConnectionUrl,
mUser, mPassword);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (SQLException e) {
} catch (ClassNotFoundException e) {
}
}
private static void loadProperties() throws FileNotFoundException,
IOException {
Properties properties = new Properties();
InputStream is;
if (BatchJobScheduler.class.getClassLoader() != null) {
is = BatchJobScheduler.class.getClassLoader().getResourceAsStream(
"batch.properties");
} else {
is = System.class.getClassLoader().getResourceAsStream(
"batch.properties");
}
properties.load(is);
mDriverClass = properties.getProperty("batch.jdbc.driver");
mConnectionUrl = properties.getProperty("batch.jdbc.url");
mUser = properties.getProperty("batch.jdbc.user");
mPassword = properties.getProperty("batch.jdbc.password");
}
public void start(WebApplicationContext wac) throws Exception {
try {
ac = new FileSystemXmlApplicationContext("batch-spring.xml");
mTransactionManager = (DataSourceTransactionManager) ac
.getBean("mTransactionManager");
mJobLauncher = (SimpleJobLauncher) ac.getBean("mJobLauncher");
mJobRepository = (JobRepository) ac.getBean("mRepositoryFactory");
mJobLauncher.afterPropertiesSet();
List<JobMetadata> jobsMetaData = getJobsData(mDriverClass,
mConnectionUrl, mUser, mPassword, null);
createAndRunScheduler(jobsMetaData);
} catch (Exception e) {
e.printStackTrace();
sLog.error("Exception while starting job", e);
}
}
#SuppressWarnings("unchecked")
public List<CronTriggerBean> getJobTriggers(List<JobMetadata> jobsMetaData)
throws Exception {
List<CronTriggerBean> triggers = new ArrayList<CronTriggerBean>();
for (JobMetadata jobMetadata : jobsMetaData) {
job = (SimpleJob) ac.getBean("job");
job.setName(jobMetadata.getJobName());
ArrayList<Step> steps = new ArrayList<Step>();
for (StepMetadata stepMetadata : jobMetadata.getSteps()) {
// System.err.println(ac.getBean("stepFactory").getClass());
stepFactory = new SimpleStepFactoryBean<String, Object>();
stepFactory.setTransactionManager(mTransactionManager);
stepFactory.setJobRepository(mJobRepository);
stepFactory.setCommitInterval(stepMetadata.getCommitInterval());
stepFactory.setStartLimit(stepMetadata.getStartLimit());
T5CItemReader itemReader = (T5CItemReader) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepReaderClass()));
itemReader
.setItems(getItemList(jobMetadata.getJobParameters()));
stepFactory.setItemReader(itemReader);
stepFactory.setItemProcessor((ItemProcessor) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepProcessorClass())));
stepFactory.setItemWriter((ItemWriter) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepWriterClass())));
stepFactory.setBeanName(stepMetadata.getStepName());
steps.add((Step) stepFactory.getObject());
}
job.setSteps(steps);
ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
mapJobRegistry = (MapJobRegistry) ac.getBean("jobRegistry");
mapJobRegistry.register(jobFactory);
jobDetail = (JobDetailBean) ac.getBean("jobDetail");
jobDetail.setJobClass(Class.forName(jobMetadata.getMJoblauncher()));
jobDetail.setGroup(jobMetadata.getJobGroupName());
jobDetail.setName(jobMetadata.getJobName());
Map<String, Object> jobDataMap = new HashMap<String, Object>();
jobDataMap.put("jobName", jobMetadata.getJobName());
jobDataMap.put("jobLocator", mapJobRegistry);
jobDataMap.put("jobLauncher", mJobLauncher);
jobDataMap.put("timestamp", new Date());
// jobDataMap.put("jobParams", jobMetadata.getJobParameters());
jobDetail.setJobDataAsMap(jobDataMap);
jobDetail.afterPropertiesSet();
cronTrigger = (CronTriggerBean) ac.getBean("cronTrigger");
cronTrigger.setJobDetail(jobDetail);
cronTrigger.setJobName(jobMetadata.getJobName());
cronTrigger.setJobGroup(jobMetadata.getJobGroupName());
cronTrigger.setCronExpression(jobMetadata.getCronExpression());
triggers.add(cronTrigger);
}
return triggers;
}
private void createAndRunScheduler(List<JobMetadata> jobsMetaData)
throws Exception {
// System.err.println(ac.getBean("schedulerFactory").getClass());
schedulerFactory = new SchedulerFactoryBean();
List<CronTriggerBean> triggerList = getJobTriggers(jobsMetaData);
Trigger[] triggers = new Trigger[triggerList.size()];
int triggerCount = 0;
for (CronTriggerBean trigger : triggerList) {
triggers[triggerCount] = trigger;
triggerCount++;
}
schedulerFactory.setTriggers(triggers);
schedulerFactory.afterPropertiesSet();
}
private List<JobMetadata> getJobsData(String driverClass,
String connectionURL, String user, String password, String query)
throws SQLException, ClassNotFoundException {
metadataFeeder.createJobMetadata(query);
return metadataFeeder.getJobsMetadata();
}
private List<String> getItemList(String jobParameterString) {
List<String> itemList = new ArrayList<String>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
itemList.add(mapKeyValue[0] + ":" + mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return itemList;
}
private Map<String, Object> getParameterMap(String jobParameterString) {
Map<String, Object> parameterMap = new HashMap<String, Object>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
parameterMap.put(mapKeyValue[0], mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return parameterMap;
}
}
public class MailJobLauncher extends QuartzJobBean {
/**
* Special key in job data map for the name of a job to run.
*/
static final String JOB_NAME = "jobName";
private static Log sLog = LogFactory.getLog(MailJobLauncher.class);
private JobLocator mJobLocator;
private JobLauncher mJobLauncher;
/**
* Public setter for the {#link JobLocator}.
*
* #param jobLocator
* the {#link JobLocator} to set
*/
public void setJobLocator(JobLocator jobLocator) {
this.mJobLocator = jobLocator;
}
/**
* Public setter for the {#link JobLauncher}.
*
* #param jobLauncher
* the {#link JobLauncher} to set
*/
public void setJobLauncher(JobLauncher jobLauncher) {
this.mJobLauncher = jobLauncher;
}
#Override
#SuppressWarnings("unchecked")
protected void executeInternal(JobExecutionContext context) {
Map<String, Object> jobDataMap = context.getMergedJobDataMap();
executeRecursive(jobDataMap);
}
private void executeRecursive(Map<String, Object> jobDataMap) {
String jobName = (String) jobDataMap.get(JOB_NAME);
JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);
sLog.info("Quartz trigger firing with Spring Batch jobName=" + jobName
+ jobDataMap + jobParameters);
try {
mJobLauncher.run(mJobLocator.getJob(jobName), jobParameters);
} catch (JobInstanceAlreadyCompleteException e) {
jobDataMap.remove("timestamp");
jobDataMap.put("timestamp", new Date());
executeRecursive(jobDataMap);
} catch (NoSuchJobException e) {
sLog.error("Could not find job.", e);
} catch (JobExecutionException e) {
sLog.error("Could not execute job.", e);
}
}
/*
* Copy parameters that are of the correct type over to {#link
* JobParameters}, ignoring jobName.
* #return a {#link JobParameters} instance
*/
private JobParameters getJobParametersFromJobMap(
Map<String, Object> jobDataMap) {
JobParametersBuilder builder = new JobParametersBuilder();
for (Entry<String, Object> entry : jobDataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String && !key.equals(JOB_NAME)) {
builder.addString(key, (String) value);
} else if (value instanceof Float || value instanceof Double) {
builder.addDouble(key, ((Number) value).doubleValue());
} else if (value instanceof Integer || value instanceof Long) {
builder.addLong(key, ((Number) value).longValue());
} else if (value instanceof Date) {
builder.addDate(key, (Date) value);
} else {
sLog
.debug("JobDataMap contains values which are not job parameters (ignoring).");
}
}
return builder.toJobParameters();
}
}
I couldnt figure it out why launcher is ignoring all other jobs please help me.
Regards
Make sure these properties are set:
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=3
org.quartz.threadPool.threadPriority=5
This will allow a few jobs to run at the same time. Adjust the settings as needed.