Showing error or success message on same page - html

this is my first time posting here since I couldn't figure the issue out, please keep in mind im fairly new to Spring and not that good at Java and coding in general.
I'm trying to program a Server application with Java Spring where you're able to create different accounts with specific roles. I want my users to be able to see a success or error message on the same page if the creation of an account succeded or failed.
Right now I'm using the error.param th:if tag from https://spring.io/guides/gs/securing-web/
the specific code in my HTML file is:
<div id="error" th:if="${param.error}">
Benutzername existiert bereits.
</div>
<div id="success" th:if="${param.success}">
Das Konto wurde erfolgreich erstellt.
</div>
Which works when I manually put ?success or ?error behind my URL.
I map my POST to the database by this method:
#PostMapping("/create/lieferant/fahrer")
public String submitDriver(#ModelAttribute Driver driver){
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
return "create/lieferant/fahrer?success";
}
The idea is to check if the username is already registered and if so, returning the create/lieferant/fahrer?error but it says
Error resolving template "create/lieferant/fahrer?error", template
might not exist or might not be accessible by any of the configured
Template Resolvers
and the same for ?success.
What I don't understand is: it's working for the login which I've gotten from the Spring getting started guide and it seems to be working without any heavy configurations or so. Atleast I don't see any.
I'd be glad if anyone could help me figuring my issue out.
Thanks a lot.

You could do something like this:
#PostMapping("/create/lieferant/fahrer")
public ModelAndView submitDriver(#ModelAttribute Driver driver){
ModelAndView mav = new ModelAndView();
mav.setViewName("create/lieferant/fahrer");
try {
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
mav.addObject("success", "All was ok");
} catch (Exception e) {
mav.addObject("error", "Error message to change");
}
return "create/lieferant/fahrer?success";
}
You could retrieve messages on page with the two keys "success" and "error"

Related

quickfixj Integration with External OMS

I am doing a development to integrate a non Java OMS system with QuickFIX/J to send buy/sell orders to multiple brokerage systems .
I have written the belog logic to send the messages
I have written this under main function which is in the same class created by implementing Application "public class Initiator implements Application"
InputStream inp = InitiatorSocket.class.getResourceAsStream("test.cfg");
SessionSettings sessionSetting = new SessionSettings(inp);
Application myApp = new Initiator();
FileStoreFactory factory = new FileStoreFactory(sessionSetting);
ScreenLogFactory sfactory = new ScreenLogFactory(sessionSetting);
DefaultMessageFactory defaultMsgFactory = new DefaultMessageFactory();
initiator = new SocketInitiator(myApp, factory, sessionSetting,sfactory,defaultMsgFactory);
initiator.start();
SessionID sessionId = initiator.getSessions().get(0);
I am using the below code to send messages after continuously listening a directory using while Loop.
while(true)
{
readFilefromSrcDirectory();
prepareFixMessage();
Session.sendToTarget(fixMessage, sessionId);
}
My above code is getting executed while debugging but when I run it normally, the Session.sendToTarget(fixMessage, sessionId); and other file read related logic which is next to initiator.start(); is not getting executed.
Kindly note that the same above code is getting executed if we add some console print statements such as System.out.print("Test");
Please help me.
Are your test.cfg settings between debug and run different? I would add console print statements everywhere and work out exactly where the runtime is failing.

How can I get a report URL via the SSRS Web Service?

