2016-02-18 3 views
4

Я пытаюсь создать CAP файл следующей программы для Java Card 2.2.1 совместимой платформы смарта-карты:Как создать Java CAP файлы с помощью командной строки

package helloWorldPackage; 

import javacard.framework.APDU; 
import javacard.framework.Applet; 
import javacard.framework.ISO7816; 
import javacard.framework.ISOException; 
import javacard.framework.Util; 

public class HelloWorldApplet extends Applet 
{ 
    private static final byte[] helloWorld = {(byte)'H',(byte)'e',(byte)'l',(byte)'l',(byte)'o',(byte)' ',(byte)'W',(byte)'o',(byte)'r',(byte)'l',(byte)'d',}; 
    private static final byte HW_CLA = (byte)0x80; 
    private static final byte HW_INS = (byte)0x00; 

    public static void install(byte[] bArray, short bOffset, byte bLength) 
     { 
     new HelloWorldApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]); 
     } 

    public void process(APDU apdu) 
     { 
     if (selectingApplet()) 
      { 
      return; 
      } 

     byte[] buffer = apdu.getBuffer(); 
     byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF); 
     byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF); 

     if (CLA != HW_CLA) 
      { 
      ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 
      } 

     switch (INS) 
      { 
      case HW_INS: 
       getHelloWorld(apdu); 
       break; 
      default: 
       ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 
      } 
     } 

    private void getHelloWorld(APDU apdu) 
     { 
     byte[] buffer = apdu.getBuffer(); 
     short length = (short) helloWorld.length; 
     Util.arrayCopyNonAtomic(helloWorld, (short)0, buffer, (short)0, (short) length); 
     apdu.setOutgoingAndSend((short)0, length); 
     } 
} 

Итак, я сохранил его в .java файл с именем HelloWorldApplet, а затем скомпилировать его .class файл, как показано ниже:

E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin>javac -g -source 1.2 -target 1.2 -cp "E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_ 
1-win-dom\lib\api.jar" "E:\ToCompile\HelloWorldApplet.java" 
warning: [options] bootstrap class path not set in conjunction with -source 1.2 
1 warning 

Q1: Что это предупреждение для?

После этого я попытался преобразовать этот .class файл в его .cap формы:

E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin>converter -debug -verbose -classdir E:\ToCompile helloWorldPackage 0xa0:0x0:0x0:0x0:0x6 
2:0x3:0x1:0xc:0x6:0x1 1.0 
error: input class directory E:\ToCompile\helloWorldPackage not found. 
Usage: converter <options> package_name package_aid major_version.minor_version 
OR 
converter -config <filename> 
        use file for all options and parameters to converter 
Where options include: 
     -classdir <the root directory of the class hierarchy> 
         set the root directory where the Converter 
         will look for classes 
     -i   support the 32-bit integer type 
     -exportpath <list of directories> 
         list the root directories where the Converter 
         will look for export files 
     -exportmap use the token mapping from the pre-defined export 
         file of the package being converted. The converter 
         will look for the export file in the exportpath 
     -applet <AID class_name> 
         set the applet AID and the class that defines the 
         install method for the applet 
     -d <the root directory for output> 
     -out [CAP] [EXP] [JCA] 
         tell the Converter to output the CAP file, 
         and/or the JCA file, and/or the export file 
     -V, -version print the Converter version string 
     -v, -verbose enable verbose output 
     -help   print out this message 
     -nowarn  instruct the Converter to not report warning messages 
     -mask   indicate this package is for mask, so restrictions on 
         native methods are relaxed 
     -debug  enable generation of debugging information 
     -nobanner  suppress all standard output messages 
     -noverify  turn off verification. Verification is default 

Ну, как вы видите я получаю ошибку: входной каталог класса E: \ ToCompile \ helloWorldPackage не найдено..

Q2: Почему конвертер ищет этот путь? Я указал каталог E:\ToCompile как класс, но он конкатенировал мой указанный путь с моим именем пакета программы! Зачем?

Q3: Когда мы открываем файл .cap с использованием Winrar, мы можем найти наш Пакет AID и нашу Апплетную AID в файлах header.cap и applet.cap. На приведенных выше шагах я указываю только мой пакет AID, и как он назначает Апплетную АД в файле cap?


Update: (Thanx г-Bodewes Ответ)

я переехал HelloWorldApplet.java и его файл генерируется класс (т.е. HelloWorldApplet.class) в папку с именем helloWorldPackage (My апплета имя пакета), в тот же каталог. А затем повторена команда новообращенный:

E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin>converter -debug -verbose -classdir E:\ToCompile\ helloWorldPackage 0xa0:0x0:0x0:0x0:0x 
62:0x3:0x1:0xc:0x6:0x1 1.0 

Java Card 2.2.2 Class File Converter, Version 1.3 
Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. 

