Example usage for javax.json Json createReader

List of usage examples for javax.json Json createReader

Introduction

In this page you can find the example usage for javax.json Json createReader.

Prototype

public static JsonReader createReader(InputStream in) 

Source Link

Document

Creates a JSON reader from a byte stream.

Usage

From source file:org.kitodo.production.forms.IndexingForm.java

private static String readMapping() {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try (InputStream inputStream = classloader.getResourceAsStream("mapping.json")) {
        String mapping = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        try (JsonReader jsonReader = Json.createReader(new StringReader(mapping))) {
            JsonObject jsonObject = jsonReader.readObject();
            return jsonObject.toString();
        }/*from  w  w w  .  j a v a2 s .  c o  m*/
    } catch (IOException e) {
        Helper.setErrorMessage(e.getLocalizedMessage(), logger, e);
        return "";
    }
}

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

/**
 * configuration and processing of the task
 *
 * @param inputDataModelID/* w ww. ja v a 2  s .  c  o m*/
 * @param projectID
 * @param outputDataModelID
 * @return
 */
private String executeTask(String inputDataModelID, String projectID, String outputDataModelID)
        throws Exception {

    String jsonResponse = null;

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        // Hole Mappings aus dem Projekt mit 'projectID'
        HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "projects/" + projectID);

        CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        String mappings = "";

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                String responseJson = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                mappings = jsonObject.getJsonArray("mappings").toString();

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole InputDataModel
        String inputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + inputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                inputDataModel = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] inputDataModel : " + inputDataModel);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputDataModel, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                String inputResourceID = jsonObject.getJsonObject("data_resource").getString("uuid");

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole OutputDataModel
        String outputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + outputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                outputDataModel = writer.toString();

                logger.info(
                        "[" + config.getProperty("service.name") + "] outputDataModel : " + outputDataModel);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // erzeuge Task-JSON
        String task = "{";
        task += "\"name\":\"" + "Task Batch-Prozess 'CrossRef'" + "\",";
        task += "\"description\":\"" + "Task Batch-Prozess 'CrossRef' zum InputDataModel '" + inputDataModelID
                + "'\",";
        task += "\"job\": { " + "\"mappings\": " + mappings + "," + "\"uuid\": \"" + UUID.randomUUID() + "\""
                + " },";
        task += "\"input_data_model\":" + inputDataModel + ",";
        task += "\"output_data_model\":" + outputDataModel;
        task += "}";

        logger.info("[" + config.getProperty("service.name") + "] task : " + task);

        // POST /dmp/tasks/
        HttpPost httpPost = new HttpPost(config.getProperty("engine.dswarm.api") + "tasks?persist="
                + config.getProperty("results.persistInDMP"));
        StringEntity stringEntity = new StringEntity(task,
                ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(stringEntity);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPost.getRequestLine());

        httpResponse = httpclient.execute(httpPost);

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                jsonResponse = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] jsonResponse : " + jsonResponse);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

    } finally {
        httpclient.close();
    }

    return jsonResponse;
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecuteImageNotFound() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doThrow(new ImageNotFoundException("idont:exist")).when(DockerUtils.class);
    DockerUtils.pullImage(anyString());//from   w w  w. j ava2 s . com

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "idont:exist").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Message wrong", "Image 'idont:exist' not found", responseBody.getString("message"));
}

From source file:csg.files.CSGFiles.java

