How - to launch print dialog when showing printable page in Oracle ADF - oracle-adf

Hello I am developing an ADF Web application. In this I have test.jsf page and a showPrintablePage behaviour command button. When user click the button adf just shows a printable page in new window. But when the user clicks on the button it should directly show in print window of browser. For this I got the following code from ADF Code Corner.
public void beforePhaseMethod(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
FacesContext fctx = FacesContext.getCurrentInstance();
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
if (adfFacesContext.getOutputMode() == OutputMode.PRINTABLE) {
ExtendedRenderKitService erks = null;
erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
erks.addScript(fctx, "window.print();");
}
}
}
I have follwed the process specified in the document. And the follwoing is the test.jsf page code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=UTF-8"%>
<%# taglib uri="http://xmlns.oracle.com/adf/faces/rich" prefix="af"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view beforePhase="#{viewScope.PieBean.beforePhaseMethod}">
<af:document title="printTest" id="d1">
<af:form id="f1">
<af:commandButton text="commandButton 1" id="cb1">
<af:showPrintablePageBehavior/>
</af:commandButton>
<af:goButton text="goButton 1" id="gb1"/>
</af:form>
</af:document>
</f:view>
but it is showing in test.jsf property inspector beforePhaseMethod is an unknown property.
And the final out is as follows
Please help.
Thanks in advance.

Did you register the bean in adfc-config or if you are using the taskflow, then in taskflow configuration. Also from the screenshot, it seems you are getting the desired output.

Related

Can't view the pdf in the browser after enabling SSL, instead.. it is downloaded (Asp.net MVC 5)

