Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonArray.

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:jsonSploit.java

/**
 * @param args the command line arguments
 *///w w w. j av  a 2 s .c o m
public static void main(String[] args) {
    // TODO code application logic here
    Gson gson = new Gson();
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println("\n\n--------------------JSON OBJECT DISPLAY----------------------------\n\n");
    // convertimos el string a json Object
    JSONObject jsonObj = new JSONObject(jsonResult);
    // System.out.println("LA CADENA JSON CONVERTIDA EN OBJETO ES>");
    System.out.println(jsonObj.toString());

    System.out
            .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n");

    JSONArray jsonArray = new JSONArray();
    jsonArray.put(jsonObj);
    gson = new Gson();
    Iterator x = jsonObj.keys();
    while (x.hasNext()) {
        String key = (String) x.next();
        jsonArray.put(jsonObj.get(key));
        System.out.println(key);

    }
    System.out
            .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n");
    JsonParser jsonParser = new JsonParser();
    JsonObject jo = (JsonObject) jsonParser.parse(jsonResult);
    JsonArray jsonArr = jo.getAsJsonArray("data");
    Gson googleJson = new Gson();
    ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
    System.out.println("Listas existentes en data : " + jsonObjList.size());
    System.out.println("los elementos de la lista son  : " + jsonObjList.toString());
    String dataResult = jsonObjList.toString();

    System.out.println("\n\n--------------------- EL OBJETO JSON  ARRAY---------------------------\n\n");
    /// jsonArr.remove(1);
    String elemento1 = null;

    Iterator<JsonElement> nombreIterator = jsonArr.iterator();
    JsonElement elemento = null;
    while (nombreIterator.hasNext()) {
        elemento = nombreIterator.next();
        System.out.print(elemento + " \n");
        elemento1 = elemento.toString();
        System.out.println("El elemento 1 es " + elemento1);
    }

    cData data = gson.fromJson(elemento1, cData.class);
    // Account account = gson.fromJson(jo, Account.class);
    if (data.getAccount().getFirst_name() == null) {
        System.out.println("Error");
    } else {
        System.out.print(data.getAccount().getFirst_name());
    }
    // System.out.println(data.acount.getNumber());

    System.out.println("\n\n--------------------- OBTENEMOS EL OBJETO ACCOUNT---------------------------\n\n");
    //JsonObject jObject = (JsonObject) jsonParser.parse(elemento1);
    // System.out.println(jObject.getAsJsonPrimitive("number"));

}

From source file:JavaTestRunner.java

License:Apache License

public static Object runQuery(JavaQuery query, JsonObject combinedInput) {
    JsonArray hierarchy = combinedInput.getAsJsonArray("inheritance");
    JsonElement input = combinedInput.get("input");
    final ZonedDateTime now;
    JsonPrimitive primnow = combinedInput.getAsJsonPrimitive("now");
    if (primnow == null) {
        now = ZonedDateTime.now();
    } else {/*from w w w  .j av a  2  s . c  om*/
        final String strnow = (String) (primnow.getAsString());
        now = ZonedDateTime.parse(strnow);
    }
    return runQuery(query, hierarchy, input, now);
}

From source file:accessControl.AuthAPIService.java

License:Open Source License

