Example usage for javax.json JsonReader readArray

List of usage examples for javax.json JsonReader readArray

Introduction

In this page you can find the example usage for javax.json JsonReader readArray.

Prototype

JsonArray readArray();

Source Link

Document

Returns a JSON array that is represented in the input source.

Usage

From source file:io.bibleget.HTTPCaller.java

public int isValidBook(String book) {
    try {//from  w  w w .  j  a  v a  2 s  .  c o  m
        JsonArrayBuilder biblebooksBldr = Json.createArrayBuilder();
        BibleGetDB bibleGetDB;
        bibleGetDB = BibleGetDB.getInstance();
        for (int i = 0; i < 73; i++) {
            String usrprop = bibleGetDB.getMetaData("BIBLEBOOKS" + Integer.toString(i));
            //System.out.println("value of BIBLEBOOKS"+Integer.toString(i)+": "+usrprop);                
            JsonReader jsonReader = Json.createReader(new StringReader(usrprop));
            JsonArray jsbooks = jsonReader.readArray();
            biblebooksBldr.add(jsbooks);
        }
        JsonArray biblebooks = biblebooksBldr.build();
        if (!biblebooks.isEmpty()) {
            return idxOf(book, biblebooks);
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HTTPCaller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * gets the all registered voters from the bulletin board and returns them as a List of Voter objects
 * @return returns a list of all voters//from w  w w  .j a  v  a2  s .  c o  m
 */
public List<Voter> getAllARegisteredVoters() {
    List<Voter> voterlist = new ArrayList<Voter>();

    try {
        URL url = new URL(bulletinBoardUrl + "/voters");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //For each Voter-Json in the Json Array
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {
            //JsonData converted into Voter Object and added to the list  
            String email = result.getString("email");
            String publicCredential = result.getString("publicCredential");
            String appVersion = result.getString("appVersion");

            Voter voter = new Voter(email, publicCredential, appVersion);
            voterlist.add(voter);
        }

    } catch (IOException x) {
        System.err.println(x);
    }
    return voterlist;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a list of all the posted ballots of the given election form the bulletin board and returns it
 * @param election//from w  w w  .j  a  va 2s.c  o  m
 * Election for which the list of ballots should be retrieved 
 * @return 
 * the list of all posted ballots to the given election
 */
public List<Ballot> getBallotsByElection(Election election) {
    List<Ballot> ballots = new ArrayList<Ballot>();
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //transforms the recieved json string into a list of ballot objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format);

            JsonObject jsonData = result.getJsonObject("jsonData");
            List<String> selectedOptions = new ArrayList<String>();
            JsonArray optionsArray = jsonData.getJsonArray("e");
            for (int i = 0; i < optionsArray.size(); i++) {
                selectedOptions.add(optionsArray.getString(i));
            }
            String u_HatString = jsonData.getString("u_Hat");
            String cString = jsonData.getString("c");
            String dString = jsonData.getString("d");
            String pi1String = jsonData.getString("pi1");
            String pi2String = jsonData.getString("pi2");
            String pi3String = jsonData.getString("pi3");
            //create ballot object and add it to the list
            Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String,
                    pi2String, pi3String, timeStamp);
            System.out.println(ballot.isValid());
            ballots.add(ballot);
        }

    } catch (IOException x) {
        System.err.println(x);
    }
    return ballots;

}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp
 * @param filter/*from   w ww.  ja  va2 s.c o  m*/
 * The filter can be set to All, Open or Closed
 * @return returns a list of election headers
 */
public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) {
    List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>();

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime actualDateTime = LocalDateTime.now();
    String dateTimeString = actualDateTime.format(format);

    URL url = null;
    //depending on the filter a different request is sent to the bulletin board
    switch (filter) {
    // if the filter is set to ALL, all the electionheaders on the bulletin board are requested
    case ALL: {
        try {
            url = new URL(bulletinBoardUrl + "/elections");
        } catch (MalformedURLException ex) {
            Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board
    case OPEN: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/open?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board
    case CLOSED: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/closed?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    }

    try {

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //Recieved Json String is transformed into a list of ElectionHeader objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            String title = result.getString("electionTitle");
            LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format);
            LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format);

            ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate);
            electionHeaderlist.add(electionHeader);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return electionHeaderlist;
}

From source file:io.bibleget.BibleGetHelp.java

/**
 * Creates new form BibleGetHelp//from  w  ww . j  a va2  s .  co  m
 */
