Not getting response while reading data from smart card using JavaCard and APDU - applet

I studied all API and specification of java card
and I write a code for read data from smart card.
But I don't know where it return response.
The code I have written is given below.
private void readData(APDU apdu) throws ISOException
{
byte[] buffer = apdu.getBuffer();
short in_len1=apdu.setIncomingAndReceive();
apdu.receiveBytes(ISO7816.OFFSET_CDATA);
}
smart card type = contact card
using java card 2.2.2 with using apdu

you have to implement the process method (similar to the main method of a c program). see also http://www.oracle.com/technetwork/java/javacard/javacard2-138597.html

Related

Send localized email in GWT [duplicate]

I have an interface that extends the com.google.gwt.i18n.client.Messages class, which I use for retrieving i18n messages in my GWT application. It looks like this:
public interface MyMessages extends com.google.gwt.i18n.client.Messages {
#DefaultMessage("Hello world")
#Key("message1")
String message1();
#DefaultMessage("Hello again")
#Key("message2")
String message2();
//...
}
Normally, I create an instance of it using GWT.create() like so:
private MyMessages messages = GWT.create(MyMessages.class);
However, this does not work with server-side code, only client-side code (it throws an error saying that GWT.create() is only usable in client-side code).
The answer to a similar question points to a separate library that you can download which will let you access the i18n messages on the server, but I don't want to download any extra libraries (this seems like a simple problem, there must be a simple solution).
In summary: How can I access my i18n messages in server-side code? Thanks.
On the server side you can use the standard Java localization tools like ResourceBundle.
Look here for a tutorial how to use it.
// Create a ResourceBundle out of your property files
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle", currentLocale);
// Get localized value
String value = labels.getString(key);
The GWT specific way of creating an interface out of your property files and providing implementations via deferred binding can not be used on sever side Java.
If you are fearless and willing to spend the time, you can implement a code generation step to read your property files and generate implementation classes for your message interface. That's exactly what the Google GWT compiler does behind the scene.
I agree with Michael.. I was having this problem of trying to "localize" messages generated on the server.... but I decided to instead just throw an Exception on the server (because it is an error message which should only happen exceptionally) which contains the message code, which the client code can then look up and show the correct localized message to the user.
There's a great library for GWT internationalization gwt-dmesg. It allows you to 'share' .properties files between clent and server. However, project looks to be abandoned by author and you must recompile it manually for use with GWT versio >= 2.1.0.
GWT.create() can only be used in client-side code.
The good thing to do is that you provide your own I18NProvider class/interface, from which then you can extend to server side I18N factory and client side I18N factory read the same resource bundle.
After that you can simply use it all over your system, unify your code.
Hope that helps.
Following vanje's answer, and considering the encoding used for the properties files (which can be troublesome as ResourceBundle uses by default "ISO-8859-1", here is the solution I came up with:
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyResourceBundle {
// feature variables
private ResourceBundle bundle;
private String fileEncoding;
public MyResourceBundle(Locale locale, String fileEncoding){
this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
this.fileEncoding = fileEncoding;
}
public MyResourceBundle(Locale locale){
this(locale, "UTF-8");
}
public String getString(String key){
String value = bundle.getString(key);
try {
return new String(value.getBytes("ISO-8859-1"), fileEncoding);
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
The way to use this would be very similar than the regular ResourceBundle usage:
private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)
Or you can use the alternate constructor which uses UTF-8 by default:
private MyResourceBundle labels = new MyResourceBundle("es");

RPCManager RPCRequest how to capture the response in gwt

hi i have requirement to capture the data for validations. i am able to fetch the data using RPCRequest and RPCManager by using setActionUrl to the controller class.from there creating the service class and dao classes .i am able to fetch the data into controller class.but i am unable get the data back into my grid.i want the data to be fetched into a variable.i am not using asynchronus service.i used async method in grid i am able to fetch into onSuccess() method.but without using how i can fetch.the data into grid.
with regards
subodh
Here example in our ServiceImpl class to retrive datas from DB
public final String getDatas(final HashMap<String, String> param) {
List<ShippingBean> result = null;
JSONObject obj = new JSONObject();
try {
// retrieve data from DB
data = dao.selectAll();
}
catch (BusinessException e) {
throw new InvocationException("BusinessException occurs ...", e);
}
obj = JSONObject.fromObject(result);
return obj.toString();
}
We use net.sf.json to serialize as DOM and return this to presenter call as AsyncCallBack method. And then , retrieve data as like that..
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("Error!");
}
public void onSuccess(final String result) {
HTML html = new HTML(result.replace(" ", "-"));
JSONValue value = JSONParser.parseLenient(html.getText());
JSONWrapper json = new JSONWrapper(value);
System.out.println(json.get(0).get("variableName").stringValue());
}
};
I have done something similar within a project with retrieve data and posting it to GWT from database. My database setup was Microsoft SQL 2012 and Hibernate framework to retrieve it. However I created a custom try/catch block and if/else bocks for validation on client side.
I used this tutorial from Hibernate to GWT to set up the transactions between the web application and the database for both saving and retrieving. Their source code provides the web page modules for setting up the displaying which I mimicked to fit to my needs since I was not storing "records" or "users".
GWT does have a validation setup but I spent a 10 hours trying to figure out the client side validation and gave up for something much simpler such as try/catch on the data being submitted since I had no concern for the format of the numbers.
Google "GWT Validation" and you should have some documentation about it but their isn't that much to choose from since everything seems to be a copy of Google's documentation.
Link - Hibernate to GWT
Hope this helps or points you in the right direction towards your answer.

