Run java class from cmd with full path? - java

I have compile a java file
javac XSDValidator.java
And I get a XSDValidator.class
Lets say I have the the class (XSDValidatorc.class) file in
C:\xampp\htdocs\xsd_validtion
And I write this in cmd
C:\xampp\htdocs\xsd_validtion> java XSDValidator students.xsd students.xml
It works fine. But its not working if I I'am in another directory and want to run the file with absolute path. Why doesn't it work?
Lite this, lets say I'am in the directory
C:\aaa\User\Document
And write like this it's not working.
java C:\xampp\htdocs\xsd_validtion\XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This is the java-file
https://www.tutorialspoint.com/xsd/xsd_validation.htm
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XSDValidator {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}

use the java classpath:
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This includes the directory where the class file is located to the classpath.
directories in java are package structures. Thats why you can not use it as a normal Path

The answer from Jens
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
can be the accepted one. I just want to give another solution, in some situations, it's better
CD C:\xampp\htdocs\xsd_validtion
java XSDValidator students.xsd students.xml
CD C:\aaa\User\Document

Related

Java, how could we log and store it into local file, a stateless session bean?

I am trying to log the program's execution flow to better understand how servlets, EJBs and JSPs work together.
Currently the difficulty I am facing is to output the log to a local file.
I have first tried with the Java logger API, studying this example:
Using Java log API:
http://wiki4.caucho.com/Java_EE_Servlet/JSP_tutorial_:_Adding_an_error_page,_logging,_and_other_forms_of_debugging#Using_Java_log_API
And I have written:
package beans;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
log.logp(Level.WARNING,
this.getClass().getName(),
this.getClass().getName(), this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
}
And it indeed outputs the log with ClassName::ClassMethod::User input info.
However it outputs the log info to the console, I need it in a local file, how could we log into a local file?
I have tried to use the PrintWriter and creating a new file with its contents:
package beans;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
try (PrintWriter out = new PrintWriter("log.txt")) {
out.println(this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
}
return "No Apto";
}
}
However this does not create a new file.
How could we create that new local file and send the log output to it?
Thank you for your help!.
I have also read:
How do I save a String to a text file using Java?
Where does the ServletContext.log messages go in tomcat 7?
EDIT: I have read the comment's tutorial: http://tutorials.jenkov.com/java-logging/handlers.html#streamhandler
ANd I have found that we can add handlers to the logger, and there is a built in handler which is FileHandler which is supposed to create one file with the log's contents. I have tried the following:
package beans;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
#Stateless
public class ComentarioNota {
private static final Logger log = Logger.getLogger(ComentarioNota.class.getName());
public String convierteComentarioNota(String evaluacion, String comentario) {
try {
FileHandler handler = new FileHandler("comentarioNota.txt");
log.addHandler(handler);
log.logp(Level.WARNING,
this.getClass().getName(),
"convierteComentarioNota", this.getClass().getName() + "::convierteComentarioNota::el usuario introdujo: " + evaluacion + comentario);
if (evaluacion.trim().equals("Apto") && comentario != null && comentario.length() > 5) {
return "Apto";
} else {
return "No Apto";
}
} catch (IOException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ComentarioNota.class.getName()).log(Level.SEVERE, null, ex);
}
return "No Apto";
}
}
However I still seeing the log being outputted to the console and no file is being created:
And no file is being creted because at least it does not show up in the IDE and I have also try to find it:
Could you help me figuring out how to log to a local file properly?
Thank you for your help.
you need to configure java.util.logging. what you're looking for is the FileHandler. I actually prefer other logging APIs but for your purposes please start here: Tutorial: Java Logging Configuration

Error executing PigServer in Java