private BibleGetHelp() throws ClassNotFoundException, UnsupportedEncodingException {
    //jTextPane does not initialize correctly, it causes a Null Exception Pointer
    //Following line keeps this from crashing the program
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

    String packagePath = BibleGetIO.getPackagePath();
    //String locale = BibleGetIO.getLocale();

    String langsSupported;
    List<String> langsLocalized = new ArrayList<>();
    String bbBooks;

    bibleGetDB = BibleGetDB.getInstance();
    if (bibleGetDB != null) {
        //System.out.println("oh good, biblegetDB is not null!");
        JsonReader jsonReader;
        langsSupported = bibleGetDB.getMetaData("LANGUAGES");
        //System.out.println(langsSupported);
        jsonReader = Json.createReader(new StringReader(langsSupported));
        bibleVersionsObj = jsonReader.readArray();
        booksLangs = bibleVersionsObj.size();
        for (JsonValue jsonValue : bibleVersionsObj) {
            //System.out.println(jsonValue.toString());
            langsLocalized.add(BibleGetI18N.localizeLanguage(jsonValue.toString()));
        }
        booksStr = StringUtils.join(langsLocalized, ", ");

        List<JsonArray> bibleBooksTemp = new ArrayList<>();
        for (int i = 0; i < 73; i++) {
            bbBooks = bibleGetDB.getMetaData("BIBLEBOOKS" + Integer.toString(i));
            jsonReader = Json.createReader(new StringReader(bbBooks));
            JsonArray bibleBooksObj = jsonReader.readArray();
            bibleBooksTemp.add(bibleBooksObj);
        }

        String curLang;
        List<String[]> booksForCurLang;
        //bibleBooks = new HashMap<>();
        booksAndAbbreviations = new HashMap<>();
        String buildStr;
        for (int q = 0; q < bibleVersionsObj.size(); q++) {
            curLang = (bibleVersionsObj.getString(q) != null)
                    ? BibleGetI18N.localizeLanguage(bibleVersionsObj.getString(q)).toUpperCase()
                    : "";
            buildStr = "";
            for (int i = 0; i < 73; i++) {

                String styleStr = "";
                if (bibleVersionsObj.getString(q).equals("TAMIL")
                        || bibleVersionsObj.getString(q).equals("KOREAN")) {
                    styleStr = " style=\"font-family:'Arial Unicode MS';\"";
                }

                JsonArray curBook = bibleBooksTemp.get(i);
                JsonArray curBookCurLang = curBook.getJsonArray(q);
                String str1 = (curBookCurLang.getString(0) != null) ? curBookCurLang.getString(0) : "";
                String str2 = (curBookCurLang.getString(1) != null) ? curBookCurLang.getString(1) : "";
                buildStr += "<tr><td" + styleStr + ">" + str1 + "</td><td" + styleStr + ">" + str2
                        + "</td></tr>";
                //buildStr += "<tr><td style=\"font-family:'Arial Unicode MS';\">"+str1+"</td><td style=\"font-family:'Arial Unicode MS';\">"+str2+"</td></tr>";
            }
            booksAndAbbreviations.put(curLang, buildStr);
        }

    } else {
        booksLangs = 0;
        booksStr = "";
    }
    kit = new HTMLEditorKit();
    doc = kit.createDefaultDocument();
    styles = kit.getStyleSheet();
    styles.addRule("body { background-color: #FFFFDD; border: 2px inset #CC9900; }");
    styles.addRule("h1 { color: #0000AA; }");
    styles.addRule("h2 { color: #0000AA; }");
    styles.addRule("h3 { color: #0000AA; }");
    styles.addRule("p { text-align: justify; }");
    styles.addRule("table { border-collapse: collapse; width: 600px; margin-left: auto; }");
    styles.addRule(
            "th { text-align: center; border: 4px ridge #DEB887; background-color: #F5F5DC; padding: 3px; }");
    styles.addRule(
            "td { text-align: justify; border: 3px ridge #DEB887; background-color: #F5F5DC; padding: 3px; }");

    //System.out.println("We have package path in BibleGetHelp! It is: "+packagePath);

    HTMLStr0 = "<html><head><meta charset=\"utf-8\"></head><body>" + "<h1>"
            + __("Help for BibleGet (Open Office Writer)") + "</h1>" + "<p>"
            + __("This Help dialog window introduces the user to the usage of the BibleGet I/O plugin for Open Office Writer.")
            + "</p>" + "<p>" + __("The Help is divided into three sections:") + "</p>" + "<ul>" + "<li>"
            + __("Usage of the Plugin") + "</li>" + "<li>" + __("Formulation of the Queries") + "</li>" + "<li>"
            + __("Biblical Books and Abbreviations") + "</li>" + "</ul>" + "<p><b>" + __("AUTHOR") + ":</b> "
            + __("John R. D'Orazio (chaplain at Roma Tre University)") + "</p>" + "<p><b>" + __("COLLABORATORS")
            + ":</b> " + __("Giovanni Gregori (computing) and Simone Urbinati (MUG Roma Tre)") + "</p>"
            + "<p><b>" + __("Version").toUpperCase() + ":</b> " + String.valueOf(BibleGetIO.VERSION) + "</p>"
            + "<p> <b>Copyright 2014 BibleGet I/O by John R. D'Orazio</b> <span style=\"color:blue;\">john.dorazio@cappellaniauniroma3.org</span></p>"
            + "<p><b>" + __("PROJECT WEBSITE")
            + ": </b><span style=\"color:blue;\">http://www.bibleget.io</span> | <b>"
            + __("EMAIL ADDRESS FOR INFORMATION OR FEEDBACK ON THE PROJECT")
            + ":</b> <span style=\"color:blue;\">bibleget.io@gmail.com</span></p>"
            + "<p>Cappellania Universit degli Studi Roma Tre - Piazzale San Paolo 1/d - 00120 Citt del Vaticano - +39 06.69.88.08.09 - <span style=\"color:blue;\">cappellania.uniroma3@gmail.com</span></p></body></html>";

    String strfmt1 = __("Insert quote from input window");
    String strfmt2 = __("About this plugin");
    String strfmt3 = __("RENEW SERVER DATA");
    String strfmt4 = strfmt1;
    String strfmt5 = __("Insert quote from text selection");
    String strfmt6 = strfmt1;

    HTMLStr1 = "<html><head><meta charset=\"utf-8\"></head><body>" + "<h2>" + __("How to use the plugin")
            + "</h2>" + "<h3>" + __("Description of the menu icons and their functionality.") + "</h3>" + "<p>"
            + __("Once the extension is installed, a new menu 'BibleGet I/O' will appear on the menu bar. Also a new floating toolbar will appear. The buttons on the floating toolbar correspond to the menu items in the new menu, as can be seen in this image:")
            + "</p><br /><br />" + "<img src=\"" + packagePath + "/images/Screenshot.jpg\" /><br /><br />"
            + "<p>"
            + __("The floating toolbar can be dragged and placed anywhere on the screen. It can also be docked to certain areas of the workspace, for example on the toolbar below the menu bar, like in this image:")
            + "</p><br /><br />" + "<img src=\"" + packagePath + "/images/Screenshot2.jpg\" /><br /><br />"
            + "<p>" + __("There are two ways of inserting a bible quote into a document.") + " "
            + __("The first way is by using the input window.") + " "
            + MessageFormat.format(__(
                    "If you click on the menu item ''{0}'', an input window will open where you can input your query and choose the version or versions you would like to take the quote from."),
                    strfmt1)
            + " "
            + __("This list of versions is updated from the available versions on the BibleGet server, but since the information is stored locally it may be necessary to renew the server information when new versions are added to the BibleGet server database.")
            + " "
            + MessageFormat.format(__(
                    "In order to renew the information from the BibleGet server, click on the ''{0}'' menu item, and then click on the button ''{1}''."),
                    strfmt2, strfmt3)
            + " "
            + MessageFormat.format(__(
                    "When you choose a version or multiple versions to quote from, this choice is automatically saved as a preference, and will be pre-selected the next time you open the ''{0}'' menu item."),
                    strfmt4)
            + "<br /><br />" + "<img src=\"" + packagePath + "/images/Screenshot4.jpg\" /><br /><br />"
            + MessageFormat.format(__(
                    "The second way is by writing your desired quote directly in the document, and then selecting it and choosing the menu item ''{0}''. The selected text will be substituted by the Bible Quote retrieved from the BibleGet server."),
                    strfmt5)
            + " "
            + MessageFormat.format(__(
                    "The versions previously selected in the ''{0}'' window will be used, so you must have selected your preferred versions at least once from the ''{0}'' window."),
                    strfmt6)
            + "</p><br /><br />" + "<img src=\"" + packagePath + "/images/Screenshot3.jpg\" /><br /><br />"
            + "<p>"
            + __("Formatting preferences can be set using the 'Preferences' window. You can choose the desired font for the Bible quotes as well as the desired line-spacing, and you can choose separate formatting (font size, font color, font style) for the book / chapter, for the verse numbers, and for the verse text. Preferences are saved automatically.")
            + "</p><br /><br />" + "<img src=\"" + packagePath + "/images/Screenshot5.jpg\" /><br /><br />"
            + "<p>"
            + __("After the 'Help' menu item that opens up this same help window, the last three menu items are:")
            + "</p>" + "<ul>" + "<li><img src=\"" + packagePath + "/images/email.png\" />" + " '"
            + __("Send feedback") + "': <span>"
            + __("This will open up your system's default email application with the bibleget.io@gmail.com feedback address already filled in.")
            + "</span></li>" + "<li><img src=\"" + packagePath + "/images/paypal.png\" />" + " '"
            + __("Contribute") + "': <span>"
            + __("This will open a Paypal page in the system's default browser where you can make a donation to contribute to the project. Even just 1 can help to cover the expenses of this project. Just the server costs 120 a year.")
            + "</span></li>" + "<li><img src=\"" + packagePath + "/images/info.png\" />" + " '"
            + __("Information on the BibleGet I/O Project") + "': <span>"
            + __("This opens a dialog window with some information on the project and it's plugins, on the author and contributors, and on the current locally stored information about the versions and languages that the BibleGet server supports.")
            + "</span></li>" + "</ul>" + "</body></html>";

    String strfmt7 = __("Biblical Books and Abbreviations");

    HTMLStr2 = "<html>" + "<head><meta charset=\"utf-8\"></head>" + "<body>" + "<h2>"
            + __("How to formulate a bible query") + "</h2>" + "<p>"
            + __("The queries for bible quotes must be formulated using standard notation for bible citation.")
            + " "
            + __("This can be either the english notation (as explained here: https://en.wikipedia.org/wiki/Bible_citation), or the european notation as explained here below. ")
            + "</p>" + "<p>"
            + __("A basic query consists of at least two elements: the bible book and the chapter.") + " "
            + __("The bible book can be written out in full, or in an abbreviated form.") + " "
            + MessageFormat.format(__(
                    "The BibleGet engine recognizes the names of the books of the bible in {0} different languages: {1}"),
                    Integer.toString(booksLangs), booksStr)
            + " "
            + MessageFormat.format(__("See the list of valid books and abbreviations in the section {0}."),
                    "<span class=\"internal-link\" id=\"to-bookabbrevs\">" + strfmt7 + "</span>")
            + " "
            + __("For example, the query \"Matthew 1\" means the book of Matthew (or better the gospel according to Matthew) at chapter 1.")
            + " " + __("This can also be written as \"Mt 1\".") + "</p>" + "<p>"
            + __("Different combinations of books, chapters, and verses can be formed using the comma delimiter and the dot delimiter (in european notation, in english notation instead a colon is used instead of a comma and a comma is used instead of a dot):")
            + "</p>" + "<ul>" + "<li>"
            + __("\",\": the comma is the chapter-verse delimiter. \"Matthew 1,5\" means the book (gospel) of Matthew, chapter 1, verse 5. (In English notation: \"Matthew 1:5\".)")
            + "</li>" + "<li>"
            + __("\".\": the dot is a delimiter between verses. \"Matthew 1,5.7\" means the book (gospel) of Matthew, chapter 1, verses 5 and 7. (In English notation: \"Matthew 1:5,7\".)")
            + "</li>" + "<li>"
            + __("\"-\": the dash is a range delimiter, which can be used in a variety of ways:") + "<ol>"
            + "<li>"
            + __("For a range of chapters: \"Matthew 1-2\" means the gospel according to Matthew, from chapter 1 to chapter 2.")
            + "</li>" + "<li>"
            + __("For a range of verses within the same chapter: \"Matthew 1,1-5\" means the gospel according to Matthew, chapter 1, from verse 1 to verse 5. (In English notation: \"Matthew 1:1-5\".)")
            + "</li>" + "<li>"
            + __("For a range of verses that span over different chapters: \"Matthew 1,5-2,13\" means the gospel according to Matthew, from chapter 1, verse 5 to chapter 2, verse 13. (In English notation: \"Matthew 1:5-2:13\".)")
            + "</li>" + "</ol>" + "</ul>" + "<p>"
            + __("Different combinations of these delimiters can form fairly complex queries, for example \"Mt1,1-3.5.7-9\" means the gospel according to Matthew, chapter 1, verses 1 to 3, verse 5, and verses 7 to 9. (In English notation: \"Mt1:1-3,5,7-9\".)")
            + "</p>" + "<p>" + __("Multiple queries can be combined together using a semi-colon \";\".") + " "
            + __("If the query following the semi-colon refers to the same book as the preceding query, it is not necessary to indicate the book a second time.")
            + " "
            + __("For example, \"Matthew 1,1;2,13\" means the gospel according to Matthew, chapter 1 verse 1 and chapter 2 verse 13. (In English notation: \"Matthew 1:1;2:13\".)")
            + " "
            + __("Here is an example of multiple complex queries combined into a single querystring: \"Genesis 1,3-5.7.9-11.13;2,4-9.11-13;Apocalypse 3,10.12-14\". (In English notation: \"Genesis 1:3-5,7,9-11,13;2:4-9,11-13;Apocalypse 3:10,12-14\").")
            + "</p>" + "<p>"
            + __("It doesn't matter whether or not you use a space between the book and the chapter, the querystring will be interpreted just the same.")
            + __("It is also indifferent whether you use uppercase or lowercase letters, the querystring will be interpreted just the same.")
            + "</p>" + "</body>" + "</html>";

    HTMLStr3 = "<html>" + "<head><meta charset=\"utf-8\"></head>" + "<body>" + "<h2>"
            + __("Biblical Books and Abbreviations") + "</h2>" + "<p>"
            + __("Here is a list of valid books and their corresponding abbreviations, either of which can be used in the querystrings.")
            + " "
            + __("The abbreviations do not always correspond with those proposed by the various editions of the Bible, because they would conflict with those proposed by other editions.")
            + " "
            + __("For example some english editions propose \"Gn\" as an abbreviation for \"Genesis\", while some italian editions propose \"Gn\" as an abbreviation for \"Giona\" (= \"Jonah\").")
            + " "
            + __("Therefore you will not always be able to use the abbreviations proposed by any single edition of the Bible, you must use the abbreviations that are recognized by the BibleGet engine as listed in the following table:")
            + "</p><br /><br />" + "<table cellspacing='0'>" + "<caption>{1}</caption>"
            + "<tr><th style=\"width:70%;\">" + __("BOOK") + "</th><th style=\"width:30%;\">"
            + __("ABBREVIATION") + "</th></tr>" + "{0}" + "</table>" + "</body>" + "</html>";

    Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    screenWidth = (int) screenSize.getWidth();
    screenHeight = (int) screenSize.getHeight();
    frameWidth = 1250;
    frameHeight = 700;
    frameLeft = (screenWidth / 2) - (frameWidth / 2);
    frameTop = (screenHeight / 2) - (frameHeight / 2);
    initComponents();
}

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