Before Enabling SSL, i can view pdf in the browser.
This link has no https ( http://localhost:50895/Home/BookDetail/1 )
After Enabling SSL, i can't view PDF and it is downloaded instead of showing it.This link has https ( https://localhost:44382/Home/BookDetail/1 )
I have tried iframe , object , embed in view
with Both Functions in Controller below.
==========Controller =================================================
[HttpGet]
public ActionResult GetBookSampleByPath(string FullPath)
{
return File(FullPath, "application/pdf");
}
[HttpGet]
public FileStreamResult GetPDF(string FullPath)
{
FileStream fs = new FileStream(FullPath, FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
==========View =================================================
<iframe src="#Url.Action("GetBookSampleByPath","Ajax",new { FullPath=Model.FilePath+Model.FileName })" type="application/pdf" style="width:100%; height:100%;" frameborder="0"></iframe>
<object data="#(Url.Action("GetPDF","Ajax",new { FullPath=Model.FilePath+Model.FileName }))" type="application/pdf" style="width:100%; height:100%;">
alt : test.pdf
</object>
<embed src="#Url.Action("GetBookSampleByPath","Ajax",new { FullPath=Model.FilePath+Model.FileName })" type="application/pdf" style="width:100%; height:100%;" />
=================================================
All Three View work if i switch back to
http://localhost:50895/Home/BookDetail/1.
And Also Both function in controller is working too.
But it is not working if i open from
https://localhost:44382/Home/BookDetail/1.
Pdf is not showing and downloaded instead.
Does Http:// and Https:// has something to do with it?
I am confused.
Please Help me !
This is screenshot for http://localhost:50895/Home/BookDetail/1
This is screenshot for https://localhost:44382/Home/BookDetail/1
Well...
I just happen to find out this solutions...Not an actual solutions..
========================================================
Here is how i do this
var Host = "your hosting address eg: www.google.com";
var Path = "your path eg: /upload/pdf/";
var filename = "a.pdf";
<embed src='https://drive.google.com/viewerng/viewer?embedded=true&url=#(Host+Path +filename)' width="500" height="375" style="width:100%; height:100%;">
=================================================================
This is not a good solutions..
i am still searching for another solution...
but i hope it help

InvalidOperationException when sending get request in browser tab despite working in ajax

I have an ajax request done with angular, its very basic, here is the code:
$http.get(url,data).success(function(data){
//Do Stuff with data
});
This works fine and the data is all good.
But when i inspect the request on the network tab in Chrome, and i right click on the request and click Open in new tab I get the following error:
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
Here is the api controller code:
[AcceptVerbs("GET")]
public object SearchRetailers(long userId, string term)
{
List<Tuple<int,string>> res = userService.SearchRetailers(userId, term);
return res.Take(20).Select(x => new
{
label = x.Item2 + " - " + x.Item1,
value = x.Item1
});
}
The code works fine and does not throw any exceptions.
i think this might have something to do with the request headers, i just want it to work when opened in the browser regularly.
Its important to note I am using Umbraco so the apicontroller inherits UmbracoApiController class.
Also, i don't see any apiwebconfig file anywhere so i cant implement other solutions i found, and my global asax also looks significantly different than in other questions i encountered, here is how it looks:
<%# Application Inherits="Umbraco.Web.UmbracoApplication" Language="C#" %>
<script RunAt="server">
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Contains("/api/");
}
</script>

Oracle ADF: Close popup after downloading file

So here's the thing. I have a popup that has a button, the button itself has a fileDownloadActionListener, this one is responsible for downloading an excel file. So what I need basically is to hide the popup right after I generate the file.
Here's my .jspx file (Just the popup)
<af:popup childCreation="deferred" autoCancel="enabled"
id="myPopUp"
contentDelivery="lazyUncached"
binding="#{viewScope.mbMyBean.myPopUp}"
partialTriggers="b17">
<af:dialog id="d16" type="cancel"
title="Do you wish to download a file?"
inlineStyle="width:400px;">
<af:panelGroupLayout id="pgl32"
inlineStyle="max-width: 200px;">
<af:outputText value="You're about to download a file. Ready?" id="ot45"
/>
</af:panelGroupLayout>
<f:facet name="buttonBar">
<af:button text="GO" id="b17"
<af:fileDownloadActionListener contentType="excelHTML"
filename="#{viewScope.mbMyBean.FileName}"
method="#{viewScope.mbMyBean.GenerateEmptyExcel}"
/>
</af:button>
</f:facet>
</af:dialog>
</af:popup>
And here's the java method:
public void GenerateEmptyExcel(FacesContext facesContext, OutputStream outputStream) {
try {
HSSFWorkbook wb1 = generateEmptyExcelFile();
wb1.write(outputStream);
outputStream.flush();
outputStream.close();
this.myPopUp.hide();
AdfFacesContext.getCurrentInstance().addPartialTarget(this.myPopUp);
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
PROBLEM
The popup won't hide.
NOTES
The popup is properly binded within the bean
I do not own this code and I'm doing a maintainance.
I do not know why the programmer used System.gc() since I consider it as a bad practice. Here's a good reason
I had the same problem after downloading a file, you should try this:
Use a resource type javascript to trigger an event click in commandButton
<af:resource type="javascript">
function customHandler(evt) {
console.log(evt);
var exportCmd = AdfPage.PAGE.findComponentByAbsoluteId("pt1:b17");
console.log(exportCmd);
var actionEvent = new AdfActionEvent(exportCmd);
console.log(actionEvent);
actionEvent.forceFullSubmit();
actionEvent.noResponseExpected();
actionEvent.queue(false);
setTimeout(function(){hidePopup();}, 1000);
}
function hidePopup() {
var popup = AdfPage.PAGE.findComponent("pt1:popupAceptarDescargarPlantilla::content");
popup.hide();
}
</af:resource>
You should have the following buttons:
<af:commandButton text="Aceptar" id="b17" visible="false" clientComponent="true" partialSubmit="true">
<af:fileDownloadActionListener contentType="excelHTML" filename="#{viewScope.mbGestionArchivos.nombre_archivo}" method="#{viewScope.mbGestionArchivos.generateExcelVacio}"/>
</af:commandButton>
<af:button text="Aceptar" id="botonPrueba" actionListener="#{viewScope.mbInformeDetalle.prepareForDownloadAction}" clientComponent="true" partialSubmit="true"></af:button>
This is the java method called by the button :
public void prepareForDownloadAction(ActionEvent act) {
FacesContext context = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(),
ExtendedRenderKitService.class);
erks.addScript(context, "customHandler();");
}
The hidden button is triggered using javascript a ADF methods, the magic happen in the setTimeout, When executing this function we avoid for a second to make submit but the request travels to the server, here we can observe how the file is started.
Ideally this.myPopUp.hide(); should close the popup but if it is not working for some reason, you can try closing the popup using javascript like:
public static void hidePopup(String popupId){
if (popupId != null)
{
ExtendedRenderKitService service =
Service.getRenderKitService(FacesContext.getCurrentInstance(),
ExtendedRenderKitService.class);
StringBuffer hidePopup = new StringBuffer();
hidePopup.append("var popupObj=AdfPage.PAGE.findComponent('" + popupId +
"'); popupObj.hide();");
service.addScript(FacesContext.getCurrentInstance(), hidePopup.toString());
}
}
You can get the popup clientId that you can pass into hidePopup using: this.myPopUp.getClientId(FacesContext.getCurrentInstance());

Getting the database in struts2

i've done a struts2 login action using mysql database which is as shown below.
for the initial login action i'm using LoginActionBean where i checks the username and password. After loging into the Main page there i need to get the team details again from the database. For that i used jsp scriplet tags. Can anyone tell me another way in which to access the team details from the database through javabeans (not through LoginActionBean) and without using the jsp scriplets.
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
</head>
<body>
<s:form action="log">
<s:textfield label="USERNAME" name="uname"/>
<s:password label="PASSWORD" name="pass"/>
<s:submit label="SUBMIT"/>
</s:form>
</body>
</html>
Main.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="DbCon.DataConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Welcome to Employee Home!</h1>
SELECT A TEAM:<select name="team">
<%
DataConnection db=new DataConnection();
ResultSet rs=db.exeQuery("select * from team");
while(rs.next())
{
%>
<option value="<%=rs.getString("teamname")%>" ><%=rs.getString("teamname")%></option>
<%
}
%>
</select>
</body>
</html>
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="log" class="login.Action.LoginActionBean" >
<result name="success">/Main.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
DataConnection.java
package DbCon;
import java.io.FileInputStream;
import java.sql.*;
public class DataConnection
{
Connection con;
Statement stmt;
PreparedStatement pstmt;
ResultSet rs=null;
public DataConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
stmt=con.createStatement();
con.setAutoCommit(false);
}catch(Exception e){
System.out.println("Err in constructor"+e);
}
}
public ResultSet exeQuery(String query)
{
try
{
// con.commit();
rs=stmt.executeQuery(query);
}catch(Exception e){System.out.println(e);}
return rs;
}
public int exeUpdate(String query)
{
int i = 0;
try
{
//con.commit();
i=stmt.executeUpdate(query);
con.commit();
}catch(Exception e){System.out.println(e);}
return i;
}
}
LoginActionBean.java
package login.Action;
import DbCon.DataConnection;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginActionBean extends ActionSupport {
public String uname,pass;
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String execute() throws SQLException
{
DataConnection db=new DataConnection();
ResultSet rs=db.exeQuery("select * from admin where name='"+uname+"' and pass='"+pass+"'");
if(rs.next())
return SUCCESS;
else
return ERROR;
}
}
Well you have already done most of the work, so you can do some simple things like in you action class
Create a bean say TeamDetails with properties you want to show in JSP
define this bean in your Action class and fill it using DB call
use OGN in your JSP to access data and show it using struts2 tag.
Action class:
public class TeamDetailAction extends ActionSupport{
List<TeamDetailData> teamDetails;
//getter and setter
public String execute() throws Exception{
teamDetails=fill it by retrieving from BD
}
}
TeamDetailData Java
public class TeamDetailData{
private teamMemberName;
// other properties
//getter and setters
}
on your JSP using OGNL iterator tag to show the data
JSP page
<s:iterator value="teamDetails">
<p>Name : <s:property value="teamMemberName"/></p>
</s:iterator>

Login Test with Jenkins and Symfony2

I configured jenkins in order to automating the tests for my project. The unit tests work well. Now I want to do some test with my database. For example the login test: enter the username, the password (submit the form). Do you have an idea of how to do this? Thank you.
Here is the test I want to do but it does not work:
Get the home page, test if the link FAQ is present two times, click on the first FAQ link, test if the link RMK is present, click on login, test if forgot password link is present, enter my username and my password submit the form, get the profile page, test if My Profile link is present.
<?php
namespace RMK\SocialBundle\Tests\FunctionalTests\Controller\Website;
use RMK\SocialBundle\Controller\Website;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
class HomeControllerTest extends WebTestCase
{
public function testViewFAQ(){
$client = static::createClient();
$crawler = $client->request('GET', '/home');
$this->assertEquals(2, $crawler->filter('a:contains("FAQ")')->count());
$this->assertEquals(2, $crawler->filter('a:contains("FAQ")')->count());
$faqlink = $crawler->filter('a:contains("FAQ")')->eq(0)->link();
$crawler = $client->click($faqlink);
$this->assertEquals(1, $crawler->filter('a:contains("RMK")')->count());
$loginLink = $crawler->filter('a:contains("Login")')->eq(0)->link();
$crawler = $client->click($loginLink);
$this->assertEquals(1, $crawler->filter('a:contains("Forgot Password?")')->count());
$form = $crawler->selectButton('_submit')->form();
$form['_username'] = 'username';
$form['_password'] = 'test';
$crawler = $client->submit($form);
$crawler = $client->followRedirect();
$crawler = $client->request('GET', '/profile');
$this->assertEquals(1, $crawler->filter('a:contains("My Profile")')->count());
}
}
?>
The last assert failed by saying: Failed asserting that 0 matches expected 1. When I put var_dump(print_r($client->getResponse()->getContent())); just before this last assert I got this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=/home" />
<title>Redirecting to /home</title>
</head>
<body>
Redirecting to /home.
</body>
</html>bool(true)
I am sure I am missed something but I don't know what. Do you have an idea? Thx.
P.S: I am on Ubuntu 12.04.

Resources