private JsonObject loadJSONFile(String jsonFilePath) throws IOException {
    InputStream is = new FileInputStream(jsonFilePath);
    JsonReader jsonReader = Json.createReader(is);
    JsonObject json = jsonReader.readObject();
    jsonReader.close();/*from  w w  w. j  a  v a2s.c  om*/
    is.close();
    return json;
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java

public List<Entity> searchObservationOnly(String searchTerm, String strategy, SecureSession session,
        String onlObs) {//  ww  w  . j  a va2  s.  co m
    List<Entity> entities = new ArrayList<Entity>();

    try {
        URI uri = new URI(this.transmartURL.split("://")[0], this.transmartURL.split("://")[1].split("/")[0],
                "/" + this.transmartURL.split("://")[1].split("/")[1] + "/textSearch/findPaths",
                "oblyObs=" + onlObs + "&term=" + searchTerm, null);

        HttpClient client = createClient(session);
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(get);
        JsonReader reader = Json.createReader(response.getEntity().getContent());
        JsonArray arrayResults = reader.readArray();

        for (JsonValue val : arrayResults) {
            JsonObject returnObject = (JsonObject) val;

            Entity returnedEntity = new Entity();
            returnedEntity
                    .setPui("/" + this.resourceName + converti2b2Path(returnObject.getString("conceptPath")));

            if (!returnObject.isNull("text")) {
                returnedEntity.getAttributes().put("text", returnObject.getString("text"));
            }
            entities.add(returnedEntity);
        }

    } catch (URISyntaxException | JsonException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return entities;
}

From source file:org.kitodo.production.forms.IndexingForm.java

private boolean isMappingEqualTo(String mapping) {
    try (JsonReader mappingExpectedReader = Json.createReader(new StringReader(mapping));
            JsonReader mappingCurrentReader = Json
                    .createReader(new StringReader(indexRestClient.getMapping()))) {
        JsonObject mappingExpected = mappingExpectedReader.readObject();
        JsonObject mappingCurrent = mappingCurrentReader.readObject().getJsonObject(indexRestClient.getIndex());
        return mappingExpected.equals(mappingCurrent);
    } catch (IOException e) {
        return false;
    }/*from   w w  w  . j  a  va2 s. co m*/
}

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 w w .java 2s  .  c om
 * 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: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) {

                }// w  w w .ja  v  a2 s .co  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:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Test
public void testJSONExport() throws IOException {
    ContentFragmentImpl fragment = (ContentFragmentImpl) getTestContentFragment(CF_TEXT_ONLY);
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithView(ContentFragmentImpl.class).writeValue(writer, fragment);
    JsonReader jsonReaderOutput = Json.createReader(IOUtils.toInputStream(writer.toString()));
    JsonReader jsonReaderExpected = Json.createReader(Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream("/contentfragment/test-expected-content-export.json"));
    assertEquals(jsonReaderExpected.read(), jsonReaderOutput.read());
}

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

/**
 * Gets the information for the given ElectionID from the bulletin board and returns it as a election object
 * @param electionId/*  ww  w  .  ja  va 2s  . com*/
 * the identifier (id) for the desired election
 * @return returns tje election object for a given id
 */
public Election getElectionById(int electionId) {
    Election election = null;
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + electionId);

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Parameters parameters = this.getParameters();

        //gets the json string and transforms it into a election object

        //translates the header information of the election
        String title = obj.getString("electionTitle");
        LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format);
        LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format);
        String appVersion = obj.getString("appVersion");
        String coefficientsString = obj.getString("coefficients");
        String h_HatString = obj.getString("electionGenerator");
        List<Voter> voterlist = new ArrayList<Voter>();

        //get th list of voters
        for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) {

            String voterEmail = result.getString("email");
            String voterPublicCredential = result.getString("publicCredential");
            String voterAppVersion = result.getString("appVersion");

            Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion);
            voterlist.add(voter);
        }
        //get the votingTopic
        JsonObject electionTopicObj = obj.getJsonObject("votingTopic");

        String topic = electionTopicObj.getString("topic");
        int pick = electionTopicObj.getInt("pick");

        ElectionTopic electionTopic = new ElectionTopic(topic, pick);
        JsonArray optionsArray = electionTopicObj.getJsonArray("options");
        for (int i = 0; i < optionsArray.size(); i++) {
            electionTopic.addOption(optionsArray.getString(i));
        }

        election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic,
                appVersion, h_HatString, coefficientsString);

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