@Override
public String call() {

    // init logger
    PropertyConfigurator.configure(config.getProperty("service.log4j-conf"));

    logger.info("[" + config.getProperty("service.name") + "] " + "Starting 'Task' ...");

    // init IDs of the prototype project
    String dataModelID = config.getProperty("prototype.dataModelID");
    String projectID = config.getProperty("prototype.projectID");
    String outputDataModelID = config.getProperty("prototype.outputDataModelID");

    // init process values
    String inputResourceID = null;
    String message = null;//from   ww w .ja  va  2 s. c  o m

    try {

        // get the resource id of the current data model >> updateResourceID replaces resourceID
        String updateResourceID = null;
        try {
            updateResourceID = getProjectResourceID(dataModelID);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("[" + config.getProperty("service.name") + "] updateResourceID = " + updateResourceID);

        // upload resource and update a InputDataModel
        String inputResourceJson = uploadFileAndUpdateResource(updateResourceID, resource,
                "resource for project '" + resource, config.getProperty("project.name") + "' - case " + cnt);
        JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputResourceJson, "UTF-8"));
        inputResourceID = jsonReader.readObject().getString("uuid");
        logger.info("[" + config.getProperty("service.name") + "] inputResourceID = " + inputResourceID);

        if (updateResourceID != null) {

            // update the datamodel (will use it's (update) resource)
            updateDataModel(dataModelID);

            // configuration and processing of the task
            String jsonResponse = executeTask(dataModelID, projectID, outputDataModelID);

            if (jsonResponse != null) {

                if (Boolean.parseBoolean(config.getProperty("results.persistInFolder"))) {

                    if (Boolean.parseBoolean(config.getProperty("results.writeDMPJson"))) {
                        // save DMP results in files
                        FileUtils.writeStringToFile(new File(config.getProperty("results.folder")
                                + File.separatorChar + dataModelID + "." + cnt + ".json"), jsonResponse);
                    }

                    // build rdf graph
                    ValueFactory factory = ValueFactoryImpl.getInstance();

                    Graph graph = new LinkedHashModel();

                    URI graphUri = factory.createURI(config.getProperty("results.rdf.graph"));

                    URI subject = null;
                    URI predicate = null;
                    URI object = null;
                    Literal literal = null;
                    Statement statement = null;

                    JsonReader dmpJsonResult = Json.createReader(IOUtils.toInputStream(jsonResponse, "UTF-8"));
                    JsonArray records = dmpJsonResult.readArray();

                    for (JsonObject record : records.getValuesAs(JsonObject.class)) {

                        subject = factory
                                .createURI(record.getJsonString("__record_id").toString().replaceAll("\"", ""));

                        for (JsonObject triple : record.getJsonArray("__record_data")
                                .getValuesAs(JsonObject.class)) {

                            for (String key : triple.keySet()) {

                                if (key.endsWith("rdf-syntax-ns#type")) {
                                    predicate = RDF.TYPE;
                                    object = factory.createURI(
                                            triple.getJsonString(key).toString().replaceAll("\"", ""));
                                    statement = factory.createStatement(subject, predicate, object, graphUri);
                                    graph.add(statement);
                                } else {

                                    predicate = factory.createURI(key);

                                    switch (triple.get(key).getValueType().toString()) {

                                    case "STRING": {

                                        try {
                                            object = factory.createURI(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, object,
                                                    graphUri);
                                            graph.add(statement);
                                        } catch (Exception e) {
                                            literal = factory.createLiteral(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, literal,
                                                    graphUri);
                                            graph.add(statement);
                                        }
                                        break;
                                    }
                                    case "ARRAY": {

                                        for (JsonString value : triple.getJsonArray(key)
                                                .getValuesAs(JsonString.class)) {

                                            try {
                                                object = factory
                                                        .createURI(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, object,
                                                        graphUri);
                                                graph.add(statement);
                                            } catch (Exception e) {
                                                literal = factory
                                                        .createLiteral(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, literal,
                                                        graphUri);
                                                graph.add(statement);
                                            }
                                        }
                                        break;
                                    }
                                    default: {

                                        logger.info("Unhandled ValueType: " + triple.get(key).getValueType());
                                    }
                                    }
                                }
                            }
                        }
                    }

                    if (graph.size() > 0) {
                        // save rdf data as 'results.rdf.format' in 'results.folder'
                        RDFFormat format = null;
                        switch (config.getProperty("results.rdf.format")) {

                        case "xml": {

                            format = RDFFormat.RDFXML;
                            break;
                        }
                        case "nquads": {

                            format = RDFFormat.NQUADS;
                            break;
                        }
                        case "jsonld": {

                            format = RDFFormat.JSONLD;
                            break;
                        }
                        case "ttl": {

                            format = RDFFormat.TURTLE;
                            break;
                        }
                        default: {

                            format = RDFFormat.RDFXML;
                        }
                        }

                        try {
                            FileOutputStream out = new FileOutputStream(
                                    config.getProperty("results.folder") + File.separatorChar + dataModelID
                                            + "." + cnt + ".rdf." + config.getProperty("results.rdf.format"));
                            RDFWriter writer = Rio.createWriter(format, out);

                            writer.startRDF();
                            for (Statement st : graph) {
                                writer.handleStatement(st);
                            }
                            writer.endRDF();

                            out.close();

                        } catch (RDFHandlerException | IOException e) {
                            e.printStackTrace();
                        }

                        message = "'" + resource + "' transformed. results in '"
                                + config.getProperty("results.folder") + File.separatorChar + dataModelID + "."
                                + cnt + ".rdf." + config.getProperty("results.rdf.format") + "'";
                    } else {

                        message = "'" + resource + "' transformed but result is empty.";
                    }
                }
            } else {

                message = "'" + resource + "' not transformed: error in task execution.";
            }
        }
    } catch (Exception e) {

        logger.error("[" + config.getProperty("service.name") + "] Processing resource '" + resource
                + "' failed with a " + e.getClass().getSimpleName());
        e.printStackTrace();
    }

    return message;
}