I am trying to run pig scripts remotely from my java machine, for that i have written below code
code:
import java.io.IOException;
import java.util.Properties;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
public class Javapig{
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("fs.default.name", "hdfs://hdfs://192.168.x.xxx:8022");
props.setProperty("mapred.job.tracker", "192.168.x.xxx:8021");
PigServer pigServer = new PigServer(ExecType.MAPREDUCE, props);
runIdQuery(pigServer, "fact");
}
catch(Exception e) {
System.out.println(e);
}
}
public static void runIdQuery(PigServer pigServer, String inputFile) throws IOException {
pigServer.registerQuery("A = load '" + inputFile + "' using org.apache.hive.hcatalog.pig.HCatLoader();");
pigServer.registerQuery("B = FILTER A by category == 'Aller';");
pigServer.registerQuery("DUMP B;");
System.out.println("Done");
}
}
but while executing i am getting below error.
Error
ERROR 4010: Cannot find hadoop configurations in classpath (neither hadoop-site.xml nor core-site.xml was found in the classpath).
I don't know what am i doing wrong.
Well, self describing error...
neither hadoop-site.xml nor core-site.xml was found in the classpath
You need both of those files in the classpath of your application.
You ideally would get those from your $HADOOP_CONF_DIR folder, and you would copy them into your Java's src/main/resources, assuming you have a Maven structure
Also, with those files, you should rather use a Configuration object for Hadoop
PigServer(ExecType execType, org.apache.hadoop.conf.Configuration conf)

getResourceAsStream() works on Windows but not on Linux

I have a following class in my project:
package com.test.schedule.payloads;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Loads payload from file
*/
public class FilePayload{
private static final Logger LOGGER = Logger.getLogger(FilePayload.class);
private final String filename;
public FilePayload(String filename) {
this.filename = filename;
}
public String getAsString() {
try {
return IOUtils.toString(new InputStreamReader(FilePayload.class.getResourceAsStream(filename), Charsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Error while loading file: '" + filename +'\'', e);
return "";
}
}
}
In resources directory of my project (maven one) I have file in following path:
com/test/schedule/payloads/schedule-payload.xml
When I execute getAsString() with filename equal to "schedule-payload.xml" on Windows everything works fine. But when the same code is executed on Linux server it returns null on getResourceAsStream(). I have no idea how to fix it so code works both on Windows and Linux. Any help would be very appreciated.
Check, that everything on your path to this file "com/test/schedule/payloads/schedule-payload.xml" is lowercase, as linux paths are case sensitive and windows paths are not case sensitive.

Java eclipse error - Multiple Markers at this line - URL & SAXException cannot be resolved to a type

I am writing a java code to validate XMLs against XSD file.
Eclipse shows 2 error in following code.
Multiple Markers at this line -
URL cannot be resolved to a type
SAXException cannot be resolved to a type
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
public class xml_validator_class {
public static void main(String argv[]) {
URL schemaFile = new URL("xsdfile.xsd");
Source xmlFile = new StreamSource(new File("xmlfile.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
}
}
Kindly refer to this link for below program :
Import the missing classes so that the unqualified types can be used in the program
import java.net.URL;
import org.xml.sax.SAXException;
This error occurs because you have used some classes from some other package and Compiler is not able to resolve those dependencies because of missing imports.
Use Ctrl+Shift+O to Auto import all the required dependencies. Or use manual import as suggested by #Reimeus.
Copy and paste 'URL' class somewhere in your machine with extension of .Java, delete URL class from package, and copy URL Class paste on package folder, Clean the projects. it's worked for me.

Could not find main class Java

I have two classes Pair.java and Users.java where Users.java has the main program. Both these java files are under the package userdetails.
In unix,
I compiled it using the command
javac -d . -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/* Pair.java Users.java
the class are under the folder userdetails.
I tried to run using the command
java -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/* userdetails.Users
I'm getting error
Could not find main class userdetails.Users
Kindly help me.
source code :-
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.util.Utf8;
public class Users {
public void createUser() {
userdetails.Pair datum = new userdetails.Pair(new Utf8("L"), new Utf8("R"));
DatumWriter writer = new SpecificDatumWriter();
DataFileWriter fileWriter = new DataFileWriter(writer);
try {
fileWriter.create(datum.getSchema(), new File("users.avro"));
fileWriter.append(datum);
System.out.println(datum);
fileWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("ERROR");
e.printStackTrace();
} }
public static void main(String[] args) {
Users user = new Users();
user.createUser();
}
}
When you specify a classpath, the current working directory is not automatically contained any more, so you must add it to the classpath:
java -classpath avro-1.7.5.jar:lib/*:jackson-core-asl-1.9.13.jar:lib/*:. userdetails.Users
You say both classes are under the package "userdetails", but there is no package declaration at the beginning of your source. Both Pair.java and User.java should begin with the line:
package userdetails;
Check out the Java Packages Tutorial

Categories

Resources