Hi I am trying to print the list from servlet to web screen (jsp)
I am using log and it's not working.
Is there anyway to do or am I using this wrong?
private static final Logger log = Logger.getLogger(TodoServiceServlet.class.getName());
.....
Todo tmp = pm.getObjectById(Todo.class, user.getEmail());
System.out.println("user email: " + user.getEmail());
if(tmp==null){
log.info("You have not stored any todo lists yet");
}else{
System.out.println("user email is there?: " + tmp.getEmail());
System.out.println("start printing");
ArrayList<String> todolists = tmp.getList();
if(todolists==null)
System.out.println("Arraylist null");
if(!todolists.isEmpty()){
for(String t : todolists){
System.out.println("In the list: " + t);
log.info("You need to do: " + t);
}
}else{
log.info("You have nothing to do chil out!");
}
System.out would print to "standard out" on the web server (usually the console) not to the screen. What you have to do is instead write to the HttpServletResponse
so something like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
resp.getWriter().println("user email is there?: " + tmp.getEmail());
} catch (IOException e) {
// handle your error here
}
}
Related
I have a bunch of unit tests that run camel routes with code like
// setup code here...
String route = "direct:someroute";
try (CamelContext context = new DefaultCamelContext()) {
Object response = runCamelRoute(context, route, ci);
checkResponse(route, response);
}
but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:
CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty("propertyName", "propetyValue");
Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.
protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
context.addRoutes(new MyRouteBuilder() {
});
setupRegistry(context);
context.start();
FluentProducerTemplate template = context.createFluentProducerTemplate();
template.withBody(message)
.withHeader("hello", "goodbye")
.withProcessor(e -> e.setProperty("propertyName", "propertyValue")) // fail use header instead
.to(route);
try {
Future<Object> future = template.asyncRequest();
return future.get();
}
catch(Exception ex) {
System.out.println(route + " " + ex.getClass().getCanonicleName() + " " + ex.getMessage());
throw ex;
}
finally {
template.stop();
context.stop();
}
}
private void setupRegistry(CamelContext context) {
DataSource ds = DataSourceHelper.createConnectionPoolDev();
context.getRegistry().bind("dataSource", ds);
context.getRegistry().bind("Transformer", new Transformer());
}
public static OracleDataSource createConnectionPoolDev() {
try {
OracleDataSource ds = new OracleDataSource();
ds.setConnectionCacheName("oraCache");
ds.setURL("jdbc:oracle:thin:#//cluster:1521/server.domain.ca");
ds.setUser("user");
ds.setPassword("pass");
return ds;
}
catch (Exception ex) {
logger.error("Failed to create connection to the database " + ex.getMessage());
}
return null;
}
Something like this may be ?
context.createFluentProducerTemplate()
.withBody(...)
.withHeader(..., ...)
.withProcessor( e -> e.setProperty(propertyName, propertyValue) )
.to("direct:someroute")
.send();
I called 'new NewForm(res).show()' in postResponse but though the connection succeed, the particular form is not seen. I found out that if I comment out 'cr.setDisposeOnCompletion(d)', then it works fine.
But infinite progress runs infinitely if any exception occurs and so on. Is this a bug? It occured after I updated to new cn1 library update. If you want to see the project, its here:
https://drive.google.com/file/d/0B8ATnICIY2S8LUdta0F5NXYzamM/view?usp=sharing
Button checkButton = new Button("Check");
checkButton.addActionListener(e -> {
ConnectionCheck cc = new ConnectionCheck(theme);
cc.connectionCheckMethod();
});
ConnectionCheck class
public class ConnectionCheck {
Resources res;
Dialog d;
public ConnectionCheck(Resources res) {
this.res = res;
}
public void connectionCheckMethod() {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jsonp = new JSONParser();
Map<String, Object> parser = jsonp.parseJSON(new InputStreamReader(input));
System.out.println("bibek " + parser);
}
#Override
protected void postResponse() {
new NewForm(res).show();
// d.dispose();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
// d.dispose();
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
// d.dispose();
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
// d.dispose();
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("login RuntimeException " + err);
// d.dispose();
}
};
cr.setPost(true);
cr.setUrl("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");
cr.setTimeout(30000);
cr.addRequestHeader("Accept", "application/json");
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d); //if this line is commented, the newForm is shown
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
NewForm class
public class NewForm extends Form{
public NewForm(Resources res){
setTitle("new Form");
add(new Label("new Form"));
}
}
You need to dispose the dialog before calling the show of the new form. Dispose on completion will dispose the dialog when the connection is done which is sometimes unpredictable.
When a dialog is disposed it returns to the previous form i.e. the one shown before the dialog was shown.
I am Using GCM (Google Cloud Messaging).In that what i want i want to send J Son from the server side .On Client side I want to receive that for simple message i have done but i am stucked how could i pass J Son from the server side to the client side.
Please help me to resolve this.
This is my Server side code
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SENDER_ID = "";
private static final String ANDROID_DEVICE = "";
private List<String> androidTargets = new ArrayList<String>();
public GCMBroadcast() {
super();
androidTargets.add(ANDROID_DEVICE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
Sender sender = new Sender(SENDER_ID);
Message message = new Message.Builder()
.collapseKey(collapseKey)
.addData("message", userMessage)
.build();
try {
MulticastResult result = sender.send(message, androidTargets, 1);
System.out.println("Response: " + result.getResults().toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println("response " +canonicalRegId );
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("XX.jsp").forward(request, response);
}
}
Your payload (added to the Message by calls to addData) can only be name/value pairs. If you want to send a JSON, you can put a JSON string in the value of such name/value pair. Then you'll have to parse that JSON yourself in the client side.
For example :
.addData("message","{\"some_json_key\":\"some_json_value\"}")
I have quite a simple question really.
I wrote a servlet for suppliers to upload XML-files to.
These files get written to a location on the server.
All the files get renamed with a timestamp.
Is there a risk of concurrency problems with the code below?
I ask because we receive files from a supplier, that look like
they have content from 2 different XML-files
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File dirToUse;
boolean mountExists = this.getDirmount().exists();
if (!mountExists) {
this.log("MOUNT " + this.getDirmount() + " does not exist!");
dirToUse = this.getDiras400();
} else {
dirToUse = this.getDirmount();
}
boolean useSimpleRead = true;
if (request.getMethod().equalsIgnoreCase("POST")) {
useSimpleRead = !ServletFileUpload.isMultipartContent(request);
}
if (useSimpleRead) {
this.log("Handle simple request.");
handleSimpleRequest(request, response, dirToUse);
} else {
this.log("Handle Multpart Post request.");
handleMultipart(request, response, dirToUse);
}
}
protected void handleMultipart(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException,
ServletException {
try {
FileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
List<FileItem> items = upload.parseRequest(request);
if (items.isEmpty()) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
boolean savedToDisk = true;
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
getFilename(request);
File diskFile = new File(dir, this.getFilename(request));
item.write(diskFile);
if (!diskFile.exists()) {
savedToDisk = false;
}
}
if (!savedToDisk) {
throw new IOException("Data not saved to disk.");
}
} catch (FileUploadException fue) {
throw new ServletException(fue);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
protected void handleSimpleRequest(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException {
// READINPUT DATA TO STRINGBUFFER
InputStream in = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
while (line != null) {
sb.append(line + "\r\n");
line = reader.readLine();
}
if (sb.length() == 0) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
//Get new Filename
String newFilename = getFilename(request);
File diskFile = new File(dir, newFilename);
saveDataToFile(sb, diskFile);
if (!diskFile.exists()) {
throw new IOException("Data not saved to disk.");
}
}
protected abstract String getFilename(HttpServletRequest request);
protected void saveDataToFile(StringBuffer sb, File diskFile) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(diskFile));
out.write(sb.toString());
out.flush();
out.close();
}
getFileName implementation:
#Override
protected String getFilename(HttpServletRequest request) {
Calendar current = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
long currentTimeMillis = current.getTimeInMillis();
System.out.println(currentTimeMillis);
return "disp_" + request.getRemoteHost() + "_" + currentTimeMillis + ".xml";
}
Anyway, thanks in advance!
There would not be synchronization problems but there can be race conditions, for example, two threads might return the same file name using the method getFileName()
We are currently working on a defect to allow special symbols also to be seen in email subject. The email is text/html mime type.
Currently, if the subject should have a heart symbol it is shown as "&heart" but in the email body a "heart" symbol is shown.
Can someone help us with the solution to have special symbols also part of subject?
Here is the code snippet.
public boolean send(String to, String from, String subject, String templatePath, Map map) {
// create a mime message using the mail sender implementation
MimeMessage mimeMessage = mailSender.createMimeMessage();
// create the message using the specified template
MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setFrom(from);
String text = VelocityEngineUtils.mergeTemplateIntoString(engine, templatePath, map);
helper.setText(text, true);
send(mimeMessage);
log.debug("in send at start" + this.getClass().getName()
+ ":SUCCESS: Sendig mail to" + to + " from " + from + " subject "
+ subject);
} catch (MessagingException e)
{
throw new MailPreparationException("unable to create the mime message helper", e);
} catch (Exception e)
{
log.debug("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ to + " from " + from + " subject " + subject);
// throw new
// MailPreparationException("unable to create the mime message helper",
// e);
}
return false;
}
public boolean send(MimeMessage mimeMessage) throws Exception {
try
{
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
multipart.addBodyPart(bodyPart);
bodyPart.setContent(mimeMessage.getContent(), "text/html");
mimeMessage.setContent(multipart);
mailSender.send(mimeMessage);
} catch (Exception e)
{
log.error("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ e.getMessage());
// e.printStackTrace();
throw e;
// return false;
}
return true;
}
public static String HTMLDecode(String encodedHTML) {
return encodedHTML.replaceAll("¡", "\u00A1")
.replaceAll("¢", "\u00A2")
.replaceAll("£", "\u00A3")
.replaceAll("¤", "\u00A4")
.replaceAll("¥", "\u00A5")
.replaceAll("¦", "\u00A6")
.replaceAll("§", "\u00A7")
.replaceAll("¨", "\u00A8")
........
You can send as Unicode / UTF-8.