From source file:wsserver.EKF1TimerSessionBean.java

private void callT1() {
    Runnable r = new Runnable() {

        public void run() {
            try {
                try {
                    cbLogsFacade.insertLog("INFO", "Start load bx_bsect",
                            "Start load bx_bsect url=" + systemURL);
                } catch (Exception lge) {

                }//from w  w  w . j a  v  a2  s .  c  o  m
                String url = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=BSECT";

                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                // optional default is GET
                con.setRequestMethod("GET");
                con.setConnectTimeout(180000);

                //add request header
                con.setRequestProperty("User-Agent", "Mozilla-Firefox");

                int responseCode = con.getResponseCode();
                System.out.println("\nSending 'GET' request to URL : " + url);
                System.out.println("Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                try {
                    cbLogsFacade.insertLog("INFO", "Complete load bx_bsect urldata",
                            "Complete load bx_bsect urldata");
                } catch (Exception lge) {

                }
                JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));

                bxBsectFacade.clearBxBsect();

                int crcnt = 0;
                int badCnt = 0;
                JsonArray jarray = jsonReader.readArray();
                //JsonParser parser = Json.createParser(in);
                boolean hasCrashes = false;
                for (int i = 0; i < jarray.size(); i++) {
                    JsonObject jobject = jarray.getJsonObject(i);
                    BxBsect bsectObj = new BxBsect();
                    bsectObj.setId(-1);
                    try {
                        bsectObj.setBxId(Tools.parseInt(jobject.getString("ID", "-1"), -1));
                    } catch (Exception e) {
                        bsectObj.setBxId(-1);
                    }

                    try {
                        String f1cId = jobject.getString("1C_ID", "");
                        if (f1cId.length() == 36)
                            bsectObj.setF1cId(f1cId);
                        else
                            bsectObj.setF1cId("NULL");
                    } catch (Exception e) {
                        bsectObj.setF1cId("NULL");
                    }
                    try {
                        bsectObj.setParentBxId(Tools.parseInt(jobject.getString("PARENT_ID", "-1"), -1));
                    } catch (Exception e) {
                        bsectObj.setParentBxId(-1);
                    }
                    try {
                        bsectObj.setName(jobject.getString("NAME", "NULL"));
                    } catch (Exception e) {
                        bsectObj.setName("NULL");
                    }
                    int try_cnt = 0;
                    boolean notSucc = true;
                    String err = "";
                    while (try_cnt < 10 && notSucc) {
                        try {
                            bxBsectFacade.create(bsectObj);
                            crcnt++;
                            notSucc = false;
                        } catch (Exception e) {
                            notSucc = true;
                            badCnt++;
                            try_cnt++;
                            err += "[[" + Tools.parseInt(jobject.getString("ID", "-1"), -1)
                                    + "]]<<==!!||||||!!==>>Error of bxBsectFacade.create " + e;
                        }
                    }

                    try {
                        if (try_cnt > 0)
                            cbLogsFacade.insertLog("ERROR", "Error of bxBSectFacade", err);
                    } catch (Exception lge) {

                    }
                    hasCrashes = hasCrashes | notSucc;
                }

                try {
                    cbLogsFacade.insertLog("INFO", "Complete load bx_bsect", "Complete load bx_bsect "
                            + ", all=" + jarray.size() + ",succ=" + crcnt + ",errcnt=" + badCnt);
                } catch (Exception lge) {

                }

                BxBsect bsectObjCompl = new BxBsect();
                bsectObjCompl.setId(-1);
                bsectObjCompl.setBxId(jarray.size());
                if (hasCrashes)
                    bsectObjCompl.setF1cId("00000000-0000-0000-0000-00nocomplete");
                else
                    bsectObjCompl.setF1cId("00000000-0000-0000-0000-0000complete");
                //bsectObjCompl.setF1cId("00000000-0000-0000-0000-0bxinprocess");
                //bsectObjCompl.setF1cId("00000000-0000-0000-0000-01?inprocess");
                //bsectObjCompl.setF1cId("00000000-0000-0000-0000-bxancomplete");
                //bsectObjCompl.setF1cId("00000000-0000-0000-0000-1cancomplete");
                bsectObjCompl.setParentBxId(badCnt);
                bsectObjCompl.setName("jasz=" + jarray.size() + ",crcnt=" + crcnt);
                int try_cnt22 = 0;
                boolean notSucc22 = true;
                while (try_cnt22 < 10 && notSucc22) {
                    try {
                        //bxBsectFacade.create(bsectObjCompl);
                        notSucc22 = false;
                    } catch (Exception e) {
                        notSucc22 = true;
                        //badCnt22++;
                        try_cnt22++;
                    }
                }

            } catch (Exception e) {
                System.out.println("<<==!!||||||!!==>>Error of get-parse json " + e);
                try {
                    cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_bsect",
                            "<<==!!||||||!!==>>Error of get-parse json " + e);
                } catch (Exception lge) {

                }
            } finally {
                callT2();
            }
        }

    };

    Thread t = new Thread(r);
    t.start();
}

