Is there any way to extract text from .tex file? - latex

I am writing a program to count words in a file. I am facing problems while parsing .tex files.
This code need to go on a website where it has to count words from the file that is being uploaded. I have managed to do it but I am looing for some better solutions
case "application/x-tex": // Avoid words with '\' and count
Scanner sc1;
try {
sc1 = new Scanner(new URL(URLPath).openStream());
while (sc1.hasNext()) {
String str = sc1.next();
if (!str.contains("\\")) {
System.out.print(str + " ");
wordCount++;
}
}
sc1.close();
} catch (IOException e) {
System.out.println("There was a problem while reading File on the URL");
break;
// e.printStackTrace();
}
if (wordCount <= 0) {
System.out.println("Total count is " + wordCount
+ ". The uploaded File is either empty or it consists of Images only");
} else {
System.out.println("");
System.out.println("**********");
System.out.println("Word Count: " + wordCount);
System.out.println("**********");
System.out.println("");
}
break;
I am expecting a String output which I could further use to count words.

// Trigger perl script
URL website = new URL(URLPath);
Path path = Paths.get("myfile.tex");
bufferFiles.add(new File("myFile.tex"));
try (InputStream in = website.openStream()) {
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
}
URL texcount = new URL("https://papertrue.s3.us-west-1.amazonaws.com/draft/77e3c992-b70f-4711-8b9b-eaf390617bb8");
Path path1 = Paths.get("texcount.pl");
bufferFiles.add(new File("texcount.pl"));
try (InputStream in = texcount.openStream()) {
Files.copy(in, path1, StandardCopyOption.REPLACE_EXISTING);
}
wordCount = 0;
Process process;
try {
process = Runtime.getRuntime().exec("/etc/papertrue/texcount.pl myfile.tex");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
String tem[] = line.split(":\\s");
log.debug(tem[tem.length - 1]);
try {
wordCount += Integer.parseInt(tem[tem.length - 1]);
} catch (Exception e) {
}
}
process.waitFor();
if (process.exitValue() == 0) {
log.debug("Command Successful");
} else {
log.debug("Command Failure");
}
log.debug(wordCount);
} catch (IOException e) {
log.debug("There was a problem while reading File on the URL");
e.printStackTrace();
break;
}

Related

I have following code to upload my attachment.But I couldn't upload it into my own path. How should I change following code?

if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
System.out.println("status"+status);
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My attachment are stored in machine dependent location. How I change it into my own location? (ex:-war/uploads/..). Now path shows my machine name also.(ex:-/home/name/NetBeansProjects/prjname/dist/wldeploy/prjname/prjname-war.war/uploads/image.jpg)

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

How to reuse j2me kxml parser?

