Return null sur ma ressource [Résolu/Fermé]

Signaler
Messages postés
32
Date d'inscription
jeudi 31 décembre 2015
Statut
Membre
Dernière intervention
8 janvier 2016
-
Messages postés
16370
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
18 juillet 2021
-
Bonjour tous le monde,

J'accède à une ressource (http://localhost:8080/CountryCode/v1/e212/33) seulement dans mon logger j'ai un return null alors que je retourne bien quelque chose.

Je vous mets l'intégralité du code, je sais que ça va être long mais j'en suis désolé, je ne vois vraiment pas le problème...

CountriesUtil.java

public class CountriesUtil {
    private static final Logger logger = Logger.getLogger(CountriesUtil.class);
    private static final JSONArray ja =  new JSONArray();
    private static final Hashtable<String, String> name = new Hashtable<String, String>();
    private static final Hashtable<String, String> alpha2 = new Hashtable<String, String>();
    private static final Hashtable<String, String> alpha3 = new Hashtable<String, String>();
    private static final Hashtable<String, String> e212 = new Hashtable<String, String>();
    private static final Hashtable<String, String> latlon = new Hashtable<String, String>();
    private static int size = 5;
    private static int nbCountries;
    
    private static String encode(String content) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer bb = ByteBuffer.wrap(content.getBytes());
        CharBuffer cb = cs.decode(bb);
        String s = cb.toString();
        return s;
    }
    private static void set(String key, JSONObject jo) {
        if (alpha2.containsKey(key))
            logger.info("key: " + key + " existe deja");
        alpha2.put(key, "{\"ISO3166_1_Alpha_2\":\"" + (String) jo.get("ISO3166_1_Alpha_2") + "\"}");
        alpha3.put(key, "{\"ISO3166_1_Alpha_3\":\"" + (String) jo.get("ISO3166_1_Alpha_3") + "\"}");
        name.put(key, "{\"name\":\"" + (String) jo.get("name") + "\"}");
        e212.put(key, "{\"ITU_E212\":\"" + (String) jo.get("ITU_E212") + "\"}");
        latlon.put(key, "{\"lat\":\"" + (String) jo.get("lat") + "\",\"lng\":\"" + (String) jo.get("lng") + "\"}");
    }
 
    @SuppressWarnings("unchecked")
    public static void init(ServletContext servletContext) {
        try {
             
            JSONObject jo = new JSONObject();
            InputStream ips = servletContext.getResourceAsStream("./WebContent/WEB-INF/countries.txt");
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String ligne;
            boolean first = true;
            String[] keys = null;
            String[] values = null;
            // create json
            while ((ligne = br.readLine()) != null) {
                ligne = encode(ligne);
                if (first) {
                    first = false;
                    keys = ligne.split(";");
                    for (int i = 0; i < keys.length; i++)
                        logger.info(keys[i]);
 
                } else {
                    values = ligne.split(";");
                    jo = new JSONObject();
                    for (int i = 0; i < keys.length; i++) {
                        jo.put(keys[i], values[i]);
                    }
                    ja.add(jo);
                    logger.info(jo.toJSONString());
                }
            }
            nbCountries = ja.size();
 
            for (int i = 0; i < ja.size(); i++) {
                jo = (JSONObject) ja.get(i);
                String CC = (String) jo.get("CC");
                String NDC = (String) jo.get("NDC");
                if (!NDC.isEmpty()) {
                    String[] NDCs = NDC.split(",");
                    for (int j = 0; j < NDCs.length; j++) {
                        String CCNDC = CC + NDCs[j];
                        logger.info("CCNDC: " + CCNDC);
                        CCNDC = CCNDC.trim();
                        if (CCNDC.length() > size)
                            size = CCNDC.length() + 1;
                        set(CCNDC, jo);
                    }
                } else {
                    set(CC, jo);
                    logger.info("CCNDC: " + CC);
                }
            }
 
            br.close();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }
 
 
 
    public static String getE212(String Number) {
        for (int i = size; i > 0; i--) {
            if (Number.length() >= i - 1) {
                String key = Number.substring(0, i - 1);
                logger.info("i: " + i + ", number: " + Number.length() + ", key: " + key);
                if (e212.containsKey(key))
                    return e212.get(key);
            }
        }
        return null;
    }
 
}



e212.java

@Path("/e212")
@Api(value = "/e212", description = "Get Mobile Code Country (E212) from the phone number")
@Produces({ "application/json", "application/xml" })
public class e212 {
 