From source file:wsserver.EKF1TimerSessionBean.java

private void callT2() {

    Runnable r2 = new Runnable() {

        public void run() {
            int badCnt2 = 0;
            boolean success_sql_operation = false;
            StringBuilder insert_sql_values_sb = new StringBuilder();
            int insert_sql_cnt = 0;
            String requestRes = "";
            try {

                try {
                    cbLogsFacade.insertLog("INFO",
                            "  ?  ?   ekfgroup.com",
                            "?  ?    ?  (Timer condition worked  Bad full exchange circle)  ? ?? - ?? ?  ??? ,   ?");
                } catch (Exception lge) {
                }/*from w w  w .  j  a v  a2s. c o  m*/

                String url2 = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=1CSECT";

                //try {
                //    cbLogsFacade.insertLog("INFO", "Start load bx_1csect", "Start load bx_1csect, url="+systemURL);
                //} catch(Exception lge)  {

                //}

                URL obj2 = new URL(url2);
                HttpURLConnection con2 = (HttpURLConnection) obj2.openConnection();

                // optional default is GET
                con2.setRequestMethod("GET");
                con2.setConnectTimeout(180000);
                con2.setReadTimeout(180000);

                //add request header
                con2.setRequestProperty("User-Agent", "Mozilla-Firefox");

                int responseCode2 = con2.getResponseCode();
                System.out.println("\nSending 'GET' request to URL : " + url2);
                System.out.println("Response Code : " + responseCode2);

                BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream()));
                String inputLine2;
                StringBuffer response2 = new StringBuffer();

                while ((inputLine2 = in2.readLine()) != null) {
                    response2.append(inputLine2);
                }
                in2.close();

                //try {
                //    cbLogsFacade.insertLog("INFO", "Exchange in process 8", "Exchange in process 8");
                //} catch(Exception lge)  { }

                requestRes = response2.toString();

                try {
                    cbLogsFacade.insertLog("INFO", "Complete load bx_1csect urldata",
                            "Complete load bx_1csect urldata, url=" + url2);
                } catch (Exception lge) {

                }

                JsonReader jsonReader2 = Json.createReader(new StringReader(response2.toString()));

                bx1CSectFacade.clearBx1CSect();

                JsonArray jarray2 = jsonReader2.readArray();
                int crcnt2 = 0;

                boolean hasCrashes2 = false;
                String saveBxSectLog = "";
                for (int i = 0; i < jarray2.size(); i++) {
                    JsonObject jobject2 = jarray2.getJsonObject(i);
                    Bx1CSect b1cssectObj = new Bx1CSect();
                    b1cssectObj.setId(-1);

                    if (insert_sql_cnt > 0)
                        insert_sql_values_sb.append(" ,");
                    insert_sql_values_sb.append("( ");

                    try {
                        b1cssectObj.setBxId(Tools.parseInt(jobject2.getString("ID", "-1"), -1));
                    } catch (Exception e) {
                        b1cssectObj.setBxId(-1);
                    }
                    try {
                        String f1cId = jobject2.getString("1C_ID", "");
                        if (f1cId.length() == 36)
                            b1cssectObj.setF1cId(f1cId);
                        else
                            b1cssectObj.setF1cId("NULL");
                    } catch (Exception e) {
                        b1cssectObj.setF1cId("NULL");
                    }
                    try {
                        b1cssectObj.setParentBxId(Tools.parseInt(jobject2.getString("PARENT_ID", "-1"), -1));
                    } catch (Exception e) {
                        b1cssectObj.setParentBxId(-1);
                    }

                    try {
                        String parent1cId = jobject2.getString("PARENT_1CID", "NULL");
                        if (parent1cId.length() == 36)
                            b1cssectObj.setParent1cId(parent1cId);
                        else
                            b1cssectObj.setParent1cId("NULL");
                    } catch (Exception e) {
                        b1cssectObj.setParent1cId("NULL");
                    }

                    try {
                        b1cssectObj.setName(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject2.getString("NAME", "NULL")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setName("NULL");
                    }

                    try {
                        b1cssectObj.setPicture(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject2.getString("PICTURE", "")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setPicture("");
                    }

                    try {
                        b1cssectObj.setMcatalog(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("MASTER_CATALOG", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setMcatalog("");
                    }

                    //inputLine2)

                    try {
                        b1cssectObj.setDescription(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject2.getString("DESCRIPTION", "")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setDescription("");
                    }

                    try {
                        b1cssectObj.setFullDescription(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("FULL_DESCRIPTION", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setFullDescription("");
                    }

                    try {
                        b1cssectObj.setTypeCompleting(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("TYPE_COMPLETING", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setTypeCompleting("");
                    }

                    try {
                        b1cssectObj.setCharGabarits(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("CHAR_GABARITS", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setCharGabarits("");
                    }

                    try {
                        b1cssectObj.setDocumentation(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("DOCUMENTATION", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setDocumentation("");
                    }

                    try {
                        b1cssectObj.setShortDesription(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("SHORT_DESCRIPTION", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setShortDesription("");
                    }

                    try {
                        b1cssectObj.setVideoDescription(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("VIDEO_DESCRIPTION", ""))
                                        .replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cssectObj.setVideoDescription("");
                    }

                    insert_sql_values_sb.append(b1cssectObj.getBxId());
                    insert_sql_values_sb.append(",'");
                    insert_sql_values_sb.append(b1cssectObj.getName().replace("'", "''"));
                    insert_sql_values_sb.append("',");
                    insert_sql_values_sb.append(b1cssectObj.getParentBxId());
                    insert_sql_values_sb.append(",'");
                    insert_sql_values_sb.append(b1cssectObj.getF1cId().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getParent1cId().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getFullDescription().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getTypeCompleting().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getCharGabarits().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getShortDesription().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getDocumentation().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getDescription().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getPicture().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cssectObj.getVideoDescription().replace("'", "''"));
                    insert_sql_values_sb.append("','");//
                    insert_sql_values_sb.append(b1cssectObj.getMcatalog().replace("'", "''"));
                    insert_sql_values_sb.append("',");
                    insert_sql_values_sb
                            .append((Tools.parseInt(jobject2.getString("COLLAPSEVC", "0"), 0) == 1 ? 1 : 0));
                    insert_sql_values_sb.append(",'");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject2.getString("ADVANTS", "")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject2.getString("FILTER_PROPS", "")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("DESCRIPTS_JSON", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("GABARITS_JSON", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("DOCS_JSON", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("',");
                    try {
                        insert_sql_values_sb.append(Tools.parseInt(
                                StringEscapeUtils.unescapeJson(jobject2.getString("SORT_ORDER", "0")), 0));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append(",'");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("SEO_ALIAS_URL", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject2.getString("SEO_TITLE", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("','");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils
                                .unescapeHtml4(StringEscapeUtils.unescapeJson(jobject2.getString("SEO_H1", ""))
                                        .replace("&quot;", "\"").replace("'", "''")));
                    } catch (Exception e) {
                    }
                    insert_sql_values_sb.append("')");

                    int try_cnt2 = 0;
                    boolean notSucc2 = true;
                    String err = "";
                    while (try_cnt2 < 10 && notSucc2) {
                        try {
                            //bx1CSectFacade.create(b1cssectObj);
                            //bx1CSectFacade.
                            crcnt2++;
                            notSucc2 = false;
                        } catch (Exception e) {
                            notSucc2 = true;
                            badCnt2++;
                            try_cnt2++;
                            err += "[[" + Tools.parseInt(jobject2.getString("ID", "-1"), -1)
                                    + "]]<<==!!||||||!!==>>Error of bx1CsectFacade.create " + e;
                        }
                    }
                    try {
                        if (try_cnt2 > 0)
                            cbLogsFacade.insertLog("ERROR", "Error of bx1CSectFacade", err);
                    } catch (Exception lge) {

                    }
                    hasCrashes2 = hasCrashes2 | notSucc2;

                    insert_sql_cnt++;
                    if (insert_sql_cnt >= 500 || i >= (jarray2.size() - 1)) {
                        try {
                            success_sql_operation = bx1CSectFacade
                                    .insertBx1SectMultiply(insert_sql_values_sb.toString(), insert_sql_cnt);
                        } catch (Exception lgesq) {
                            success_sql_operation = false;
                            try {
                                cbLogsFacade.insertLog("INFO",
                                        "!!!Unsuccess sending complex sql instruct to bx_1csect",
                                        "Err " + lgesq);
                            } catch (Exception lge) {

                            }
                        }

                        if (!success_sql_operation) {
                            try {
                                cbLogsFacade.insertLog("INFO", "!!!Unsuccess complex sql instruct to bx_1csect",
                                        "Count record to bx_1csect " + insert_sql_cnt);
                            } catch (Exception lge) {

                            }
                            break;
                        } else {
                            //saveBxSectLog+=("Count record to bx_1cpsect "+insert_sql_cnt+". ");
                            //try {
                            //    cbLogsFacade.insertLog("INFO", "Success complex sql instruct to bx_1csect", "Count record to bx_1cpsect "+insert_sql_cnt);
                            //} catch(Exception lge)  {

                            //}
                        }
                        insert_sql_cnt = 0;
                        insert_sql_values_sb.setLength(0);
                    }
                }

                try {
                    cbLogsFacade.insertLog("INFO", "Complete load bx_1csect",
                            saveBxSectLog + " Complete load bx_1csect " + ", all=" + jarray2.size() + ",succ="
                                    + crcnt2 + ",errcnt=" + badCnt2);
                } catch (Exception lge) {

                }

                if (badCnt2 <= 0 && success_sql_operation)
                    callT3();
                else
                    exchangeInProcess = false;

            } catch (Exception e) {
                exchangeInProcess = false;
                try {
                    cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_1csect",
                            "<<==!!||||||!!==>>Error of get-parse json " + e + ",server reply["
                                    + requestRes.substring(0, 200) + "]");
                } catch (Exception lge) {

                }

            } finally {

            }
        }

    };

    Thread t2 = new Thread(r2);
    t2.start();

}

From source file:wsserver.EKF1TimerSessionBean.java

private void callT3() {
    Runnable r3 = new Runnable() {

        public void run() {
            int badCnt3 = 0;
            int crcnt = 0;
            int allcnt = -1;
            boolean success_sql_operation = false;
            StringBuilder insert_sql_values_sb = new StringBuilder();
            int insert_sql_cnt = 0;
            try {

                String url = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=1CPROD";

                //try {
                //    cbLogsFacade.insertLog("INFO", "Start load bx_1cprod", "Start load bx_1cprod, url="+systemURL);
                //} catch(Exception lge)  {

                //}

                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                // optional default is GET
                con.setRequestMethod("GET");
                con.setConnectTimeout(180000);
                con.setReadTimeout(180000);

                //add request header
                con.setRequestProperty("User-Agent", "Mozilla-Firefox");

                int responseCode = con.getResponseCode();
                System.out.println("\nSending 'GET' request to URL : " + url);
                System.out.println("Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }/*from   w  ww  .j ava2s .co m*/
                in.close();

                try {
                    cbLogsFacade.insertLog("INFO", "Complete load bx_1cprod urldata",
                            "Complete load bx_1cprod urldata, url=" + systemURL);
                } catch (Exception lge) {

                }
                JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));

                //int icnt = 0;//bx1CProdFacade.insertBx1ProdMultiply();

                //try {
                //    cbLogsFacade.insertLog("INFO", "Complete persist test bx_1cprod urldata ", "Complete persist test bx_1cprod urldata "+icnt);
                //} catch(Exception lge)  {
                //}

                bx1CProdFacade.clearBx1CProd();

                JsonArray jarray = jsonReader.readArray();

                boolean hasCrashes = false;
                String saveBxDataLog = "";
                for (int i = 0; i < jarray.size(); i++) {
                    JsonObject jobject = jarray.getJsonObject(i);
                    Bx1CProd b1cprodObj = new Bx1CProd();

                    b1cprodObj.setId(-1);
                    if (insert_sql_cnt > 0)
                        insert_sql_values_sb.append(" ,");
                    insert_sql_values_sb.append("( ");
                    try {
                        b1cprodObj.setBxId(Tools.parseInt(jobject.getString("ID", "-1"), -1));
                    } catch (Exception e) {
                        b1cprodObj.setBxId(-1);
                    }

                    try {
                        String f1cId = jobject.getString("1C_ID", "NULL");
                        if (f1cId.length() == 36)
                            b1cprodObj.setF1cId(f1cId);
                        else
                            b1cprodObj.setF1cId("NULL");
                    } catch (Exception e) {
                        b1cprodObj.setF1cId("NULL");
                    }
                    try {
                        b1cprodObj.setParentBxId(Tools.parseInt(jobject.getString("PARENT_ID", "-1"), -1));
                    } catch (Exception e) {
                        b1cprodObj.setParentBxId(-1);
                    }

                    try {
                        String parent1cId = jobject.getString("PARENT_1CID", "NULL");
                        if (parent1cId.length() == 36)
                            b1cprodObj.setParent1cId(parent1cId);
                        else
                            b1cprodObj.setParent1cId("NULL");
                    } catch (Exception e) {
                        b1cprodObj.setParent1cId("NULL");
                    }

                    try {
                        b1cprodObj.setName(StringEscapeUtils.unescapeHtml4(StringEscapeUtils
                                .unescapeJson(jobject.getString("NAME", "NULL")).replace("&quot;", "\"")));
                    } catch (Exception e) {
                        b1cprodObj.setName("NULL");
                    }

                    try {
                        b1cprodObj.setArtikul(StringEscapeUtils.unescapeHtml4(
                                StringEscapeUtils.unescapeJson(jobject.getString("ARTICUL", "NULL"))));
                    } catch (Exception e) {
                        b1cprodObj.setArtikul("NULL");
                    }

                    insert_sql_values_sb.append(b1cprodObj.getBxId());
                    insert_sql_values_sb.append(",'");
                    insert_sql_values_sb.append(b1cprodObj.getName().replace("'", "''"));
                    insert_sql_values_sb.append("',");
                    insert_sql_values_sb.append(b1cprodObj.getParentBxId());
                    insert_sql_values_sb.append(",'");
                    insert_sql_values_sb.append(b1cprodObj.getF1cId().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cprodObj.getParent1cId().replace("'", "''"));
                    insert_sql_values_sb.append("','");
                    insert_sql_values_sb.append(b1cprodObj.getArtikul().replace("'", "''"));

                    insert_sql_values_sb.append("',");

                    try {
                        b1cprodObj.setPrice(new BigDecimal(jobject.getString("PRICE", "0")));
                        insert_sql_values_sb.append(jobject.getString("PRICE", "0").replace(",", "."));
                    } catch (Exception e) {
                        b1cprodObj.setPrice(new BigDecimal(0));
                        insert_sql_values_sb.append("0");
                    }
                    insert_sql_values_sb.append(",");

                    try {
                        b1cprodObj.setAmount(new BigDecimal(jobject.getString("QUANTITY", "0")));
                        insert_sql_values_sb.append(jobject.getString("QUANTITY", "0").replace(",", "."));
                    } catch (Exception e) {
                        b1cprodObj.setAmount(new BigDecimal(0));
                        insert_sql_values_sb.append("0");
                    }
                    insert_sql_values_sb.append(",");

                    try {
                        b1cprodObj.setBprice(new BigDecimal(jobject.getString("BPRICE", "0")));
                        insert_sql_values_sb.append(jobject.getString("BPRICE", "0").replace(",", "."));
                    } catch (Exception e) {
                        b1cprodObj.setBprice(new BigDecimal(0));
                        insert_sql_values_sb.append("0");
                    }
                    insert_sql_values_sb.append(",");

                    try {
                        //b1cprodObj.setBprice(new BigDecimal(jobject.getString("SORT_ORDER", "0")));
                        insert_sql_values_sb.append(jobject.getString("SORT_ORDER", "0").replace(",", "."));
                    } catch (Exception e) {
                        //b1cprodObj.setBprice(new BigDecimal(0));
                        insert_sql_values_sb.append("0");
                    }
                    insert_sql_values_sb.append(",'");
                    try {
                        insert_sql_values_sb.append(StringEscapeUtils
                                .unescapeHtml4(
                                        StringEscapeUtils.unescapeJson(jobject.getString("MAIN_PICT", "")))
                                .replace("'", "''"));
                    } catch (Exception e) {
                    }

                    insert_sql_values_sb.append("',");

                    try {
                        //b1cprodObj.setBprice(new BigDecimal(jobject.getString("SORT_ORDER", "0")));
                        insert_sql_values_sb.append("" + jobject.getInt("PROP_CNT", 0));
                    } catch (Exception e) {
                        //b1cprodObj.setBprice(new BigDecimal(0));
                        insert_sql_values_sb.append("0");
                    }

                    insert_sql_values_sb.append(")");

                    int try_cnt = 0;
                    boolean notSucc = true;
                    String err = "";
                    while (try_cnt < 10 && notSucc) {
                        try {
                            //bx1CSectFacade.
                            //bx1CProdFacade.create(b1cprodObj);
                            crcnt++;
                            notSucc = false;
                        } catch (Exception e) {
                            notSucc = true;
                            badCnt3++;
                            try_cnt++;
                            err += "[[" + Tools.parseInt(jobject.getString("ID", "-1"), -1)
                                    + "]]<<==!!||||||!!==>>Error of bx1CProdFacade.create " + e;
                        }
                    }

                    try {
                        if (try_cnt > 0) {
                            cbLogsFacade.insertLog("ERROR", "Error of bx1CProdFacade", err);
                        }
                    } catch (Exception lge) {

                    }
                    hasCrashes = hasCrashes | notSucc;

                    insert_sql_cnt++;
                    if (insert_sql_cnt >= 500 || i >= (jarray.size() - 1)) {
                        try {
                            success_sql_operation = bx1CProdFacade
                                    .insertBx1ProdMultiply(insert_sql_values_sb.toString(), insert_sql_cnt);
                        } catch (Exception lgesq) {
                            success_sql_operation = false;
                            try {
                                cbLogsFacade.insertLog("INFO",
                                        "!!!Unsuccess sending complex sql instruct to bx_1cprod",
                                        "Err " + lgesq);
                            } catch (Exception lge) {

                            }
                        }

                        if (!success_sql_operation) {
                            try {
                                cbLogsFacade.insertLog("INFO", "!!!Unsuccess complex sql instruct to bx_1cprod",
                                        "Count record to bx_1cprods " + insert_sql_cnt);
                            } catch (Exception lge) {

                            }
                            break;
                        } else {
                            saveBxDataLog += ("Succ " + insert_sql_cnt);//complex sql instruct to bx_1cprod. "+
                            //        "Count record to bx_1cprods "+insert_sql_cnt);
                            //try {
                            //    cbLogsFacade.insertLog("INFO", "Success complex sql instruct to bx_1cprod", "Count record to bx_1cprods "+insert_sql_cnt);
                            //} catch(Exception lge)  {

                            //}
                        }
                        insert_sql_cnt = 0;
                        insert_sql_values_sb.setLength(0);
                    }
                }

                try {
                    allcnt = jarray.size();
                    cbLogsFacade.insertLog("INFO", "Complete load bx_1cprod",
                            saveBxDataLog + " Complete load bx_1cprods " + ", all=" + allcnt + ",succ=" + crcnt
                                    + ",errcnt=" + badCnt3);
                } catch (Exception lge) {

                }

                if (badCnt3 <= 20 && (allcnt == crcnt) && success_sql_operation) {
                    //sendCompareData();
                    //sendCompareSectDataDel();
                    //sendCompareSectDataUpd();
                    boolean repeat_load = true;
                    int repeat_counter = 0;
                    while (repeat_load && repeat_counter < 10) {
                        repeat_counter++;
                        String selectExchngDataLog = "";
                        try {

                            if (tablesOperatingStateFacade.getEkfGrExchDataCorrupt() && false) {
                                Thread.sleep(30000);
                                try {
                                    cbLogsFacade.insertLog("INFO", "getEkfGrExchDataCorrupt",
                                            "Wait on 30 sec, attempt " + repeat_counter + " of 10...");
                                } catch (Exception lgex) {

                                }
                            } else {
                                repeat_load = false;
                                int ekfProdCount = cbLogsFacade.ekfProdCount();
                                int ekfProdSectCount = cbLogsFacade.ekfProdSectCount();
                                if (ekfProdCount >= 1000 && ekfProdCount <= 100000 && ekfProdSectCount >= 200
                                        && ekfProdSectCount <= 10000) {
                                    if (tablesOperatingStateFacade.setEkfGrExchDataCorrupt()) {

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request cbNewPrFrom1cWpropsFacade", "Start of request cbNewPrFrom1cWpropsFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Start of request cbNewPrFrom1cWpropsFacade ";
                                        npwps_ = cbNewPrFrom1cWpropsFacade.findAll();

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupDel1csectFromBxFacade", "Complete prev, Start of request cbEkfgroupDel1csectFromBxFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Complete prev, Start of request cbEkfgroupDel1csectFromBxFacade ";
                                        dswps_ = cbEkfgroupDel1csectFromBxFacade.findAll();

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupUpd1csectToBxFacade", "Complete prev, Start of request cbEkfgroupUpd1csectToBxFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Complete prev, Start of request cbEkfgroupUpd1csectToBxFacade ";
                                        uswps_ = cbEkfgroupUpd1csectToBxFacade.findAll();

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupAdd1csectToBxFacade", "Complete prev, Start of request cbEkfgroupAdd1csectToBxFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Complete prev, Start of request cbEkfgroupAdd1csectToBxFacade ";
                                        nswps_ = cbEkfgroupAdd1csectToBxFacade.findAll();

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request cbEkfroupDelFromBxViewFacade", "Complete prev, Start of request cbEkfroupDelFromBxViewFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Complete prev, Start of request cbEkfroupDelFromBxViewFacade ";
                                        dpwps_ = cbEkfroupDelFromBxViewFacade.findAll();

                                        //try {
                                        //    cbLogsFacade.insertLog("INFO", "Start of request CbEkfgroupToUpdatedBx1cFacade", "Complete prev, Start of request CbEkfgroupToUpdatedBx1cFacade");
                                        //} catch(Exception lge)  { }
                                        selectExchngDataLog += "Complete prev, Start of request CbEkfgroupToUpdatedBx1cFacade ";
                                        upwps_ = cbEkfgroupToUpdatedBx1cFacade.findAll();
                                        try {
                                            cbLogsFacade.insertLog("INFO",
                                                    "End of request CbEkfgroupToUpdatedBx1cFacade",
                                                    selectExchngDataLog
                                                            + " End of request CbEkfgroupToUpdatedBx1cFacade");
                                        } catch (Exception lge) {
                                        }

                                        if (npwps_.size() == 0 && upwps_.size() == 0 && dpwps_.size() == 0) {
                                            if (cbSettingsFacade.updExchanheLastDt()) {
                                                //try {
                                                //    cbLogsFacade.insertLog("INFO", "Success update exchange last datetime", 
                                                //            "Success update exchange last datetime");
                                                //} catch(Exception lge)  {

                                                //}
                                            } else {
                                                try {
                                                    cbLogsFacade.insertLog("ERROR",
                                                            "Unsuccess update exchange last datetime",
                                                            "Unsuccess update exchange last datetime");
                                                } catch (Exception lge) {

                                                }
                                            }
                                        }

                                        if (tablesOperatingStateFacade.setEkfGrExchDataUnCorrupt()) {
                                            sendCompareSectDataAdd();
                                        } else {
                                            exchangeInProcess = false;
                                            try {
                                                cbLogsFacade.insertLog("ERROR",
                                                        "Unsuccess setEkfGrExchDataCorrupt 0",
                                                        "Unsuccess setEkfGrExchDataCorrupt 0");
                                            } catch (Exception lgex) {

                                            }

                                        }

                                    } else {
                                        exchangeInProcess = false;
                                        try {
                                            cbLogsFacade.insertLog("ERROR",
                                                    "Unsuccess setEkfGrExchDataCorrupt 1",
                                                    "Unsuccess setEkfGrExchDataCorrupt 1");
                                        } catch (Exception lgex) {

                                        }
                                    }
                                } else {
                                    exchangeInProcess = false;
                                    try {
                                        cbLogsFacade.insertLog("ERROR", "Invalid data sizes, exchange stopped",
                                                "Data sizes mismatch conditions 200<=ekfProdSectCount<=10000, "
                                                        + "1000<=ekfProdCount<=100000");
                                    } catch (Exception lgex) {

                                    }
                                }
                            }
                        } catch (Exception lge) {
                            exchangeInProcess = false;
                            repeat_load = false;
                            try {
                                cbLogsFacade.insertLog("ERROR",
                                        "Error of getEkfGrExchDataCorrupt or setEkfGrExchDataCorrupt or MDS data load",
                                        "Error of getEkfGrExchDataCorrupt, detail: " + selectExchngDataLog);
                            } catch (Exception lgex) {

                            }
                        }
                    }

                    if (repeat_load) {
                        hasLong1CWait = true;
                        exchangeInProcess = false;
                    }

                } else
                    exchangeInProcess = false;

            } catch (Exception e) {
                exchangeInProcess = false;
                System.out.println("<<==!!||||||!!==>>Error of get-parse bx_1cprod json " + e);
                try {
                    cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_1cprod",
                            "<<==!!||||||!!==>>Error of get-parse json " + e);
                } catch (Exception lge) {

                }
            } finally {
                try {
                    //tablesOperatingStateFacade.setEkfGrExchDataUnDelta();
                    if (tablesOperatingStateFacade.setEkfGrExchDataUnCorrupt()) {

                    } else {
                        try {
                            cbLogsFacade.insertLog("ERROR", "Unsuccess setEkfGrExchDataCorrupt 0",
                                    "Unsuccess setEkfGrExchDataCorrupt 0");
                        } catch (Exception lgex) {

                        }
                    }
                } catch (Exception lgex) {

                }
            }
        }

    };

    Thread t3 = new Thread(r3);
    t3.start();
}

From source file:org.fuin.esmp.Downloads.java

/**
 * Loads the data from the JSON download versions file.
 * /*from   ww w .  java 2 s . c  om*/
 * @throws IOException
 *             Parsing the event store version file failed.
 */
public final void parse() throws IOException {

    final Reader reader = new FileReader(jsonDownloadsFile);
    try {
        final JsonReader jsonReader = Json.createReader(reader);
        final JsonArray osArray = jsonReader.readArray();
        for (int i = 0; i < osArray.size(); i++) {
            final JsonObject osObj = (JsonObject) osArray.get(i);
            final String os = osObj.getString("os");
            final String currentVersion = osObj.getString("currentVersion");
            final JsonArray downloadsArray = osObj.getJsonArray("downloads");
            final List<DownloadVersion> versions = new ArrayList<>();
            for (int j = 0; j < downloadsArray.size(); j++) {
                final JsonObject downloadObj = (JsonObject) downloadsArray.get(j);
                final String version = downloadObj.getString("version");
                final String url = downloadObj.getString("url");
                versions.add(new DownloadVersion(version, url));
            }
            Collections.sort(versions);
            osList.add(new DownloadOS(os, currentVersion, versions));
        }
        Collections.sort(osList);
    } finally {
        reader.close();
    }

    for (final DownloadOS os : osList) {
        LOG.info("Latest '" + os + "': " + os.getLatestVersion() + " (Versions: " + os.getVersions().size()
                + ")");
    }

}