What METHOD do I use for a Delayed Capture process?

The documentation I see says I should be making a call and passing an ORIGID. But, what is the METHOD? Straight from the documentation:
TRXTYPE=D&TENDER=C&PWD=x1y2z3&PARTNER=PayPal&VENDOR=.SuperMerchant
&USER=SuperMerchant&ORIGID=VXYZ00887892
Okay, that's awesome. How do I actually make that call? Am I using the wrong API's? I have been doing a DoCapture, but this requires a three step process to get a Transaction ID, which appears to be vastly different from this ORIGID.
PayPal has several flavors of APIs. The API string you listed is an example of the Payflow Pro API suite which is commonly used by merchants who use PayPal as a payment gateway only. It does not have a METHOD: instead TRXTYPE=D specifies that it is a delayed capture. For more info on Payflow API you should refer to https://www.paypalobjects.com/webstatic/en_US/developer/docs/pdf/pp_payflowpro_guide.pdf.
I struggled with this for a long time. The PayPal folks don't seem to understand .NET much. So I finally got it to work this way (.Net solution). This solution uses an added user (test123)I created at PayPal:
protected void Button1_Click(object sender, EventArgs e)
{
string myTokenRequest = "PARTNER=PayPal&VENDOR=kathypatrick77&USER=test123&PWD=test321&TRXTYPE=A&AMT=2.00&CREATESECURETOKEN=Y&SECURETOKENID=20128208de1413abc3d60c86v46yd+#dffg5";
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create("https://pilot-payflowpro.paypal.com");
wrWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(myTokenRequest);
requestWriter.Close();
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
//and read the response
string responseData = responseReader.ReadToEnd();
TextBox1.Text = responseData.ToString();
responseReader.Close();
}

JAX-WS SoapHandler with large messages: OutOfMemoryError