parsing E:\ToCompile\helloWorldPackage\HelloWorldApplet.class 
converting helloWorldPackage.HelloWorldApplet 
error: export file framework.exp of package javacard.framework not found. 

conversion completed with 1 errors and 0 warnings. 

Из-за ошибки, я добавил -exportpath параметр в команде и попытался снова:

E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin>converter -debug -verbose -exportpath E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_ 
1-win-dom\api_export_files -classdir E:\ToCompile\ helloWorldPackage 0xa0:0x0:0x0:0x0:0x62:0x3:0x1:0xc:0x6:0x1 1.0 

Java Card 2.2.2 Class File Converter, Version 1.3 
Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. 

parsing E:\ToCompile\helloWorldPackage\HelloWorldApplet.class 
converting helloWorldPackage.HelloWorldApplet 
parsing E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\api_export_files\javacard\framework\javacard\framework.exp 
parsing E:\ToCompile\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\api_export_files\java\lang\javacard\lang.exp 
writing E:\ToCompile\helloWorldPackage\javacard\helloWorldPackage.exp 
writing E:\ToCompile\helloWorldPackage\javacard\helloWorldPackage.jca 
error: Static array initialization in class helloWorldPackage/HelloWorldApplet in library package not allowed. 

Cap file generation failed. 

conversion completed with 1 errors and 0 warnings. 

После небольшого борьбы, я, наконец, нашел, что, есть параметры для converter с именем applet, что, если я не использую его (в форме -applet <AppletAID> AppletClassName) в командной строке, тогда конвертер рассмотрит этот пакет как пакет библиотеки (у него нет Аппп-аптек в содержимом), но если я добавьте этот параметр в командную строку, как показано ниже, конвертер рассматривает пакет как Apple t и используйте AID, который я добавил к параметрам для назначения AID в header.cap (или, может быть, applet.cap) в файле cap. (Ответ моего Q3):

C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin>converter -debug -verbose -exportpath C:\Users\AmirEbrahim\Desktop\JC_C 
onverter\JCDK\java_card_kit-2_2_1-win-dom\bin -classdir C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin -applet 0xa0:0 
x0:0x0:0x0:0x62:0x3:0x1:0xc:0x6:0x1:0x2 HelloWorldApplet helloWorldPackage 0xa0:0x0:0x0:0x0:0x62:0x3:0x1:0xc:0x6:0x1 1.0 

Java Card 2.2.2 Class File Converter, Version 1.3 
Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. 

parsing C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin\helloWorldPackage\HelloWorldApplet.class 
converting helloWorldPackage.HelloWorldApplet 
parsing C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin\javacard\framework\javacard\framework.exp 
parsing C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin\java\lang\javacard\lang.exp 
writing C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin\helloWorldPackage\javacard\helloWorldPackage.exp 
writing C:\Users\AmirEbrahim\Desktop\JC_Converter\JCDK\java_card_kit-2_2_1-win-dom\bin\helloWorldPackage\javacard\helloWorldPackage.jca 

conversion completed with 0 errors and 0 warnings. 

ответ

2

warning: [options] bootstrap class path not set in conjunction with -source 1.2

What is this warning for?

предупреждение потому, что вы компиляции для совместимости кода в 1,2 источника с новой загрузки, то есть путь к классам одной из текущей JRE. Теперь, если вы используете более новые классы в JRE, вы не будете совместимы с Java 1.2. Это, конечно, не проблема, если все ваши классы используют только классы Java Card, как вам следует. Другими словами, вы можете смело игнорировать его.

Q2: Why the converter looking for this path? I specified E:\ToCompile directory as class directory, but it concatenated my specified path with my program package name! why?

В принципе структура папок исходного кода приложений Java не определена.На практике, однако, источники размещаются в папках, которые отражают имена пакетов. Поэтому, если в заявлении пакета указано package package1.package2; для MyApplet, тогда большинство инструментов ожидают, что исходный код будет в package1/package2/MyApplet.java в вашей исходной папке. Файлы классов помещаются в папки одинаково. Это справедливо для любого приложения Java, а не только для Java-карты.

Q3: When we open a .cap file using Winrar, we can find our Package AID and our Applet AID in header.cap and applet.cap files in it. In the above steps, I only specify my package AID, So how it assign the Applet AID in the cap file?

Если вы не предоставляете Applet класса/AID к преобразователю, то пакет считается пакетом библиотеки (который является пакетом без какого-либо состояния самостоятельно, состоящий только из кода, который может быть использован другие библиотеки и, конечно, апплеты).

+0

Я попытаюсь проверить последний ответ. –

+0

Еще раз благодарю вас, господин Бодеес. Вопрос обновлен. Взгляни, пожалуйста. –

+0

Спасибо за обновление, я изменил последнюю часть ответа соответственно. –

Смежные вопросы