In my project I have a web reference to SSRS (2005). I would like to display links that can take users directly to rendered reports. I know I can provide a link such as this one:
http://server/ReportServer/Pages/ReportViewer.aspx?/path/to/report&rs:Command=Render&rc:parameters=false&rs:format=HTML4.0
The question is how can I get that URL from the web service? And if the report takes parameters is there a way to provide values to the web service and have it format the URL for me?
I know I can build the URL myself, but I don't like reinventing wheels.
There are a few things to think of about HOW SSRS works and HOW MUCH TIME you want to invest in monkeying with it.
I. You can traverse the root but I highly doubt you meant that. From the root you can add items whether they are directories or reports. And to add to that you can add the parameter directly to the Rest URI to render a report and you may also output a value as well. For example:
Main part of address root:
http:// <server>/ReportServer/Pages/ReportViewer.aspx?
path to directory:
%2fTest
path to report (labeled it the same name lol)
%2fTest
what to do with it? (render it)
&rs:Command=Render
Put a paremeter in and execute it as well (Yes I called my parameter Test too!)
&Test=Value
Put it all together:
http:// <servername>/ReportServer/Pages/ReportViewer.aspx?%2fTest%2fTest&rs:Command=Render&Test=Value
II. You have a database you can query for traversing things but I believe MS does NOT document it well. Generally it is a SQL Server database named 'ReportServer' on whatever server you installed SSRS on. Generally most items are in the table 'dbo.Catalog' with 'Type' of 2 for reports. You can get their info and even parameters from them there.
III. You want to go full bore and dive into .NET and just talk to the service directly? You can do that too. You need the two main services though to do that:
A: http://<Server Name>/reportserver/reportservice2010 (gets info on existing items on server)
B: http:// <Server Name>reportserver/reportexecution2005 (gets info for in code creating reports to types directly in code)
I had another thread on exporting this here: Programmatically Export SSRS report from sharepoint using ReportService2010.asmx; but you will to get info as well probably. ONCE you have created the proxy classes (or made a reference to the web services) you can do code in .NET like so. These services do all the magic so without them you can't really model much in SSRS. Basically I create a class that you pass the 'SERVER' you need to reference to the class like 'http:// /ReportServer'.
private ReportingService2010 _ReportingService = new ReportingService2010();
private ReportExecutionService _ReportingExecution = new ReportExecutionService();
private string _server { get; set; }
public ReaderWriter(string server)
{
_server = server;
_ReportingService.Url = _server + #"/ReportService2010.asmx";
_ReportingService.Credentials = System.Net.CredentialCache.DefaultCredentials;
_ReportingExecution.Url = _server + #"/ReportExecution2005.asmx";
_ReportingExecution.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
public List<ItemParameter> GetReportParameters(string report)
{
try
{
return _ReportingService.GetItemParameters(report, null, false, null, null).ToList();
}
catch (Exception ex)
{
MessageBox.Show("Getting Parameter info threw an error:\n " + ex.Message);
return new List<ItemParameter> { new ItemParameter { Name = "Parameter Not Found" } };
}
}
public List<CatalogItem> GetChildInfo(string dest)
{
try
{
return _ReportingService.ListChildren("/" + dest, false).ToList();
}
catch (Exception ex)
{
MessageBox.Show("Getting Child info of location threw an error:\n\n" + ex.Message);
return new List<CatalogItem> { new CatalogItem { Name = "Path Does Not exist", Path = "Path Does not exist" } };
}
}
ListChildren is the way to go. You can always set the second parameter to true to return all catalog items when you have reports in many folders.
Dim items As CatalogItem() = rs.ListChildren(reportPath, True)

A plain HTML Submit button passes to the controller only after the second click

I have many submit buttons in my plain HTML . The one not working is as below:- the other are as same as below
< form:submit cssClass="action-button" name="excelBTNX" value="Excel" id="excelBTNX" />
The function of the above button in the controller is to create a excel sheet and put in session(I can download it from cookies ) and returns back .
The defination of the corrosponding method in Controller is as same as for other buttons which are working fine .
The problem with this is ,it works only at even count hit .When I click for the first time the page gets refreshed . When I click for the second time , control passes to the controller and my excel comes up as cookies.
I tried to track whether the submit is working or not with javaScript code as
$(‘form’).submit(function(){
alert("event getting fired");
});
and it gives the alert for both the cases.
I have done the validation part from the controller(manually), so local inbuilt validators are not used . So I believe they are not the case.
How do I fix it ?
Controller codes:-
#RequestMapping(value = "execute.action", method = RequestMethod.POST, params = "excelBTNX")
public String excelOut(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("mymodel") myModel model, BindingResult bindingResult, ModelMap modelmap) {
scr14(request).initializeSomeCalculation(model);// some innercalss called to manupulate model
HttpSession session = request.getSession(false);
if(1=1){//CRUD condition here true in READ mode.
model= new myModel ();
}
byte[] excel = createExcelS14(model,request);
String fileName = getExcelName() + ".xls";
String filepath = myFrameWorkUtils.createTempFile(excel, fileName);
if (session != null) {
session.setAttribute(fileDownload, filepath);
}
scr14(request).initializeSomeCalculation(model);
model.setDate(somedate);
return "myPanel";}
Here are some steps:
Check whether this issue is related to your Excel processing or whether it is something with your Controller. I assume you have something like
#RequestMapping(..., params = "excelBTNX")
public ModelAndView next(...)
{ <EXCEL FUNCTIONALITY> }
Just comment out the in the Controller and verify that the method is called every time. Please test this a let us know whether this is working.
What happens that makes you think the Controller is only called at the second click? Maybe the signs that you are looking at don't really mean that the controller is only called every second click. Please explain.
Fix if (1=1) code. = in Java is the assignment operator, == is the comparison operator. I assume you want to do a comparison. It also seems like you simplified this part of the code, but it may actually be the problem. Please post the actual code here.
I don't see anything about cookies here. It looks to me like you are creating a temporary Excel file, and setting the name of the file in the session.
session.setAttribute(fileDownload, filepath) cannot work, since the key of the session attribute map is of type String. It should probably be session.setAttribute("fileDownload", filepath).
Can you see whether there is a new temp Excel file generated with each click? You should be able to tell by the timestamp.
This may still not point to the problem, but it will certainly get us closer.

JavaMail SMTPSendFailedException

I am writing a bulk email program using the JavaMail api. I have a Microsoft Exhange server which I am trying to send the emails in to. When I run my program I get the following error:
**com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.postMail(SendEmail.java:100)
at EmailGenerator.main(EmailGenerator.java:52)**
The part of my code trying to send the message is as follows:
Properties props = new Properties();
props.put("mail.smtp.host", email_server);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
class EmailAuthenticator extends Authenticator {
String user;
String pw;
EmailAuthenticator (String FROM, String PASSWORD)
{
super();
this.user = FROM;
this.pw = PASSWORD;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Session session = Session.getInstance(props, new EmailAuthenticator(USER, PASSWORD));
session.setDebug(debug);
System.out.println("Session created");
.. CREATED MESSAGE HERE...
Transport transport = session.getTransport("smtp");
transport.connect(exchange_server,user,password);
transport.send(msg);
transport.close();
I wonder am I missing some configuration on the Exchange server side, or is an issue with my code?
OK I figured out where I was going wrong here and am posting up the answer incase anybody else can get some value out of it. I had the following line of code:
props.put("mail.smtp.auth", true);
This was telling my application that it needed to authenticate to the SMTP server, when in fact it didnt. This was causing my application from logging into the SMTP server and sending the email and thus producing the error message. Setting this property to false or not having this line of code fixed the issue for me. This line of code is only necessary for SMTP servers that require you to login, which my Exchange server didnt.

Handling database connection exceptions with Linq to SQL and Rx

I am trying learn how to best use the Reactive Extensions library and have set up simple test WPF application to view a logging database table. In a ViewModel class I am populating an ObservableCollection with the first 100 log entries from a Linq to Sql DataContext and I'm trying to use Rx to keep the UI responsive.
The following snippet works unless the database is unavailable at which point the app throws an exception and crashes. Where would be the best place to handle database connection exceptions and why are they not handled by the OnError method of the Observer?
ObservableCollection<LogEntry> _logEntries = new ObservableCollection<LogEntry>();
DataContext dataContext = new DataContext( "connection string" );
(from e in dataContext.LogEntries
select e).Take( 100 ).ToObservable()
.SubscribeOn( Scheduler.ThreadPool )
.ObserveOnDispatcher()
.Subscribe( _logEntries.Add, ex => System.Diagnostics.Debug.WriteLine( ex.ToString() ) );
Try this instead of ToObservable:
public static IObservable<T> SafeToObservable(this IEnumerable<T> This)
{
return Observable.Create(subj => {
try {
foreach(var v in This) {
subj.OnNext(v);
}
subj.OnCompleted();
} catch (Exception ex) {
subj.OnError(ex);
}
return Disposable.Empty;
});
}
In general though, this isn't a great use of Rx since the data source isn't very easy to Rx'ify - in fact, the code will execute most of the work on the UI thread, send it out to random worker threads, then send it back (i.e. completely wasted work). Task + Dispatcher.BeginInvoke might suit you better here.