Run js file in mongo using spring data - java

I am trying to run js file using mongo-template.
See StackOverFlow thread here
I am trying to use same code base, no change at all.
This does not work for me.
I get Exception at this line:
scriptOps.register(new NamedMongoScript("echo", echoScript));
Error:
org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type
[org.springframework.data.mongodb.core.script.NamedMongoScript] to
type [com.mongodb.DBObject]
Complete StackTrace ...
org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:313)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176)
at
org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:375)
at

try{
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\piyush\\t.js")));
try {
while (true) {
String line = br.readLine();
if (line == null)
break;
text.append(line).append("\n");
}
} finally {
try { br.close(); } catch (Exception ignore) {
System.out.println(ignore);
}
}
ExecutableMongoScript echoScript = new ExecutableMongoScript(text.toString());
Object ob=mongoOperation.scriptOps().execute(echoScript, "hello");
System.out.println(ob);
t.js
function(x) { return x; }
it will print hello

Related

Why i got a null message when retrieveng an string line from a file in java

I tried to retrieve a single line of text from a text file in java, and indeed i got what i expect but at the end it adds a null reference, but i don't know why. here my code:
public class EncryptDecryptFile {
public void writeDecryptionFile(String message) {
File f;
FileWriter writeArchive;
try {
f = new File("C:\\Users\\Dell\\Training\\DecryptionFile.txt");
writeArchive = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(writeArchive);
PrintWriter text = new PrintWriter(bw);
text.write(message+"\n");
text.close();
bw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public String readEncryptionFile() {
File file = new File("C:\\Test\\EncryptionFile.txt");
String line = "";
try (
BufferedReader br = new BufferedReader(new FileReader(file))) {
while (true) {
line = br.readLine();
if (line != null) {
System.out.print(line);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
public static void main(String[] args) {
EncryptDecryptFile file = new EncryptDecryptFile();
file.writeDecryptionFile("Hello World!!!");
System.out.println(file.readEncryptionFile());
}
}
The result is as follows
Hello World!!!
null
Where is that null coming from ?
I appreciate any help :(
You are returning line and printing it at the end of System.out.println(file.readEncryptionFile()); at that time it must be null (or the loop would not end). Solution, don't print it. Just do
file.readEncryptionFile();
Note: You also print with-in readEncryptionFile()
Do not do
System.out.println(file.readEncryptionFile());
You are already printing it out in this method, so just calling
file.readEncryptionFile();
should suffice.
Of course you do not need to return a String from this method.
Alternative in the readEncryptionFile, create a StringBuilder Object and append to that if the line is not null, then return the String of the StringBuilder Object.

Content can not be resolved

While building package in eclipse:
public static String getContents(File aFile)
{
contents = new StringBuffer();
BufferedReader input = null;
try
{
input = new BufferedReader(new FileReader(aFile));
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
}
return contents.toString();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if (input != null) {
input.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
we are getting following three errors:
contents can not be resolved (On line number 10)
contents can not be resolved (On line number 12)
contents can not be resolved to a variable (On line number 3)
We are using Eclipse Neon (4.6.0) and java jdk1.8.0_102
Already tried clean and refresh in Eclipse
You define contents variable wrong. To define variable in Java you need to start with a type, then variable name and initializing expression (which is optional by the way).
So contents must be defined as follows:
StringBuffer contents = new StringBuffer();
Edit
If you don't need synchronization support you should use StringBuilder class instead of StringBuffer

Download JSON from URL(java)

Good evening, I'm sorry for my english. I want to try to deduce, using a link from json in the console. Sometimes is used json-simple-1.1.1.jar. I do not understand what the problem is, writes
Exception in thread "main" java.lang.NullPointerException at
kkkkkkkkkkkk.main.main (main.java:34)
private static final String filePath = "http://ksupulse.tk/get_all.php";
public static void main(String[] args) throws org.json.simple.parser.ParseException {
try {
URL serverAddress = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.connect();
int rc = connection.getResponseCode();
if(rc == 200) {
String line = null;
BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
sb.append(line + '\n');
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
//error
JSONArray array = (JSONArray) obj.get("response"); //<-------err this line
for(int i = 0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("id")+": "+list.get("name"));
}
} else {
System.out.println("Connect error");
}
connection.disconnect();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
} catch (java.net.ProtocolException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
Can u provide the json text ?This is happening due to improper parsing of json text. The error is "Null Pointer Exception" . These types of error occur when you try to access some undefined resource . A good way to debug this one is to use a general exception and try to find the exact error . Your code is only handling 3 errors .You need to handle other errors also. Try using this.
try{
//Some code
}(Exception e){
System.out.println("Error:"+e.toString());
}

Reading from a text file in java is returning some garbage value

I'm performing certain commands through command prompt and storing the values in a text file.
wmic logicaldisk where drivetype=3 get deviceid > drive.txt
Now I want to read the string stored in the text file from my java file. When I try to do this:
try {
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i=0;
while ((string[i] = in.readLine()) != null) {
System.out.println(string[i]);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I get the output as follows:
ÿþD[]E[]V[]I[]C[]E[]
how to avoid this?
while ((string[i] = in.readLine()) != null) {
System.out.println(string[2]);
}
over there you are missing the i++;
However I would advise you to use this structure: Use a ArrayList instead of an array, since this allows you to have a self-resizing structure, also instead in the while use the method ready(); from the BufferedRead in order to check the end from the document, at the end the for it's just to display the elements in String ArrayList.
ArrayList<String> string = new ArrayList<String>();
try {
File file = new File("drive.txt");
BufferedReader entrada;
entrada = new BufferedReader(new FileReader(file));
entrada.readLine();
while (entrada.ready()) {
string.add(entrada.readLine());
}
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String elements : string) {
System.out.println(elements);
}
Why do you need a string array here? The size of the array may be wrong? Simply use a string instead of array. I tried this and works fine for me:
try {
String string;
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i = 0;
while ((string = in.readLine()) != null) {
System.out.println(string);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.

how do i use java classes in web context?

I have a text file and a class (Reader) that reads the text file and stores each line in a String [].
String name;
String [] lines;
Reader(String name){
this.name = name;
}
public String toString(){
return this.name;
}
public readFile(String filename){
String line = "";
int i = 0;
try{
BufferedReader reader = new BufferedReader(new FileReader(filename));
while(line = reader.readLine()) != null){
lines[i] = line;
i++;
}// while
reader.close();
}
catch(etc...){}
}
I wish to print each array element in table on my jsp page.
Reader r = new Reader("test");
out.print(r.toString());
works and prints 'test' but...
r.readFile("test.txt")
for (int i=0; i < r.lines.length; i++)
out.print(r.lines[i])
does not... However if I run this on the command line its prints the lines [ ] fine
How do I go about doing it in web context?
Try replacing the following:
BufferedReader reader = new BufferedReader(new FileReader(filename));
with
BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(filename)));
That should work since the input file is in the same package as Reader.
Update:
I think the problem lies in the TeamData.
readFile("skytest\\data.file")
That's not a valid path to the file. Neither in filesystem, nor in the classpath.
Since, the data.file is in the classpath, you can use getResourceAsStream to load it.
And, since skytest is the root directory (package), "/skytest/data.file" would also be valid here (the leading / means relative package root). Or, since the file lies in the same package as the TeamData, just the file name should be enough "data.file".
So, use of the following:
readFile("data.file")
And change the following:
BufferedReader reader = new BufferedReader(new FileReader(requiredFile));
to
BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(requiredFile)));
Also, the following is really a bad practice (that's called swallowing the exception):
catch (IOException ioe) {
//do something about the exception here
return false;
}
Try something like this:
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(new File("path/to/filename.txt")));
String nextLine = reader.readLine();
while (nextLine != null)
{
System.out.println(nextLine); // do stuff with the line you read in.
nextLine = reader.readLine();
}
reader.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories