In the below program, the last line in the code is showing an error. df and d cannot be resolved. I used the same logic in a normal Java program and I got the output. Can somebody explain the problem in this.
package com.first;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AgeCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
public AgeCalc() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//request parameters
String name1=request.getParameter("name1");
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
}
catch(Exception e){}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
}
}
d and df variables are defined inside try block and are not visible outside of it. Either declare them outside:
DateFormat df = null;
Date d = null;
try {
df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
d=df.parse(dob);
} catch(Exception e){
}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
or better, wrap everything in one huge try block:
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
} catch(Exception e){
}
This is basic Java, not really related to servlets. Also you please do something with the exception, at least:
} catch(Exception e){
e.printStackTrace();
}
Related
I have an input string like :
billDate="2016-03-16T10:48:59+05:30" (please see the T in between).
Now I want to convert this to another timestamp (America/New_York).
My final result should be like 16 march 2016 or 15th march 2016 depending upon the hour value.
I saw many examples but got no hint how I can convert the above long datetime string to another string for America/New_York.
Can somebody help me on this?
I tried below code but it always gives 16 march for any hour value.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) {
String output = formatDate("2016-03-1611T:27:58+05:30");
System.out.println(output);
}
public static String formatDate(String inputDate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date parsedDate = sdf.parse(inputDate);
return sdf.format(parsedDate);
}
catch (ParseException e) {
// handle exception
}
return null;
}
}
After trying I finally got the code to solve the issue:
The below code works fine:
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class Test {
public static final SimpleDateFormat fDateTime = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
public static void main(String[] args) {
String output = getFormattedDate("2016-03-1611T23:27:58+05:30");
System.out.println(output);
}
public static String getFormattedDate(String inputDate) {
try {
Date dateAfterParsing = fDateTime.parse(inputDate);
fDateTime.setTimeZone(TimeZone.getTimeZone("timeZone"));
return fDateTime.format(dateAfterParsing);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
I wrote an interceptor in Apache CXF and get a SoapMessage. How do I get the raw XML from the SOAP message without changing the data to hurt the verification of the digital signature?
I refer to org.apache.cxf.binding.soap.SoapMessage:
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.binding.soap.interceptor.EndpointSelectionInterceptor;
import org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class XmlSignatureVerifyInInterceptor extends AbstractSoapInterceptor {
private static final Logger log = LogManager.getLogger(XmlSignatureVerifyInInterceptor.class);
public XmlSignatureVerifyInInterceptor() {
super(Phase.READ);
log.entry();
addAfter(ReadHeadersInterceptor.class.getName());
addAfter(EndpointSelectionInterceptor.class.getName());
}
#Override
public void handleMessage(SoapMessage soapMessage) throws Fault {
log.entry(soapMessage);
}
}
Cheers and thank you in advance!
Fireball
If you are refering a javax.xml.soap.SOAPMessage, and you want a String result of XML, use ByteArrayOutputStream:
SOAPMessage message;
ByteArrayOutputStream out = new ByteArrayOutputStream();
String msg = "";
try {
message.writeTo(out);
msg = out.toString("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
I use UTF-8 as encoding, you can change it to any others.
Strange, I have a Java application in Eclipse Luna and when debugging it and I'm trying to use F6 it doesn't "step over", but instead it "steps into".
I was trying to build a Java applicaton in Eclipse Luna. It was a database application from
here.
With two source files (DB.java):
`import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public Connection conn = null;
public DB() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/Crawler";
conn = DriverManager.getConnection(url, "root", "admin213");
System.out.println("conn built");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public ResultSet runSql(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.executeQuery(sql);
}
public boolean runSql2(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.execute(sql);
}
#Override
protected void finalize() throws Throwable {
if (conn != null || !conn.isClosed()) {
conn.close();
}
}
}`
and Main.java:
`import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
public static DB db = new DB();
public static void main(String[] args) throws SQLException, IOException {
db.runSql2("TRUNCATE Record;");
processPage("http://www.mit.edu");
}
public static void processPage(String URL) throws SQLException, IOException{
//check if the given URL is already in database
String sql = "select * from Record where URL = '"+URL+"'";
ResultSet rs = db.runSql(sql);
if(rs.next()){
}else{
//store the URL to database to avoid parsing again
sql = "INSERT INTO `Crawler`.`Record` " + "(`URL`) VALUES " + "(?);";
PreparedStatement stmt = db.conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, URL);
stmt.execute();
//get useful information
Document doc = Jsoup.connect("http://www.mit.edu/").get();
if(doc.text().contains("research")){
System.out.println(URL);
}
//get all links and recursively call the processPage method
Elements questions = doc.select("a[href]");
for(Element link: questions){
if(link.attr("href").contains("mit.edu"))
processPage(link.attr("abs:href"));
}
}
}
}`
I forgot to include the mysql-connector-java-5.1.16-bin.jar into the buildpath.
This resulted in an exception occuring in the initialization that occurs in the DB()
initializer code. At least this is my assumption that the behaviour of Eclipse was
irritated (maybe it's a feature?) and the step over didn't work right.
I am not able to compile my DriverClass at the job.waitforcompletion(boolean) clause.It gives me a NoClassFoundException.If I catch the exception ,the run method throws the error that its expecting a int value.I am using MapReduce New API.Could anyone suggest what is the issue :
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class Dist_Driver extends Configured implements Tool {
public int run(String args[]) throws IOException, InterruptedException {
// Configuration phase
// Configuration conf=new Configuration();
Job job = new Job(new Configuration());
job.setJarByClass(Dist_Driver.class);
// Mapper Reducer InputFormat
job.setInputFormatClass(FileInputFormat.class);
// Mapper and Reducer Class
job.setMapperClass(Dist_Mapper.class);
job.setReducerClass(DistCache_Reducer.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setInputFormatClass(KeyValueTextInputFormat.class);
// set FileInputOutput
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// setting number of reduce tasks and submit it
job.setNumReduceTasks(2);
// Lets check if the file exist
File f1 = new File("/home/hdfs/trials_mapreduce_progams/emp_id");
if (f1.exists())
System.out.println("The Files Exists");
else
System.out.println("The File doesnot exist");
URI path1;
try {
path1 = new URI(
"/home/hdfs/trials_mapreduce_progams/emp_lookup.txt");
DistributedCache.addCacheFile(path1, job.getConfiguration());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (job.waitForCompletion(true))
return 0;
else
return 1;
}
public static void main(String[] args) throws Exception {
int exitcode = ToolRunner.run(new Dist_Driver(), args);
System.exit(exitcode);
}
}
Just add the ClassNotFoundException to the run method signature
public int run(String args[]) throws IOException,
InterruptedException,
ClassNotFoundException {
The reason you get an error when you try and try/catch it is because if there is a ClassNotFoundException thrown during execution, there will be no return value, and the method has to return something.
If you really want to catch it, just return 1 in the catch clause, which is the error exit code
I am trying to convert string into date type object but keep getting class cast exception.I checked everywhere and found the same way as I am using .I have no idea what mistake I am committing.kindly help.
String str;
SimpleDateFormat formatter;
Date date;
str="12/23/2011"
formatter=new SimpleDateFormat("MM/dd/yyyy");
try {
date=(Date)formatter.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This code works fine with me, maybe you made an error with the imports.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
String str = "12/23/2011";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = null;
try {
date = formatter.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}