public ArrayList<Path> getAvailablePaths(String subjectInfo, boolean isCertificate) {

    HttpURLConnection connection = null;
    try {//from www.  j  av  a 2 s  .c  o  m
        //Create connection
        String finalURL = authServiceURI + "?getPaths=true";
        logger.debug("Sending request. URI:" + finalURL);
        URL url = new URL(finalURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        if (!isCertificate)
            connection.setRequestProperty("Cookie", subjectInfo);

        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.connect();

        if (isCertificate) {
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(subjectInfo);
            wr.flush();
            wr.close();
        }

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
        }
        rd.close();

        String response_result = response.toString();

        // If the whole tree is allowed (administrator mode)
        // We need this since the list of administrators is stored on AC side
        if (response_result.equalsIgnoreCase("true")) {
            ArrayList<Path> res = new ArrayList<>();
            res.add(new Path("all"));
            return res;
        } else if (response_result.equalsIgnoreCase("false"))
            return null;

        // Parse the paths and return them
        JsonObject paths = new JsonParser().parse(response_result).getAsJsonObject();
        JsonArray json_paths = paths.getAsJsonArray("paths");

        ArrayList<Path> finalPaths = new ArrayList<>(json_paths.size());

        logger.debug(json_paths.size() + " PATHS FOUND");

        for (int i = 0; i < json_paths.size(); i++) {
            String pathString = json_paths.get(i).getAsString();
            logger.debug(pathString);
            Path nextPath = new Path(pathString);
            finalPaths.add(nextPath);
        }

        return finalPaths;

    } catch (Exception e) {
        logger.error("During getAvailablePaths request", e);
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:account.PurchsaeReturnRegisterDetailAccount.java

private void jbtnViewActionPerformedRoutine() {
    try {/*from   w w w  . j ava2s .  c o m*/
        AccountAPI accountAPI = lb.getRetrofit().create(AccountAPI.class);

        if (ac_cd == null) {
            ac_cd = "";
        }
        if (!jCheckBox1.isSelected()) {
            ac_cd = "";
        }
        JsonObject call = accountAPI.PurchaseReturnRegisterAccount(jComboBox1.getSelectedIndex(),
                jComboBox3.getSelectedIndex(), lb.ConvertDateFormetForDB(jtxtFromDate.getText()),
                lb.ConvertDateFormetForDB(jtxtToDate.getText()), ac_cd).execute().body();

        lb.addGlassPane(this);
        if (call != null) {
            JsonObject result = call;
            if (result.get("result").getAsInt() == 1) {
                JsonArray array = call.getAsJsonArray("data");
                dtm.setRowCount(0);
                dtm.setRowCount(0);
                double cash = 0.00, bank = 0.00, card = 0.00;
                String tax_name = "";
                for (int i = 0; i < array.size(); i++) {
                    Vector row = new Vector();
                    row.add(array.get(i).getAsJsonObject().get("ref_no").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("v_type").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("inv_no").getAsString());
                    row.add(lb.ConvertDateFormetForDisplay(
                            array.get(i).getAsJsonObject().get("v_date").getAsString()));
                    row.add(array.get(i).getAsJsonObject().get("fname").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("SR_ALIAS").getAsString());
                    cash = array.get(i).getAsJsonObject().get("CASH_AMT").getAsDouble();
                    bank = array.get(i).getAsJsonObject().get("BANK_AMT").getAsDouble();
                    card = array.get(i).getAsJsonObject().get("CARD_AMT").getAsDouble();
                    tax_name = array.get(i).getAsJsonObject().get("tax_name").getAsString();
                    row.add(array.get(i).getAsJsonObject().get("SR_NAME").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("IMEI_NO").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("SERAIL_NO").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("QTY").getAsInt());
                    row.add(array.get(i).getAsJsonObject().get("RATE").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("BASIC_ITEM_AMT").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("tax_amt").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("add_tax_amt").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("DISC_RATE").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("MRP").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("AMT").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("net_amt").getAsDouble());
                    row.add(tax_name);
                    row.add(cash);
                    row.add(bank);
                    row.add(card);
                    row.add(array.get(i).getAsJsonObject().get("bajaj_amt").getAsDouble());
                    row.add(lb.Convert2DecFmtForRs(
                            array.get(i).getAsJsonObject().get("net_amt").getAsDouble() - cash - bank - card
                                    - array.get(i).getAsJsonObject().get("bajaj_amt").getAsDouble()));
                    row.add(Constants.BRANCH.get(array.get(i).getAsJsonObject().get("branch_cd").getAsInt() - 1)
                            .getBranch_name());
                    dtm.addRow(row);
                }
                lb.setColumnSizeForTable(jTable1, jPanel1.getWidth());
                lb.removeGlassPane(PurchsaeReturnRegisterDetailAccount.this);
            } else {
                lb.removeGlassPane(PurchsaeReturnRegisterDetailAccount.this);
                lb.showMessageDailog(call.get("Cause").getAsString());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(PurchsaeReturnRegisterDetailAccount.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:account.SalesRegisterCardWise.java

private void jbtnViewActionPerformedRoutine() {
    try {//from   www  .  j ava 2s .c  o m
        AccountAPI accountAPI = lb.getRetrofit().create(AccountAPI.class);

        JsonObject call = accountAPI.SalesRegisterCardWise(jCheckBox1.isSelected()).execute().body();

        lb.addGlassPane(this);

        if (call != null) {
            JsonObject result = call;
            if (result.get("result").getAsInt() == 1) {
                JsonArray array = call.getAsJsonArray("data");
                dtm.setRowCount(0);
                double net = 0.00;
                for (int i = 0; i < array.size(); i++) {
                    try {
                        Vector row = new Vector();
                        row.add(i + 1);
                        row.add((array.get(i).getAsJsonObject().get("AC_CD").getAsString()));
                        row.add((array.get(i).getAsJsonObject().get("FNAME") == null) ? ""
                                : array.get(i).getAsJsonObject().get("FNAME").getAsString());
                        row.add((array.get(i).getAsJsonObject().get("CARD_NO").getAsString()));
                        row.add((array.get(i).getAsJsonObject().get("MOBILE1").getAsString()));
                        row.add(lb.Convert2DecFmtForRs(
                                array.get(i).getAsJsonObject().get("NET_AMT").getAsDouble()));
                        dtm.addRow(row);
                        net += array.get(i).getAsJsonObject().get("NET_AMT").getAsDouble();
                    } catch (Exception e) {

                    }
                }

                Vector row = new Vector();
                row.add(" ");
                row.add(" ");
                row.add(" ");
                row.add(" ");
                row.add(" ");
                row.add(" ");
                dtm.addRow(row);

                row = new Vector();
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add(lb.Convert2DecFmtForRs(net));
                dtm.addRow(row);

                lb.setColumnSizeForTable(jTable1, jPanel1.getWidth());
                lb.removeGlassPane(SalesRegisterCardWise.this);
            } else {
                lb.removeGlassPane(SalesRegisterCardWise.this);
                lb.showMessageDailog(call.get("Cause").getAsString());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(SalesRegisterCardWise.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:account.SalesRegisterDetailCardWise.java

private void jbtnViewActionPerformedRoutine() {
    try {/*  w  w w . jav a2s .  co  m*/
        AccountAPI accountAPI = lb.getRetrofit().create(AccountAPI.class);

        if (ac_cd == null) {
            ac_cd = "";
        }
        if (!jCheckBox1.isSelected()) {
            ac_cd = "";
        }
        JsonObject call = accountAPI.CardWiseSalesDetailStatement(ac_cd).execute().body();

        lb.addGlassPane(this);

        if (call != null) {
            JsonObject result = call;
            if (result.get("result").getAsInt() == 1) {
                JsonArray array = call.getAsJsonArray("data");
                dtm.setRowCount(0);
                dtm.setRowCount(0);
                double basic_amt = 0.00, tax_amt = 0.00, net_amt = 0.00, buy_back_amt = 0.00, ins_amt = 0.00,
                        bajaj = 0.00;
                double cash = 0.00, bank = 0.00, card = 0.00;
                String tax_name = "";
                String buy_back_model = "";
                String old_ref_no = "";
                for (int i = 0; i < array.size(); i++) {
                    if (!old_ref_no.equalsIgnoreCase("") && !old_ref_no
                            .equalsIgnoreCase(array.get(i).getAsJsonObject().get("ref_no").getAsString())) {
                        Vector row = new Vector();
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add(basic_amt);
                        row.add(lb.Convert2DecFmtForRs(tax_amt));
                        row.add(net_amt);
                        row.add(tax_name);
                        row.add(cash);
                        row.add(bank);
                        row.add(card);
                        row.add(bajaj);
                        row.add(buy_back_amt);
                        row.add(buy_back_model);
                        row.add(ins_amt);
                        row.add(lb.Convert2DecFmtForRs(
                                basic_amt + tax_amt - cash - bank - card - buy_back_amt + ins_amt - bajaj));
                        basic_amt = 0.00;
                        dtm.addRow(row);
                    }
                    Vector row = new Vector();
                    row.add(array.get(i).getAsJsonObject().get("ref_no").getAsString());
                    if (basic_amt == 0.00) {
                        row.add(array.get(i).getAsJsonObject().get("v_type").getAsString());
                        row.add(array.get(i).getAsJsonObject().get("inv_no").getAsInt());
                        row.add(lb.ConvertDateFormetForDisplay(
                                array.get(i).getAsJsonObject().get("v_date").getAsString()));
                        row.add((array.get(i).getAsJsonObject().get("fname") == null) ? ""
                                : array.get(i).getAsJsonObject().get("fname").getAsString());
                    } else {
                        row.add("");
                        row.add("");
                        row.add("");
                        row.add("");
                    }
                    row.add(array.get(i).getAsJsonObject().get("SR_ALIAS").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("SR_NAME").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("IMEI_NO").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("SERAIL_NO").getAsString());
                    row.add(array.get(i).getAsJsonObject().get("QTY").getAsInt());
                    row.add(array.get(i).getAsJsonObject().get("RATE").getAsDouble());
                    row.add(array.get(i).getAsJsonObject().get("AMT").getAsDouble());
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    row.add("");
                    dtm.addRow(row);
                    basic_amt = array.get(i).getAsJsonObject().get("det_tot").getAsDouble();
                    tax_amt = array.get(i).getAsJsonObject().get("tax_amt").getAsDouble()
                            + array.get(i).getAsJsonObject().get("add_tax_amt").getAsDouble();
                    net_amt = array.get(i).getAsJsonObject().get("net_amt").getAsDouble();
                    cash = array.get(i).getAsJsonObject().get("CASH_AMT").getAsDouble();
                    bank = array.get(i).getAsJsonObject().get("BANK_AMT").getAsDouble();
                    card = array.get(i).getAsJsonObject().get("CARD_AMT").getAsDouble();
                    tax_name = array.get(i).getAsJsonObject().get("tax_name").getAsString();
                    buy_back_model = array.get(i).getAsJsonObject().get("buy_back_model").getAsString();
                    buy_back_amt = array.get(i).getAsJsonObject().get("buy_back_amt").getAsDouble();
                    ins_amt = array.get(i).getAsJsonObject().get("ins_amt").getAsDouble();
                    bajaj = array.get(i).getAsJsonObject().get("bajaj_amt").getAsDouble();
                    old_ref_no = array.get(i).getAsJsonObject().get("ref_no").getAsString();
                }
                Vector row = new Vector();
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add(basic_amt);
                row.add(lb.Convert2DecFmtForRs(tax_amt));
                row.add(net_amt);
                row.add(tax_name);
                row.add(cash);
                row.add(bank);
                row.add(card);
                row.add(bajaj);
                row.add(buy_back_amt);
                row.add(buy_back_model);
                row.add(ins_amt);
                row.add(lb.Convert2DecFmtForRs(
                        basic_amt + tax_amt + ins_amt - cash - bank - card - buy_back_amt - bajaj));
                basic_amt = 0.00;
                dtm.addRow(row);

                double tot_basic = 0.00, tot_tax = 0.00, tot_cash = 0.00, tot_bank = 0.00, tot_card = 0.00,
                        tot_buyBack = 0.00, tot_deb = 0.00, tot_ins_amt = 0.00, tot_bajaj_amt = 0.00,
                        tot_net_amt = 0.00;
                for (int i = 0; i < jTable1.getRowCount(); i++) {
                    tot_basic += lb.isNumber2(jTable1.getValueAt(i, 12).toString());
                    tot_tax += lb.isNumber2(jTable1.getValueAt(i, 13).toString());
                    tot_net_amt += lb.isNumber2(jTable1.getValueAt(i, 14).toString());
                    tot_cash += lb.isNumber2(jTable1.getValueAt(i, 16).toString());
                    tot_card += lb.isNumber2(jTable1.getValueAt(i, 18).toString());
                    tot_bajaj_amt += lb.isNumber2(jTable1.getValueAt(i, 19).toString());
                    tot_buyBack += lb.isNumber2(jTable1.getValueAt(i, 20).toString());
                    tot_ins_amt += lb.isNumber2(jTable1.getValueAt(i, 22).toString());
                    tot_deb += lb.isNumber2(jTable1.getValueAt(i, 23).toString());
                }
                row = new Vector();
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add("");
                row.add(lb.Convert2DecFmtForRs(tot_basic));
                row.add(lb.Convert2DecFmtForRs(tot_tax));
                row.add(lb.Convert2DecFmtForRs(tot_net_amt));
                row.add("");
                row.add(lb.Convert2DecFmtForRs(tot_cash));
                row.add(lb.Convert2DecFmtForRs(tot_bank));
                row.add(lb.Convert2DecFmtForRs(tot_card));
                row.add(lb.Convert2DecFmtForRs(tot_bajaj_amt));
                row.add(lb.Convert2DecFmtForRs(tot_buyBack));
                row.add("");
                row.add(lb.Convert2DecFmtForRs(tot_ins_amt));
                row.add(lb.Convert2DecFmtForRs(tot_deb));
                dtm.addRow(row);

                lb.setColumnSizeForTable(jTable1, jPanel1.getWidth());
                lb.removeGlassPane(SalesRegisterDetailCardWise.this);
            } else {
                lb.removeGlassPane(SalesRegisterDetailCardWise.this);
                lb.showMessageDailog(call.get("Cause").getAsString());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(SalesRegisterDetailCardWise.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:account.SalesRegisterDetailCardWise.java

private void jtxtCardNoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtxtCardNoKeyPressed
    // TODO add your handling code here:

    if (lb.isEnter(evt) && !lb.isBlank(jtxtCardNo)) {
        try {//  ww w .j a  v  a  2  s.co m
            lb.addGlassPane(this);
            JsonObject call = lb.getRetrofit().create(SalesAPI.class)
                    .GetDataFromServer(jtxtCardNo.getText(), "22").execute().body();
            lb.removeGlassPane(SalesRegisterDetailCardWise.this);
            if (call != null) {
                JsonArray array = call.getAsJsonArray("data");
                if (array.size() > 0) {
                    ac_cd = (array.get(0).getAsJsonObject().get("AC_CD").getAsString());
                    jtxtAcAlias.setText(ac_cd);
                    jtxtAcName.setText(array.get(0).getAsJsonObject().get("FNAME").getAsString());
                    jtxtCardNo.setText(array.get(0).getAsJsonObject().get("CARD_NO").getAsString());
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SalesRegisterDetailCardWise.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:allout58.mods.techtree.tree.TechNodeGSON.java

License:Open Source License

@Override
public TechNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject obj = json.getAsJsonObject();
    final int id = obj.get("id").getAsInt();
    final String name = obj.get("name").getAsString();
    final int science = obj.get("scienceRequired").getAsInt();
    final String description = obj.get("description").getAsString();
    final ItemStack[] items = context.deserialize(obj.get("lockedItems"), ItemStack[].class);

    final TechNode node = new TechNode(id);
    //        ItemStack[] items = new ItemStack[] { new ItemStack(Items.apple), new ItemStack(Items.arrow), new ItemStack(Items.bow) };
    node.setup(name, science, description, items);

    final JsonArray jsonParentArray = obj.getAsJsonArray("parents");
    for (int i = 0; i < jsonParentArray.size(); i++) {
        node.addParentNode(jsonParentArray.get(i).getAsInt());
    }//from w  ww  .  java2  s .  com

    return node;
}

From source file:application.rest.LibertyRestEndpoint.java

License:Apache License

@POST
@Path("/text")
@Produces("text/plain") // sends JSON
public String hello(@FormParam("phrase") String phrase, @FormParam("language") String targetLang) {

    String decodePhrase = new String(Base64.getDecoder().decode(phrase.getBytes()));
    System.out.println(decodePhrase);

    LanguageDetection ld = new LanguageDetection();
    com.ibm.watson.developer_cloud.alchemy.v1.model.Language sourceLang = ld.detect(decodePhrase);

    TranslateCredentials tc = new TranslateCredentials();
    LanguageTranslator service = new LanguageTranslator();

    service.setEndPoint(tc.getUrl());/*  ww  w . j av  a  2 s .  c om*/
    service.setUsernameAndPassword(tc.getUser(), tc.getPass());

    TranslationResult translationResult = null;

    Language lans = getLanguaje(sourceLang.getLanguage().toLowerCase());
    Language lant = getLanguaje(targetLang.toLowerCase());

    try {
        if (lans != null && lant != null)
            translationResult = service.translate(decodePhrase, lans, lant).execute();
        else
            throw new Exception();
    } catch (Exception e) {
        //return Base64.getEncoder().encode("Error detecting languaje or source/target translation is not implemented".getBytes());
        return "Error detecting languaje or source/target translation is not implemented";
    }
    JsonObject result = new JsonParser().parse(translationResult.toString()).getAsJsonObject();
    System.out.println(result);
    JsonObject translations = result.getAsJsonArray("translations").get(0).getAsJsonObject();
    System.out.println(translations);
    String translation = translations.get("translation").getAsString();
    //return Base64.getEncoder().encode(translation.getBytes());
    return translation;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

@SuppressWarnings("unchecked")
private <E extends FCAAbstract> Map<Long, E> json2Absctract(JsonObject json,
        Map<Long, LearningObject> learningObjects, Class<E> type) {
    HashMap<Long, E> objects = new HashMap<Long, E>();
    JsonObject block = null;//from ww w.  j a v  a  2  s .c  o m
    if (type == FCAObject.class)
        block = json.get(SECTION_O).getAsJsonObject();
    else if (type == FCAAttribute.class)
        block = json.get(SECTION_A).getAsJsonObject();
    Set<Entry<String, JsonElement>> entries = block.entrySet();
    for (Entry<String, JsonElement> o : entries) {
        JsonObject jsO = o.getValue().getAsJsonObject();
        E object;
        String creationId;
        if (!jsO.has(CID)) {
            double num = rand.nextDouble() * 10000;
            int val = (int) num;
            creationId = Integer.toString(val, 16);
        } else
            creationId = jsO.get(CID).getAsString();
        if (type == FCAObject.class)
            object = (E) new FCAObject(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        else
            object = (E) new FCAAttribute(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        Set<LearningObject> lObjs = new HashSet<LearningObject>();
        Set<LearningObject> lObjsByLearner = new HashSet<LearningObject>();
        Iterator<JsonElement> lOs = jsO.getAsJsonArray(SECTION_LO).iterator();
        while (lOs.hasNext()) {
            LearningObject lo = learningObjects.get((lOs.next().getAsLong()));
            if (lo != null)
                lObjs.add(lo);
        }
        try {
            Iterator<JsonElement> lOsByLearner = jsO.getAsJsonArray(SECTION_LO_L).iterator();
            while (lOsByLearner.hasNext()) {
                LearningObject lo = learningObjects.get((lOsByLearner.next().getAsLong()));
                if (lo != null)
                    lObjsByLearner.add(lo);
            }
        } catch (Exception notAnError) {

        }
        clean(lObjsByLearner);
        object.setLearningObjectsByLearners(lObjsByLearner);
        clean(lObjs);
        object.setLearningObjects(lObjs);
        objects.put(Long.parseLong(o.getKey()), object);
    }
    return objects;
}