my response.sendRedirect(); is not working - java

I'm trying to redirect a new page with this syntax
try {
usuarios usu = new usuarios();
usu.setNombreusuario(request.getParameter("parCodigo"));
System.out.println(usu.getUsuario());
usu.setContrasena(request.getParameter("parContrasenha"));
System.out.println(usu.getContrasena());
usu = usuariosDAO.login(usu);
System.out.println("es valido? " + usu.isValid());
if (usu.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("usuario", usu.getUsuario());
response.sendRedirect("/KolaEscocesaCRM/menumobile.jsp");
return;
} else {
response.sendRedirect("/KolaEscocesaCRM/loginmobile.jsp");
}
} catch (Exception ex) {
ex.printStackTrace();
}
My problem is that when I submit I get this:
http://localhost:8084/KolaEscocesaCRM/srvMenu2?parCodigo=admin&parContrasenha=kola
I don't know what to do please any help would be fine

If you get a dear 404
Most of the time, because the entry application is mapped into something like /myapp instead of /(root)
The server says to the browser go to /KolaEscocesaCRM/loginmobile.jsp where it should be /.myapp/KolaEscocesaCRM/loginmobile.jsp
The simplest way is changing the context-path to root (/ or empty string)

Related

How to control loading in Selenium WebDriver?

When i try to run my scripts and call this method, when i enter URL into address bar, loading starts and loading take much time,
but sometime when refresh page page proper loaded on the spot so please help me out.
How can i handle this issue in automation.
public static MainPage LaunchBrowserAndLogin(String currentScriptName, String LoginUser) throws Throwable {
try {
killprocess();
LaunchBrowser();
String siteUrl = null;
if (excelSiteURL != null) {
if (excelSiteURL.equalsIgnoreCase("")) {
siteUrl = CONFIG.getProperty("siteName");
}else{
if (excelSiteURL.contains("SiteName")) {
siteUrl=excelSiteURL;
}
}
} else {
siteUrl = CONFIG.getProperty("SiteName");
}
driver.get("https://QA.YYYY.com/ABC9/#/login");
System.out.println("URL for Login: "+siteUrl);
CheckErrorPageNotFound();
driver.manage().timeouts().pageLoadTimeout(Long.parseLong(CONFIG.getProperty("pageLoadTime")), TimeUnit.SECONDS);
enterUserID(currentScriptName, LoginUser);
enterPasswd(currentScriptName);
MandatoryFieldSkipErrMsg("~~~~~~ Mandatory Field is skipped, Getting Error: ");
ClickLoginButton();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
}catch(){
DesireScreenshot("AfterClickOnLoginButton");
String stackTrace = Throwables.getStackTraceAsString(t);
String errorMsg = t.getMessage();
errorMsg = "\n\n\n\n Login failed.See screenshot 'LoginFailed' \n\n\n\n" + errorMsg + stackTrace;
Exception c = new Exception(errorMsg);
ErrorUtil.addVerificationFailure(c);
killprocess();
IsBrowserPresentAlready = false;
throw new Exception(errorMsg);
}
return new MainPage(driver);
}
First you need to check whether page is fully loaded or not in that case we will use the below code.
new WebDriverWait(driver, 5).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Then as per your question I believe that some web elements are not properly getting loaded. So what you can do add one more explicit wait and put that wait inside try catch block as shown below.
try
{
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.id("Abhishek")));
System.out.println("Completed");
}
catch( TimeoutException e)
{
System.out.println("Reloading");
driver.navigate().refresh();
}
If it is unable to find that element then in the catch block it will refresh the page and in this way you can proceed further.
Note: I could have written the script for you but application url is invalid.

Cookie is deleted locally but not when deployed

I'm trying to invalidate a cookie created by my code. I want to do this creating a new endpoint to logout. I have to choose between two paths to redirect depending on whether an endpoint returns data or not. When I run the code locally it works like a charm. Deletes the cookie and redirects to the correct url but, if I test it deployed on a remote server, it doesn't work, meaning that it redirects correctly but doesn't expire the cookie nor modifies its value. My whole code must be a back end one so i cannot redirect to a javascript that would delete the cookie and redirect again.
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public void cookieKiller(
#CookieValue(name = "theCookie", required = false) Cookie myCookie,
HttpServletResponse response, HttpServletRequest request) {
if (myCookie != null) {
} else { // Just being cautious, if the cookie is not retrieved, would be overwritten anyway just in case
myCookie = new Cookie("theCookie","");
}
myCookie.setMaxAge(0);
myCookie.setValue("");
myCookie.setPath("/");
response.addCookie(myCookie);
boolean endpointHealthy = true;
if(haveITheEndpointUrls()) {
endpointHealthy = false;
} else {
try {
String eaiResponseJson = restTemplateAutowired.getForEntity(new URI(oneUrl),String.class).getBody();
if (eaiResponseJson != null && !eaiResponseJson.isBlank()) {
response.sendRedirect(eaiSamlUrl);
} else {
endpointHealthy = false;
}
} catch (IOException e) {
endpointHealthy = false;
} catch (ResourceAccessException e) {
endpointHealthy = false;
} catch (HttpClientErrorException e) {
endpointHealthy = false;
} catch (Exception e) {
endpointHealthy = false;
}
}
if (!endpointHealthy) {
try {
response.sendRedirect(request.getContextPath() + "/internal/Path");
} catch (IOException ex) {
// ...
}
}
}
If I add a new cookie, the domain that is generated is different than the original one, introduced in the front part of the application. Being the back one "domain.com" and the front one ".domain.com" so I guess it's a domain thing
I've been trying to change the path, to change the value, etc, but it won't work either, i've surfed stackoverflow a lot in search for an answer but without any result. Some suggestion or clue about domains or any hint that i could've been missing?
My code in local was generating a cookie like domain.com but SHibboleth needs cookie domains starting with a dot. I tried to create a cookie this way but that was not possible in Tomcat unless you use a LegacyCookieManager.

