Getting String values from a ".properties like" file
I'm finishing up my first servlet based application. I would like to get some of the error messages out of the code and into a file that will be read when the application is initialized -- much like one would use a .properties file in a Java program.
This will allow error messages to be edited later, without recompiling the code.
What's the servlet oriented approach to reading strings on initialization? I have a hunch it has something to do with ServletContext . . .
Bonus Question! Does this approach read strings only at initialization? I can't afford the cost of reading them every time!
Thanks in advance,
Josh Collins
You can use a RessourceBundle object to read such property file... and you will be able to set localized message.
Sylvain Gibier
Similar Messages
-
How to get string value from xml in JSF??
In JSF How to get string value from xml, .ini and properties file. I want to get string value from xml or text to JSF
Just use the appropriate API's for that. There are enough API's out which can read/parse/write XML, ini and properties files. E.g. JAXP or DOM4J for xml files, INI4J for ini files and Sun's own java.util.Properties for propertiesfiles.
JSF supports properties files as message bundle and resource bundle so that you can use them for error messages and/or localization. -
How to get string value from database table using Visual Studio 2005?
Hi,
Im developing plugin in illustrator cs3 using visual studio 2005. I need to get the values eneterd in database. Im able to get the integer values. But while getting string values it is returning empty value.
Im using the below code to get the values from database table
bool Table::Get(char* FieldName,int& FieldValue)
try
_variant_t vtValue;
vtValue = m_Rec->Fields->GetItem(FieldName)->GetValue();
FieldValue=vtValue.intVal;
CATCHERRGET
sprintf(m_ErrStr,"Success");
return 1;
Im using the below code to get the values.
AIErr getProjects()
char buf[5000];
int i;
std::string catName;
::CoInitialize(NULL);
Database db;
Table tbl;
errno_t err;
err = fopen(&file,"c:\\DBResult.txt","w");
fprintf(file, "Before Connection Established\n");
//MessageBox(NULL,CnnStr,"Connection String",0);
if(!db.Open(g->username,g->password,CnnStr))
db.GetErrorErrStr(ErrStr);
fprintf(file,"Error: %s\n",ErrStr);
fprintf(file, "After Connection Established\n");
if(!db.Execute("select ProjectID,ProjectName from projectsample",tbl))
db.GetErrorErrStr(ErrStr);
fprintf(file,"Error: %s\n",ErrStr);
int ProjectID;
int UserID;
int ProjectTitle;
char ProjectName[ProjectNameSize];
if(!tbl.ISEOF())
tbl.MoveFirst();
ProjectArrCnt=0;
for(i=0;i<128;i++)
buf[i]='\0';
int j=0;
while(!tbl.ISEOF())
if(tbl.Get("ProjectID",ProjectID))
fprintf(file,"Project ID: %d ",ProjectID);
ProjectInfo[ProjectArrCnt].ProjectID = ProjectID;
sprintf(buf,"%d",ProjectID);
//MessageBox(NULL, buf,"f ID", 0);
j++;
else
tbl.GetErrorErrStr(ErrStr);
fprintf(file,"Error: %s\n",ErrStr);
break;
//if(tbl.Get("ProjectTitle",ProjectName))
if(tbl.Get("ProjectName",ProjectName))
MessageBox(NULL,"Inside","",0);
fprintf(file,"ProjectTitle: %s\n",ProjectName);
//catName=CategoryName;
ProjectInfo[ProjectArrCnt].ProjectName=ProjectName;
//sprintf(buf,"%s",ProjectName);
MessageBox(NULL,(LPCSTR)ProjectName,"",0);
else
tbl.GetErrorErrStr(ErrStr);
fprintf(file,"Error: %s\n",ErrStr);
break;
ProjectArrCnt++;
//MessageBox(NULL, "While", "WIN API Test",0);
tbl.MoveNext();
//MessageBox(NULL, ProjectInfo[i].ProjectName.c_str(),"f Name", 0);
::CoUninitialize();
//sprintf(buf,"%s",file);
//MessageBox(NULL,buf,"File",0);
fprintf(file, "Connection closed\n");
fclose(file);
for(i=0;i<ProjectArrCnt;i++)
sprintf(buf,"%i",ProjectInfo[i].ProjectID);
//MessageBox(NULL,buf,"Proj ID",0);
//MessageBox(NULL,ProjectInfo[i].ProjectName.c_str(),"Project Name",0);
return 0;
In the above code im geeting project D which is an integer value. But not able to get the project name.
Please some one guide me.As I said in the other thread, this really isn't the place to ask questions about a database API unrelated to the Illustrator SDK. You're far more like to find people familliar with your problem on a forum that is dedicated to answering those kinds of questions instead.
-
Get string value from enumerated value on AE user interface
Hello.
I'm trying to get the string value from a enumerated value on a layer's property.
When I get the value via script, I have 1D value. However, I need the string value.
In this example, the value I would get is 1. Is there any way I can get "Horizontal and Vertical".
I'm looking for a generic way (any property value defined this way), not for this case only.
Thanks for the help.
cheers.You get the selected value via the value property of the component.
Timo -
Getting string values from DB query
I am using the following code:
<%@ page import="java.sql.*" %>
<%
String userName = request.getParameter("usernameField");
String password = request.getParameter("passwordField");
String connectionURL = "jdbc:mysql://localhost:3306/babbemployees?user=DBUser;password=MyPassword";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection (connectionURL, "DBUser", "MyPassword");
statement = connection.createStatement();
String queryString = "SELECT * FROM tbemployees where userID='"+userName+"'";
rs = statement.executeQuery(queryString);
String isAuthenticated;
if (userName == rs.getString("userID") && password == rs.getString("password")[0])
isAuthenticated = "AUTHENTICATED";
else
isAuthenticated = "NOT AUTHENTICATED";
rs.close();
%>
<html>
<body>
<h1><%= isAuthenticated %></h1>
<hr>
</body>
</html>I am trying to get a String value for rs.getString() but for some reason this is not working out. Is there anything I can do to get the values for the queries in a String value?
Thanks,
HarlinWhen a ResultSet is returned to you, it is always positioned before the first row.
You need to insert a rs.next(); after your executeQuery(). -
How to get each value from a parameter passed like this '(25,23,35,1)'
Hi
One of the parameter passed to the function is
FUNCTION f_main_facility(pi_flag_codes VARCHAR2) return gc_result_set AS
pi_flag_codes will be passed a value in this way '(25,23,35,1)'
How to get each value from the string
like 25 first time
23 second time
35 third time
1 fourth time
I need to build a select query with each value as shown below:-
(SELECT t2.org_id, t4.description
from org_name t2, ref_org_name t3, code_table t4
where t2.att_data = t4.code
and t3.ref_code = t2.att_type
and t2.att_type = 25 and t3.code_type = t4.code_type
and to_date('01-JAN-10', 'DD-MON-YY') between t2.att_start_date AND t2.att_end_date) q1,
(SELECT t2.org_id, t4.description
from org_name t2, ref_org_name t3,code_table t4
where t2.att_data = t4.code
and t3.ref_code = t2.att_type
and t2.att_type = 23 and t3.code_type = t4.code_type
and to_date('01-JAN-10', 'DD-MON-YY') between t2.att_start_date AND t2.att_end_date) q2,
(SELECT t2.org_id, RTRIM(xmlagg(xmlelement(e, t4.description || ';')
ORDER BY t4.description).EXTRACT('//text()'), ';') AS DESCRIPTION
from org_name t2, ref_org_name t3,code_table t4
where t2.att_data = t4.code
and t3.ref_code = t2.att_type
and t2.att_type = 35 and t3.code_type = t4.code_type
and to_date('01-JAN-10', 'DD-MON-YY') between t2.att_start_date AND t2.att_end_date
group by t2.org_id) q3,
(SELECT t2.org_id, t4.description
from org_name t2, ref_org_name t3, code_table t4
where t2.att_data = t4.code
and t3.ref_code = t2.att_type
and t2.att_type = 1 and t3.code_type = t4.code_type
and to_date('01-JAN-10', 'DD-MON-YY') between t2.att_start_date AND t2.att_end_date) q4
Please help me with extracting each alue from the parm '(25,23,35,1)' for the above purpose. Thank You.chris227 wrote:
I would propose the usage of regexp for readibiliy purposes and only in the case if this doesnt perform well, look at solutions using substr etc.
select
regexp_substr( '(25,23,35,1)', '\d+', 1, 1) s1
,regexp_substr( '(25,23,35,1)', '\d+', 1, 2) s2
,regexp_substr( '(25,23,35,1)', '\d+', 1, 3) s3
,regexp_substr( '(25,23,35,1)', '\d+', 1, 4) s4
from dual
S1 S2 S3 S4
"25" "23" "35" "1"In pl/sql you do something like l_val:= regexp_substr( '(25,23,35,1)', '\d+', 1, 1);
If t2.att_type is type of number you will do:
t2.att_type= to_number(regexp_substr( '(25,23,35,1)', '\d+', 1, 1))Edited by: chris227 on 01.03.2013 08:00Sir,
I am using oracle 10g.
In the process of getting each number from the parm '(25,23,35,1)' , I also need the position of the number
say 25 is at 1 position.
23 is at 2
35 is at 3
1 is at 4.
the reason I need that is when I build seperate select for each value, I need to add the query number at the end of the select query.
Please see the code I wrote for it, But the select query is having error:-
BEGIN
IF(pi_flag_codes IS NOT NULL) THEN
SELECT length(V_CNT) - length(replace(V_CNT,',','')) FROM+ ----> the compiler gives an error for this select query : PLS-00428:
*(SELECT '(25,23,35,1)' V_CNT FROM dual);*
DBMS_OUTPUT.PUT_LINE(V_CNT);
-- V_CNT := 3;
FOR L_CNT IN 0..V_CNT LOOP
if L_CNT=0 then
V_S_POS:=1;
V_E_POS:=instr(pi_flag_codes, ',', 1, 1)-1;
else
V_S_POS:=instr(pi_flag_codes,',',1,L_CNT)+1;
V_E_POS:=instr(pi_flag_codes, ',', 1, L_CNT+1)-V_S_POS;
end if;
if L_CNT=V_CNT then
V_ID:=TO_NUMBER(substr(pi_flag_codes,V_S_POS));
else
V_ID:=TO_NUMBER(substr(pi_flag_codes,V_S_POS,V_E_POS));
end if;
VN_ATYPE := ' t2.att_type = ' || V_ID;
rec_count := rec_count +1;
query_no := 'Q' || rec_count;
Pls help me with fetching each value to build the where cond of the select query along with the query number.
Thank You. -
How to get the value from a JavaScript and send the same to Java file?
Hi.
How to get the value from a JavaScript (this JS is called when an action invoked) and send the value from the JS to a Java file?
Thanks and regards,
Leslie VYes, I am trying with web application.
In the below code, a variable 'message' carries the needed info. I would like to send this 'message' variable with the 'request'.
How to send this 'message' with and to the 'request'?
Thanks for the help :-)
The actual JS code is:
function productdeselection()
var i=0;
var j=0;
var deselectedproduct = new Array(5);
var message = "Are you sure to delete Product ";
mvi=document.forms[0].MVI;
mei=document.forms[0].MEI;
lpi=document.forms[0].LPI;
if(null != mvi)
++i;
if(null != mei )
++i;
if(null != lpi)
++i;
if(null != mvi && mvi.checked)
deselectedproduct[++j]="MVI?";
if(null != mei && mei.checked)
deselectedproduct[++j]="GAP?";
if(null != lpi && lpi.checked)
deselectedproduct[++j]="LPI?";
if( 0!=j)
if(i!=j)
for (x=0; x<deselectedproduct.length; x++)
if(null != deselectedproduct[x])
message =message+ "-" +deselectedproduct[x];
alert(message);
else
//alert(" You cannot remove all products!");
return false;
return true;
} -
How to get int value from [session.getAttribute("String")]
i am not able to get int value from the following statiment
int i=session.getAttribute("String");
i also try by casting it into int but it dont work, can somebody help me in this regardabuu wrote:
i am not able to get int value from the following statiment
int i=session.getAttribute("String");
i also try by casting it into int but it dont work, can somebody help me in this regard
Integer i=(Integer)session.getAttribute("String");
i.intValue();but know how it is working. that is useful.
Diablo. -
Get numerical values from 2D array of string
Hello!
I start by saying that I have a base knowledge of LabView. I'm using LabView 2011. I'm doing some communications test via Can-Bus protocol. As you can see in pictures of the block diagram and of the front panel that I've attached I'm using "Transmit Receive same Port" LabView example. It works very good but I would need to insert the 8 data bytes that I receive from the server in 8 different numerical variables so that I could use them to make some operations. How can I get numerical values from the 2D array of string that I attached?
Every example that you can provide is important!
Thank you very much!
Attachments:
1.jpg 69 KB
2.jpg 149 KBHi martiflix,
ehm: to unbundle data from a cluster I would use the function Unbundle(ByName)…
When you are new to LabVIEW you should take all the FREE online resources offered by NI on their website!
Best regards,
GerdW
CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
Kudos are welcome -
How to get the value from the checkbox
Hi All,
Good Evening,
i want to get the value from the check box.
for this i wrote like this
OAMessageCheckBoxBean cbb=(OAMessageCheckBoxBean)webBEan.findChildRecurssive("item240")
String val=cbb.getvalue(pageContext).toString();
val getting the value only when checkbox is checked.
suppose check box is not checked that time i got NULL POINTER exceptionn.
so
i tried the following way alsoo
string val=pageContext.getParameter("item240");
here val return 'on' only when checkbox is checked.
otherwise NULL value returnss.
but i want to get the value is 'Y' when i am checked the checkbox
otherwise returns NULL valuee.
already i set the checkbox properties alsoo
Checked :Y
unchecked:N
pls tell meHi,
use
try
OAMessageCheckBoxBean cbb=(OAMessageCheckBoxBean)webBEan.findChildRecurssive("item240")
String test = cbb.getvalue(pageContext).toString();
catch(Exception e)
String test = "";
this way you can handle null pointer exception.
Thanks,
Gaurav -
Get/Set values from a drop down list
I am trying to modify the http://www.netbeans.org/kb/60/web/web-jpa-part2.html so that instead of entering the data from a text field (in update & add) the values come from a drop down list from a table. I have drop down lists that are populated bothe from the DB and hard coding. When I run, I am able to see the options on the DDs. But none of the CRUD work. I think this is because my set and get for the drop down is wrong. Then again, I also have a few text fields from the original example which also don't seem to work. Here is a piece of my addButton():
RowKey[] selectedRowKeys = getTableRowGroup1().getSelectedRowKeys();
PaymentDetails[] pv = getSessionBean1().getPaymentVoucher();
int rowId = Integer.parseInt(selectedRowKeys[0].getRowId());
PaymentDetails upPV = pv[rowId];
bankCodeDD.getSelected();
statusDD.getSelected(); // hard coded value
upPV.setPrepBy((String) prepByField.getText());
PaymentDetailsController pvController = new PaymentDetailsController();
pvController.addPaymentDetails(upPV);
addRequest = false;
return null;How do I set and get the values from the drop down so than it passed to my bean? When I choose a row to be updated, make changes and click Update, I get this message on my Tomcat:
com.sun.webui.jsf.component.DropDown::The current value of component form1:deptCodeDD does not match any of the selections.
Did you forget to reset the value after changing the options?Can someone please point me to a place which shows how I can add a default value from my DD? I tried to follow http://www.netbeans.org/kb/55/dropdowncomp.html, but unable to complete because I get an error for Options api. The auto-fix imported import org.apache.jasper.Options; But the package given in the tutorial is com.sun.webui.jsf.model.Option. My Java version is 1.6.0_07.
private Options listOptions[];
...//getter setter goes here
listOptions = new Option[noofDBRows + 1];Many Thanks!I don't guess what I may add.
The contents of the table named lookup appear on the screenshot.
cell A1 contains the string One-Piece, cell B1 contains the 'associated' value 160.
cell A2 contains the string Two-Piece, cell B2 contains the 'associated' value 130.
cell A3 contains the string Three-Quarter, cell B3 contains the 'associated' value 150.
Now table Main
In column B the cells contain a pop_up menu with four items like the ones described by Jerrold.
In column C of the cells contain the formula :
=IFERROR(VLOOKUP(B,Tableau 2 :: A:B,2,FALSE),"")
I enhanced it since yesterdays because I forgot to treat the case when cell is blank in column B.
I apologize but as I'm using my machine in French, the screenshot display the French formulas.
I repeat that you may find useful infos in the PDFs files which we may download from the menus:
Help > Numbers User Guide
Help > iWork Formulas and Functions User Guide
As you are in Stoke-on-Trent maybe your system is set to use the comma as decimal separator.
If it's that, you must replace the comma by semi-colons in the formulas (you may see them in my screenshot).
Yvan KOENIG (VALLAURIS, France) mercredi 24 mars 2010 09:27:53 -
How to retrieve query string value from the URL in my portlet
Hi,
When user clicks on "Advance Search", i am redirecting to page in the community. At the same i am adding some more values to the query string (to the URL).
My URL will look like this.
http://ctp-mc0149/portal/server.pt?space=CommunityPage&parentname=CommunityPage&parentid=0&in_hi_userid=200&cached=true&control=SetCommunity&PageID=202&CommunityID=200&searchType=2
Now in one of my portlet in that page, i want to retrieve the query string values from the URL.
Please help me regarding this.
Thanks in advance.
Thanks,
sreekanth.Hi,
Look at the following threads,
For programmatically getting the iview properties,
Programmatically getting iView Properties
Also,
Get Properties of IView Programmatically
Permanent change of iView property programmatically
Hope these threads help u.
Regards
Srinivasan T -
NullPointerException - Cannot get the value from variable f_cashGiven
In SubCheckout.java (a POS), what I want is when Payment button (f_cashPayment) is pressed, the action "Cash" is performed, get the value from Cash Given (f_cashGiven), do the subtraction and post the value as Cash Return (f_cashReturn). The code is filled in actionPerformed. But I cannot get the value by using f_cashGiven.getValue() from VNumber class. It returns NULL. This should be quite straight forward, but I do not know what is wrong. Please help!
Enclosed please find the source code of SubCheckout.java and VNumber.java
This is the code of SubCheckout.java :
* The contents of this file are subject to the Compiere License Version 1.1
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.compiere.org/license.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
* Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
* are Copyright (C) 1999-2005 Jorg Janke.
* All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved.
* Contributor(s): ______________________________________.
package org.compiere.pos;
import java.awt.*;
import java.awt.event.*;
import java.math.BigDecimal;
import javax.swing.border.*;
import org.compiere.grid.ed.*;
import org.compiere.swing.*;
import org.compiere.util.*;
* POS Checkout Sub Panel
* @author Jorg Janke
* @version $Id: SubCheckout.java,v 1.3 2005/03/11 20:28:22 jjanke Exp $
public class SubCheckout extends PosSubPanel implements ActionListener
* Constructor
* @param posPanel POS Panel
public SubCheckout (PosPanel posPanel)
super (posPanel);
} // PosSubCheckout
private CButton f_register = null;
private CButton f_summary = null;
private CButton f_process = null;
private CButton f_print = null;
private CLabel f_lcreditCardNumber = null;
private CTextField f_creditCardNumber = null;
private CLabel f_lcreditCardExp = null;
private CTextField f_creditCardExp = null;
private CLabel f_lcreditCardVV = null;
private CTextField f_creditCardVV = null;
private CButton f_cashPayment = null;
private CLabel f_lcashGiven = null;
private VNumber f_cashGiven = null;
private CLabel f_lcashReturn = null;
private VNumber f_cashReturn = null;
private CButton f_creditPayment = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(SubCheckout.class);
* Initialize
public void init()
// Title
TitledBorder border = new TitledBorder(Msg.getMsg(Env.getCtx(), "Checkout"));
setBorder(border);
// Content
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = INSETS2;
// -- 0
gbc.gridx = 0;
f_register = createButtonAction("Register", null);
gbc.gridy = 0;
add (f_register, gbc);
f_summary = createButtonAction("Summary", null);
gbc.gridy = 1;
add (f_summary, gbc);
f_process = createButtonAction("Process", null);
gbc.gridy = 2;
add (f_process, gbc);
f_print = createButtonAction("Print", null);
gbc.gridy = 3;
add (f_print, gbc);
// -- 1 -- Cash
gbc.gridx = 1;
gbc.gridheight = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = .1;
CPanel cash = new CPanel(new GridBagLayout());
cash.setBorder(new TitledBorder(Msg.getMsg(Env.getCtx(), "Cash")));
gbc.gridy = 0;
add (cash, gbc);
GridBagConstraints gbc0 = new GridBagConstraints();
gbc0.insets = INSETS2;
gbc0.anchor = GridBagConstraints.WEST;
f_lcashGiven = new CLabel(Msg.getMsg(Env.getCtx(),"CashGiven"));
cash.add (f_lcashGiven, gbc0);
f_cashGiven = new VNumber("CashGiven", false, false, true, DisplayType.Amount,
Msg.translate(Env.getCtx(), "CashGiven"));
f_cashGiven.addActionListener(this);
f_cashGiven.setColumns(10, 25);
cash.add (f_cashGiven, gbc0);
f_cashGiven.setValue(Env.ZERO);
f_lcashReturn = new CLabel(Msg.getMsg(Env.getCtx(),"CashReturn"));
cash.add (f_lcashReturn, gbc0);
f_cashReturn = new VNumber("CashReturn", false, true, false, DisplayType.Amount,
"CashReturn");
f_cashReturn.setColumns(10, 25);
cash.add (f_cashReturn, gbc0);
f_cashReturn.setValue(Env.ZERO);
f_cashPayment = createButtonAction("Payment", null);
f_cashPayment.setActionCommand("Cash");
gbc0.anchor = GridBagConstraints.EAST;
gbc0.weightx = 0.1;
cash.add (f_cashPayment, gbc0);
// -- 1 -- Creditcard
CPanel creditcard = new CPanel(new GridBagLayout());
creditcard.setBorder(new TitledBorder(Msg.translate(Env.getCtx(), "CreditCardType")));
gbc.gridy = 2;
add (creditcard, gbc);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = INSETS2;
gbc1.anchor = GridBagConstraints.WEST;
gbc1.gridx = 0;
gbc1.gridy = 0;
f_lcreditCardNumber = new CLabel(Msg.translate(Env.getCtx(), "CreditCardNumber"));
creditcard.add (f_lcreditCardNumber, gbc1);
gbc1.gridy = 1;
f_creditCardNumber = new CTextField(18);
creditcard.add (f_creditCardNumber, gbc1);
gbc1.gridx = 1;
gbc1.gridy = 0;
f_lcreditCardExp = new CLabel(Msg.translate(Env.getCtx(),"CreditCardExp"));
creditcard.add (f_lcreditCardExp, gbc1);
gbc1.gridy = 1;
f_creditCardExp = new CTextField(5);
creditcard.add (f_creditCardExp, gbc1);
gbc1.gridx = 2;
gbc1.gridy = 0;
f_lcreditCardVV = new CLabel(Msg.translate(Env.getCtx(), "CreditCardVV"));
creditcard.add (f_lcreditCardVV, gbc1);
gbc1.gridy = 1;
f_creditCardVV = new CTextField(5);
creditcard.add (f_creditCardVV, gbc1);
gbc1.gridx = 3;
gbc1.gridy = 0;
gbc1.gridheight = 2;
f_creditPayment = createButtonAction("Payment", null);
f_creditPayment.setActionCommand("CreditCard");
gbc1.anchor = GridBagConstraints.EAST;
gbc1.weightx = 0.1;
creditcard.add (f_creditPayment, gbc1);
} // init
* Get Panel Position
public GridBagConstraints getGridBagConstraints()
GridBagConstraints gbc = super.getGridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
return gbc;
} // getGridBagConstraints
* Dispose - Free Resources
public void dispose()
super.dispose();
} // dispose
* Action Listener
* @param e event
public void actionPerformed (ActionEvent e)
String action = e.getActionCommand();
if (action == null || action.length() == 0)
return;
log.info( "PosSubCheckout - actionPerformed: " + action);
if (e.getSource() == f_cashGiven) {
f_cashGiven.setValue(f_cashGiven.getValue());
System.out.println("f_cashGiven"+f_cashGiven.getDisplay());
// Register
// Summary
// Print
if (action.equals("Cash")) {
BigDecimal CashGiven, GrandTotal, CashReturn;
System.out.println("Cash given is "+f_cashGiven.getDisplay());
CashGiven = (BigDecimal)f_cashGiven.getValue();
GrandTotal = (BigDecimal)p_posPanel.f_curLine.getOrder().getGrandTotal();
CashReturn = CashGiven.subtract(GrandTotal);
f_cashReturn.setValue(CashReturn);
// Cash (Payment)
// CreditCard (Payment)
} // actionPerformed
} // PosSubCheckoutThis is the code of VNumber.java :
* The contents of this file are subject to the Compiere License Version 1.1
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.compiere.org/license.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
* Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
* are Copyright (C) 1999-2005 Jorg Janke.
* All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved.
* Contributor(s): ______________________________________.
package org.compiere.grid.ed;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.math.*;
import java.text.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.text.*;
import org.compiere.apps.*;
import org.compiere.model.*;
import org.compiere.swing.*;
import org.compiere.util.*;
* Number Control
* @author Jorg Janke
* @version $Id: VNumber.java,v 1.41 2005/09/03 01:57:16 jjanke Exp $
public final class VNumber extends JComponent
implements VEditor, ActionListener, KeyListener, FocusListener
/** Number of Columns (12) */
public final static int SIZE = 12;
* IDE Bean Constructor
public VNumber()
this("Number", false, false, true, DisplayType.Number, "Number");
} // VNumber
* Create right aligned Number field.
* no popup, if WindowNo == 0 (for IDs)
* @param columnName column name
* @param mandatory mandatory
* @param isReadOnly read only
* @param isUpdateable updateable
* @param displayType display type
* @param title title
public VNumber(String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable,
int displayType, String title)
super();
super.setName(columnName);
m_columnName = columnName;
m_title = title;
setDisplayType(displayType);
LookAndFeel.installBorder(this, "TextField.border");
this.setLayout(new BorderLayout());
// this.setPreferredSize(m_text.getPreferredSize()); // causes r/o to be the same length
// int height = m_text.getPreferredSize().height;
// setMinimumSize(new Dimension (30,height));
// *** Text ***
m_text.setBorder(null);
m_text.setHorizontalAlignment(JTextField.TRAILING);
m_text.addKeyListener(this);
m_text.addFocusListener(this);
// Background
setMandatory(mandatory);
this.add(m_text, BorderLayout.CENTER);
// *** Button ***
m_button.setIcon(Env.getImageIcon("Calculator10.gif"));
m_button.setMargin(new Insets(0, 0, 0, 0));
m_button.setFocusable(false);
m_button.addActionListener(this);
this.add (m_button, BorderLayout.EAST);
// Prefereed Size
this.setPreferredSize(this.getPreferredSize()); // causes r/o to be the same length
// Size
setColumns(SIZE, CComboBox.FIELD_HIGHT-4);
// ReadWrite
if (isReadOnly || !isUpdateable)
setReadWrite(false);
else
setReadWrite(true);
} // VNumber
* Dispose
public void dispose()
m_text = null;
m_button = null;
m_mField = null;
} // dispose
* Set Document
* @param doc document
protected void setDocument(Document doc)
m_text.setDocument(doc);
} // getDocument
private String m_columnName;
protected int m_displayType; // Currency / UoM via Context
private DecimalFormat m_format;
private String m_title;
private boolean m_setting;
private String m_oldText;
private String m_initialText;
private boolean m_rangeSet = false;
private Double m_minValue;
private Double m_maxValue;
private boolean m_modified = false;
/** The Field */
private CTextField m_text = new CTextField(SIZE); // Standard
/** The Button */
private CButton m_button = new CButton();
private MField m_mField = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VNumber.class);
* Set no of Columns
* @param columns columns
public void setColumns (int columns, int height)
m_text.setPreferredSize(null);
m_text.setColumns(columns);
Dimension size = m_text.getPreferredSize();
if (height > size.height) // default 16
size.height = height;
if (CComboBox.FIELD_HIGHT-4 > size.height)
size.height = VLookup.FIELD_HIGHT-4;
this.setPreferredSize(size); // causes r/o to be the same length
this.setMinimumSize(new Dimension (columns*10, size.height));
m_button.setPreferredSize(new Dimension(size.height, size.height));
} // setColumns
* Set Range with min & max
* @param minValue min value
* @param maxValue max value
* @return true, if accepted
public boolean setRange(Double minValue, Double maxValue)
m_rangeSet = true;
m_minValue = minValue;
m_maxValue = maxValue;
return m_rangeSet;
} // setRange
* Set Range with min & max = parse US style number w/o Gouping
* @param minValue min value
* @param maxValue max value
* @return true if accepted
public boolean setRange(String minValue, String maxValue)
if (minValue == null || maxValue == null)
return false;
try
m_minValue = Double.valueOf(minValue);
m_maxValue = Double.valueOf(maxValue);
catch (NumberFormatException nfe)
return false;
m_rangeSet = true;
return m_rangeSet;
} // setRange
* Set and check DisplayType
* @param displayType display type
public void setDisplayType (int displayType)
m_displayType = displayType;
if (!DisplayType.isNumeric(displayType))
m_displayType = DisplayType.Number;
m_format = DisplayType.getNumberFormat(displayType);
m_text.setDocument (new MDocNumber(displayType, m_format, m_text, m_title));
} // setDisplayType
* Set ReadWrite
* @param value value
public void setReadWrite (boolean value)
if (m_text.isReadWrite() != value)
m_text.setReadWrite(value);
if (m_button.isReadWrite() != value)
m_button.setReadWrite(value);
// Don't show button if not ReadWrite
if (m_button.isVisible() != value)
m_button.setVisible(value);
} // setReadWrite
* IsReadWrite
* @return true if rw
public boolean isReadWrite()
return m_text.isReadWrite();
} // isReadWrite
* Set Mandatory (and back bolor)
* @param mandatory mandatory
public void setMandatory (boolean mandatory)
m_text.setMandatory(mandatory);
} // setMandatory
* Is it mandatory
* @return true if mandatory
public boolean isMandatory()
return m_text.isMandatory();
} // isMandatory
* Set Background
* @param color color
public void setBackground(Color color)
m_text.setBackground(color);
} // setBackground
* Set Background
* @param error error
public void setBackground (boolean error)
m_text.setBackground(error);
} // setBackground
* Set Foreground
* @param fg foreground
public void setForeground(Color fg)
m_text.setForeground(fg);
} // setForeground
* Set Editor to value
* @param value value
public void setValue(Object value)
log.finest("Value=" + value);
if (value == null)
m_oldText = "";
else
m_oldText = m_format.format(value);
// only set when not updated here
if (m_setting)
return;
m_text.setText (m_oldText);
m_initialText = m_oldText;
m_modified = false;
} // setValue
* Property Change Listener
* @param evt event
public void propertyChange (PropertyChangeEvent evt)
if (evt.getPropertyName().equals(org.compiere.model.MField.PROPERTY))
setValue(evt.getNewValue());
} // propertyChange
* Return Editor value
* @return value value (big decimal or integer)
public Object getValue()
if (m_text == null || m_text.getText() == null || m_text.getText().length() == 0)
return null;
String value = m_text.getText();
// return 0 if text deleted
if (value == null || value.length() == 0)
if (!m_modified)
return null;
if (m_displayType == DisplayType.Integer)
return new Integer(0);
return Env.ZERO;
if (value.equals(".") || value.equals(",") || value.equals("-"))
value = "0";
try
Number number = m_format.parse(value);
value = number.toString(); // converts it to US w/o thousands
BigDecimal bd = new BigDecimal(value);
if (m_displayType == DisplayType.Integer)
return new Integer(bd.intValue());
if (bd.signum() == 0)
return bd;
return bd.setScale(m_format.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP);
catch (Exception e)
log.log(Level.SEVERE, "Value=" + value, e);
if (m_displayType == DisplayType.Integer)
return new Integer(0);
return Env.ZERO;
} // getValue
* Return Display Value
* @return value
public String getDisplay()
return m_text.getText();
} // getDisplay
* Get Title
* @return title
public String getTitle()
return m_title;
} // getTitle
* Plus - add one.
* Also sets Value
* @return new value
public Object plus()
Object value = getValue();
if (value == null)
if (m_displayType == DisplayType.Integer)
value = new Integer(0);
else
value = Env.ZERO;
// Add
if (value instanceof BigDecimal)
value = ((BigDecimal)value).add(Env.ONE);
else
value = new Integer(((Integer)value).intValue() + 1);
setValue(value);
return value;
} // plus
* Minus - subtract one, but not below minimum.
* Also sets Value
* @param minimum minimum
* @return new value
public Object minus (int minimum)
Object value = getValue();
if (value == null)
if (m_displayType == DisplayType.Integer)
value = new Integer(minimum);
else
value = new BigDecimal(minimum);
setValue(value);
return value;
// Subtract
if (value instanceof BigDecimal)
BigDecimal bd = ((BigDecimal)value).subtract(Env.ONE);
BigDecimal min = new BigDecimal(minimum);
if (bd.compareTo(min) < 0)
value = min;
else
value = bd;
else
int i = ((Integer)value).intValue();
i--;
if (i < minimum)
i = minimum;
value = new Integer(i);
setValue(value);
return value;
} // minus
* Action Listener
* @param e event
public void actionPerformed (ActionEvent e)
log.config(e.getActionCommand());
if (ValuePreference.NAME.equals(e.getActionCommand()))
if (MRole.getDefault().isShowPreference())
ValuePreference.start (m_mField, getValue());
return;
if (e.getSource() == m_button)
m_button.setEnabled(false);
String str = startCalculator(this, m_text.getText(), m_format, m_displayType, m_title);
m_text.setText(str);
m_button.setEnabled(true);
try
fireVetoableChange (m_columnName, m_oldText, getValue());
catch (PropertyVetoException pve) {}
m_text.requestFocus();
} // actionPerformed
* Key Listener Interface
* @param e event
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
* Key Listener.
* - Escape - Restore old Text
* - firstChange - signal change
* @param e event
public void keyReleased(KeyEvent e)
log.finest("Key=" + e.getKeyCode() + " - " + e.getKeyChar()
+ " -> " + m_text.getText());
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
m_text.setText(m_initialText);
m_modified = true;
m_setting = true;
try
if (e.getKeyCode() == KeyEvent.VK_ENTER) // 10
fireVetoableChange (m_columnName, m_oldText, getValue());
fireActionPerformed();
else // indicate change
fireVetoableChange (m_columnName, m_oldText, null);
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
* Focus Gained
* @param e event
public void focusGained (FocusEvent e)
if (m_text != null)
m_text.selectAll();
} // focusGained
* Data Binding to MTable (via GridController.vetoableChange).
* @param e event
public void focusLost (FocusEvent e)
// log.finest(e.toString());
// APanel - Escape
if (e.getOppositeComponent() instanceof AGlassPane)
m_text.setText(m_initialText);
return;
try
fireVetoableChange (m_columnName, m_initialText, getValue());
fireActionPerformed();
catch (PropertyVetoException pve) {}
} // focusLost
* Invalid Entry - Start Calculator
* @param jc parent
* @param value value
* @param format format
* @param displayType display type
* @param title title
* @return value
public static String startCalculator(Container jc, String value,
DecimalFormat format, int displayType, String title)
log.config("Value=" + value);
BigDecimal startValue = new BigDecimal(0.0);
try
if (value != null && value.length() > 0)
Number number = format.parse(value);
startValue = new BigDecimal (number.toString());
catch (ParseException pe)
log.info("InvalidEntry - " + pe.getMessage());
// Find frame
Frame frame = Env.getFrame(jc);
// Actual Call
Calculator calc = new Calculator(frame, title,
displayType, format, startValue);
AEnv.showCenterWindow(frame, calc);
BigDecimal result = calc.getNumber();
log.config( "Result=" + result);
calc = null;
if (result != null)
return format.format(result);
else
return value; // original value
} // startCalculator
* Set Field/WindowNo for ValuePreference
* @param mField field
public void setField (MField mField)
m_mField = mField;
if (m_mField != null
&& MRole.getDefault().isShowPreference())
ValuePreference.addMenu (this, popupMenu);
} // setField
* Remove Action Listner
* @param l Action Listener
public void removeActionListener(ActionListener l)
listenerList.remove(ActionListener.class, l);
} // removeActionListener
* Add Action Listner
* @param l Action Listener
public void addActionListener(ActionListener l)
listenerList.add(ActionListener.class, l);
} // addActionListener
* Fire Action Event to listeners
protected void fireActionPerformed()
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent)
modifiers = ((InputEvent)currentEvent).getModifiers();
else if (currentEvent instanceof ActionEvent)
modifiers = ((ActionEvent)currentEvent).getModifiers();
ActionEvent ae = new ActionEvent (this, ActionEvent.ACTION_PERFORMED,
"VNumber", EventQueue.getMostRecentEventTime(), modifiers);
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2)
if (listeners==ActionListener.class)
((ActionListener)listeners[i+1]).actionPerformed(ae);
} // fireActionPerformed
} // VNumberIf getValue() returns null, you need to trace the execution of the code and figure out which sequence of code is leading to the return of null. This method looks complex - a lot of if statements. If you do not have a debugger, put System.out.println statements inside the method to figure out what's going on.
-
How to get the value from a database without submitting a jsp page
I have a jsp which has a text box depending on the value entered I want to get the value from a database for other two fields with out submitting jsp page. I am using struts.
Thanks For any assistance provided.Alright,here is an example for you for the first case.
Present.jsp:
============
<html:html>
<head>
<title><html:message key="page.title"/></title>
</head>
<body>
<html:form action="ChangeEvent.do">
<html:hidden property="method"/>
<!-- Submitting the Form onKeyUp of EmpId field and trying to save the
state of the Form in the scope of session -->
Emp Id:<html:text property="empId" size="5" onkeyup="if(true){this.form.elements[0].value='populateDetails';this.form.submit();}"/>
Emp Name:<html:text property="empName" size="10" />
Email Address:<html:text property="email" size="10" />
<html:submit>Submit</html:submit>
</html:form>
</body>
</html:html>struts-config.xml:
==================
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<!-- Form bean which stores the properties of all the Form elements -->
<form-beans>
<form-bean name="employeeFormBean" type="org.apache.struts.action.DynaActionForm">
<form-property name="empId" type="java.lang.String"/>
<form-property name="empName" type="java.lang.String"/>
<form-property name="email" type="java.lang.String" />
</form-bean>
</form-bean>
<action-mappings>
<action path="/ChangeEvent" type="Test.GetChangeAction" name="employeeFormBean" scope="request" parameter="method">
<!-- On successful call of DB the Page has to be forwarded to the same page again by
uploading updated form bean values. -->
<forward name="success" path="/Present.jsp"></forward>
<forward name="failed" path="/error.jsp"></forward>
</action>
</action-mappings>
</struts-config>GetChangeAction.java:
=====================
public class GetChangeAction extends DispatchAction{
public ActionForward populateDetails(ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
DynaActionForm dForm = (DynaActionForm)form;
String empId = dForm.get("empId");
// calling Model / Db and then getting back Employee Details
EmployeeBean eb = ModelUtils.getDetails(empId);
// Updating form bean by updating values from the Model
dForm.set("empName".eb.getEmpName());
dForm.set("email".eb.getEmail());
return mapping.findForward("success");
}well to me this should work regardless to any browser but we need to make sure we put in our logic properly. -
How to get argument value from portal desktop URL
hi,guys
I have a question ,it is how to get argument value.see:
in one portal desktop,I have a hyperlink like this
http://localhost:7001/TestPortal/appmanager/testPortal/testDST?eventId=1
after click,then will be switch another desktop "testDST"
I tried to get value from request,but failure.
@RequestMapping
public String listTestList(RenderRequest request, RenderResponse response,ModelMap model) {
//HttpServletRequest httpRequest = (HttpServletRequest) ; //request.getAttribute("javax.portlet.portletc.httpServletRequest");
//log.debug("httprequest eventId>>>" + httpRequest.getParameter("eventId"));
log.debug("render request eventId>>>" + request.getParameter("eventId"));
I can't get this value from request,also tried httpServeltRequest,but httpServletRequest can't get,it is null;
so ,how to get this value,thank you very much.
regards
arisHello,
It is true for JSR168 portlets that you can't just arbitrarily set parameters on a URL and get access to them inside your portlet- you must use the appropriate APIs on the PortletURL class to set parameters that you can retrieve. This is the only portable (standards-compliant) way to implement the functionality you want.
However, for your particular use-case, you can get the URL parameters from the (non-JSR168) HttpServletRequest object. The only reason you are getting a null object for that is because the attribute name is wrong. This should work:
HttpServletRequest httpRequest = (HttpServletRequest)(request.getAttribute("javax.servlet.request"));
String eventId = httpRequest.getParameter("eventId");
Kevin
Maybe you are looking for
-
Help! 10.5.5 has been acting up lately on my MacBook Pro!
Here is the deal! Below are a list of bugs that I notice every so often. Please tell me if you have seen any of them before or think there is a way to fix them: 1) Mail shows that there are two messages at the top of the window, where there is only O
-
Hello All, I am trying to deploy a webdynpro app .The backend connection fails . I am able to test the Jco Connection on SLD and the test is sucessfull. Please help Root Cause The initial exception that caused the request to fail, was: com.sap.tc.web
-
Duplex printing challenges - Canon Imagerunner C2550
I'm trying to perform some duplex printing with a Canon C2550. The printer is capable of duplex printing however the option to enable duplex printing in the printer settings on the Mac is greyed out. Trying to use the Canon iR C2380/2550 UFR II (US)
-
Hi, I'm developing some EJBs using workshop/ejbgen. I have an MDB working and now want to refer another local-ejb within it. Basically I have one application (top-level folder) in workshop with two EJB projects under it. One is the MDB and the other
-
Macbook pro 13 20 min boots and hangs
I got this in dec of 09 and its been great until now. Its taking like 20 mins to boot up and everything is so slow once it does. Ive tried disc utility, no errors. I put it into vebrose mode snd its saying somthing about convert launchd dashboardadvi