how to generate html report if my Junit is not run by Ant but by JunitCore.run - junit-runner

I worked on a project in which testclasses are run via JunitCore.run(testClasses) not via Ant because I have to run the project even with no ANT framework (so no Testng for the same reason). But I still need to create html and xml reports same as JUNIT/ANT. How to generate them in my case?
Right now I found https://github.com/barrypitman/JUnitXmlFormatter/blob/master/src/main/java/barrypitman/junitXmlFormatter/AntXmlRunListener.java may be used to generate xml report. How do I generate html similar to junit-noframes.html? Are there existing methods to convert the TESTS-TestSuites.xml to junit-noframes.html and how? if not, how to generate the html? I do not even find the standard of the html format.

1) Write a test class
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MyTest{
#Test
public void test(){
int i=5;
int j=5;
assertTrue(i==j);
}
#Test
public void test2(){
int i=5;
int j=15;
assertTrue(i!=j);
}
}
2)Create a class which extends RunListner:
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
public class MyRunListner extends RunListener{
private int numberOfTestClass;
private int testExecuted;
private int testFailed;
private long begin;
public MyRunListner(int numberOfTestClass){
this.setBegin(System.currentTimeMillis());
this.numberOfTestClass = numberOfTestClass;
}
public void testStarted(Description description) throws Exception{
this.testExecuted += 1;
}
public void testFailure(Failure failure) throws Exception{
this.testFailed += 1;
}
/**
* #return the numberOfTestClass
*/
public int getNumberOfTestClass(){
return numberOfTestClass;
}
/**
* #param numberOfTestClass the numberOfTestClass to set
*/
public void setNumberOfTestClass(int numberOfTestClass){
this.numberOfTestClass = numberOfTestClass;
}
/**
* #return the testExecuted
*/
public int getTestExecuted(){
return testExecuted;
}
/**
* #param testExecuted the testExecuted to set
*/
public void setTestExecuted(int testExecuted){
this.testExecuted = testExecuted;
}
/**
* #return the testFailed
*/
public int getTestFailed(){
return testFailed;
}
/**
* #param testFailed the testFailed to set
*/
public void setTestFailed(int testFailed){
this.testFailed = testFailed;
}
/**
* #return the begin
*/
public long getBegin(){
return begin;
}
/**
* #param begin the begin to set
*/
public void setBegin(long begin){
this.begin = begin;
}
}
3) Generate the report.
import java.io.FileWriter;
import java.io.IOException;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
public class JUnitTest{
public static void main(String[] args){
JUnitTest junit = new JUnitTest();
junit.runTest();
}
public void runTest(){
try {
String filePath = "C:/temp";
String reportFileName = "myReport.htm";
Class[] myTestToRunTab = {MyTest.class};
int size = myTestToRunTab.length;
JUnitCore jUnitCore = new JUnitCore();
jUnitCore.addListener(new MyRunListner(myTestToRunTab.length));
Result result = jUnitCore.run(myTestToRunTab);
StringBuffer myContent = getResultContent(result,size);
writeReportFile(filePath+"/"+reportFileName,myContent);
}
catch (Exception e) {
}
}
private StringBuffer getResultContent(Result result,int numberOfTestFiles){
int numberOfTest = result.getRunCount();
int numberOfTestFail = result.getFailureCount();
int numberOfTestIgnore = result.getIgnoreCount();
int numberOfTestSuccess = numberOfTest-numberOfTestFail-numberOfTestIgnore;
int successPercent = (numberOfTest!=0) ? numberOfTestSuccess*100/numberOfTest : 0;
double time = result.getRunTime();
StringBuffer myContent = new StringBuffer("<h1>Junit Report</h1><h2>Result</h2><table border=\"1\"><tr><th>Test Files</th><th>Tests</th><th>Success</th>");
if ((numberOfTestFail>0)||(numberOfTestIgnore>0)) {
myContent.append("<th>Failure</th><th>Ignore</th>");
}
myContent.append("<th>Test Time (seconds)</th></tr><tr");
if ((numberOfTestFail>0)||(numberOfTestIgnore>0)) {
myContent.append(" style=\"color:red\" ");
}
myContent.append("><td>");
myContent.append(numberOfTestFiles);
myContent.append("</td><td>");
myContent.append(numberOfTest);
myContent.append("</td><td>");
myContent.append(successPercent);
myContent.append("%</td><td>");
if ((numberOfTestFail>0)||(numberOfTestIgnore>0)) {
myContent.append(numberOfTestFail);
myContent.append("</td><td>");
myContent.append(numberOfTestIgnore);
myContent.append("</td><td>");
}
myContent.append(Double.valueOf(time/1000.0D));
myContent.append("</td></tr></table>");
return myContent;
}
private void writeReportFile(String fileName,StringBuffer reportContent){
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileName);
myFileWriter.write(reportContent.toString());
}
catch (IOException e) {
}
finally {
if (myFileWriter!=null) {
try {
myFileWriter.close();
}
catch (IOException e) {
}
}
}
}
}
4) Finally our report is ready
I hope it helps you!

