I would like to create journal for my physical file using java program.
a) How we can get the existing journal name and description by passing schema name.?
Ex: DSPFD FILE(SCHEMA_NAME/TABLE_NAME) command is executing successfully but no output in java console.
b) How we can read actual name of table and display in java console.
Thanks in advance.
/**
* Test program to test the AS/400 Command from Java.
*/
public static void main(String[] args) {
String server = "SERVER1";
String user = "USER_ID";
String pass = "PWD_ABC";
String getjournalcmd = "DSPFD FILE(SCHEMA_NAME/TABLE_NAME) OUTPUT(*PRINT)";
String createjournalcmd = "STRJRNPF FILE(SCHEMA_NAME/TABLE_NAME) JRN(SCH_JRN_LIB_NAME/JRN_NAME)";
AS400 as400 = null;
try {
// Create an AS400 object
as400 = new AS400(server, user, pass);
// Create a Command object
CommandCall command = new CommandCall(as400);
// Run the command.
System.out.println("Executing: " + getjournalcmd);
boolean success = command.run(getjournalcmd);
if (success) {
System.out.println("Command Executed Successfully.");
} else {
System.out.println("Command Failed!");
}
// Get the command results
AS400Message[] messageList1 = command.getMessageList();
System.out.println(messageList1.length);
for (AS400Message message : messageList1) {
System.out.println(message.getText());
}
// Create journal
System.out.println("Executing: " + createjournalcmd);
boolean success1 = command.run(createjournalcmd);
if (success1) {
System.out.println("Command Executed Successfully.");
} else {
System.out.println("Command Failed!");
}
// Get the command results
AS400Message[] messageList = command.getMessageList();
System.out.println(messageList.length);
for (AS400Message message : messageList) {
System.out.println(message.getText());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Make sure to disconnect
as400.disconnectAllServices();
} catch (Exception e) {
}
}
System.exit(0);
}
The IBM Toolbox for Java has a class to retrieve that information. Here is the Javadocs. You are going to have to use the IFS name of the object in question which looks like this /QSYS.LIB/libraryname.LIB/filename.FILE
If I wanted to do this, I would try something like this:
String journal = "";
FileAttributes fa = new FileAttributes(myConnection, ifsPath);
if (fa.isJournalingStatus()) {
journal = fa.getJournal();
}
DSPFD output(*print) produces a report but doesn't return anything back to caller. You can use QDBRTVFD API instead to have the values returned back to the caller Java method. Alternative is to create a program on IBM i (AS400) backend that gets the information you need and has a simplified parameter structure.
Related
So I wrote a program where I have a email table and it contains columns such as id,user,recipient,content,subject,etc. I would be running this as a backend service for 24/7 to keep fetching records to keep sending emails.
It's something like this:
public void schedule(){
Thread service;
service = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Email service is ready");
email();
} catch (Exception e) {
e.printStackTrace();
}
}
});
service.start();
}
public void email() throws Exception {
try{
while(true) {
readConfig();
String portNumber = (String) settingsMap.get("COBRA_PORT");
if (ejbCon.checkConnection(portNumber) == -1) {
TerminalLogger.printMsg("failed to init EJB Beans on cobra port : " + portNumber);
stop = true;
}
List<Emailqueue> emailList=ejbCon.getSettingsFacade().emailrecord();
for (Emailqueue obj : emailList) {
String emailStatus = "DONE";
String errormsg=sendEmail(obj.getRecipient(), obj.getSubject(), obj.getContent(),obj.getUlnodeid(),obj.getUser());
if (!errormsg.equals("")) {
emailStatus = "FAILED";
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
}
}catch(Exception e){
e.printStackTrace();
TerminalLogger.printMsg("Exception: "+e.toString());
}
Thread.sleep(2000);
}
So in email method,it fetches record from the table where the status are 'pending' and get it's relevant values and pass them as parameters.So if there are two pending records,it will fetch them and for loop each to send to their respectively recipient. It works fine.
However,I kept the program running and I tried inserting new record to the table but it is not picking it up.There's no error too.I thought while(true) always keep picking up records from the table if there are pending email records.
Did I do any mistake?
Edit:
Apparently the while loop keeps running and picking newly inserted records when I implemented with JDBC but with JPA(in this case),it does not keep looping.
Edit 2:
Apparently, the while(true) works now and I have no idea why. Although,the program will throw an communication timeout error after a period of time,probably because there's no record. Would need to resolve that.
This is how the loop looks like now:
try{
while(true) {
readConfig();
String portNumber = (String) settingsMap.get("COBRA_PORT");
if (ejbCon.checkConnection(portNumber) == -1) {
TerminalLogger.printMsg("failed to init EJB Beans on cobra port : " + portNumber);
stop = true;
}
List<Emailqueue> emailList=ejbCon.getSettingsFacade().emailrecord();
for (Emailqueue obj : emailList) {
String emailStatus = "DONE";
String errormsg=sendEmail(obj.getRecipient(), obj.getSubject(), obj.getContent(),obj.getUlnodeid(),obj.getUser());
if (!errormsg.equals("")) {
emailStatus = "FAILED";
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
Thread.sleep(2000);
}
I think its prefer use cron scheduler rather than using while(true) inside of thread. it will be more safe than while(true) itself.
I have referred documentation on Stellar.
Then I have started to run the send payment and receiving payment code after creating an account in Java.
Send payment code is working , but receiving payment code got terminated. I have mentioned code below :
public class receivePayment {
public static void main(String args[]) {
Server server = new Server("https://horizon-testnet.stellar.org");
KeyPair account = KeyPair.fromAccountId("GC2BKLYOOYPDEFJKLKY6FNNRQMGFLVHJKQRGNSSRRGSMPGF32LHCQVGF");
// Create an API call to query payments involving the account.
PaymentsRequestBuilder paymentsRequest = server.payments().forAccount(account);
// If some payments have already been handled, start the results from
// the
// last seen payment. (See below in `handlePayment` where it gets
// saved.)
/*
* String lastToken = loadLastPagingToken(); if (lastToken != null) {
* paymentsRequest.cursor(lastToken); }
*/
// `stream` will send each recorded payment, one by one, then keep the
// connection open and continue to send you new payments as they occur.
paymentsRequest.stream(new EventListener<OperationResponse>() {
#Override
public void onEvent(OperationResponse payment) {
// Record the paging token so we can start from here next time.
// savePagingToken(payment.getPagingToken());
// The payments stream includes both sent and received payments.
// We only
// want to process received payments here.
if (payment instanceof PaymentOperationResponse) {
if (((PaymentOperationResponse) payment).getTo().equals(account)) {
return;
}
String amount = ((PaymentOperationResponse) payment).getAmount();
Asset asset = ((PaymentOperationResponse) payment).getAsset();
String assetName;
if (asset.equals(new AssetTypeNative())) {
assetName = "lumens";
} else {
StringBuilder assetNameBuilder = new StringBuilder();
assetNameBuilder.append(((AssetTypeCreditAlphaNum) asset).getCode());
assetNameBuilder.append(":");
assetNameBuilder.append(((AssetTypeCreditAlphaNum) asset).getIssuer().getAccountId());
assetName = assetNameBuilder.toString();
}
StringBuilder output = new StringBuilder();
output.append(amount);
output.append(" ");
output.append(assetName);
output.append(" from ");
output.append(((PaymentOperationResponse) payment).getFrom().getAccountId());
System.out.println(output.toString());
}
}
});
}
}
I don't understand why it gets terminated. If I checked the balance from my account URL, but shows me the sending-receiving result, but it is not showing result in Eclipse.
I have also referred below reference link and follow the answer but still it is not working.
Stellar payments query
Can anyone tell me how to run this code which continuously receive the payments and maintain the logs on console. ?
The thing is this is a streaming service, so if you just run the service in main method then it will obviously terminated while running in main method and the scope will go outside and EventListener will not be able to be executed. As you said you are using eclips,one thing you can do is instead of run try debug and insert a debugpoint at this Server server = new Server("https://horizon-testnet.stellar.org"); line and press F6 and go one by one line. While debugging Once it reaches the last line of the program then wait,don't run. You will see the data in the console. this way you will understand how the program is working.
If you want to run it fast then use the code that I have added with the existing code. I have added two options. you can use any of this. This will display the output.
public class TestStellar2 {
public static void main(String args[]) {
Server server = new Server("https://horizon-testnet.stellar.org");
KeyPair account = KeyPair.fromAccountId("GC2BKLYOOYPDEFJKLKY6FNNRQMGFLVHJKQRGNSSRRGSMPGF32LHCQVGF");
PaymentsRequestBuilder paymentsRequest = server.payments().forAccount(account);
paymentsRequest.stream(new EventListener <OperationResponse>(){
#Override
public void onEvent(OperationResponse payment) {
if (payment instanceof PaymentOperationResponse) {
if (((PaymentOperationResponse) payment).getTo().equals(account)) {
return;
}
String amount = ((PaymentOperationResponse) payment).getAmount();
Asset asset = ((PaymentOperationResponse) payment).getAsset();
String assetName;
if (asset.equals(new AssetTypeNative())) {
assetName = "lumens";
} else {
StringBuilder assetNameBuilder = new StringBuilder();
assetNameBuilder.append(((AssetTypeCreditAlphaNum) asset).getCode());
assetNameBuilder.append(":");
assetNameBuilder.append(((AssetTypeCreditAlphaNum) asset).getIssuer().getAccountId());
assetName = assetNameBuilder.toString();
}
StringBuilder output = new StringBuilder();
output.append(amount);
output.append(" ");
output.append(assetName);
output.append(" from ");
output.append(((PaymentOperationResponse) payment).getFrom().getAccountId());
System.out.println(output.toString());
}
}
});
/**
* option 1
*
*/
/*try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
/**
* option 2
*/
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output will look like below :
10.0000000 lumens from GC2BKLYOOYPDEFJKLKY6FNNRQMGFLVHJKQRGNSSRRGSMPGF32LHCQVGF many line like this
I wrote a very simple Java web application ,just included some basic function like register , sign in , changing the password and some others.
I don't use database. I just create a file in the app to record the users' information and do the database stuff.
I used JMeter to stressing the web application, especially the register interface.
The JMeter shows that the result of the 1000 thread is right
but when I look into the information.txt , which stores the users' information, it's wrong because it stores 700+ record :
but it should include 1000 record, it must be somewhere wrong
I use the singleton class to do the write/read stuff, and i add a synchronized word to the class, the insert() function which is used by register to record the register information is shown as below: (a part of it)
public class Database {
private static Database database = null;
private static File file = null;
public synchronized static Database getInstance() {
if (database == null) {
database = new Database();
}
return database;
}
private Database() {
String path = this.getClass().getClassLoader().getResource("/")
.getPath() + "information.txt";
file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void insert(String account, String password, String username) {
RandomAccessFile infoFile = null;
try {
infoFile = new RandomAccessFile(file, "rw");
String record;
long offset = 0;
while ((record = infoFile.readLine()) != null ) {
offset += record.getBytes().length+2;
}
infoFile.seek(offset);
record = account+"|"+password+"|"+username+"\r\n";
infoFile.write(record.getBytes());
infoFile.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (infoFile != null) {
try {
infoFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
the question is why would this happened , the synchronized is thread safe, why i lost so many data and some blank line was inserted into it, what could I do the correct it !
You are synchronizing the getInstance() method, but not the insert() method. This makes the retrieval of the instance of Database thread-safe, but not the write operation.
I am currently working on a project about calculations.I have done the main part of my project,Also integrated SVN Commit function to my code (using .ini file to read the specific address etc. )
I can easily Commit the files, what I am trying is I want to implement the real-time log to my console. Is there any way to implement the log to the console ? Not the general log but the commit log which should be real time.
I am using eclipse for mac, I've heard about SVNKit but I am really poor about SVN.
Thanks in advance for any information
--- EDIT ---
This is the code for reading the svn commands from .ini file
public static String iniSVNOkut(String deger, String getObje, String fetchObje){
Ini uzantilariAlIni = null;
try
{
String uzantiAyarlari = "Uzantilar.ini";
try
{
uzantilariAlIni = new Ini(new FileReader(uzantiAyarlari));
}
catch (InvalidFileFormatException e)
{
System.err.print("Hata InvalidFileFormat : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch(FileNotFoundException e)
{
System.err.print("Hata FileNotFoundException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch (IOException e)
{
System.err.print("Hata IOException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
return deger = uzantilariAlIni.get(getObje).fetch(fetchObje);
}
finally
{
}
}
This is what .ini includes
[svnAdresi]
svnAdresiniAl = svn co http://svn.svnkit.com/repos/svnkit/trunk/ /Users/sample/Documents/workspace/SatirHesaplaGUI/svnTestMAC
This is how I call it
String svnAdresi;
svnAdresi = IniFonksiyon.iniSVNOkut(svnAdresi, "svnAdresi", "svnAdresiniAl");
Runtime cmdCalistir = Runtime.getRuntime();
try
{
Process islem = cmdCalistir.exec(svnAdresi);
}
catch (Exception e)
{
e.printStackTrace();
}
If I understand your question correctly, you want to read the Subversion commit log into your console application.
The easiest way is to use SVNKit.
Here's how I did it.
private static List<SVNLogEntry> logEntryList;
/*
* Gets the Subversion log records for the directory
*/
LogHandler handler = new LogHandler();
String[] paths = { directory };
try {
repository.log(paths, latestRevision, 1L, false, true, handler);
} catch (SVNException svne) {
if (svne.getMessage().contains("not found")) {
logEntryList = new ArrayList<SVNLogEntry>();
} else {
CobolSupportLog.logError(
"Error while fetching the repository history: "
+ svne.getMessage(), svne);
return false;
}
}
logEntryList = handler.getLogEntries();
directory - string pointing to a particular directory or module
latestRevision - largest revision number from Subversion. Placing the latestRevision second in the log method invocation returns the log records in most recent order.
If you want the log records in sequential order, from 1 to latestRevision, then the 1L would be placed second, and the latestRevision would be placed third.
repository - Subversion repository that you've already authenticated.
Here's LogHandler.
public class LogHandler implements ISVNLogEntryHandler {
protected static final int REVISION_LIMIT = 5;
protected List<SVNLogEntry> logEntryList;
public LogHandler() {
logEntryList = new ArrayList<SVNLogEntry>();
}
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
logEntryList.add(logEntry);
}
public List<SVNLogEntry> getLogEntries() {
if (logEntryList.size() <= REVISION_LIMIT) {
return logEntryList;
} else {
return logEntryList.subList(0, REVISION_LIMIT);
}
}
}
i have java class in which i have done database connection for SQL server and trying to retrieve data from table its working fine. but now i created web service in java for that class then its showing me ClassNotFoundException :net.sourceforge.jtds.jdbc.Driver i have import external jar as well.
Actually i need to show data from database to Android layout that's why i created web service which will helpful to retrieve data from database.
But when i am trying to retrieve data from database then Drivers are not loading.its showing above error.
i also tried like following :
//DatabaseConnetivityClass.java
public class DatabaseConnetivityClass
{
public static void main(String Args[])
{
new DatabaseConnetivityClass().getData();
}
public String getData()
{
String s = null;
try {
s = new MainConnection().getData();
} catch (SQLException e) {
e.printStackTrace();
}
return s;
}
}
MainConnection.java
public class MainConnection {
Connection con;
public MainConnection() {
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/databasename","username","password");
}
catch (Exception e) {
System.out.println("exp:"+e);
}
}
public String getData() throws SQLException {
StringBuffer sb = new StringBuffer();
Statement select = con.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM Personal_Info");
while (result.next()) {
// process results one row at a time
String val = result.getString(1);
sb.append(val);
System.out.println("val = " + val);
}
select.close();
return sb.toString();
}}
i thought it will work but its giving the same error.
So please help me if anybody knows the solution