I am very new to struts and the application is using struts , and every time I submit the form the old values are submitted until and unless I change the values by selecting different options from drop down or I go to other tab and come back again to the same tab then in this case the values are resetting..
In my scenario what I want to achieve is to reset some of the values after they executed once.on the basis of those values I have to search some data and show it on the form, if I don't remove this value then it .
This is my execute method :
public class ListTerminalDevicesAction extends BaseQueryAction {
private RetailerService retailerService;
private DataBinder<OmposTerminalQuery> dataBinder;
private TerminalDeviceService terminalDeviceService;
private ImportCSVService importCSVService;
#Inject
public void setImportCSVService(ImportCSVService importCSVService) {
this.importCSVService = importCSVService;
}
#Inject
public void setRetailerService(final RetailerService retailerService) {
this.retailerService = retailerService;
}
#Inject
public void setTerminalDeviceService(final TerminalDeviceService terminalDeviceService) {
this.terminalDeviceService = terminalDeviceService;
}
#Inject
private DataBinder<OmposTerminalQuery> getDataBinder() {
if (dataBinder == null) {
final BeanBinder<OmposTerminalQuery> binder = BeanBinder.instance(OmposTerminalQuery.class);
binder.registerBinder("pageParameters", DataBinderHelper.pageBinder());
binder.registerBinder("retailer", PropertyBinder.instance(OmposRetailer.class, "retailer"));
binder.registerBinder("branch", PropertyBinder.instance(OmposBranch.class, "branch"));
binder.registerBinder("store", PropertyBinder.instance(OmposStore.class, "store"));
binder.registerBinder("terminalId", PropertyBinder.instance(String.class, "terminalId"));
binder.registerBinder("terminalSearchByTid",
PropertyBinder.instance(String.class, "terminalSearchByTid"));
dataBinder = binder;
}
return dataBinder;
}
#Override
protected void executeQuery(ActionContext context, QueryParameters queryParameters) {
final OmposTerminalQuery query = (OmposTerminalQuery) queryParameters;
query.setResultType(ResultType.PAGE);
// List<OmposRetailer> retailerList = retailerService.searchRetailers();
// context.getRequest().setAttribute("retailers", retailerList);
// if (query.getRetailer() != null) {
// OmposBranchQuery branchQuery = new OmposBranchQuery();
// branchQuery.setOmposRetailer(query.getRetailer());
// List<OmposBranch> branchList = retailerService.searchBranchByRetailer(branchQuery);
// context.getRequest().setAttribute("branches", branchList);
// if (query.getBranch() != null) {
// OmposStoreQuery storeQuery = new OmposStoreQuery();
// storeQuery.setOmposBranch(query.getBranch());
// List<OmposStore> storeList = retailerService.searchStore(storeQuery);
List<OmposStore> storeList = retailerService.searchStores();
context.getRequest().setAttribute("stores", storeList);
if (query.getStore() != null) {
ListTerminalDevicesForm form = context.getForm();
final FormFile uploadTerminal = form.getUploadTerminal();
if (uploadTerminal != null && uploadTerminal.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForTerminal = new ImportCSVDTO();
// uploadDtoForTerminal.setRetailer(query.getRetailer());
// uploadDtoForTerminal.setBranch(query.getBranch());
uploadDtoForTerminal.setStore(query.getStore());
int records = importCSVService.importCSV(TMSEntity.TERMINAL, uploadDtoForTerminal,
uploadTerminal.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgTerminal", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadTerminal.destroy();
}
}
OmposTerminalQuery terminalQuery = new OmposTerminalQuery();
List<OmposTerminal> terminalList = null;
if (query.getStore() != null && query.getTerminalSearchByTid() != null) {
terminalQuery.setTerminalSearchByTid(query.getTerminalSearchByTid());
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchTerminalByTidAndStoreId(terminalQuery);
} else {
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchByStore(terminalQuery);
}
context.getRequest().setAttribute("terminals", terminalList);
if (query.getTerminalId() != null) {
OmposTerminal omposTerminal = new OmposTerminal();
omposTerminal.setTerminalId(query.getTerminalId());
OmposDeviceQuery deviceQuery = new OmposDeviceQuery();
deviceQuery.setOmposTerminal(omposTerminal);
final FormFile uploadDevice = form.getUploadDevice();
if (uploadDevice != null && uploadDevice.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForDevice = new ImportCSVDTO();
uploadDtoForDevice.setRetailer(query.getRetailer());
uploadDtoForDevice.setBranch(query.getBranch());
uploadDtoForDevice.setStore(query.getStore());
uploadDtoForDevice.setTerminal(new OmposTerminal(null, query.getTerminalId(), null));
int records = importCSVService.importCSV(TMSEntity.DEVICE, uploadDtoForDevice,
uploadDevice.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgDevice", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadDevice.destroy();
}
}
context.getRequest().setAttribute("terminalId", query.getTerminalId());
List<OmposDevice> deviceList = terminalDeviceService.searchByTerminal(deviceQuery);
context.getRequest().setAttribute("devices", deviceList);
}
}
// }
// }
}
#Override
protected QueryParameters prepareForm(ActionContext context) {
final ListTerminalDevicesForm form = context.getForm();
final OmposTerminalQuery query = getDataBinder().readFromString(form.getQuery());
return query;
}
#Override
protected boolean willExecuteQuery(final ActionContext context,
final QueryParameters queryParameters) throws Exception {
return true;
}
}
I have to reset "terminalSearchByTid" field after the execution.
override Struts' Action reset() method
Related
Is there any equivalent method for getJavascript in pdf reader in itext7? we are looking for sanitizing the pdf document for malicious content using itext7.
As far as I can see there is not a dedicated method for that in iText 7.
Essentially, though, the old PdfReader.getJavaScript() method merely looked for the JavaScript name tree and put all the values into a string buffer.
You can output these values like this in iText 7:
PdfNameTree javascript = pdfDocument.getCatalog().getNameTree(PdfName.JavaScript);
Map<String, PdfObject> objs2 = javascript.getNames();
for (Map.Entry<String, PdfObject> entry : objs2.entrySet())
{
System.out.println();
System.out.println(entry.getKey());
System.out.println();
PdfObject object = entry.getValue();
if (object.isDictionary()) {
object = ((PdfDictionary)object).get(PdfName.JS);
if (object.isString()) {
System.out.println(((PdfString)object).getValue());
} else if (object.isStream()) {
System.out.println(new String(((PdfStream)object).getBytes()));
}
}
System.out.println();
}
(ShowDocumentLevelJavaScript test testREJECT_ContainsJavaScript)
Obviously you can in a similar manner collect the pieces of JavaScript into some string buffer.
In a comment James claimed
I tried using (and extending) your answer but cannot detect the JavaScript popup that fires when I open a sample PDF
Applying the above code to the PDF file provided by #James I get the output:
e.pdf Freeware Hinweis
if (app.viewerVersion>=5)
{
var result=app.alert(
"Diese Datei wurde mit der Freeware Version von CIB e.pdf erzeugt.\n\nMöchten Sie nähere Informationen?"
, 3
, 2
, "e.pdf Freeware Hinweis"
);
if (result==4)
getURL("http://www.cib.de/deutsch/products/pdfplugin/epdfbeta.asp", false);
}
The JavaScript popup can clearly be seen as an app.alert call here. Thus, I cannot reproduce the issue.
For anyone able to use iText 7.1.1 or newer, I expect the solution by mkl to be better. If you are forced to use iText 7.0.5 like I was, the following worked for my reference PDF:
private static boolean hasJavascript(PdfDocument pdfDoc, String theFile) {
int n = pdfDoc.getNumberOfPages();
for (int i = 1; i <= n; i++) {
PdfPage pdfPage = pdfDoc.getPage(i);
List<PdfAnnotation> annotList = pdfPage.getAnnotations();
if (ListUtility.hasData(annotList)) {
for (PdfAnnotation annot : annotList) {
if (annot.getSubtype().equals(PdfName.Link)) {
continue;
}
PdfDictionary annotationAction = annot.getPdfObject().getAsDictionary(PdfName.A);
if (annotationAction != null && PdfName.JavaScript.equals(annotationAction.get(PdfName.S))) {
PdfString javascript = annotationAction.getAsString(PdfName.JS);
if (StringUtility.hasData(javascript.getValue())) {
log.debug("JavaScript found in PDF on page " + i);
log.trace(javascript.getValue());
return true;
}
}
}
}
}
String javaScriptInPdf = getJavaScriptFromPdfDocument(pdfDoc);
if (StringUtility.hasData(javaScriptInPdf)) {
log.debug("JavaScript found using iText 7");
log.trace(javaScriptInPdf);
return true;
}
log.debug("JavaScript not found in PDF");
return false;
}
//
private static String getJavaScriptFromPdfDocument(PdfDocument pdfDoc) {
StringBuilder strBuf = new StringBuilder();
try {
PdfDictionary pdfDictionaryCatalog = pdfDoc.getCatalog().getPdfObject();
if (pdfDictionaryCatalog == null) {
log.trace("getJavaScriptFromPdfDocument(): pdfDictionaryCatalog null; return null");
return null;
}
PdfDictionary pdfDictionaryNames = pdfDictionaryCatalog.getAsDictionary(PdfName.Names);
if (pdfDictionaryNames == null) {
log.trace("getJavaScriptFromPdfDocument(): PdfDictionary for PdfName.Names null; return null");
return null;
}
PdfDictionary pdfDictionaryJavaScript = pdfDictionaryNames.getAsDictionary(PdfName.JavaScript);
if (pdfDictionaryJavaScript == null) {
log.trace("getJavaScriptFromPdfDocument(): PdfDictionary for PdfName.JavaScript null; return null");
return null;
}
Set<Entry<PdfName, PdfObject>> set = pdfDictionaryJavaScript.entrySet();
for (Entry<PdfName, PdfObject> pdfObjectEntry : set) {
PdfObject pdfObj = pdfObjectEntry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
} else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && pdfObjectEntry.getKey().getValue().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
}
catch (Exception e) {
log.debug(e,e);
}
return strBuf.toString();
}
//
private static void getJavaScriptFromPdfArray(PdfArray pdfArray, StringBuilder strBuf) {
if (pdfArray == null) {
return;
}
for (PdfObject pdfObj : pdfArray) {
// To get same output as getJavaScriptUsingiText559(), not appending String values found in array to strBuf
if (pdfObj == null) {
continue;
}
else if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}
else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
}
}
}
//
private static void getJavaScriptFromPdfDictionary(PdfDictionary pdfDict, StringBuilder strBuf) {
if (pdfDict == null) {
return;
}
PdfObject pdfObj = pdfDict.get(PdfName.JS);
if (pdfObj == null) {
return;
}
if (pdfObj.isString()) {
strBuf.append(((PdfString) pdfObj).getValue());
}
else if (pdfObj.isStream()) {
strBuf.append(getStringFromPdfStream((PdfStream) pdfObj, TRUNCATE_PDF_STREAM_AT));
}
else if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary) pdfObj, strBuf);
}
else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
}
}
I know this is a very old thread, still sharing my code to add couple of things, on top of what mkl and James wrote.
// iText V 7.0.2
//To get javascript that is added through OpenAction
PdfDocument srcPdf = new PdfDocument(new PdfReader(srcFilePath));
PdfDictionary pdfDictionaryCatalog = srcPdf.getCatalog().getPdfObject();
PdfDictionary namesDictionary = pdfDictionaryCatalog.getAsDictionary(PdfName.OpenAction);
if(namesDictionary != null) {
PdfObject pdfObj = namesDictionary.get(PdfName.JS);
if(pdfObj != null) {
StringBuilder strBuf = new StringBuilder();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString()) {
strBuf.append(((PdfString) pdfObj).getValue());
}
System.out.println("*****OPENACTION****** "+strBuf.toString());
}
}
// To get java script available from NAMES dictionary
namesDictionary = pdfDictionaryCatalog.getAsDictionary(PdfName.Names);
if(namesDictionary != null) {
PdfDictionary javascriptDictionary = namesDictionary.getAsDictionary(PdfName.JavaScript);
if(javascriptDictionary != null) {
StringBuilder strBuf = new StringBuilder();
Set<Entry<PdfName, PdfObject>> set = javascriptDictionary.entrySet();
for (Entry<PdfName, PdfObject> entry : set) {
PdfObject pdfObj = entry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && entry.getKey().getValue().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
System.out.println("*****JAVASCRIPT****** "+strBuf.toString());
}
}
// To get java script from name tree JAVASCRIPT
PdfNameTree nameTree = srcPdf.getCatalog().getNameTree(PdfName.JavaScript);
if(nameTree != null) {
Map<String, PdfObject> objs = nameTree.getNames();
if(objs != null) {
StringBuilder strBuf = new StringBuilder();
for (Entry<String, PdfObject> entry : objs.entrySet()) {
PdfObject pdfObj = entry.getValue();
if (pdfObj.isDictionary()) {
getJavaScriptFromPdfDictionary((PdfDictionary)pdfObj, strBuf);
}else if (pdfObj.isArray()) {
getJavaScriptFromPdfArray((PdfArray)pdfObj, strBuf);
} else if (pdfObj.isString() && entry.getKey().equals(PdfName.JS.getValue())) {
strBuf.append(((PdfString) pdfObj).getValue());
}
}
System.out.println("*****JAVASCRIPT NAMED TREE****** "+strBuf.toString());
}
}
// To get java script at the annotation action level
for (int i = 1; i <= srcPdf.getNumberOfPages(); i++) {
PdfPage page = srcPdf.getPage(i);
List<PdfAnnotation> annotList = page.getAnnotations();
if(annotList != null) {
for (PdfAnnotation pdfAnnotation : annotList) {
if(pdfAnnotation.getPdfObject() != null) {
PdfDictionary annotationAction = pdfAnnotation.getPdfObject().getAsDictionary(PdfName.A);
if (annotationAction != null && PdfName.JavaScript.equals(annotationAction.get(PdfName.S))) {
PdfString javascript = annotationAction.getAsString(PdfName.JS);
if(javascript != null) {
System.out.println("ANNOTATION "+javascript);
}
}
}
}
}
}
/*getJavaScriptFromPdfDictionary() and getJavaScriptFromPdfArray() methods are the same from James answer. */
I'm trying to port materialprime to primefaces 6. I already updated the widgets to use core.js and components.js but I have a problem rendering the materialprime. selectOne is not rendering also the jsf selectOneMenu is not rendering only the priemfaces SelectOneMenu works, the console says:
widget not available: selectOne
Any ideas?
This is the code of the 4 files related to selectOne:
MaterialWidgetBuilder.java:
public class MaterialWidgetBuilder extends WidgetBuilder {
private static final String KEY = MaterialWidgetBuilder.class.getName();
public static MaterialWidgetBuilder getInstance(final FacesContext context) {
MaterialWidgetBuilder wb = (MaterialWidgetBuilder) context.getExternalContext().getRequestMap().get(KEY);
if (wb == null) {
wb = new MaterialWidgetBuilder(context);
context.getExternalContext().getRequestMap().put(KEY, wb);
}
return wb;
}
public MaterialWidgetBuilder(FacesContext context) {
super(context);
}
protected WidgetBuilder init(String widgetClass, String widgetVar, String id, String resourcePath, boolean endFunction) throws IOException {
this.endFunction = endFunction;
context.getResponseWriter().write("MaterialPrime.cw(\"");
context.getResponseWriter().write(widgetClass);
context.getResponseWriter().write("\",\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\",{");
context.getResponseWriter().write("id:\"");
context.getResponseWriter().write(id);
if (widgetVar == null) {
context.getResponseWriter().write("\"");
} else {
context.getResponseWriter().write("\",widgetVar:\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\"");
}
return this;
}
}
SelectOne.java:
#ResourceDependencies({
#ResourceDependency(library = "primefaces", name = "jquery/jquery.js"),
#ResourceDependency(library = "primefaces", name="core.js"),
#ResourceDependency(library = "primefaces", name="components.js"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.css"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.css"),
#ResourceDependency(library = "material-prime", name = "selectone/selectOne.js")
})
public class SelectOne extends SelectOneMenu{
public static final String COMPONENT_TYPE = "org.primefaces.material.component.SelectOne";
protected enum PropertyKeys {
nativeMode
}
public SelectOne() {
setRendererType(SelectOneRenderer.RENDERER_TYPE);
}
#Override
public String getFamily() {
return MaterialPrime.COMPONENT_FAMILY;
}
public boolean isNativeMode(){
return (Boolean) getStateHelper().eval(PropertyKeys.nativeMode,false);
}
public void setNativeMode(boolean nativeMode){
getStateHelper().put(PropertyKeys.nativeMode, nativeMode);
}
}
SelectOneRenderer.java:
public class SelectOneRenderer extends InputRenderer {
public static final String RENDERER_TYPE = "org.primefaces.material.component.SelectOneRenderer";
#Override
public void decode(FacesContext context, UIComponent component) {
SelectOne selectOne = (SelectOne) component;
if(selectOne.isDisabled()) {
return;
}
decodeBehaviors(context, selectOne);
String clientId = selectOne.getClientId(context);
String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input");
if(submittedValue!=null){
selectOne.setSubmittedValue(submittedValue);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
SelectOne selectOne = (SelectOne) component;
encodeMarkup(context, selectOne);
encodeScript(context, selectOne);
}
private void encodeMarkup(FacesContext context, SelectOne selectOne) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String inputId = selectOne.getClientId() + "_input";
List<SelectItem> selectItems = getSelectItems(context, selectOne);
writer.startElement("div", selectOne);
writer.writeAttribute("class", "input-field", null);
writer.startElement("select", selectOne);
writer.writeAttribute("class", getSelectClass(selectOne), null);
writer.writeAttribute("id", inputId, null);
writer.writeAttribute("name", inputId, null);
for (SelectItem selectItem : selectItems) {
writer.startElement("option", null);
if(selectItem.getValue().equals(selectOne.getValue())){
writer.writeAttribute("selected", "selected", null);
}
writer.writeAttribute("value", selectItem.getValue(),null);
writer.write(selectItem.getLabel());
writer.endElement("option");
}
writer.endElement("select");
writer.endElement("div");
}
private String getSelectClass(SelectOne selectOne) {
String toReturn = "";
if(selectOne.isNativeMode()){
toReturn += " browser-default ";
}
return toReturn;
}
private void encodeScript(FacesContext context, SelectOne selectOne) throws IOException {
String clientId = selectOne.getClientId();
String widgetVar = selectOne.resolveWidgetVar();
WidgetBuilder wb = MaterialWidgetBuilder.getInstance(context);
wb.initWithDomReady("SelectOne", widgetVar, clientId);
wb.attr("widgetName", widgetVar);
encodeClientBehaviors(context, selectOne);
wb.finish();
}
}
SelectOne.js
MaterialPrime.widget.SelectOne = PrimeFaces.widget.BaseWidget.extend({
init : function(cfg) {
this._super(cfg);
this.input = jQuery(this.jqId+"_input");
var that = this;
this.input.material_select();
this.input.on("change",function(){
if(that.cfg.behaviors && that.cfg.behaviors.valueChange) {
that.cfg.behaviors.valueChange.call(that.input);
}
});
}
});
I am trying to create a realtime line chart with random numbers, following this tutorial:
http://www.c-sharpcorner.com/uploadfile/jj12345678910/real-time-chart-using-signalr-and-chart-js/
The code I have is like this:
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/Chart.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.20.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
function checkHTML5() {
var canvasForLineChart = document.getElementById("canvasForLineChart");
if (canvasForLineChart == null || canvasForLineChart == "") {
document.write("Browser doesn't support HTML5 2D Context");
return false;
}
if (canvasForLineChart.getContext) {
}
else {
document.write("Browser doesn't support HTML5 2D Context");
return false;
}
}
$(function () {
//If not HTML5 Support the Exit
if (checkHTML5() == false) return;
//Create the Hub
var chartHub = $.connection.chartHub;
//Call InitChartData
$.connection.hub.start().done(function () {
chartHub.server.initChartData();
});
//Call to Update LineChart from Server
chartHub.client.updateChart = function (line_data,pie_data) {
UpdateLineChart(line_data); //Call the LineChart Update method
UpdatePieChart(pie_data); //Call the PieChart Update method
};
});
</script>
The code is failing on this line:
var chartHub = $.connection.chartHub
with this error:
Index:68 Uncaught TypeError: Cannot read property 'chartHub' of undefined
My charthub.cs
public class ChartHub : Hub
{
// Create the instance of ChartDataUpdate
private readonly ChartDataUpdate _ChartInstance;
public ChartHub() : this(ChartDataUpdate.Instance) { }
public ChartHub(ChartDataUpdate ChartInstance)
{
_ChartInstance = ChartInstance;
}
public void InitChartData()
{
//Show Chart initially when InitChartData called first time
LineChart lineChart = new LineChart();
lineChart.SetLineChartData();
Clients.All.UpdateChart(lineChart);
//Call GetChartData to send Chart data every 5 seconds
_ChartInstance.GetChartData();
}
}
And mychartbroadcaster.cs
public class Chart_Broadcaster
{
public class RandomNumberGenerator
{
static Random rnd1 = new Random();
static public int randomScalingFactor()
{
return rnd1.Next(100);
}
static public int randomColorFactor()
{
return rnd1.Next(255);
}
}
//The Line Chart Class
public class LineChart
{
[JsonProperty("lineChartData")]
private int[] lineChartData;
[JsonProperty("colorString")]
private string colorString;
public void SetLineChartData()
{
lineChartData = new int[7];
lineChartData[0] = RandomNumberGenerator.randomScalingFactor();
lineChartData[1] = RandomNumberGenerator.randomScalingFactor();
lineChartData[2] = RandomNumberGenerator.randomScalingFactor();
lineChartData[3] = RandomNumberGenerator.randomScalingFactor();
lineChartData[4] = RandomNumberGenerator.randomScalingFactor();
lineChartData[5] = RandomNumberGenerator.randomScalingFactor();
lineChartData[6] = RandomNumberGenerator.randomScalingFactor();
colorString = "rgba(" + RandomNumberGenerator.randomColorFactor() + "," + RandomNumberGenerator.randomColorFactor() + "," + RandomNumberGenerator.randomColorFactor() + ",.3)";
}
}
}
public class ChartDataUpdate
{
// Singleton instance
private readonly static Lazy<ChartDataUpdate> _instance = new Lazy<ChartDataUpdate>(() => new ChartDataUpdate());
// Send Data every 5 seconds
readonly int _updateInterval = 5000;
//Timer Class
private Timer _timer;
private volatile bool _sendingChartData = false;
private readonly object _chartUpateLock = new object();
LineChart lineChart = new LineChart();
private ChartDataUpdate()
{
}
public static ChartDataUpdate Instance
{
get
{
return _instance.Value;
}
}
// Calling this method starts the Timer
public void GetChartData()
{
_timer = new Timer(ChartTimerCallBack, null, _updateInterval, _updateInterval);
}
private void ChartTimerCallBack(object state)
{
if (_sendingChartData)
{
return;
}
lock (_chartUpateLock)
{
if (!_sendingChartData)
{
_sendingChartData = true;
SendChartData();
_sendingChartData = false;
}
}
}
private void SendChartData()
{
lineChart.SetLineChartData();
GetAllClients().All.UpdateChart(lineChart);
}
private static dynamic GetAllClients()
{
return GlobalHost.ConnectionManager.GetHubContext<ChartHub>().Clients;
}
}
Initially hold_mode value is set to 0, after commandButton click, it changed to 1 through JavaScript onclick event...but in PhaseListener beforePhase() method, the value is 0. I did not understand why the value is still 0.
Can anyone please explain me on this.?
info.xhtml
<h:form id="userForm">
<h:inputHidden id="hold_mode" value="0" />
<h:commandButton id="hold" style="width: 60px;" value="#{myForm.holdbtntitle}" disabled="#{myForm.holdbtn}" action="#{myForm.hold}" actionListener="#{convo.holdListener}" onclick="return send(true,'3');" rendered="#{myForm.holdpanelflg}"/>
JavaScript
function send(confirmFlg,msgFlg) {
isClicked = true;
if(confirmFlg) {
msg = 'From Hold';
if(confirm(msg) == false) {
isClicked = false;
event.returnValue = false;
return false;
}
}
if(isClicked) {
if(msgFlg == '3') {
document.all.item('myForm:hold_mode').value='1';
}
pep_OpenWaitDirect('../../../html/common/printwait.xhtml');
return true;
} else {
return false;
}
}
PhaseListener
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
private FacesContext old = null;
public void beforePhase(PhaseEvent e) {
System.out.println("Before "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
old = FacesContext.getCurrentInstance();
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
System.out.println("After "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
StateManager stateManager = (StateManager)context.getApplication().getStateManager();
stateManager.restoreView(old,old.getViewRoot().getViewId(),old.getViewRoot().getRenderKitId());
}
}
}
private boolean findHoldMode(UIComponent comp){
boolean rtnFlg = false;
List list = comp.getChildren();
for (int i = 0; i < list.size(); i++) {
UIComponent temp = (UIComponent) list.get(i);
if (!(temp instanceof HtmlBody)) {
continue;
} else {
List<UIComponent> childList = temp.getChildren();
for (int j = 0; j < childList.size(); j++) {
UIComponent childTemp = (UIComponent) childList.get(j);
if (!(childTemp instanceof HtmlPanelGrid)) {
continue;
} else {
List<UIComponent> child2List = childTemp.getChildren();
for (int k = 0; k < child2List.size(); k++) {
UIComponent child2Temp = (UIComponent) child2List.get(k);
if (!(child2Temp instanceof HtmlForm)) {
continue;
}
UIComponent hold = child2Temp.findComponent(JsfBase.HOLD_MODE_COMPNAME);
if (hold == null) {
continue;
}
if (!(hold instanceof UIInput)) {
continue;
}
Object mode = ((UIInput) hold).getValue();
if (mode == null || !(mode.toString().equals(JsfBase.HOLD_MODE_ON))) {
continue;
} else {
rtnFlg = true;
((UIInput) hold).setValue("0");
break;
}
}
}
}
}
}
return rtnFlg;
}
private void removeValidatorsForComponentTree(UIComponent comp){
removeValidators(comp);
List complist = comp.getChildren();
if (complist.size()>0){
for(int i = 0; i < complist.size(); i++) {
UIComponent uicom = (UIComponent) complist.get(i);
removeValidatorsForComponentTree(uicom);
}
}
}
private void removeValidators(UIComponent comp){
if(comp instanceof UIInput){
removeValidator((UIInput)comp);
}
}
public void removeValidator(UIInput comp){
Validator[] validator = comp.getValidators();
for(int i=0;i < validator.length;i++){
comp.removeValidator(validator[i]);
}
if(comp.isRequired()){
comp.setRequired(false);
}
}
}
I tried this <h:inputHidden id="hold_mode" value="0" immediate="true" /> and it works for the current screen but the problem is when I click the commandButton in other screens, the following exception occured
java.lang.IllegalStateException: FacesContext already released
Issue got fixed after modified PhaseListener
Why I got IllegalStateException is as I have declared FacesContext object old globally. In that case, I had declared it inside befoerPhase method as we don't declare FacesContext globally..
Before code modification, what we did is we removed validators in beforePhase and we are restoring the view state in afterPhase, but it did not worked properly. So now I am saving the view state before validators removal in beforePhase instead of restoring it in afterPhase..
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
public void beforePhase(PhaseEvent e) {
if (e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = context.getViewRoot();
StateManager stateManager = (StateManager) context.getApplication().getStateManager();
stateManager.saveView(context);
if (findHoryuMode(comp)) {
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
}
}
I am using ReCaptcha with the javascript API on my aspx page on localhost. I read somewhere that I don't need a key as long as I use it on localhost. So, I use some random key that I found somewhere. I could render the recaptcha challenge successfully. The following is my javascript code.
Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
tabindex: 1,
theme: "clean",
callback: Recaptcha.focus_response_field
});
//To Validate user response
function Recaptcha_IsCorrect()
{
var xmlHttpRequest;
var PageURL = document.URL;
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
else
{
xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
}
var challenge = Recaptcha.get_challenge();
var userResponse = Recaptcha.get_response();
var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;
xmlHttpRequest.open("GET", url);
xmlHttpRequest.onreadystatechange = function ()
{
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
alert(xmlHttpRequest.responseText);
}
};
xmlHttpRequest.send();
}
The following is my code for the webservice which exposed the webmethod to validate ReCaptcha user input. I get the error "invalid-site-private-key".
namespace YADA.YADAYADA{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PIAsyncAjax : System.Web.Services.WebService
{
[WebMethod]
public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
{
bool isValid = false;
string validationResponse = "";
reCaptchaValidation validator =
new reCaptchaValidation(null,
clientIP,
privateKey,
challenge,
response);
isValid = validator.Validate();
if (isValid)
{
validationResponse = "true";
}
else
{
if (!validator.IsErrored)
{
validationResponse = "false";
}
else
{
// oh dear, something not right
if (validator.Exception != null) // an exception occurred while
// trying to validate
validationResponse = validator.Exception.ToString();
else if (validator.ValidationResult != null) // the validation web service
// returned an error code
// (other than an invalid captcha solution)
validationResponse = "web service error: " + validator.ValidationResult;
}
}
return validationResponse;
}
}
public class reCaptchaValidation
{
private string challenge, response, privateKey, ip;
private IWebProxy proxy;
public reCaptchaValidation(string clientIP, string privateKey,
string challenge, string response) : this(null, clientIP, privateKey,
challenge, response) { }
public reCaptchaValidation(IWebProxy proxy, string clientIP,
string privateKey, string challenge, string response)
{
this.proxy = proxy;
this.ip = clientIP;
this.privateKey = privateKey;
this.challenge = challenge;
this.response = response;
}
private bool _errored;
public bool IsErrored
{
get
{
return _errored;
}
}
private Exception _ex;
public Exception Exception
{
get
{
return _ex;
}
}
private string _vr;
public string ValidationResult
{
get
{
return _vr;
}
}
public bool Validate()
{
try
{
string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) +
"&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" +
HttpUtility.UrlEncode(challenge) + "&response=" +
HttpUtility.UrlEncode(response);
WebRequest wr = HttpWebRequest.Create
("http://www.google.com/recaptcha/api/verify");
wr.Method = "POST";
if (proxy != null)
wr.Proxy = proxy;
wr.ContentLength = post.Length;
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(post);
sw.Close();
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string valid = sr.ReadLine();
if (valid != null)
{
if (valid.ToLower().Trim() == "false")
{
string errorcode = sr.ReadLine();
if (errorcode != null)
{
if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
{
_vr = errorcode;
_errored = true;
return false;
}
}
}
return (valid.ToLower().Trim() == "true");
}
else _vr = "empty web service response";
sr.Close();
return false;
}
}
catch (Exception caught)
{
_errored = true;
_ex = caught;
}
return false;
}
}}
What am I doing wrong? Should I have to get a private key? Any help would be great.
Thanks in advance,
Venkat.
It works with the public and private keys that I just created. Damn, I just assumed, "localhost" would not be accepted as a legal domain-name while signing up.