In fact I solved the problem myself in this way:
First I use https://code.google.com/p/reporting-junit-runner/source/browse/trunk/src/junitrunner/XmlWritingListener.java?spec=svn2&r=2
to create TESTS-*.xml
Then I write the following code myself to create TEST-SUITE.xml and junit-noframes.html. The idea is make use of API of ANT to create reports without really running test. so far the solution works for me.
Project project = new Project();
//a fake project feeding to ANT API so that latter not complain
project.setName("dummy");
project.init();
FileSet fs = new FileSet();
fs.setDir(new File(reportToDir));
fs.createInclude().setName("TEST-*.xml");
XMLResultAggregator aggregator = new XMLResultAggregator();
aggregator.setProject(project);
aggregator.addFileSet(fs);
aggregator.setTodir(new File(reportToDir));
//create TESTS-TestSuites.xml
AggregateTransformer transformer = aggregator.createReport();
transformer.setTodir(new File(reportToDir));
Format format = new Format();
format.setValue(AggregateTransformer.NOFRAMES);
transformer.setFormat(format);
//create junit-noframe.html
aggregator.execute();

Related

Trying to read values returned on jsp form submission in springboot project by setters and use the combination to call another java class

So, I have values in getter setter variables when I click on form submit but now want to have those values in variables and check combination of them to run code from another java class
I have tried using parametrized constructor or may be having a common setter but that did not help.
package com.grt.dto;
import java.util.Set;
public class WDPayrollRecon {
public Set<String> dataType;
public String planCountry;
public String payPeriod;
public String currentPeriod;
public String lastPayPeriod;
Set<String> test;
public Set<String> getdataType() {
return dataType;
}
public void setdataType(Set<String> dataType) {
this.dataType = dataType;
System.out.println("this is dataType" +dataType);
test = dataType;
}
public String getPlanCountry() {
return planCountry;
}
public void setPlanCountry(String planCountry) {
this.planCountry = planCountry;
}
public String getPayPeriod() {
return payPeriod;
}
public void setPayPeriod(String payPeriod) {
this.payPeriod = payPeriod;
}
public String getCurrentPeriod() {
return currentPeriod;
}
public void setCurrentPeriod(String currentPeriod) {
this.currentPeriod = currentPeriod;
}
public String getlastPayPeriod() {
return lastPayPeriod;
}
public void setlastPayPeriod(String lastPayPeriod) {
this.lastPayPeriod = lastPayPeriod;
}
public WDPayrollRecon()
{
}
public WDPayrollRecon(Set<String> dataType,String planCountry,String payPeriod,String currentPeriod,String lastPayPeriod)
{
this.dataType = dataType;
this.planCountry = planCountry;
this.payPeriod = payPeriod;
this.currentPeriod = currentPeriod;
this.lastPayPeriod = lastPayPeriod;
if(dataType.contains("GTLI")& planCountry.equals("USA")){
System.out.println("This is test");
}
else{
System.out.println("This is not test");
}
}
}

multi-tenant application in spring - connecting to DB