    private static final Logger logger = Logger.getLogger(e212.class);
 
    @GET
    @Path("/{param}")
    @ApiOperation(value = "return param", notes = "see ITU-E212", response = e212.class)
    @ApiImplicitParam(name = "param",value = "id", required = true, dataType = "string", paramType = "path")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Process error"),
            @ApiResponse(code = 204, message = "No content") })
    @Produces(MediaType.TEXT_HTML)
    public String getSomething(@PathParam("param") String id) {
 
        logger.info("start");
        if (logger.isDebugEnabled()) {
            logger.debug("Start getSomething");
            logger.debug("data: '" + id + "'");
        }
        String response = CountriesUtil.getE212(id);
 
        if (logger.isDebugEnabled()) {
            logger.debug("result: '" + response + "'");
            logger.debug("End getSomething");
        }
        return response;
    }
 
     
}


ContextListener.java

public class ContextListener implements ServletContextListener {
 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        BasicConfigurator.configure();
        CountriesUtil.init(sce.getServletContext());
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
 
    }
 
}


countries.txt

name;ISO3166_1_Alpha_2;ISO3166_1_Alpha_3;ITU_E212;CC;NDC;is_independent;lat;lng
Andorra;AD;AND;213;376; ;Yes;42.5;1.5
United Arab Emirates;AE;ARE;430,424,431;971; ;Yes;24;54
Afghanistan;AF;AFG;412;93; ;Yes;33;65
Antigua and Barbuda;AG;ATG;344;1;268;Yes;17.05;-61.8
Anguilla;AI;AIA;365;1;264;Territory of GB;18.25;-63.1667
Albania;AL;ALB;276;355; ;Yes;41;20
Armenia;AM;ARM;283;374; ;Yes;40;45
Angola;AO;AGO;631;244; ;Yes;-12.5;18.5
Antarctica;AQ;ATA; ;672;10,11,12,13;International;-90;0
Argentina;AR;ARG;722;54; ;Yes;-34;-64
American Samoa;AS;ASM;544;1;684;Territory of US;-14.3333;-170
Austria;AT;AUT;232;43; ;Yes;47.3333;13.3333
Australia;AU;AUS;505;61; ;Yes;-27;133
Aruba;AW;ABW;363;297; ;Part of NL;12.5;-69.9667
Åland Islands;AX;ALA; ;358;18; ;12.5;-69.9667
Azerbaijan;AZ;AZE;400;994; ;Yes;40.5;47.5
Bosnia and Herzegovina;BA;BIH;218;387; ;Yes;44;18
Barbados;BB;BRB;342;1;246;Yes;13.1667;-59.5333
Bangladesh;BD;BGD;470;880; ;Yes;24;90
Belgium;BE;BEL;206;32; ;Yes;50.8333;4
Burkina Faso;BF;BFA;613;226; ;Yes;13;-2
Bulgaria;BG;BGR;284;359; ;Yes;43;25
Bahrain;BH;BHR;426;973; ;Yes;26;50.55
Burundi;BI;BDI;642;257; ;Yes;-3.5;30
Benin;BJ;BEN;616;229; ;Yes;9.5;2.25
Saint Barthélemy;BL;BLM; ;590;27,29;Part of FR;9.5;2.25
Bermuda;BM;BMU;350;1;441;Territory of GB;32.3333;-64.75
Brunei Darussalam;BN;BRN;528;673; ;Yes;4.5;114.6667
Bolivia,Plurinational State of;BO;BOL;736;591; ;Yes;-17;-65
Bonaire,Sint Eustatius and Saba;BQ;BES;362;599;717,5;Part of NL;-17;-65
Brazil;BR;BRA;724;55; ;Yes;-10;-55
Bahamas;BS;BHS;364;1;242;Yes;24.25;-76
Bhutan;BT;BTN;402;975; ;Yes;27.5;90.5
Bouvet Island;BV;BVT; ;47; ;Territory of NO;-54.4333;3.4
Botswana;BW;BWA;652;267; ;Yes;-22;24
Belarus;BY;BLR;257;375; ;Yes;53;28
Belize;BZ;BLZ;702;501; ;Yes;17.25;-88.75
Canada;CA;CAN;302;1;204,226,236,249,250,289,306,343,365,403,416,418,431,438,450,506,514,519,579,581,587,604,613,647,705,709,778,780,807,819,825,867,873,902,905;Yes;60;-95
Cocos (Keeling) Islands;CC;CCK; ;61;8;Territory of AU;-12.5;96.8333
Congo,the Democratic Republic of the;CD;COD;630;243; ;Yes;0;25
Central African Republic;CF;CAF;623;236; ;Yes;7;21
Congo;CG;COG;629;242; ;Yes;-1;15
Switzerland;CH;CHE;228;41; ;Yes;47;8
Côte d'Ivoire;CI;CIV;612;225; ;Yes;8;-5
Cook Islands;CK;COK;548;682; ;Associated with NZ;-21.2333;-159.767
Chile;CL;CHL;730;56; ;Yes;-30;-71
Cameroon;CM;CMR;624;237; ;Yes;6;12
China;CN;CHN;460,461;86; ;Yes;35;105
Colombia;CO;COL;732;57; ;Yes;4;-72
Costa Rica;CR;CRI;712;506; ;Yes;10;-84
Cuba;CU;CUB;368;53; ;Yes;21.5;-80
Cape Verde;CV;CPV;625;238; ;Yes;16;-24
Curaçao;CW;CUW;362;599;9;Part of NL;16;-24
Christmas Island;CX;CXR; ;61;89164;Territory of AU;-10.5;105.6667
Cyprus;CY;CYP;280;357; ;Yes;35;33
Czech Republic;CZ;CZE;230;420; ;Yes;49.75;15.5
Germany;DE;DEU;262;49; ;Yes;51;9
Djibouti;DJ;DJI;638;253; ;Yes;11.5;43
Denmark;DK;DNK;238;45; ;Yes;56;10
Dominica;DM;DMA;366;1;767;Yes;15.4167;-61.3333
Dominican Republic;DO;DOM;370;19;809,829,849;Yes;19;-70.6667
Algeria;DZ;DZA;603;213; ;Yes;28;3
Ecuador;EC;ECU;740;593; ;Yes;-2;-77.5
Estonia;EE;EST;248;372; ;Yes;59;26
Egypt;EG;EGY;602;20; ;Yes;27;30
Western Sahara;EH;ESH; ;212; ;In contention;24.5;-13
Eritrea;ER;ERI;657;291; ;Yes;15;39
Spain;ES;ESP;214;34; ;Yes;40;-4
Ethiopia;ET;ETH;636;251; ;Yes;8;38
Finland;FI;FIN;244;358; ;Yes;64;26
Fiji;FJ;FJI;542;679; ;Yes;-18;175
Falkland Islands (Malvinas);FK;FLK;750;500;21,32;Territory of GB;-51.75;-59
Micronesia,Federated States of;FM;FSM;550;691; ;Yes;6.9167;158.25
Faroe Islands;FO;FRO;288;298; ;Part of DK;62;-7
France;FR;FRA;208;33; ;Yes;46;2
Gabon;GA;GAB;628;241; ;Yes;-1;11.75
United Kingdom;GB;GBR;234,235;44; ;Yes;54;-2
Grenada;GD;GRD;352;1;473;Yes;12.1167;-61.6667
Georgia;GE;GEO;282;995; ;Yes;42;43.5
French Guiana;GF;GUF;742;594; ;Part of FR;4;-53
Guernsey;GG;GGY; ;44;1481;Crown dependency of GB;4;-53
Ghana;GH;GHA;620;233; ;Yes;8;-2
Gibraltar;GI;GIB;266;350; ;Territory of GB;36.1833;-5.3667
Greenland;GL;GRL;290;299; ;Part of DK;72;-40
Gambia;GM;GMB;607;220; ;Yes;13.4667;-16.5667
Guinea;GN;GIN;611;224; ;Yes;11;-10
Guadeloupe;GP;GLP;340;590; ;Part of FR;16.25;-61.5833
Equatorial Guinea;GQ;GNQ;627;240; ;Yes;2;10
Greece;GR;GRC;202;30; ;Yes;39;22
South Georgia and the South Sandwich Islands;GS;SGS; ;500; ;Territory of GB;-54.5;-37
Guatemala;GT;GTM;704;502; ;Yes;15.5;-90.25
Guam;GU;GUM; ;1;671;Territory of US;13.4667;144.7833
Guinea-Bissau;GW;GNB;632;245; ;Yes;12;-15
Guyana;GY;GUY;738;592; ;Yes;5;-59
Hong Kong;HK;HKG;454;852; ;Part of CN;22.25;114.1667
Heard Island and McDonald Mcdonald Islands;HM;HMD; ;672; ;Territory of AU;-53.1;72.5167
Honduras;HN;HND;708;504; ;Yes;15;-86.5
Croatia;HR;HRV;219;385; ;Yes;45.1667;15.5
Haiti;HT;HTI;372;509; ;Yes;19;-72.4167
Hungary;HU;HUN;216;36; ;Yes;47;20
Indonesia;ID;IDN;510;62; ;Yes;-5;120
Ireland;IE;IRL;272;353; ;Yes;53;-8
Israel;IL;ISR;425;972; ;Yes;31.5;34.75
Isle of Man;IM;IMN; ;44;1624;Crown dependency of GB;31.5;34.75
India;IN;IND;404,405,406;91; ;Yes;20;77
British Indian Ocean Territory;IO;IOT; ;246; ;Territory of GB;-6;71.5
Iraq;IQ;IRQ;418;964; ;Yes;33;44
Iran,Islamic Republic of;IR;IRN;432;98; ;Yes;32;53
Iceland;IS;ISL;274;354; ;Yes;65;-18
Italy;IT;ITA;222;39; ;Yes;42.8333;12.8333
Jersey;JE;JEY; ;44;1534;Crown dependency of GB;42.8333;12.8333
Jamaica;JM;JAM;338;1;876;Yes;18.25;-77.5
Jordan;JO;JOR;416;962; ;Yes;31;36
Japan;JP;JPN;440,441;81; ;Yes;36;138
Kenya;KE;KEN;639;254; ;Yes;1;38
Kyrgyzstan;KG;KGZ;437;996; ;Yes;41;75
Cambodia;KH;KHM;456;855; ;Yes;13;105
Kiribati;KI;KIR;545;686; ;Yes;1.4167;173
Comoros;KM;COM;654;269; ;Yes;-12.1667;44.25
Saint Kitts and Nevis;KN;KNA;356;1;869;Yes;17.3333;-62.75
Korea,Democratic People's Republic of;KP;PRK;467;850; ;Yes;40;127
Korea,Republic of;KR;KOR;450;82; ;Yes;37;127.5
Kuwait;KW;KWT;419;965; ;Yes;29.3375;47.6581
Cayman Islands;KY;CYM;346;1;345;Territory of GB;19.5;-80.5
Kazakhstan;KZ;KAZ;401;7;700;Yes;48;68
Lao People's Democratic Republic;LA;LAO;457;856; ;Yes;18;105
Lebanon;LB;LBN;415;961; ;Yes;33.8333;35.8333
Saint Lucia;LC;LCA;358;1;758;Yes;13.8833;-61.1333
Liechtenstein;LI;LIE;295;423; ;Yes;47.1667;9.5333
Sri Lanka;LK;LKA;413;94; ;Yes;7;81
Liberia;LR;LBR;618;231; ;Yes;6.5;-9.5
Lesotho;LS;LSO;651;266; ;Yes;-29.5;28.5
Lithuania;LT;LTU;246;370; ;Yes;56;24
Luxembourg;LU;LUX;270;352; ;Yes;49.75;6.1667
Latvia;LV;LVA;247;371; ;Yes;57;25
Libya;LY;LBY;606;218; ;Yes;25;17
Morocco;MA;MAR;604;212; ;Yes;32;-5
Monaco;MC;MCO;212;377; ;Yes;43.7333;7.4
Moldova,Republic of;MD;MDA;259;373; ;Yes;47;29
Montenegro;ME;MNE;297;382; ;Yes;42;19
Saint Martin (French part);MF;MAF; ;590;90,52,87,70,53,64;Part of FR;42;19
Madagascar;MG;MDG;646;261; ;Yes;-20;47
Marshall Islands;MH;MHL;551;692; ;Yes;9;168
Macedonia,the Former Yugoslav Republic of;MK;MKD;294;389; ;Yes;41.8333;22
Mali;ML;MLI;610;223; ;Yes;17;-4
Myanmar;MM;MMR;414;95; ;Yes;22;98
Mongolia;MN;MNG;428;976; ;Yes;46;105
Macao;MO;MAC;455;853; ;Part of CN;22.1667;113.55
Northern Mariana Islands;MP;MNP; ;1;670;Commonwealth of US;15.2;145.75
Martinique;MQ;MTQ;340;596; ;Part of FR;14.6667;-61
Mauritania;MR;MRT;609;222; ;Yes;20;-12
Montserrat;MS;MSR;354;1;664;Territory of GB;16.75;-62.2
Malta;MT;MLT;278;356; ;Yes;35.8333;14.5833
Mauritius;MU;MUS;617;230; ;Yes;-20.2833;57.55
Maldives;MV;MDV;472;960; ;Yes;3.25;73
Malawi;MW;MWI;650;265; ;Yes;-13.5;34
Mexico;MX;MEX;334;52; ;Yes;23;-102
Malaysia;MY;MYS;502;60; ;Yes;2.5;112.5
Mozambique;MZ;MOZ;643;258; ;Yes;-18.25;35
Namibia;NA;NAM;649;264; ;Yes;-22;17
New Caledonia;NC;NCL;546;687; ;Territory of FR;-21.5;165.5
Niger;NE;NER;614;227; ;Yes;16;8
Norfolk Island;NF;NFK; ;672;3;Territory of AU;-29.0333;167.95
Nigeria;NG;NGA;621;234; ;Yes;10;8
Nicaragua;NI;NIC;710;505; ;Yes;13;-85
Netherlands;NL;NLD;204;31; ;Yes;52.5;5.75
Norway;NO;NOR;242;47; ;Yes;62;10
Nepal;NP;NPL;429;977; ;Yes;28;84
Nauru;NR;NRU;536;674; ;Yes;-0.5333;166.9167
Niue;NU;NIU;555;683; ;Associated with NZ;-19.0333;-169.867
New Zealand;NZ;NZL;530;64; ;Yes;-41;174
Oman;OM;OMN;422;968; ;Yes;21;57
Panama;PA;PAN;714;507; ;Yes;9;-80
Peru;PE;PER;716;51; ;Yes;-10;-76
French Polynesia;PF;PYF;547;689; ;Territory of FR;-15;-140
Papua New Guinea;PG;PNG;537;675; ;Yes;-6;147
Philippines;PH;PHL;515;63; ;Yes;13;122
Pakistan;PK;PAK;410;92; ;Yes;30;70
Poland;PL;POL;260;48; ;Yes;52;20
Saint Pierre and Miquelon;PM;SPM;308;508; ;Part of FR;46.8333;-56.3333
Pitcairn;PN;PCN; ;870; ;Territory of GB;46.8333;-56.3333
Puerto Rico;PR;PRI;330;1;787;Commonwealth of US;18.25;-66.5
Palestine,State of;PS;PSE; ;970; ;In contention;32;35.25
Portugal;PT;PRT;268;351; ;Yes;39.5;-8
Palau;PW;PLW;552;680; ;Yes;7.5;134.5
Paraguay;PY;PRY;744;595; ;Yes;-23;-58
Qatar;QA;QAT;427;974; ;Yes;25.5;51.25
Réunion;RE;REU;647;262;262,692,693;Part of FR;-21.1;55.6
Romania;RO;ROU;226;40; ;Yes;46;25
Serbia;RS;SRB;220;381; ;Yes;44;21
Russian Federation;RU;RUS;250;7; ;Yes;60;100
Rwanda;RW;RWA;635;250; ;Yes;-2;30
Saudi Arabia;SA;SAU;420;966; ;Yes;25;45
Solomon Islands;SB;SLB;540;677; ;Yes;-8;159
Seychelles;SC;SYC;633;248; ;Yes;-4.5833;55.6667
Sudan;SD;SDN;634;249; ;Yes;15;30
Sweden;SE;SWE;240;46; ;Yes;62;15
Singapore;SG;SGP;525;65; ;Yes;1.3667;103.8
Saint Helena,Ascension and Tristan da Cunha;SH;SHN;658;290; ;Territory of GB;-15.9333;-5.7
Slovenia;SI;SVN;293;386; ;Yes;46;15
Svalbard and Jan Mayen;SJ;SJM; ;47;79;Territory of NO;78;20
Slovakia;SK;SVK;231;421; ;Yes;48.6667;19.5
Sierra Leone;SL;SLE;619;232; ;Yes;8.5;-11.5
San Marino;SM;SMR;292;378; ;Yes;43.7667;12.4167
Senegal;SN;SEN;608;221; ;Yes;14;-14
Somalia;SO;SOM;637;252; ;Yes;10;49
Suriname;SR;SUR;746;597; ;Yes;4;-56
South Sudan;SS;SSD;659;211; ;Yes;4;-56
Sao Tome and Principe;ST;STP;626;239; ;Yes;1;7
El Salvador;SV;SLV;706;503; ;Yes;13.8333;-88.9167
Sint Maarten (Dutch part);SX;SXM;362;1;721;Part of NL;13.8333;-88.9167
Syrian Arab Republic;SY;SYR;417;963; ;Yes;35;38
Swaziland;SZ;SWZ;653;268; ;Yes;-26.5;31.5
Turks and Caicos Islands;TC;TCA;376;1;649;Territory of GB;21.75;-71.5833
Chad;TD;TCD;622;235; ;Yes;15;19
French Southern Territories;TF;ATF;647;262;00;Territory of FR;-43;67
Togo;TG;TGO;615;228; ;Yes;8;1.1667
Thailand;TH;THA;520;66; ;Yes;15;100
Tajikistan;TJ;TJK;436;992; ;Yes;39;71
Tokelau;TK;TKL;772;690; ;Territory of NZ;-9;-172
Timor-Leste;TL;TLS;514;670; ;Yes;-9;-172
Turkmenistan;TM;TKM;438;993; ;Yes;40;60
Tunisia;TN;TUN;605;216; ;Yes;34;9
Tonga;TO;TON;539;676; ;Yes;-20;-175
Turkey;TR;TUR;286;90; ;Yes;39;35
Trinidad and Tobago;TT;TTO;374;1;868;Yes;11;-61
Tuvalu;TV;TUV;553;688; ;Yes;-8;178
Taiwan,Province of China;TW;TWN;466;886; ;Yes;23.5;121
Tanzania,United Republic of;TZ;TZA;640;255; ;Yes;-6;35
Ukraine;UA;UKR;255;380; ;Yes;49;32
Uganda;UG;UGA;641;256; ;Yes;1;32
United States;US;USA;310,311,312,313,314,315,316;1;205,251,256,334,659,938,907,250,480,520,602,623,928,327,479,501,870,209,213,310,323,341,369,408,415,424,442,510,530,559,562,619,626,627,628,650,657,661,669,707,714,747,760,764,805,818,831,858,909,916,925,935,949,951,303,719,720,970,203,475,860,959,302,202,239,305,321,352,386,407,561,689,727,754,772,786,813,850,863,904,941,954,229,404,470,478,678,706,762,770,912,808,208,217,224,309,312,331,447,464,618,630,708,730,773,779,815,847,872,219,260,317,574,765,812,930,319,515,563,641,712,316,620,785,913,270,364,502,606,859,225,318,337,504,985,207,227,240,301,410,443,667,339,351,413,508,617,774,781,857,978,231,248,269,313,517,586,616,679,734,810,906,947,989,218,320,507,612,651,763,952,228,601,662,769,314,417,557,573,636,660,816,975,406,308,402,531,702,775,603,201,551,609,732,848,856,862,908,973,505,575,212,315,347,516,518,585,607,631,646,716,718,845,914,917,929,252,336,704,828,910,919,980,984,701,216,234,283,330,380,419,440,513,567,614,740,937,405,539,580,918,458,503,541,971,215,267,272,412,445,484,570,582,610,717,724,814,835,878,401,803,843,864,605,423,615,731,865,901,931,210,214,254,281,325,361,409,430,432,469,512,682,713,737,806,817,830,832,903,915,936,940,956,972,979,385,435,801,802,276,434,540,571,703,757,804,206,253,360,425,509,564,304,681,262,274,414,534,608,715,920,307;Yes;38;-97
Uruguay;UY;URY;748;598; ;Yes;-33;-56
Uzbekistan;UZ;UZB;434;998; ;Yes;41;64
Holy See (Vatican City State);VA;VAT;225;39;6;Yes;41.9;12.45
Saint Vincent and the Grenadines;VC;VCT;360;1;784;Yes;13.25;-61.2
Venezuela,Bolivarian Republic of;VE;VEN;734;58; ;Yes;8;-66
Virgin Islands,British;VG;VGB;348;1;284;Territory of GB;18.5;-64.5
Virgin Islands,U.S.;VI;VIR;332;1;340;Territory of US;18.3333;-64.8333
Viet Nam;VN;VNM;452;84; ;Yes;16;106
Vanuatu;VU;VUT;541;678; ;Yes;-16;167
Wallis and Futuna;WF;WLF;543;681; ;Territory of FR;-13.3;-176.2
Samoa;WS;WSM;549;685; ;Yes;-13.5833;-172.333
Yemen;YE;YEM;421;967; ;Yes;15;48
Mayotte;YT;MYT;647;262; ;Part of FR;-12.8333;45.1667
South Africa;ZA;ZAF;655;27; ;Yes;-29;24
Zambia;ZM;ZMB;645;260; ;Yes;-15;30
Zimbabwe;ZW;ZWE;648;263; ;Yes;-20;30