I am useing kxml parser for my j2me application. I am reading the file from phone memory and parsing the xml file to display the data(have various level of filter). On each filter i need to read the data from this file. For first time i created the parser and every time i re-assign this parser1(reference-original) to the paerser2(used to parse data). For first time i got the correct answer, but second time i haven't got the file content it shows null as data.
Here is my code:
FileConnection fc = (FileConnection)Connector.open(rmsObj.rmsData.elementAt(0).toString());
InputStream in = fc.openInputStream();
InputStreamReader is = new InputStreamReader(in);
commonAppObj.externParser = new XmlParser(is);
commonAppObj class file.
protected void fileread() {
try {
if(externParser != null){
parser = externParser;
fileparser(parser);
}else{
InputStream in = this.getClass().getResourceAsStream(this.dataBase);
InputStreamReader is = new InputStreamReader(in);
parser = new XmlParser(is);
fileparser(parser);
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
private void fileparser(XmlParser parser){
try {
ParseEvent event = null;
dataflag = 0;
dataflagS = 0;
System.out.println("findtags = " + findtags);
while (((event = parser.read()).getType() != Xml.END_DOCUMENT) && (dataflag != 1)) {
if (event.getType() == Xml.START_TAG) {
String name = event.getName();
if (name != null && name.equals(findtags)) {
dataflag = 0;
parseAddressTag(parser);
}
name = null;
}
event = null;
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
}
If your InputStream returns true in a call to markSupported you may reset it at the end of fileparser method, but first you need to call mark right after creating it.
if (in.markSupported()) {
in.mark(in.available());
}

j2me openOutputStream stream already open

Im having difficulties with the HttpConnection posting data to my server. The first time everything goes well. The second time it says; 'Stream already open', but i close everything after the response.
Here is my code:
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.*;
import java.io.*;
class GetSnowheights
{
HttpConnection http = null;
QualifiedCoordinates q = null;
public String result = "Geen data";
private boolean running;
public GetSnowheights(QualifiedCoordinates q) {
try
{
/*
this.http = (HttpConnection)Connector.open("http://www.diamond4it.nl/bb/");
this.http.setRequestMethod(HttpConnection.POST);
this.http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
*/
//Internet.getInstance();
this.http = Internet.getConnection();
}catch(Exception err){
err.printStackTrace();
}
this.q = q;
this.result = "Running";
}
public void GetResult(){
StringBuffer sb = new StringBuffer();
this.result = "GetResult";
if(this.http != null){
OutputStream os = null;
InputStream is = null;
try
{
//Send request
os = this.http.openOutputStream();
String data = "lat=1&lng=1";
//String data = "lat=" + this.q.getLatitude() + "&lng=" + this.q.getLongitude();
os.write(data.getBytes());
os.flush();
os.close();
this.result = "dataSend";
//Check response and read data
int res = this.http.getResponseCode();
this.result = "Result: " + res;
if(res == 200){
is = this.http.openInputStream();
int ch;
// Check the Content-Length first
long len = this.http.getLength();
if(len!=-1) {
for(int i = 0;i<len;i++){
if((ch = is.read())!= -1){
sb.append((char)ch);
}
}
} else {
// if the content-length is not available
while ((ch = is.read()) != -1){
sb.append((char)ch);
}
}
is.close();
}
this.result = sb.toString();
}catch(Exception err){
//err.printStackTrace();
this.result = err.toString() + "\r\n" + err.getMessage();
}finally{
if(is != null){
try{
is.close();
}catch(Exception err){
err.printStackTrace();
}
}
if(os != null){
try{
//os.flush();
os.close();
}catch(Exception err){
err.printStackTrace();
}
}
/*
if(http != null){
try{
http.close();
}catch(Exception err){
err.printStackTrace();
}
}
*/
}
}else{
this.result = "No connection";
}
}
}
2 ideas:
Why have you commented out the http.close() in finally block? We should always close HttpConnections.
Don't you call GetResult() from several threads simultaneously? If yes, then make the method synchronized by adding synchronized keyword in its definition.
P.S. I find the design of the class a bit misleading. It's very easy to make a mistake by incorrect usage of it. I'd combine GetSnowheights and GetResult into the only synchronized method.

MonoDroid: Copying an Asset to SD Card

Using MonoDroid in Visual Studio and an emulator, I am trying to copy a asset, "db.sqlite" from the assets folder to the SD card so that I can open the database for read/write.
When I run the app, it dies. MonoDroid is not giving me any debug info.
string destPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.Personal), "db.sqlite");
if (!File.Exists(destPath))
using (Stream stream = Assets.Open("db.sqlite"))
{
stream.CopyTo(File.Create(destPath));
stream.Close();
}
Check the Android Debug Log:
http://android.xamarin.com/Documentation/Guides/Android_Debug_Log
Try saving the file with database file .mp3 extension and then use the following script to copy it to SD card
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs());
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".mp3")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
Code that worked for me (it copies recursively file or directory and all subdirectories ):
private void copy(string SourcePath){
string[] list = Assets.List(SourcePath);
if (list.Length > 0) {
Directory.CreateDirectory(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath);
foreach (string dirPath in Assets.List(SourcePath)){
string newPath = SourcePath + "/" + dirPath;
copy(newPath);
}
}
else{
Assets.Open(SourcePath).CopyTo(new FileStream(AndroidResorces.GetDatabaseStorage() + "/" + SourcePath, FileMode.OpenOrCreate));
}
}
Usage: copy(path_relative_to_assets_root);

Resources