Hi Experts,
I am working on a multi-tenant project. It's a table per tenant architecture.
We are using spring and JPA (eclipse-link) for this purpose.
Here our use case is when ever a new customer subscribes to our application a new data base would be created for the customer.
As spring configuration would be loaded only during start-up how to load this new db configuration at run time?
Could some one please give some pointers?
Thanks in advance.
BR,
kitty
For multitenan, first you need to create MultitenantConfig.java
like below file.
here tenants.get("Musa") is my tenant name, comes from application.properties file
#Configuration
#EnableConfigurationProperties(MultitenantProperties.class)
public class MultiTenantConfig extends WebMvcConfigurerAdapter {
/** The Constant log. */
private static final Logger log = LoggerFactory.getLogger(MultiTenantConfig.class);
/** The multitenant config. */
#Autowired
private MultitenantProperties multitenantConfig;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MultiTenancyInterceptor());
}
/**
* Data source.
*
* #return the data source
*/
#Bean
public DataSource dataSource() {
Map<Object, Object> tenants = getTenants();
MultitenantDataSource multitenantDataSource = new MultitenantDataSource();
multitenantDataSource.setDefaultTargetDataSource(tenants.get("Musa"));
multitenantDataSource.setTargetDataSources(tenants);
// Call this to finalize the initialization of the data source.
multitenantDataSource.afterPropertiesSet();
return multitenantDataSource;
}
/**
* Gets the tenants.
*
* #return the tenants
*/
private Map<Object, Object> getTenants() {
Map<Object, Object> resolvedDataSources = new HashMap<>();
for (Tenant tenant : multitenantConfig.getTenants()) {
DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(this.getClass().getClassLoader());
dataSourceBuilder.driverClassName(tenant.getDriverClassName()).url(tenant.getUrl())
.username(tenant.getUsername()).password(tenant.getPassword());
DataSource datasource = dataSourceBuilder.build();
for (String prop : tenant.getTomcat().keySet()) {
try {
BeanUtils.setProperty(datasource, prop, tenant.getTomcat().get(prop));
} catch (IllegalAccessException | InvocationTargetException e) {
log.error("Could not set property " + prop + " on datasource " + datasource);
}
}
log.info(datasource.toString());
resolvedDataSources.put(tenant.getName(), datasource);
}
return resolvedDataSources;
}
}
public class MultitenantDataSource extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
return TenantContext.getCurrentTenant();
}
}
public class MultiTenancyInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
TenantContext.setCurrentTenant("Musa");
return true;
}
}
#ConfigurationProperties(prefix = "multitenancy")
public class MultitenantProperties {
public static final String CURRENT_TENANT_IDENTIFIER = "tenantId";
public static final int CURRENT_TENANT_SCOPE = 0;
private List<Tenant> tenants;
public List<Tenant> getTenants() {
return tenants;
}
public void setTenants(List<Tenant> tenants) {
this.tenants = tenants;
}
}
public class Tenant {
private String name;
private String url;
private String driverClassName;
private String username;
private String password;
private Map<String,String> tomcat;
//setter gettter
public class TenantContext {
private static ThreadLocal<Object> currentTenant = new ThreadLocal<>();
public static void setCurrentTenant(Object tenant) {
currentTenant.set(tenant);
}
public static Object getCurrentTenant() {
return currentTenant.get();
}
}
add below properties in application.properties
multitenancy.tenants[0].name=Musa
multitenancy.tenants[0].url<url>
multitenancy.tenants[0].username=<username>
multitenancy.tenants[0].password=<password>
multitenancy.tenants[0].driver-class-name=<driverclass>

how to consume an object from producer to consumer in kafka?

following are the classes for producer and consumer. When am able to produce the data and not able to consume it with the following code. Can any one help me here? Did I do any wrong in the coding? My aim is to read the CustomMessage object from the consumer and store the data in DB.
In my cmd prompt I have opened 5 instances 1 for zookeeper, 1 for kafka, 1 for producer and 1 for consumer. I really don't understand. Do I need to keep all the instances up when I run the producer and consumer classes?
Any pointers here will be really helpful.
Thanks in advance.
producer class:::
package com.kafka.test.demo;
import java.io.IOException;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.xml.sax.SAXException;
public class KafkaaProducer {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
Properties props = new Properties();
//customMessage is a pojo object which should be send to the consumer..
CustomMessage customMessage= new CustomMessage();
customMessage.setMessage("hello kafka");
customMessage.setFan("1234213123");
customMessage.setSourceSystem("Dmap");
customMessage.setStatus("Unenrolled");
customMessage.setMessageTyep("Simple Message");
customMessage.setCreatedTime("5");
customMessage.setProcessedTime("6");
customMessage.setRetryCount("3");
props.put("metadata.broker.list", "localhost:9092");
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("request.required.acks", "1");
props.put("bootstrap.servers", "localhost:9092,localhost:9093");
//CustomMessageSerializer
props.put("key.serializer","com.kafka.test.demo.CustomMessageSerializer");
props.put("value.serializer", "com.kafka.test.demo.CustomMessageSerializer");
try {
KafkaProducer<String, CustomMessage> producer = new KafkaProducer<String, CustomMessage>(props);
producer.send(new ProducerRecord<String, CustomMessage>("NewMessageTopic", "customMessage",customMessage));
//producer.send(new ProducerRecord<String, CustomMessage>("NewMessageTopic", customMessage));
System.out.println("Message " + "" + " sent !!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
consumer class::
package com.kafka.test.demo;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class KafkaaConsumer {
public static void main(String[] args) throws InterruptedException {
Properties props = new Properties();
props.put("zookeeper.connect", "localhost:2181");
props.put("group.id", "testgroup");
props.put("zookeeper.session.timeout.ms", "4000");
props.put("zookeeper.sync.time.ms", "300");
props.put("rebalance.backoff.ms", "40000");
props.put("bootstrap.servers", "localhost:9092,localhost:9093");
props.put("value.deserializer", "com.kafka.test.demo.CustomMessageDeserializer");
props.put("key.deserializer", "com.kafka.test.demo.CustomMessageDeserializer");
//perisitMessage();
try{
KafkaConsumer<String,CustomMessage> consumer = new KafkaConsumer<String, CustomMessage>(props);
consumer.subscribe(Collections.singletonList("NewMessageTopic"));
while (true) {
ConsumerRecords<String, CustomMessage> messages = consumer.poll(100);
for (ConsumerRecord<String, CustomMessage> message : messages) {
System.out.println("Message received " + message);
}
perisitMessage();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void perisitMessage() {
// TODO Auto-generated method stub
CustomMessage customMessage = new CustomMessage();
customMessage.setMessage("hello kafka");
customMessage.setFan("1234213123");
customMessage.setSourceSystem("Dmap");
customMessage.setStatus("Unenrolled");
customMessage.setMessageTyep("Simple Message");
customMessage.setCreatedTime("5");
customMessage.setProcessedTime("6");
customMessage.setRetryCount("3");
try {
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("DeviceTrack");
DBCollection msgCollection = db.getCollection("messages");
BasicDBObject document = new BasicDBObject();
document.put("message", customMessage.getMessage());
document.put("fan", customMessage.getFan());
document.put("SourceSystem", customMessage.getSourceSystem());
document.put("RetryCount", customMessage.getRetryCount());
document.put("ProcessedTime", customMessage.getProcessedTime());
document.put("CreatedTime", customMessage.getCreatedTime());
document.put("MessageTyep", customMessage.getMessageTyep());
document.put("Status", customMessage.getStatus());
msgCollection.insert(document);
System.out.println("Inserted in the data in DB succesfully");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.kafka.test.demo;
import java.util.Map;
import org.apache.kafka.common.serialization.Deserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomMessageDeserializer implements Deserializer {
public Object deserialize(String arg0, byte[] arg1) {
ObjectMapper mapper = new ObjectMapper();
System.out.println("arg1"+arg1);
CustomMessage message = null;
try {
message = mapper.readValue(arg1, CustomMessage.class);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(""+message);
return message;
}
public void close() {
// TODO Auto-generated method stub
}
public void configure(Map arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
package com.kafka.test.demo;
import java.util.Map;
import org.apache.kafka.common.serialization.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomMessageSerializer implements Serializer {
public byte[] serialize(String arg0, Object arg1) {
byte[] retVal = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
retVal = objectMapper.writeValueAsString(arg1).getBytes();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("value ::::::"+retVal);
return retVal;
}
public void close() {
// TODO Auto-generated method stub
}
public void configure(Map arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
package com.kafka.test.demo;
public class CustomMessage {
private String messageId;
private String parentMsgId;
private String fan;
private String message;
private String sourceSystem;
private String status;
private String messageTyep;
private String createdTime;
private String processedTime;
private String retryCount;
/**
* #return the messageId
*/
public String getMessageId() {
return messageId;
}
/**
* #param messageId the messageId to set
*/
public void setMessageId(String messageId) {
this.messageId = messageId;
}
/**
* #return the parentMsgId
*/
public String getParentMsgId() {
return parentMsgId;
}
/**
* #param parentMsgId the parentMsgId to set
*/
public void setParentMsgId(String parentMsgId) {
this.parentMsgId = parentMsgId;
}
/**
* #return the fan
*/
public String getFan() {
return fan;
}
/**
* #param fan the fan to set
*/
public void setFan(String fan) {
this.fan = fan;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* #return the sourceSystem
*/
public String getSourceSystem() {
return sourceSystem;
}
/**
* #param sourceSystem the sourceSystem to set
*/
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
/**
* #return the status
*/
public String getStatus() {
return status;
}
/**
* #param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* #return the messageTyep
*/
public String getMessageTyep() {
return messageTyep;
}
/**
* #param messageTyep the messageTyep to set
*/
public void setMessageTyep(String messageTyep) {
this.messageTyep = messageTyep;
}
/**
* #return the createdTime
*/
public String getCreatedTime() {
return createdTime;
}
/**
* #param createdTime the createdTime to set
*/
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
/**
* #return the processedTime
*/
public String getProcessedTime() {
return processedTime;
}
/**
* #param processedTime the processedTime to set
*/
public void setProcessedTime(String processedTime) {
this.processedTime = processedTime;
}
/**
* #return the retryCount
*/
public String getRetryCount() {
return retryCount;
}
/**
* #param retryCount the retryCount to set
*/
public void setRetryCount(String retryCount) {
this.retryCount = retryCount;
}
}
You only need the zookeeper and kafka instance.
Start Zookeeper
Start Kafka
Create your Topics ("NewMessageTopic")
Start your Producer and Consumer Code
If i understand you right u use the "kafka-console-producer" & "kafka-console-consumer" ? They are not needed to use your Kafka cluster. If your code work this shoud be fine. If it`s to much work to start the kafka via cmd you can write a .bat.
Like
:startZK
echo Zookeeper wird gestartet
Start "Zookeper" C:\zookeeper-3.4.9\bin\zkServer.cmd
echo Bitte warten bis Zookeeper gestartet ist.
pause
echo Kafka Wird Gestartet
Start "Kafka" C:\kafka_2.11-0.10.2.0\bin\windows\kafka-server-start.bat C:\kafka_2.11-0.10.2.0\config\server.properties
goto Top
On the first look on your code it look right.
I don`t know you only print the data u get to your system.out?
while (true) {
ConsumerRecords<String, CustomMessage> messages = consumer.poll(100);
for (ConsumerRecord<String, CustomMessage> message : messages) {
System.out.println("Message received " + message);<-- just a syso not more :/
}
perisitMessage(); <-- maybe give him the message ?
}
If u see your messages on the outline?? it worked fine. if u don`t see any i can take a close look this evening. Just give me a hint. But I have no experience with MongoDB.
Yes you need zookeeper running, then Kafka broker running, then start your consumer and then start producing you should see it in the consumer.
Also when you using a Custom object I would recommend serializing to a string using Jackson and sending it. On the other side you can always deserialize it. Then change all of your serializers to string.

Execute Stored Procedure in JPA 2.0

I have the following problem and I do not how to solve it.
I have a stored procedure with one parameter ( a date in the format: yyyy-MM-dd ) on my MSSQL Server 2008.
Then I have an #Entity class with a #NamedNativeQuery:
#NamedNativeQuery(name = "my_stored_proc",query = "? = exec EMIR_GUI.get_OTCLite_ACKNACK_Report ?", resultClass = EmirFacade.class)
#Entity
public class EmirFacade {
#Column(name="MessageType", nullable=false)
#Basic(fetch = FetchType.EAGER)
private String mesageType;
My Bean class looks like this:
#PersistenceContext(unitName=Globals.__TWHUNITNAME)
private EntityManager em;
public List<EmirFacade> get_EmirReport(Date date) {
try {
#SuppressWarnings("unchecked")
Query q = em.createNamedQuery("my_stored_proc").setParameter(1, date);
List<EmirFacade> emir_report = q.getResultList();
//List emir_report = q.getResultList();
return emir_report;
} catch (Exception e) {
return Collections.emptyList();
}
}
Now, I always get back the following error message ( it is in german, so I have to translate it as good as I can )
Index "0" is out of range.
I tried nearly everything but I cannot find any way to solve my problem.
Maybe, somebody has a good suggestion for me?
Thank you very much!
JPA 2.0 has no explicit support for stored procedures (JPA 2.1 has).
One workaround is to use native queries (like {CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}), but that doesn’t work when the procedure has out-parameters.
Here is a sample implementation that uses Hibernate’s Work interface:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class CampanhaBrindesStoredProcedure {
#PersistenceContext
private EntityManager entityManager;
private String mensagem;
private String geroubrinde;
#Transactional
public void apurarCampamha(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
try {
MyStoredProc storedProc = new MyStoredProc(numeroPedido, codigoFilialNF,
cgcEntCGCENT, numeroSequencia, integradora);
entityManager.unwrap(Session.class).doWork(storedProc);
setGeroubrinde(storedProc.getGeroubrinde());
setMensagem(storedProc.getMensagem());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getGeroubrinde() {
return geroubrinde;
}
public void setGeroubrinde(String geroubrinde) {
this.geroubrinde = geroubrinde;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
private static final class MyStoredProc implements Work {
private final Long numeroPedido;
private final String codigoFilialNF;
private final String cgcEntCGCENT;
private final Long numeroSequencia;
private final String integradora;
private String mensagem;
private String geroubrinde;
private MyStoredProc(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
this.numeroPedido = numeroPedido;
this.codigoFilialNF = codigoFilialNF;
this.cgcEntCGCENT = cgcEntCGCENT;
this.numeroSequencia = numeroSequencia;
this.integradora = integradora;
}
#Override
public void execute(Connection conn) throws SQLException {
try (CallableStatement stmt = conn
.prepareCall("{CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}")) {
stmt.setLong(1, numeroPedido);
stmt.setString(2, codigoFilialNF);
stmt.setString(3, cgcEntCGCENT);
stmt.setLong(4, numeroSequencia);
stmt.setString(5, integradora);
stmt.registerOutParameter(6, Types.VARCHAR);
stmt.registerOutParameter(7, Types.VARCHAR);
stmt.executeUpdate();
mensagem = stmt.getString(6);
geroubrinde = stmt.getString(7);
if (stmt.wasNull()) {
geroubrinde = null;
mensagem = null;
}
}
}
public String getMensagem() {
return mensagem;
}
public String getGeroubrinde() {
return geroubrinde;
}
}
}
If you can switch to JPA 2.1 (and I strongly suggest you to do so) you can simply do:
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("yourStoredprocedure");
// set parameters
storedProcedure.registerStoredProcedureParameter("parameterName", String.class, ParameterMode.IN);
storedProcedure.setParameter("parameterName", "yourParameter");
// execute stored procedure
storedProcedure.execute();
otherwise it's a bit more convoluted, simply follow this tutorial.

can't find method java

So I run the following program and my cmd prompt gives me an error saying that the getDescriptions() method is not found in the DataElements class. I'm sure there's a simple solution but I'm just stuck. Here's the DataElements class:
import java.io.*;
public class DataElements
{
File file;
private int columns;
private int row;
private int length;
private String name;
private String type;
private int position;
private String[] descriptions;
public File getFile(){
return file;
}
public void setFile(File f){
file = f;
}
public int getColumns(){
return columns;
}
public void setColumns(int c){
columns = c;
}
public int getRow(){
return row;
}
public void setRow(int r){
row = r;
}
public int getLength(){
return length;
}
public void setLength(int l){
length = l;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public String getType(){
return type;
}
public void setType(String t){
type = t;
}
public int getPosition(){
return position;
}
public void setPosition(int p){
position = p;
}
public String[] getDescriptions(){
return description;
}
public void setDescriptions(String[] d){
description = d;
}
}
And here's the main method. If you need the CMSReader class let me know, but the problem seems to be stuck in these two classes
import java.util.Scanner;
import java.io.*;
public class Project2{
public static void main(String[] args) throws FileNotFoundException{
Scanner keyboard = new Scanner(System.in);
boolean fileParsed = false;
String inFile;
String outFile;
if(args.length != 1){
System.out.println("Error. Enter one argument: the file that needs to be parsed.");
System.exit(0);
}
Scanner scan = new Scanner(new File(args[0]));
DataElements storage = new DataElements();
CMSReader reader = new CMSReader(scan,storage);
reader.scanTopData();
System.out.println("Input File - " + storage.getName());
System.out.println("Output File - ");//*************Look at this*********************
System.out.println("Number of Variables - " + storage.getColumns());
System.out.println("Number of Records - " + storage.getRow());
System.out.println("Record Length - " + storage.getLength());
System.out.println("Variable information:");
reader.scanVariableData();
String[] variableData = storage.getDescriptions();
for(int i = 0; i < variableData.length ; i++){
System.out.println(variableData[i]);
}
}
}
I appreciate any help. Like I said, I'm sure it's something dumb but I've been looking at this for too long.
The variable description is not declared in your DataElements class, which is why DataElements file cannot compile, and my guess is that you have an older compiled version (.class file) of DataElements which does not contain that method.
Recommendation:
Start working with a good IDE (IntelliJ is my personal favorite, but Eclipse and Netbeans are also good options). A good IDE, on top of all other goodies it provides, will highlight such issues in a way you won't miss.