Calling Active-x object from Javascript inside Java code

I'm trying to get windows username from liferay portlet in java code using javascript and active-x.
When I run the code only with javascript and acitive-x on plain HTML it works.
But when I put it in java, it doesn't work.
Here is my code:
String script = "function getUser() {return ((new ActiveXObject('WScript.NetWork')).UserName); }";
try {
engine.eval(script);
} catch (ScriptException e) {
e.printStackTrace();
}
Invocable inv = (Invocable) engine;
try {
log.info("try invoke script");
String teste = (String) inv.invokeFunction("getUser");
log.info("meu teste " +teste);
} catch (ScriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
When I change the content on function for somthing else like returning string it prints the result.
Java-s JavaScript doesn't have Active X capabilities, but you don't have to use JavaScript to get the running machines users username.
Get login username in java
If you want to know client-s OS-s username then one approach would be to use client side JavaScript to find it out and submit this information to server side via AJAX.

How to get OrganizationId after Login -Liferay

I am using liferay6.I deployed my web application inside liferay.After Login,it is redirecting to one page.In that jsp page,i want to set organization id of logged in user in a javascript variable.How can i do this.Can anyone pls explain.
You can get userId of logged in User by themeDisplay.getUserId()
Using this userId, you can get the User's Organizations by OrganizationLocalServiceUtil.getUserOrganizations(userId)
Then you can iterate through the Organizations to get the organizationId you require.
com.liferay.portal.model.Group currentGroup;
long organizationId = 0;
try {
currentGroup = themeDisplay.getLayout().getGroup();
if (currentGroup.isOrganization()) {
organizationId = currentGroup.getClassPK();
}
} catch (Exception e) {
log.error(e);
}
return organizationId;

Getting NullPointerException with row.setAttribute on Oracle ADF

I'm now trying to learn Oracle ADF and I'm getting a NullPointerException while running the following code on a Java bean.
Can you help me figure out what I'm doing wrong please? This is being invoked from a button on a JSPX page.
public String cb1_action() {
try{
BindingContext bindingctx = BindingContext.getCurrent();
BindingContainer bindings = bindingctx.getCurrentBindingsEntry();
DCBindingContainer bindingsImpl = (DCBindingContainer)bindings;
DCIteratorBinding iter = bindingsImpl.findIteratorBinding("ViewObj1Iterator");
Row row = iter.getCurrentRow();
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste");
}
catch(Exception e) {
System.out.println("Excepcao em: ");
e.printStackTrace();
}
return null;
}
According to the Stack trace, the error occurs on the first row.setAttribute() line.
Also, I'm using the latest version of JDeveloper with the integrated WebLogic server.
Best regards,
Pedro
Row row = iter.getCurrentRow();
if(row != null){
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste"); //name?
}
The info that you get the error at
row.setAttribute("Id", 123);
let me think that you try to alter the primary key attribute of the row, which is not allowed. Not sure about this as you did not mention the error you get.
Ok, so here's how I figured out how to get around this:
First, I asked jDeveloper to generate a class for the Application Module.
In that class, I added the following methods:
public void testEntityObject()
{
System.out.println("Let's try our Entity Object...");
try
{
EntityDefImpl entity = TesteEOImpl.getDefinitionObject();
TesteEOImpl ti = (TesteEOImpl)entity.createInstance2(getDBTransaction(), null);
ti.setId(new BigDecimal(123));
ti.setNome("Entity Object test...");
getDBTransaction().commit();
System.out.println("Looks good :-)");
}
catch(Exception e)
{
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
public void testViewObject() {
System.out.println("Let's try our View Object...");
ViewObjectImpl vo = this.getTeste1();
try{
Row row = vo.createRow();
row.setAttribute("Id", 234);
row.setAttribute("Nome", "VO test");
vo.insertRow(row);
getDBTransaction().commit();
System.out.println("Looks good :-)")
}
catch(Exception e) {
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
These methods are being called by a managed bean that is connected to two buttons on the page. This managed bean has the following methods. I'll post just one of them as only the method names change:
public String cb1_action() {
try{
FacesContext fctx = FacesContext.getCurrentInstance();
BindingContext bindingContext = BindingContext.getCurrent();
DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
AppModuleAMImpl am = (AppModuleAMImpl)dc.getDataProvider();
am.criarTesteComEntityObject();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
I know this is not rocket science or anything but it took a while for me to get there...
Basically, your answers helped me a lot to go and investigate what was happening. The cause? Poor design! ADF is supposed to be organized...
Thank you everyone! :D

Categories