Search in sources :

Example 86 with JsonReader

use of javax.json.JsonReader in project opentheso by miledrousset.

the class SelectedTerme method majNoticeBdd.

private void majNoticeBdd() {
    // ResourceBundle bundlePref = getBundlePref();
    // st.getTaskResultSet().getFragmentCount();
    nbNotices = 0;
    urlNotice = user.getNodePreference().getUrlBdd();
    if (user.getNodePreference().isBddUseId()) {
        urlNotice = urlNotice.replace("##value##", idC);
    } else {
        urlNotice = urlNotice.replace("##value##", nom);
    }
    // récupération du total des notices
    String urlCounterBdd = user.getNodePreference().getUrlCounterBdd();
    urlCounterBdd = urlCounterBdd.replace("##conceptId##", idC);
    // urlCounterBdd = "http://healthandco.test.o2sources.com/concept/40/total";
    // exemple des données récupérées
    // "{\"content\":[{\"nb_notices\":\"s7\"}],\"debug\":\"\",\"error\":0}\" ";
    // {"content":[{"nb_notices":"7"}],"debug":"","error":0}
    URL url;
    try {
        url = new URL(urlCounterBdd);
        InputStream is = url.openStream();
        JsonReader reader = Json.createReader(is);
        JsonObject totalNotices = reader.readObject();
        reader.close();
        JsonArray values = totalNotices.getJsonArray("content");
        String name;
        for (int i = 0; i < values.size(); i++) {
            JsonObject item = values.getJsonObject(i);
            try {
                name = item.getString("nb_notices");
                if (name != null) {
                    if (!name.isEmpty())
                        nbNotices = Integer.parseInt(name);
                }
            } catch (JsonException e) {
                System.out.println(e.toString());
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(SelectedTerme.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SelectedTerme.class.getName()).log(Level.SEVERE, null, ex);
    }
// try {
// urlNotice = URLEncoder.encode(urlNotice);
// } catch (UnsupportedEncodingException ex) {
// Logger.getLogger(SelectedTerme.class.getName()).log(Level.SEVERE, null, ex);
// }
}
Also used : JsonArray(javax.json.JsonArray) JsonException(javax.json.JsonException) MalformedURLException(java.net.MalformedURLException) InputStream(java.io.InputStream) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) PrefixString(com.k_int.IR.QueryModels.PrefixString) IOException(java.io.IOException) URL(java.net.URL) JsonException(javax.json.JsonException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SearchException(com.k_int.IR.SearchException) SQLException(java.sql.SQLException) MalformedURLException(java.net.MalformedURLException) TimeoutExceededException(com.k_int.IR.TimeoutExceededException) IOException(java.io.IOException)

Example 87 with JsonReader

use of javax.json.JsonReader in project opentheso by miledrousset.

the class ReadJson method getJsonObject.

/**
 * permet de lire un fichier Json d'après une inputStream
 * @param is
 * @return
 */
public JsonObject getJsonObject(InputStream is) {
    JsonReader reader = Json.createReader(is);
    JsonObject jsonObject = reader.readObject();
    reader.close();
    return jsonObject;
}
Also used : JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Example 88 with JsonReader

use of javax.json.JsonReader in project opentheso by miledrousset.

the class ReadJson method getJsonObject.

/**
 * Permet de lire un texte en Json
 * @param jsonText
 * @return
 */
public JsonObject getJsonObject(String jsonText) {
    // String total = " {\"content\":[{\"nb_notices\":\"7\"}],\"debug\":\"\",\"error\":0}\" ";
    JsonReader reader = Json.createReader(new StringReader(jsonText));
    JsonObject jsonObject = reader.readObject();
    reader.close();
    return jsonObject;
}
Also used : StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Example 89 with JsonReader

use of javax.json.JsonReader in project dataverse by IQSS.

the class EditDatafilesPage method handleDropBoxUpload.

// end: getDropBoxInputStream
/**
 * Using information from the DropBox choose, ingest the chosen files
 *  https://www.dropbox.com/developers/dropins/chooser/js
 *
 * @param event
 */
public void handleDropBoxUpload(ActionEvent event) {
    logger.fine("handleDropBoxUpload");
    uploadComponentId = event.getComponent().getClientId();
    // -----------------------------------------------------------
    // Read JSON object from the output of the DropBox Chooser:
    // -----------------------------------------------------------
    JsonReader dbJsonReader = Json.createReader(new StringReader(dropBoxSelection));
    JsonArray dbArray = dbJsonReader.readArray();
    dbJsonReader.close();
    // -----------------------------------------------------------
    // Iterate through the Dropbox file information (JSON)
    // -----------------------------------------------------------
    DataFile dFile = null;
    GetMethod dropBoxMethod = null;
    String localWarningMessage = null;
    for (int i = 0; i < dbArray.size(); i++) {
        JsonObject dbObject = dbArray.getJsonObject(i);
        // -----------------------------------------------------------
        // Parse information for a single file
        // -----------------------------------------------------------
        String fileLink = dbObject.getString("link");
        String fileName = dbObject.getString("name");
        int fileSize = dbObject.getInt("bytes");
        logger.fine("DropBox url: " + fileLink + ", filename: " + fileName + ", size: " + fileSize);
        /* ----------------------------
                Check file size
                - Max size NOT specified in db: default is unlimited
                - Max size specified in db: check too make sure file is within limits
            // ---------------------------- */
        if ((!this.isUnlimitedUploadFileSize()) && (fileSize > this.getMaxFileUploadSizeInBytes())) {
            String warningMessage = "Dropbox file \"" + fileName + "\" exceeded the limit of " + fileSize + " bytes and was not uploaded.";
            // FacesContext.getCurrentInstance().addMessage(event.getComponent().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "upload failure", warningMessage));
            if (localWarningMessage == null) {
                localWarningMessage = warningMessage;
            } else {
                localWarningMessage = localWarningMessage.concat("; " + warningMessage);
            }
            // skip to next file, and add error mesage
            continue;
        }
        dFile = null;
        dropBoxMethod = new GetMethod(fileLink);
        // -----------------------------------------------------------
        // Download the file
        // -----------------------------------------------------------
        InputStream dropBoxStream = this.getDropBoxInputStream(fileLink, dropBoxMethod);
        if (dropBoxStream == null) {
            logger.severe("Could not retrieve dropgox input stream for: " + fileLink);
            // Error skip this file
            continue;
        }
        // -----------------------------------------------------------
        if (this.isFileReplaceOperation()) {
            this.handleReplaceFileUpload(event, dropBoxStream, fileName, FileUtil.MIME_TYPE_UNDETERMINED_DEFAULT, null, event);
            this.setFileMetadataSelectedForTagsPopup(fileReplacePageHelper.getNewFileMetadatasBeforeSave().get(0));
            return;
        }
        // -----------------------------------------------------------
        List<DataFile> datafiles = new ArrayList<>();
        // -----------------------------------------------------------
        try {
            // Note: A single uploaded file may produce multiple datafiles -
            // for example, multiple files can be extracted from an uncompressed
            // zip file.
            // datafiles = ingestService.createDataFiles(workingVersion, dropBoxStream, fileName, "application/octet-stream");
            datafiles = FileUtil.createDataFiles(workingVersion, dropBoxStream, fileName, "application/octet-stream", systemConfig);
        } catch (IOException ex) {
            this.logger.log(Level.SEVERE, "Error during ingest of DropBox file {0} from link {1}", new Object[] { fileName, fileLink });
            continue;
        } finally /*catch (FileExceedsMaxSizeException ex){
                this.logger.log(Level.SEVERE, "Error during ingest of DropBox file {0} from link {1}: {2}", new Object[]{fileName, fileLink, ex.getMessage()});
                continue;
            }*/
        {
            if (dropBoxMethod != null) {
                dropBoxMethod.releaseConnection();
            }
            // -----------------------------------------------------------
            try {
                dropBoxStream.close();
            } catch (IOException ex) {
                logger.log(Level.WARNING, "Failed to close the dropBoxStream for file: {0}", fileLink);
            }
        }
        if (datafiles == null) {
            this.logger.log(Level.SEVERE, "Failed to create DataFile for DropBox file {0} from link {1}", new Object[] { fileName, fileLink });
            continue;
        } else {
            // -----------------------------------------------------------
            // Check if there are duplicate files or ingest warnings
            // -----------------------------------------------------------
            uploadWarningMessage = processUploadedFileList(datafiles);
            logger.fine("Warning message during upload: " + uploadWarningMessage);
        /*if (warningMessage != null){
                     logger.fine("trying to send faces message to " + event.getComponent().getClientId());
                     FacesContext.getCurrentInstance().addMessage(event.getComponent().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "upload failure", warningMessage));
                     if (uploadWarningMessage == null) {
                         uploadWarningMessage = warningMessage;
                     } else {
                         uploadWarningMessage = uploadWarningMessage.concat("; "+warningMessage);
                     }
                }*/
        }
    }
    if (localWarningMessage != null) {
        if (uploadWarningMessage == null) {
            uploadWarningMessage = localWarningMessage;
        } else {
            uploadWarningMessage = localWarningMessage.concat("; " + uploadWarningMessage);
        }
    }
}
Also used : InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) IOException(java.io.IOException) JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Example 90 with JsonReader

use of javax.json.JsonReader in project dataverse by IQSS.

the class ExternalToolHandler method getQueryParametersForUrl.

// TODO: rename to handleRequest() to someday handle sending headers as well as query parameters.
public String getQueryParametersForUrl() {
    String toolParameters = externalTool.getToolParameters();
    JsonReader jsonReader = Json.createReader(new StringReader(toolParameters));
    JsonObject obj = jsonReader.readObject();
    JsonArray queryParams = obj.getJsonArray("queryParameters");
    if (queryParams == null || queryParams.isEmpty()) {
        return "";
    }
    List<String> params = new ArrayList<>();
    queryParams.getValuesAs(JsonObject.class).forEach((queryParam) -> {
        queryParam.keySet().forEach((key) -> {
            String value = queryParam.getString(key);
            String param = getQueryParam(key, value);
            if (param != null && !param.isEmpty()) {
                params.add(getQueryParam(key, value));
            }
        });
    });
    return "?" + String.join("&", params);
}
Also used : JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Aggregations

JsonReader (javax.json.JsonReader)130 JsonObject (javax.json.JsonObject)110 StringReader (java.io.StringReader)78 Test (org.junit.Test)47 JsonArray (javax.json.JsonArray)44 JsonString (javax.json.JsonString)42 HashMap (java.util.HashMap)21 IOException (java.io.IOException)17 ArrayList (java.util.ArrayList)13 File (java.io.File)10 LinkedHashMap (java.util.LinkedHashMap)10 JsonParser (edu.harvard.iq.dataverse.util.json.JsonParser)9 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)8 ByteArrayInputStream (java.io.ByteArrayInputStream)8 PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)8 InputStream (java.io.InputStream)7 Gson (com.google.gson.Gson)6 AsyncCompletionHandler (com.ning.http.client.AsyncCompletionHandler)6 Response (com.ning.http.client.Response)6 JsonParseException (edu.harvard.iq.dataverse.util.json.JsonParseException)5