I'm creating a csv file with data saved to it. The next thing i wanna do is that any person can download that file from a link in a HTML page.
The problem is I've never worked before with Java and I've searched for some good options but non of them seems to work. I hope any one can help me with this.
This is how is save to my CSV file
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Logbook {
public Logbook() {
super();
}
/**
* #param date
* #param memoryMax
* #param memoryCommitted
* #param memoryUsed
* #param JvmUpTimeH
* #param JvmUpTimeD
* #param JvmUpTimeM
* #param JvmUpTimeS
*/
public void writeLog(String date, Long memoryMax, Long memoryCommitted, Long memoryUsed, String TotalTime) {
File Logbook = new File("C:/Logbook/Logbook.csv");
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(Logbook, true)))) {
out.println(date + " , " + memoryMax + " b" + " , " + memoryCommitted + " b" + " , " + memoryUsed + " b" + " , " + TotalTime);
} catch (IOException e) {
// exception handling left as an exercise for the reader
}
}
}
After this I have a new page were it refreshes the page every sec my code to write it in the file is here
Long memoryUsed=agent.readMemoryUsed();
Long memoryCommitted=agent.readMemoryCommitted();
Long memoryMax=agent.readMemoryMax();
Date today2 = new Date();
SimpleDateFormat savedLog = new SimpleDateFormat("dd/MM/YY kk:mm:ss");
String date = savedLog.format(today2);
Logbook logBook = new Logbook();
logBook.writeLog(date, memoryMax,memoryCommitted,memoryUsed, TotalTime);
All I want now is to download the file with that information into it for any person that wanna download it.
Probably the easiest way to address this is to write the file to a location under your web server's file directory. You can serve this file statically - you don't need it to go through a webapp to provide it.
You don't mention what web server you're using, or even if you're using an application server on top of it, so we really can't help you that much more. If your question is actually about how to setup a web server - that gets beyond the scope of StackOverflow.
Related
I'm trying to use Twilio to receive SMS messages, and use the body of the SMS to perform various DB functions. The part where I'm stuck is parsing the message that I get from Twilio when they receive a text message.
Here's the controller:
#RequestMapping(
value = "/incomingSMS",
method = RequestMethod.POST)
public void getPhrase(#RequestBody String request) {
System.out.println("***********************************");
System.out.println(request);
System.out.println("***********************************");
}
And here's what is getting printed out (with new lines added for readability, and some numbers censored.):
ToCountry=US&
ToState=statecode&
SmsMessageSid=smsMessageSid&
NumMedia=0&
ToCity=city&
FromZip=zipCode&
SmsSid=SmsSid&
FromState=statecode&
SmsStatus=received&
FromCity=city&
Body=Hello+it%27s+John+&
FromCountry=US&
To=%2B1toPhoneNumber&
ToZip=55401&
NumSegments=1&
MessageSid=messageSid&
AccountSid=accountSid&
From=%2B1fromPhoneNumber&
ApiVersion=2010-04-01
I can see in "Body" my message is hiding. I also see the phone number. Is there any way I can just parse this into a Twilio object that I don't know about, so I can use methods like getBody(), getFrom()?
You can easily manipulate it by using the good old java.util.Properties class.
For the example bellow, I'm using the Apache Common IO lib to transform the String into an InputStream witch is required by Properties class. After that, all you have to do is use getProperty method to get what you need.
package com.pipocandobits.maven;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.util.Properties;
public class App {
public static void main( String[] args ) throws IOException {
System.out.println( "Hello World!" );
String source = "ToCountry=US&\n" +
"ToState=statecode&\n" +
"SmsMessageSid=smsMessageSid&\n" +
"NumMedia=0&\n" +
"ToCity=city&\n" +
"FromZip=zipCode&\n" +
"SmsSid=SmsSid&\n" +
"FromState=statecode&\n" +
"SmsStatus=received&\n" +
"FromCity=city&\n" +
"Body=Hello+it%27s+John+&\n" +
"FromCountry=US&\n" +
"To=%2B1toPhoneNumber&\n" +
"ToZip=55401&\n" +
"NumSegments=1&\n" +
"MessageSid=messageSid&\n" +
"AccountSid=accountSid&\n" +
"From=%2B1fromPhoneNumber&\n" +
"ApiVersion=2010-04-01";
Properties properties = new Properties();
properties.load(IOUtils.toInputStream(source, "UTF-8"));
System.out.println("Message body = " + properties.getProperty("Body"));
}
}
For more on how to use the java.util.Properties class check this link https://www.tutorialspoint.com/java/java_properties_class.htm
I am writing a program to allow my students to engage in a rudimentary AI game (similar to something IBM did years ago). The idea is pretty simple. Everyone has a project with the game jar, and their AI class MyAI.java (which implements AbstractAI). The structure is all working, they can write code into their AI class, and submit it to a common folder. The structure of the folder once a few students have submitted is:
school/stud1/MyAI.class
school/stud2/MyAI.class
I have also written code that I thought (in retrospect quite naively) would load and instantiate all of the classes into an ArrayList. The problem, is that I end up with an ArrayList of x instances of the current class.
I've found some similar questions, but the accepted answers did not work in this instance.
Some of the Loader class (not prettied up, it was just a proof of concept) is included below:
/**
* Load a single ai from a given location
* #param location The path where the ai is: example: c:\\tourney
* #param className The complete class: "org.mrd.Tournament.MyAI"
* #return The instance of AbstractAI loaded
*/
public static AbstractAI loadAI(String location, String className){
Object o = null;
try {
o = new URLClassLoader( new URL[]{new File(location).toURI().toURL()}
).loadClass(className).newInstance();
} catch ...{
}
if (o == null) return null;
return (AbstractAI)o;
}
/**
* Load all current files in tournament folder.
*/
public static ArrayList<AbstractAI> loadCurrentTourneyFiles(){
File dirs = new File("d:\\tourney\\school");
//list of all file names
ArrayList<String> names = new ArrayList<String>(Arrays.asList(dirs.list()));
//Create an arraylist for all loaded AIs and load them.
ArrayList<AbstractAI> arar = new ArrayList();
for (String dir:names){
arar.add(loadAI(dirs.getAbsolutePath() + "\\" + dir, "org.mrd.Tournament.MyAI"));
}
return arar;
}
Most relevant threads:
Java ClassLoader: load same class twice
Java - how to load different versions of the same class?
You can try to use compilation-toolbox, the idea is that you would try to load each of student jar with the following snippet:
JavaSourceCompiler javaSourceCompiler = new JavaSourceCompilerImpl();
JavaSourceCompiler.CompilationUnit compilationUnit = javaSourceCompiler.createCompilationUnit();
compilationUnit.addClassPathEntry("ai_student1.jar");
compilationUnit.addClassPathEntry("abstract_ai.jar");
String aiProvider = "package com.ai;\n" +
" import com.ai.student.AI;\n" +
"import com.ai.AbstractAI;\n" +
" public class AIProvider {\n" +
" public AbstractAI get() {\n" +
" return new AI();\n" +
" }\n\n" +
" }";
ClassLoader classLoader = javaSourceCompiler.compile(compilationUnit);
Class aIProvider = classLoader.loadClass("com.ai.Provider");
I've commented code like below :
/*System.out.println("Parsed in main : " + parsed);
System.out.println("Parsed sum " + (parsed.getHour() + parsed.getMinute()));
System.out.println(isSessionSelected("10:00:00 am"));*/
However, after organize import it disturb the import and look like this :
/*
* System.out.println("Parsed in main : " + parsed);
* System.out.println("Parsed sum " + (parsed.getHour() + parsed.getMinute()));
* System.out.println(isSessionSelected("10:00:00 am"));
*/
This eats my time as every time I uncomment code I have to remove extra *.
How to not let eclipse do this?
If you want to remove those extra *.
in eclipse go to
Window->Preferences->Java->Code Style->Formatter.
Create a new profile by clicking on new button.
after that a new dialog appears,
Select Comments tab
uncheck Enable block comment formatting.
I am developing tally application in swing. Now I want integrate with the Tally.
If I import the data to Tally I am getting error like this.
Importing Data from 'New.xml' on 13-Apr-2016 at 14:11:51
Importing Data to company: 'Technologies Pvt Ltd'
ERROR: Voucher: ID:<REMOTEID:face3a8f-f920-4781-a14b-ed095d0b0145-00000006>, Voucher Type: Payment, Source Voucher Number: 203, Voucher Number: , Date:
Import Summary
Created : 0
Altered : 0
Deleted : 0
Combined: 0
Ignored : 0
Errors : 1
----------------------------------------------
This is my XML file.
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>Vouchers</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>Technologies Pvt Ltd</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="face3a8f-f920-4781-a14b-ed095d0b0145-00000006" VCHKEY="face3a8f-f920-4781-a14b-ed095d0b0145-0000a748:000000061" VCHTYPE="Payment" ACTION="Create" OBJVIEW="Accounting Voucher View">
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<DATE>20160413</DATE>
<GUID>face3a8f-f920-4781-a14b-ed095d0b0145-00000006</GUID>
<NARRATION>100</NARRATION>
<VOUCHERTYPENAME>Payment</VOUCHERTYPENAME>
<VOUCHERNUMBER>203</VOUCHERNUMBER>
<PARTYLEDGERNAME>Cash</PARTYLEDGERNAME>
<CSTFORMISSUETYPE/>
<CSTFORMRECVTYPE/>
<FBTPAYMENTTYPE>Default</FBTPAYMENTTYPE>
<PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
<VCHGSTCLASS/>
<DIFFACTUALQTY>No</DIFFACTUALQTY>
<ISMSTFROMSYNC>No</ISMSTFROMSYNC>
<ASORIGINAL>No</ASORIGINAL>
<AUDITED>No</AUDITED>
<FORJOBCOSTING>No</FORJOBCOSTING>
<ISOPTIONAL>No</ISOPTIONAL>
<EFFECTIVEDATE>20170331</EFFECTIVEDATE>
<USEFOREXCISE>No</USEFOREXCISE>
<ISFORJOBWORKIN>No</ISFORJOBWORKIN>
<ALLOWCONSUMPTION>No</ALLOWCONSUMPTION>
<USEFORINTEREST>No</USEFORINTEREST>
<USEFORGAINLOSS>No</USEFORGAINLOSS>
<USEFORGODOWNTRANSFER>No</USEFORGODOWNTRANSFER>
<USEFORCOMPOUND>No</USEFORCOMPOUND>
<USEFORSERVICETAX>No</USEFORSERVICETAX>
<ISEXCISEVOUCHER>No</ISEXCISEVOUCHER>
<EXCISETAXOVERRIDE>No</EXCISETAXOVERRIDE>
<USEFORTAXUNITTRANSFER>No</USEFORTAXUNITTRANSFER>
<EXCISEOPENING>No</EXCISEOPENING>
<USEFORFINALPRODUCTION>No</USEFORFINALPRODUCTION>
<ISTDSOVERRIDDEN>No</ISTDSOVERRIDDEN>
<ISTCSOVERRIDDEN>No</ISTCSOVERRIDDEN>
<ISTDSTCSCASHVCH>No</ISTDSTCSCASHVCH>
<INCLUDEADVPYMTVCH>No</INCLUDEADVPYMTVCH>
<ISSUBWORKSCONTRACT>No</ISSUBWORKSCONTRACT>
<ISVATOVERRIDDEN>No</ISVATOVERRIDDEN>
<IGNOREORIGVCHDATE>No</IGNOREORIGVCHDATE>
<ISSERVICETAXOVERRIDDEN>No</ISSERVICETAXOVERRIDDEN>
<ISISDVOUCHER>No</ISISDVOUCHER>
<ISEXCISEOVERRIDDEN>No</ISEXCISEOVERRIDDEN>
<ISEXCISESUPPLYVCH>No</ISEXCISESUPPLYVCH>
<ISVATPRINCIPALACCOUNT>No</ISVATPRINCIPALACCOUNT>
<ISSHIPPINGWITHINSTATE>No</ISSHIPPINGWITHINSTATE>
<ISCANCELLED>No</ISCANCELLED>
<HASCASHFLOW>Yes</HASCASHFLOW>
<ISPOSTDATED>No</ISPOSTDATED>
<USETRACKINGNUMBER>No</USETRACKINGNUMBER>
<ISINVOICE>No</ISINVOICE>
<MFGJOURNAL>No</MFGJOURNAL>
<HASDISCOUNTS>No</HASDISCOUNTS>
<ASPAYSLIP>No</ASPAYSLIP>
<ISCOSTCENTRE>No</ISCOSTCENTRE>
<ISSTXNONREALIZEDVCH>No</ISSTXNONREALIZEDVCH>
<ISEXCISEMANUFACTURERON>No</ISEXCISEMANUFACTURERON>
<ISBLANKCHEQUE>No</ISBLANKCHEQUE>
<ISVOID>No</ISVOID>
<ISONHOLD>No</ISONHOLD>
<ORDERLINESTATUS>No</ORDERLINESTATUS>
<VATISAGNSTCANCSALES>No</VATISAGNSTCANCSALES>
<VATISPURCEXEMPTED>No</VATISPURCEXEMPTED>
<ISVATRESTAXINVOICE>No</ISVATRESTAXINVOICE>
<ISDELETED>No</ISDELETED>
<CHANGEVCHMODE>No</CHANGEVCHMODE>
<ALTERID/>
<MASTERID/>
<VOUCHERKEY>183927679483912</VOUCHERKEY>
<EXCLUDEDTAXATIONS.LIST/>
<OLDAUDITENTRIES.LIST/>
<ACCOUNTAUDITENTRIES.LIST/>
<AUDITENTRIES.LIST/>
<DUTYHEADDETAILS.LIST/>
<SUPPLEMENTARYDUTYHEADDETAILS.LIST/>
<INVOICEDELNOTES.LIST/>
<INVOICEORDERLIST.LIST/>
<INVOICEINDENTLIST.LIST/>
<ATTENDANCEENTRIES.LIST/>
<ORIGINVOICEDETAILS.LIST/>
<INVOICEEXPORTLIST.LIST/>
<ALLLEDGERENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>WATER EXP</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>No</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>Yes</ISLASTDEEMEDPOSITIVE>
<AMOUNT>-100.00</AMOUNT>
<SERVICETAXDETAILS.LIST/>
<BANKALLOCATIONS.LIST/>
<BILLALLOCATIONS.LIST/>
<INTERESTCOLLECTION.LIST/>
<OLDAUDITENTRIES.LIST/>
<ACCOUNTAUDITENTRIES.LIST/>
<AUDITENTRIES.LIST/>
<INPUTCRALLOCS.LIST/>
<DUTYHEADDETAILS.LIST/>
<EXCISEDUTYHEADDETAILS.LIST/>
<SUMMARYALLOCS.LIST/>
<STPYMTDETAILS.LIST/>
<EXCISEPAYMENTALLOCATIONS.LIST/>
<TAXBILLALLOCATIONS.LIST/>
<TAXOBJECTALLOCATIONS.LIST/>
<TDSEXPENSEALLOCATIONS.LIST/>
<VATSTATUTORYDETAILS.LIST/>
<COSTTRACKALLOCATIONS.LIST/>
<REFVOUCHERDETAILS.LIST/>
<INVOICEWISEDETAILS.LIST/>
<VATITCDETAILS.LIST/>
</ALLLEDGERENTRIES.LIST>
<ALLLEDGERENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>Cash</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>Yes</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>No</ISLASTDEEMEDPOSITIVE>
<AMOUNT>100.00</AMOUNT>
<SERVICETAXDETAILS.LIST/>
<BANKALLOCATIONS.LIST>
<DATE>20170331</DATE>
<INSTRUMENTDATE>20170331</INSTRUMENTDATE>
<NAME>d29faa3c-2cb8-429e-9d50-cb4243b68a8d</NAME>
<TRANSACTIONTYPE>Cheque</TRANSACTIONTYPE>
<PAYMENTFAVOURING>Water Exp</PAYMENTFAVOURING>
<CHEQUECROSSCOMMENT>A/c Payee</CHEQUECROSSCOMMENT>
<UNIQUEREFERENCENUMBER>3CODSsNV01ippV7T</UNIQUEREFERENCENUMBER>
<STATUS>No</STATUS>
<PAYMENTMODE>Transacted</PAYMENTMODE>
<BANKPARTYNAME>Water Exp</BANKPARTYNAME>
<ISCONNECTEDPAYMENT>No</ISCONNECTEDPAYMENT>
<ISSPLIT>No</ISSPLIT>
<ISCONTRACTUSED>No</ISCONTRACTUSED>
<AMOUNT>1000.00</AMOUNT>
<CONTRACTDETAILS.LIST/>
</BANKALLOCATIONS.LIST>
<BILLALLOCATIONS.LIST/>
<INTERESTCOLLECTION.LIST/>
<OLDAUDITENTRIES.LIST/>
<ACCOUNTAUDITENTRIES.LIST/>
<AUDITENTRIES.LIST/>
<INPUTCRALLOCS.LIST/>
<DUTYHEADDETAILS.LIST/>
<EXCISEDUTYHEADDETAILS.LIST/>
<SUMMARYALLOCS.LIST/>
<STPYMTDETAILS.LIST/>
<EXCISEPAYMENTALLOCATIONS.LIST/>
<TAXBILLALLOCATIONS.LIST/>
<TAXOBJECTALLOCATIONS.LIST/>
<TDSEXPENSEALLOCATIONS.LIST/>
<VATSTATUTORYDETAILS.LIST/>
<COSTTRACKALLOCATIONS.LIST/>
<REFVOUCHERDETAILS.LIST/>
<INVOICEWISEDETAILS.LIST/>
<VATITCDETAILS.LIST/>
</ALLLEDGERENTRIES.LIST>
<PAYROLLMODEOFPAYMENT.LIST></PAYROLLMODEOFPAYMENT.LIST>
<ATTDRECORDS.LIST></ATTDRECORDS.LIST>
</VOUCHER>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>
Is there any error in my xml file,
please help me. there is no enough document in online.
#shimbu shambu, I also faced the same problem and resolved it by changing the date value in DATE tag. This issue occured due to the variation in the date that of passing in the xml and the current date in tally.If you are using the educational version of tally then you can't change the date in the tally. You have to change it in the xml file.
Try passing invalid XML data like this: <![CDATA[ {INVALID XML}]]>
I saw this post when I was trying to the same task which you are doing, wish to share somethings what I did for solving this may be it will help you to proceed further..
java code is as bellow
TallyRequest.java
package tallyrequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class TallyRequest {
public String CreateRequest() {
String TXML = null;
TXML = "<ENVELOPE>"
+ "<HEADER><TALLYREQUEST>Import Data</TALLYREQUEST></HEADER>"
+ "<BODY>"
+ "<IMPORTDATA>"
+ "<REQUESTDESC><REPORTNAME>Vouchers</REPORTNAME><STATICVARIABLES><SVCURRENTCOMPANY>Crane</SVCURRENTCOMPANY></STATICVARIABLES></REQUESTDESC>"
+ "<REQUESTDATA>"
+ "<TALLYMESSAGE xmlns:UDF=\"TallyUDF\">"
+ "<VOUCHER REMOTEID=\"00000001\" VCHTYPE=\"Receipt\" ACTION=\"Create\" OBJVIEW=\"Accounting Voucher View\">"
+ "<DATE>20160701</DATE>"
+ "<VOUCHERTYPENAME>Receipt</VOUCHERTYPENAME>"
+ "<VOUCHERNUMBER>3</VOUCHERNUMBER>"
+ "<PARTYLEDGERNAME>Cash</PARTYLEDGERNAME>"
+ "<PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>"
+ "<ALLLEDGERENTRIES.LIST>"
+ "<LEDGERNAME>Mahes</LEDGERNAME>"
+ "<ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>"
+ "<AMOUNT>0</AMOUNT>"
+ "</ALLLEDGERENTRIES.LIST>"
+ "<ALLLEDGERENTRIES.LIST>"
+ "<LEDGERNAME>Cash</LEDGERNAME>"
+ "<ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>"
+ "<AMOUNT>-150000.00</AMOUNT>"
+ "</ALLLEDGERENTRIES.LIST>"
+ "</VOUCHER>"
+ "</TALLYMESSAGE>"
+ "</REQUESTDATA>"
+ "</IMPORTDATA>"
+ "</BODY>"
+ "</ENVELOPE>";
return TXML;
}
public void SendToTally() throws Exception {
String Url = "http://127.0.0.1:9000/";
String SOAPAction = "";
String Voucher = this.CreateRequest();
// Create the connection where we're going to send the file.
URL url = new URL(Url);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayInputStream bin = new ByteArrayInputStream(Voucher.getBytes());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Copy the SOAP file to the open connection.
copy(bin, bout);
byte[] b = bout.toByteArray();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
public static void copy(InputStream in, OutputStream out)
throws IOException {
// do not allow other threads to read from the
// input or write to the output while copying is
// taking place
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
}
}
}
public static void main(String[] args) throws Exception {
TallyRequest r = new TallyRequest();
r.SendToTally();
}
}
here this send the xml output as bellow
XML Message as below
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>Vouchers</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>Crane</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="00000001" VCHTYPE="Receipt" ACTION="Create" OBJVIEW="Accounting Voucher View">
<DATE>20160701</DATE>
<VOUCHERTYPENAME>Receipt</VOUCHERTYPENAME>
<VOUCHERNUMBER>3</VOUCHERNUMBER>
<PARTYLEDGERNAME>Cash</PARTYLEDGERNAME>
<PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
<ALLLEDGERENTRIES.LIST>
<LEDGERNAME>Mahes</LEDGERNAME>
<ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
<AMOUNT>0</AMOUNT>
</ALLLEDGERENTRIES.LIST>
<ALLLEDGERENTRIES.LIST>
<LEDGERNAME>Cash</LEDGERNAME>
<ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
<AMOUNT>-150000.00</AMOUNT>
</ALLLEDGERENTRIES.LIST>
</VOUCHER>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>
the above code will indicate the ledger and the bill passed from java to tally for the company name, when XML message is be passed to tally make sure that tally is having the same arguments which is passed or modify where ever necessary otherwise message will not pass and you will get a error which can be seen in java Console as well as in tally.imp file on Tally.ERP9 root folder. For doubt regarding the tally XML message structure from your tally just fetch the backup of the Ledger or any other which ever you need to send data to get the format.. or refer the links which was useful for me to send a correct format of XML.
Full reference to Tally and Java integration based on SOAP
Architecture Reference
For further quires pleased do comment elaborating your needs so that I will try to help you!
Remove the remote ID in the voucher TAG and the ID in the GUID tag. Keep the tags, though and see if the voucher is created in the response.
You are probably using the educational version of Tally.
Tally hasn't handled the XML error response for Date not being accessible in Tally - this happens only in the educational version where only the 1st, 2nd and end of month are available to work on.
Try changing the date to 20160401 (you could also play around with the date format-year first, month first or day first).
the one and the only reason for this error is the coding data.
Just remove or delete the data from inverted comma in this 2 lines -
<VOUCHER REMOTEID="face3a8f-f920-4781-a14b-ed095d0b0145-00000006"
VCHKEY="face3a8f-f920-4781-a14b-ed095d0b0145-0000a748:000000061"
and in this line too
<GUID>face3a8f-f920-4781-a14b-ed095d0b0145-00000006</GUID>
remove only
" face3a8f-f920-4781-a14b-ed095d0b0145-00000006 "
and problem solved. :D
As we know we can perform svn operations like checkout, commit, update using tools like Tortoise svn etc.
Now I am trying to perform svn operations like svn checkout, commit, update using ant script (so svn process will be much easier).
I am trying using svnkit sdk with their given as follows:
/*
* ====================================================================
* Copyright (c) 2004-2010 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
/*
* The following example program demonstrates how you can use SVNRepository to
* obtain a history for a range of revisions including (for each revision): all
* changed paths, log message, the author of the commit, the timestamp when the
* commit was made. It is similar to the "svn log" command supported by the
* Subversion client library.
*
* As an example here's a part of one of the program layouts (for the default
* values):
*
* ---------------------------------------------
* revision: 1240
* author: alex
* date: Tue Aug 02 19:52:49 NOVST 2005
* log message: 0.9.0 is now trunk
*
* changed paths:
* A /trunk (from /branches/0.9.0 revision 1239)
* ---------------------------------------------
* revision: 1263
* author: sa
* date: Wed Aug 03 21:19:55 NOVST 2005
* log message: updated examples, javadoc files
*
* changed paths:
* M /trunk/doc/javadoc-files/javadoc.css
* M /trunk/doc/javadoc-files/overview.html
* M /trunk/doc/examples/src/org/tmatesoft/svn/examples/wc/StatusHandler.java
* ...
*
*/
public class History {
/*
* args parameter is used to obtain a repository location URL, a start
* revision number, an end revision number, user's account name & password
* to authenticate him to the server.
*/
public static void main(String[] args) {
/*
* Default values:
*/
String url = "svnUrl";
String name = "username";
String password = "password";
long startRevision = 0;
long endRevision = -1;//HEAD (the latest) revision
/*
* Initializes the library (it must be done before ever using the
* library itself)
*/
setupLibrary();
if (args != null) {
/*
* Obtains a repository location URL
*/
url = (args.length >= 1) ? args[0] : url;
/*
* Obtains the start point of the revisions range
*/
startRevision = (args.length >= 2) ? Long.parseLong(args[1])
: startRevision;
/*
* Obtains the end point of the revisions range
*/
endRevision = (args.length >= 3) ? Long.parseLong(args[2])
: endRevision;
/*
* Obtains an account name (will be used to authenticate the user to
* the server)
*/
name = (args.length >= 4) ? args[3] : name;
/*
* Obtains a password
*/
password = (args.length >= 5) ? args[4] : password;
}
SVNRepository repository = null;
try {
/*
* Creates an instance of SVNRepository to work with the repository.
* All user's requests to the repository are relative to the
* repository location used to create this SVNRepository.
* SVNURL is a wrapper for URL strings that refer to repository locations.
*/
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
} catch (SVNException svne) {
/*
* Perhaps a malformed URL is the cause of this exception.
*/
System.err
.println("error while creating an SVNRepository for the location '"
+ url + "': " + svne.getMessage());
System.exit(1);
}
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
repository.setAuthenticationManager(authManager);
/*
* Gets the latest revision number of the repository
*/
try {
endRevision = repository.getLatestRevision();
} catch (SVNException svne) {
System.err.println("error while fetching the latest repository revision: " + svne.getMessage());
System.exit(1);
}
Collection logEntries = null;
try {
logEntries = repository.log(new String[] {""}, null,
startRevision, endRevision, true, true);
} catch (SVNException svne) {
System.out.println("error while collecting log information for '"
+ url + "': " + svne.getMessage());
System.exit(1);
}
for (Iterator entries = logEntries.iterator(); entries.hasNext();) {
/*
* gets a next SVNLogEntry
*/
SVNLogEntry logEntry = (SVNLogEntry) entries.next();
System.out.println("---------------------------------------------");
/*
* gets the revision number
*/
System.out.println("revision: " + logEntry.getRevision());
/*
* gets the author of the changes made in that revision
*/
System.out.println("author: " + logEntry.getAuthor());
/*
* gets the time moment when the changes were committed
*/
System.out.println("date: " + logEntry.getDate());
/*
* gets the commit log message
*/
System.out.println("log message: " + logEntry.getMessage());
/*
* displaying all paths that were changed in that revision; cahnged
* path information is represented by SVNLogEntryPath.
*/
String logMessage = "log message";
try {
ISVNEditor editor = repository.getCommitEditor( logMessage , null /*locks*/ , true /*keepLocks*/ , null /*mediator*/ );
History.copyDir(editor, "C:/svnCommitCode/src","svnurl/src", logEntry.getRevision());
} catch (SVNException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (logEntry.getChangedPaths().size() > 0) {
System.out.println();
System.out.println("changed paths:");
/*
* keys are changed paths
*/
Set changedPathsSet = logEntry.getChangedPaths().keySet();
for (Iterator changedPaths = changedPathsSet.iterator(); changedPaths
.hasNext();) {
/*
* obtains a next SVNLogEntryPath
*/
SVNLogEntryPath entryPath = (SVNLogEntryPath) logEntry
.getChangedPaths().get(changedPaths.next());
/*
* SVNLogEntryPath.getPath returns the changed path itself;
*
* SVNLogEntryPath.getType returns a charecter describing
* how the path was changed ('A' - added, 'D' - deleted or
* 'M' - modified);
*
* If the path was copied from another one (branched) then
* SVNLogEntryPath.getCopyPath &
* SVNLogEntryPath.getCopyRevision tells where it was copied
* from and what revision the origin path was at.
*/
System.out.println(" "
+ entryPath.getType()
+ " "
+ entryPath.getPath()
+ ((entryPath.getCopyPath() != null) ? " (from "
+ entryPath.getCopyPath() + " revision "
+ entryPath.getCopyRevision() + ")" : ""));
}
}
}
}
/*
* Initializes the library to work with a repository via
* different protocols.
*/
private static void setupLibrary() {
/*
* For using over http:// and https://
*/
DAVRepositoryFactory.setup();
/*
* For using over svn:// and svn+xxx://
*/
SVNRepositoryFactoryImpl.setup();
/*
* For using over file:///
*/
FSRepositoryFactory.setup();
}
private static SVNCommitInfo copyDir( ISVNEditor editor , String srcDirPath , String dstDirPath , long revision ) throws SVNException {
editor.openRoot( -1 );
editor.addDir( dstDirPath , srcDirPath , revision );
System.out.println("done--------------------");
//Closes dstDirPath.
editor.closeDir( );
//Closes the root directory.
editor.closeDir( );
return editor.closeEdit( );
}
}
I am able to get some of the outputs as history:
revision: 7
author: username
date: Wed Apr 23 15:47:58 2014
log message: testing
changed paths:
A /testCode/src
But I am getting below error when I am calling SVNCommitInfo copyDir() method:
org.tmatesoft.svn.core.SVNException: svn: E160013: '/testCode/!svn/bc/2/C:/svnCommitCode/src' path not found: 404 Not Found (http://svnUrl)
I am providing both source (my local system directory path) and destination path (svn directory path), what I am doing wrong over here? (Means on svn same 'src' folder exist, I just want to replace with current local directory.)
Can anyone guide me in this context?
This solution worked for me.
First call this method getSVNClientManager to get authenticated,it will return clientManager which will be used to get different kind of svn clients instances to do different activities.
public SVNClientManager getSVNClientManager () throws IOException{
SVNURL url = SVNURL
.parseURIDecoded("<path to the base svn repository>");
SVNRepository repository = SVNRepositoryFactory.create(url, null);
ISVNOptions myOptions = SVNWCUtil.createDefaultOptions(true);
//provide svn username and password
//username = name used to connect to svn
//password = password used to connect to svn
ISVNAuthenticationManager myAuthManager = SVNWCUtil
.createDefaultAuthenticationManager("<username>", "<password>");
repository.setAuthenticationManager(myAuthManager);
//clientManager will be used to get different kind of svn clients instances to do different activities
//like update, commit, view diff etc.
SVNClientManager clientManager = SVNClientManager.newInstance(
myOptions, myAuthManager);
return clientManager ;
}
and then call method commitToSvn()
public void commitToSvn(SVNClientManager clientManager)
throws SVNException {
SVNCommitClient commitClient = clientManager.getCommitClient();
File fileToCheckin = new File("LocalDir/SampleFileFolder/SampleFile1");
boolean recursive = true;
SVNCommitInfo importInfo = commitClient
.doImport(
fileToCheckin ,
SVNURL.parseURIDecoded("<path at which we want to check-in the file>"),
"testing svn kit integration", recursive);
System.out.println(importInfo.getNewRevision());
}
Similarly we can call checkout method exportFromSvn()
public void exportFromSvn(SVNClientManager clientManager) throws SVNException {
SVNUpdateClient updateClient = clientManager.getUpdateClient();
SVNURL url = SVNURL.parseURIDecoded("<svn url to export from>");
//destination path
File dstPath = new File("LocalDirNew");
//the revision number which should be looked upon for the file path
SVNRevision pegRevision = SVNRevision.create(<right svn revision number>);
//the revision number which is required to be exported.
SVNRevision revision = SVNRevision.create(<right svn revision number>);
//if there is any special character for end of line (in the file) then it is required. For our use case, //it can be null, assuming there are no special characters. In this case the OS specific EoF style will //be assumed
String eolStyle = null;
//this would force the operation
boolean force = true;
//Till what extent under a directory, export is required, is determined by depth. INFINITY means the whole subtree of that directory will be exported
SVNDepth recursive = SVNDepth.INFINITY;
updateClient.doExport(url, dstPath, pegRevision, revision, eolStyle, force, recursive );
}