Merci à vous et vraiment désolé.
A voir également:

3 réponses

Messages postés
32
Date d'inscription
jeudi 31 décembre 2015
Statut
Membre
Dernière intervention
8 janvier 2016
1
Merci à toi j'ai regardé ça attentivement ;)
Je débute donc oui le pom.xml je l'ai récupérer par hasard et au fil du temps, quand j'aurais compris à quoi servent ses dépendances je les enlèverais ;)

J'ai un autre soucis, j'ai créer une ressource /doc pour y faire apparaître mon swagger (en .json) j'ai créer une fonction de lecture getDoc mais je n'arrive pas à l'afficher : (Le fichier spécifié est introuvable)

public static String getDoc() {
String chaine="";

//lecture du fichier texte
try{
InputStream ips=new FileInputStream("swagger.json");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String ligne;
while ((ligne=br.readLine())!=null){
System.out.println(ligne);
chaine+=ligne+"\n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
return null;
}


Merci à toi.
1
Merci

Quelques mots de remerciements seront grandement appréciés. Ajouter un commentaire

CCM 65492 internautes nous ont dit merci ce mois-ci

Messages postés
32
Date d'inscription
jeudi 31 décembre 2015
Statut
Membre
Dernière intervention
8 janvier 2016
1
Oui mais ça ne me l affiche pas dans ce format la{"Iso_Alpha2": "FR", "e212": 208}
Messages postés
32
Date d'inscription
jeudi 31 décembre 2015
Statut
Membre
Dernière intervention
8 janvier 2016
1
Ça m affiche uniquement FR et 208
Messages postés
16370
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
18 juillet 2021
2 856
Comme je l'indiquais hier, ce n'est pas le travail du serveur de faire ce tri.
Peu importe qu'il y ait plus d'informations dans ce que renvoie le serveur, si le client n'en a pas besoin, il les ignore.

Sinon deux moyens de faire un format réduit : tu créés un bean réduit qui ne contient que ces deux champs là. Ou alors tu simules un tel comportement en vidant le bean de ses données en remplissant la valeur avec des null comme je te l'ai déjà indiqué dans ma réponse d'hier.
Messages postés
32
Date d'inscription
jeudi 31 décembre 2015
Statut
Membre
Dernière intervention
8 janvier 2016
1
Salut, tout d abord merci à toi, j ai réussi à faire tous ce que je voulais faire. Mais je me demande une chose dans la réponse par exemple y a "name": "France" (j ai pas vraiment compris comment tu as fais le "name" puisque j aimerais le modifier en "country name")
Messages postés
16370
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
18 juillet 2021
2 856
Par défaut toutes les méthodes publiques du bean sont utilisées. Dans la classe Country il y a une méthode "getName" donc dans le json on retrouve la clé "name" dont la valeur est le résultat de cette méthode.

Remarque : il est donc impératif de respecter les conventions de nommages Java EE parce que si ta méthode a un nom exotique elle ne pourra plus être utilisée automatiquement.

Pour changer le nom dans le json il faut rajouter l'annotation @XmlElement sur la méthode, j'en ai parlé ici : https://forums.commentcamarche.net/forum/affich-32976517-return-null-sur-ma-ressource#36
Messages postés
16370
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
18 juillet 2021
2 856
(Re)bonjour,

Je me base aussi sur les infos de ton autre question.

Déjà, à mon avis il y a pas mal de dépendances Maven dont tu n'as pas besoin, tu as un fait un copier-coller d'un projet existant ?

Ensuite il faudrait savoir en quelle version de Java tu codes. Mais les Hashtable ça sent le vieux...

De plus tu construit ton JSON moitié à la main, moitié avec les JSONObject...

Si tu le veux bien on va tout reprendre de zéro.
Dis moi juste quelles sont tes contraintes techniques (si tu en as).
Messages postés
16370
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
18 juillet 2021
2 856
Voici une "base propre" pour travailler avec le strict nécessaire.

J'ai pas forcément refait tout ce que tu avais codé, mais l'essentiel y est.

Tu peux démarrer ton serveur en utilisant le plugin Jetty :
mvn jetty:run

Les URL sont ensuite :
http://localhost:8080/rest/v1/countries
http://localhost:8080/rest/v1/countries/e212/208

Voici l'architecture du projet :

Le fichier countries.csv c'est la même chose que ton fichier countries.txt mais avec la première ligne en moins (les en-têtes de colonne), je l'ai placé à la racine de src/main/resources (hiérarchie standard en Maven)

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>rayan958</groupId>
	<artifactId>country-server</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>country-server</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.19</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-json</artifactId>
			<version>1.19</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>country-server</finalName>
		<plugins>
			<plugin>
				<!-- Run the server using "mvn jetty:run" -->
				<!-- http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html -->
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.3.6.v20151106</version>
			</plugin>
		</plugins>
	</build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<servlet>
		<servlet-name>rest-v1</servlet-name>
		<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>rayan958.countries.rest.v1</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>rest-v1</servlet-name>
		<url-pattern>/rest/v1/*</url-pattern>
	</servlet-mapping>
</web-app>

Le bean suivant va permettre de générer automatiquement le JSON à partir de l'objet Java, ce qui évite de manipuler des JSONObject.
Si tu veux ajouter/supprimer/renommer la clé XXX dans le JSON généré il faut considérer la méthode getXXX associée.

package rayan958.countries.bean;

import java.util.List;

public class Country {

    private final String name;
    private final String alpha2;
    private final String alpha3;
    private final Integer e212;
    private final Integer cc;
    private final List<Integer> ndc;
    private final String independant;
    private final Double latitude;
    private final Double longitude;

    public Country(String name, String alpha2, String alpha3, Integer e212, Integer cc, List<Integer> ndc, String independant, Double latitude, Double longitude) {
        this.name = name;
        this.alpha2 = alpha2;
        this.alpha3 = alpha3;
        this.e212 = e212;
        this.cc = cc;
        this.ndc = ndc;
        this.independant = independant;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String getName() {
        return name;
    }

    public String getAlpha2() {
        return alpha2;
    }

    public String getAlpha3() {
        return alpha3;
    }

    public Integer getE212() {
        return e212;
    }

    public Integer getCc() {
        return cc;
    }

    public List<Integer> getNdc() {
        return ndc;
    }

    public String getIndependant() {
        return independant;
    }

    public Double getLatitude() {
        return latitude;
    }

    public Double getLongitude() {
        return longitude;
    }
}

package rayan958.countries.services;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import rayan958.countries.bean.Country;

public final class CountriesService {

    private final static List<Country> countriesCache = loadCountries();

    private CountriesService() {
    }

    private static List<Country> loadCountries() {
        List<Country> list = new ArrayList<Country>(300);
        Scanner sc = new Scanner(Thread.currentThread().getContextClassLoader().getResourceAsStream("countries.csv"), "UTF-8");
        while (sc.hasNextLine()) {
            Country country = parseCountry(sc.nextLine());
            if (country != null)
                list.add(country);
        }
        sc.close();
        return list;
    }

    private static Country parseCountry(String str) {
        try {
            String[] tab = str.split(";");
            return new Country(parseString(tab[0]), parseString(tab[1]), parseString(tab[2]), parseInt(tab[3]), parseInt(tab[4]), parseNdc(tab[5]), parseString(tab[6]), parseDouble(tab[7]), parseDouble(tab[8]));
        } catch (RuntimeException e) {
            System.err.println("Error parsing country: " + str);
            e.printStackTrace();
            return null;
        }
    }

    private static List<Integer> parseNdc(String str) {
        if (str == null)
            return new ArrayList<>(0);
        String[] ndc = str.split(",");
        List<Integer> ndcList = new ArrayList<>(ndc.length);
        for (String s : ndc) {
            Integer n = parseInt(s);
            if (n != null)
                ndcList.add(n);
        }
        return ndcList;
    }

    private static String parseString(String str) {
        if (str == null)
            return null;
        str = str.trim();
        if (str.isEmpty())
            return null;
        return str;
    }

    private static Integer parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (RuntimeException e) {
            return null;
        }
    }

    private static Double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (RuntimeException e) {
            return null;
        }
    }

    public static List<Country> getAll() {
        return countriesCache;
    }

    public static Country getE212(Integer e212) {
        if (e212 == null)
            return null;
        for (Country country : countriesCache)
            if (e212.equals(country.getE212()))
                return country;
        return null;
    }
}

package rayan958.countries.rest.v1;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import rayan958.countries.services.CountriesService;

@Path("/countries")
public class CountriesResource {

    @GET
    @Produces("application/json")
    public Response getAll() {
        try {
            return Response.status(Status.OK).entity(CountriesService.getAll()).build();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    @GET
    @Path("e212/{code}")
    @Produces("application/json")
    public Response getE212(@PathParam("code") Integer code) {
        try {
            return Response.status(Status.OK).entity(CountriesService.getE212(code)).build();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}