Using JAX-WS 2, I see an issue that others have spoken about as well. The issue is that if a SOAP message is received inside a handler, and that SOAP message is large - whether due to inline SOAP body elements that happen to have lots of content, or due to MTOM attachments - then it is dangerously easy to get an OutOfMemoryError.
The reason is that the call to getMessage() seems to set off a chain of events that involve reading the entire SOAP message on the wire, and creating an object (or objects) representing what was on the wire.
For example:
...
public boolean handleMessage(SOAPMessageContext context)
{
// for a large message, this will cause an OutOfMemoryError
System.out.println( context.getMessage().countAttachments() );
...
My question is: is there a known mechanism/workaround for dealing with this? Specifically, it would be nice to access the SOAP part in a SOAP message without forcing the attachments (if MTOM for example) to also be vacuumed up.
For those who run their app on JBoss 6 & 7 (with Apache CXF)... I was able to troubleshoot the problem by implementing my handler from the LogicalHandler interface instead of the SOAPHandler.
In this case your handleMessage() method would get the LogicalMessageContext context (instead of SOAPMessageContext) in the arguments that has no issues with the context.getMessage() call
There's actually a JAX-WS RI (aka Metro) specific solution for this which is very effective.
See https://javaee.github.io/metro/doc/user-guide/ch02.html#efficient-handlers-in-jax-ws-ri. Unfortunately that link is now broken but you can find it on WayBack Machine. I'll give the highlights below:
The Metro folks back in 2007 introduced an additional handler type, MessageHandler<MessageHandlerContext>, which is proprietary to Metro. It is far more efficient than SOAPHandler<SOAPMessageContext> as it doesn't try to do in-memory DOM representation.
Here's the crucial text from the original blog article:
MessageHandler:
Utilizing the extensible Handler framework provided by JAX-WS
Specification and the better Message abstraction in RI, we introduced
a new handler called MessageHandler to extend your Web Service
applications. MessageHandler is similar to SOAPHandler, except that
implementations of it gets access to MessageHandlerContext (an
extension of MessageContext). Through MessageHandlerContext one can
access the Message and process it using the Message API. As I put in
the title of the blog, this handler lets you work on Message, which
provides efficient ways to access/process the message not just a DOM
based message. The programming model of the handlers is same and the
Message handlers can be mixed with standard Logical and SOAP handlers.
I have added a sample in JAX-WS RI 2.1.3 showing the use of
MessageHandler to log messages and here is a snippet from the sample:
public class LoggingHandler implements MessageHandler<MessageHandlerContext> {
public boolean handleMessage(MessageHandlerContext mhc) {
Message m = mhc.getMessage().copy();
XMLStreamWriter writer = XMLStreamWriterFactory.create(System.out);
try {
m.writeTo(writer);
} catch (XMLStreamException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean handleFault(MessageHandlerContext mhc) {
.....
return true;
}
public void close(MessageContext messageContext) { }
public Set getHeaders() {
return null;
}
}
(end quote from 2007 blog post)
You can find a full example in the Metro GitHub repo.
What JAX-WS implementation runtime are you using? If there's a way to do this using the runtime built into WebSphere I'm certain there's a way to do this cleanly in other runtimes like Axis2 (proper), Apache CXF, and Metro/RI.
I am using the other way to reduce the memory costing, which is Message Accessor.
Instead of using context.getMessage(), I changed it to this way:
Object accessor = context.get("jaxws.message.accessor");
if (accessor != null) {
baosInString = accessor.toString();
}
Base on advice from IBM website. http://www-01.ibm.com/support/docview.wss?uid=swg1PM21151

Binary Data and GWT

There are a couple of questions about binary data and GWT already. After reading them I am still not sure if the following is possible or not (I am a complete GWT beginner though!):
I have some very complicated data-files with only exist in binary form and I cannot convert them to something like XML or JSON. I have a closed source library though that accepts a byte[] and returns a Java object I can use. To get my GWT-app running I 'printed out' one of those binary data files and hard-coded the resulting byte[] in a .java file I access from my GWT-app code. Everything works fine. Obviously this is only a test and in the deployed app I cannot hard-code those data-files. I want to place them in the directory my GWT-app resides and the 'load' them with my GWT app.
I take it I can 'load' text files from my server with GWT, right? Why can't I read binary data with GWT? Or can I read the binary-data-files as text and the String into a byte[]? I read a lot about base64 encoding and that GWT can read it, although I don't really understand what they are talking about. Can I configure my server to serve those binary-data-files as base64 encoded and then read them with GWT?
Or is there some other solution? I wouldn't like to touch any JS code if I can help it. That's why I started using GWT ;)
Thanks for your help :)
Let's presume we are on HTML 4.
GWT client cannot "read" files. GWT client is javascript running on a browser. Browser security does not allow you to read local files. You have to get the servlet to proxy read the file for you on the server.
You set the mime type for a file because you want the browser to download a file and invoke the local PC to invoke the appropriate software - for example, pdf to invoke pdf reader or xls to invoke ms excel. Nothing to do with GWT Java or Javascript (except to enable the download).
Why do you need GWT client to read the binary file? If you do, your architecture is probably wrong. "Wrong" is an unkind word. Perhaps, misaligned is a better word. Your concept of AJAX thin client-server is misaligned. Drop your desktop processing concepts and habits at the door when you enter the door of GWT.
GWT is Java but not Java
I keep having to remind people that GWT Java is merely a more coherent representation of Javascript. When you code in GWT Java, always remember you are actually coding in Javascript not Java. All Java source is translated to Javascript
Therefore, the GWT compiler needs all Java classes to be supplied in source code. The GWT compiler has no ability to translate Java bytecode jar/class files into Javascript. If your library is in bytecode or your source library calls a bytecode library anywhere down the calling chain, the compilation will fail.
Confusion between server side and client side GWT
GWT RPC is sometimes source of confusion for GWT newbies. They don't seem to realise that the remote servlet is the only part that is compiled into bytecode because it is running on the server. Especially so, if you are using Vaadin - because they have so intentionally blurred the line between server and browser. And so the GWT newbie goes off wondering, "why do my bytecode libraries work at certain parts of the app only?"
The ajax client server architecture
GWT is merely a web enabled UI. Why can't you do whatever you want to do on the server and let the server reflect what it is doing or has done to the UI? Why must it be done on the browser?
Just imagine your GWT interface as a souped up JSP. Imagine you are writing a JSP. Do you get your JSP to suck your binary data into the browser and get the JSP to generate Javascript to analyse the binary data there?
I have written complex statistical analyses and I merely used the browser as a reflection of what is being done on the server. The engineer thinks he/she is running the analysis on his/her PC. Charts/reports are generated. But it's all done on the server by calling SAS.
The service oriented pattern/architecture
Your server will present services. Your browser GWT client will request for those services.
Open a file, read the file, analyse the file, generate a visual/mime representation of analysis and pass it to the browser. Simply think of the GWT browser client as the display monitor for your server based manipulation. GWT is a magician's trick to help me conjure the illusion to let the engineers feel they are performing analysis on the local PC. Being engineers, of course, most of them know the browser is not actually doing the work.
When your user is satisfied with the analysis, get your service to generate a mime-representation of the results so that it could be downloaded by the browser to invoke the appropriate local PC software as mapped by the mime.
Do it on the server and reflect it on the browser.
Further Edits: Concerning binary data ...
The motivation behind base64 encoding being used in web apps: transmission of auth tokens, picture, audio files - so that their binary representation and sequencing would not be messed up by architectural nuances like endianness.
e.g., do not attempt writing a browser app to read a raw binary spreadsheet - always have the server translate it into XML or JSON (preferably JSON) where any binary element should be base64 encoded, before sending it to the browser app. Or if the purpose of your life is to climb Mt Everest, invent an architecture-agnostic encoding in place of base64 to transmit binary data.
Use only binary info if it was for the browser's OS processing (like audio, pictures, pdfs). No point in sending binary data to be processed solely by a javascript routine. The javascript routine would have to use extraneous processing time to translate it (unless again, if the purpose in your life is to climb ... ).
Yes it is possible.
Two solutions depending on the type of data.
Dynamic (if the binary data is dynamic and might change):
Just Base64 encode your binary data on your backend and serve them (i.e GET request).
Then you can use any of GWT's communication protocols (see here for more details) to retrieve the data from the backend.
You then have to base64 decode the data and work with it (as you already have solved it).
Static (if the binary data won't change and is known during compile time):
You can use ClientBundle (i.e.: DataResource) to generate those binary files during compile time and they can then be automatically retrieved on the client side without manually setting up transferring them.
Client Side:
#Override
public void onModuleLoad()
{
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "/test");
try
{
rb.sendRequest(null, new RequestCallback()
{
#Override
public void onResponseReceived( Request request, Response response )
{
String encoded = response.getText();
byte[] data = decode(encoded);
System.out.println(Arrays.toString(data));
}
#Override
public void onError( Request request, Throwable exception )
{
}
});
}
catch( RequestException e )
{
e.printStackTrace();
}
}
private final static String base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public static byte[] decode( String s )
{
// remove/ignore any characters not in the base64 characters list
// or the pad character -- particularly newlines
s = s.replaceAll("[^" + base64chars + "=]", "");
// replace any incoming padding with a zero pad (the 'A' character is
// zero)
String p = (s.charAt(s.length() - 1) == '=' ? (s.charAt(s.length() - 2) == '=' ? "AA" : "A") : "");
s = s.substring(0, s.length() - p.length()) + p;
int resLength = (int) Math.ceil(((s.length()) / 4f) * 3f);
byte[] bufIn = new byte[resLength];
int bufIn_i = 0;
// increment over the length of this encrypted string, four characters
// at a time
for( int c = 0; c < s.length(); c += 4 )
{
// each of these four characters represents a 6-bit index in the
// base64 characters list which, when concatenated, will give the
// 24-bit number for the original 3 characters
int n = (base64chars.indexOf(s.charAt(c)) << 18) + (base64chars.indexOf(s.charAt(c + 1)) << 12)
+ (base64chars.indexOf(s.charAt(c + 2)) << 6) + base64chars.indexOf(s.charAt(c + 3));
// split the 24-bit number into the original three 8-bit (ASCII)
// characters
char c1 = (char) ((n >>> 16) & 0xFF);
char c2 = (char) ((n >>> 8) & 0xFF);
char c3 = (char) (n & 0xFF);
bufIn[bufIn_i++] = (byte) c1;
bufIn[bufIn_i++] = (byte) c2;
bufIn[bufIn_i++] = (byte) c3;
}
byte[] out = new byte[bufIn.length - p.length()];
System.arraycopy(bufIn, 0, out, 0, out.length);
return out;
}
Server Side(Java):
#Override
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
byte[] binaryData = new byte[1000];
for( int i = 0; i < 1000; i++ )
binaryData[i] = (byte) (Byte.MIN_VALUE + (i % (Math.pow(2, Byte.SIZE))));
System.out.println("Sending: " + Arrays.toString(binaryData));
byte[] base64Encoded = org.apache.commons.codec.binary.Base64.encodeBase64(binaryData);
response.setContentType("application/octet-stream");
PrintWriter out = response.getWriter();
out.write(new String(base64Encoded));
}
Here's a solution that lets you easily read bytes from any URL:
XMLHttpRequest request = XMLHttpRequest.create();
request.open("GET", "http://127.0.0.1:8888/sample/index.bin");
request.setResponseType(ResponseType.ArrayBuffer);
request.setOnReadyStateChange(new ReadyStateChangeHandler() {
#Override
public void onReadyStateChange(XMLHttpRequest xhr) {
if (xhr.getReadyState() == XMLHttpRequest.DONE) {
if (xhr.getStatus() == 200) {
ArrayBuffer buffer = xhr.getResponseArrayBuffer();
Uint8Array array = TypedArrays.createUint8Array(buffer);
System.out.println("got " + array.length() + " bytes: ");
for (int i = 0; i < array.length(); i++) {
System.out.println(array.get(i));
}
} else {
System.out.println("response status: " + xhr.getStatus() + " " + xhr.getStatusText());
}
}
}
});
request.send();