Search in sources :

Example 26 with JSONArray

use of org.json.JSONArray in project MovieGuide by esoxjem.

the class MovieDetailsParser method parseReviews.

public static List<Review> parseReviews(String body) throws JSONException {
    ArrayList<Review> reviews = new ArrayList<>(4);
    JSONObject response = new JSONObject(body);
    if (!response.isNull(RESULTS)) {
        JSONArray results = response.getJSONArray(RESULTS);
        for (int i = 0; i < results.length(); i++) {
            Review review = new Review();
            JSONObject reviewJson = results.getJSONObject(i);
            if (!reviewJson.isNull(ID)) {
                review.setId(reviewJson.getString(ID));
            }
            if (!reviewJson.isNull(AUTHOR)) {
                review.setAuthor(reviewJson.getString(AUTHOR));
            }
            if (!reviewJson.isNull(CONTENT)) {
                review.setContent(reviewJson.getString(CONTENT));
            }
            if (!reviewJson.isNull(URL)) {
                review.setUrl(reviewJson.getString(URL));
            }
            reviews.add(review);
        }
    }
    return reviews;
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) Review(com.esoxjem.movieguide.Review)

Example 27 with JSONArray

use of org.json.JSONArray in project Libraries-for-Android-Developers by eoecn.

the class JsonHttpResponseHandler method onFailure.

@Override
public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) {
    if (responseBytes != null) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    final Object jsonResponse = parseResponse(responseBytes);
                    postRunnable(new Runnable() {

                        @Override
                        public void run() {
                            if (jsonResponse instanceof JSONObject) {
                                onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse);
                            } else if (jsonResponse instanceof JSONArray) {
                                onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse);
                            } else if (jsonResponse instanceof String) {
                                onFailure(statusCode, headers, (String) jsonResponse, throwable);
                            } else {
                                onFailure(statusCode, headers, new JSONException("Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null);
                            }
                        }
                    });
                } catch (final JSONException ex) {
                    postRunnable(new Runnable() {

                        @Override
                        public void run() {
                            onFailure(statusCode, headers, ex, (JSONObject) null);
                        }
                    });
                }
            }
        }).start();
    } else {
        Log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)");
        onFailure(statusCode, headers, throwable, (JSONObject) null);
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 28 with JSONArray

use of org.json.JSONArray in project OpenRefine by OpenRefine.

the class CustomizableTabularExporterUtilities method exportRows.

public static void exportRows(final Project project, final Engine engine, Properties params, final TabularSerializer serializer) {
    String optionsString = (params != null) ? params.getProperty("options") : null;
    JSONObject optionsTemp = null;
    if (optionsString != null) {
        try {
            optionsTemp = ParsingUtilities.evaluateJsonStringToObject(optionsString);
        } catch (JSONException e) {
        // Ignore and keep options null.
        }
    }
    final JSONObject options = optionsTemp;
    final boolean outputColumnHeaders = options == null ? true : JSONUtilities.getBoolean(options, "outputColumnHeaders", true);
    final boolean outputEmptyRows = options == null ? false : JSONUtilities.getBoolean(options, "outputBlankRows", true);
    final int limit = options == null ? -1 : JSONUtilities.getInt(options, "limit", -1);
    final List<String> columnNames;
    final Map<String, CellFormatter> columnNameToFormatter = new HashMap<String, CustomizableTabularExporterUtilities.CellFormatter>();
    JSONArray columnOptionArray = options == null ? null : JSONUtilities.getArray(options, "columns");
    if (columnOptionArray == null) {
        List<Column> columns = project.columnModel.columns;
        columnNames = new ArrayList<String>(columns.size());
        for (Column column : columns) {
            String name = column.getName();
            columnNames.add(name);
            columnNameToFormatter.put(name, new CellFormatter());
        }
    } else {
        int count = columnOptionArray.length();
        columnNames = new ArrayList<String>(count);
        for (int i = 0; i < count; i++) {
            JSONObject columnOptions = JSONUtilities.getObjectElement(columnOptionArray, i);
            if (columnOptions != null) {
                String name = JSONUtilities.getString(columnOptions, "name", null);
                if (name != null) {
                    columnNames.add(name);
                    columnNameToFormatter.put(name, new CellFormatter(columnOptions));
                }
            }
        }
    }
    RowVisitor visitor = new RowVisitor() {

        int rowCount = 0;

        @Override
        public void start(Project project) {
            serializer.startFile(options);
            if (outputColumnHeaders) {
                List<CellData> cells = new ArrayList<TabularSerializer.CellData>(columnNames.size());
                for (String name : columnNames) {
                    cells.add(new CellData(name, name, name, null));
                }
                serializer.addRow(cells, true);
            }
        }

        @Override
        public boolean visit(Project project, int rowIndex, Row row) {
            List<CellData> cells = new ArrayList<TabularSerializer.CellData>(columnNames.size());
            int nonNullCount = 0;
            for (String columnName : columnNames) {
                Column column = project.columnModel.getColumnByName(columnName);
                CellFormatter formatter = columnNameToFormatter.get(columnName);
                CellData cellData = formatter.format(project, column, row.getCell(column.getCellIndex()));
                cells.add(cellData);
                if (cellData != null) {
                    nonNullCount++;
                }
            }
            if (nonNullCount > 0 || outputEmptyRows) {
                serializer.addRow(cells, false);
                rowCount++;
            }
            return limit > 0 && rowCount >= limit;
        }

        @Override
        public void end(Project project) {
            serializer.endFile();
        }
    };
    FilteredRows filteredRows = engine.getAllFilteredRows();
    filteredRows.accept(project, visitor);
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) CellData(com.google.refine.exporters.TabularSerializer.CellData) FilteredRows(com.google.refine.browsing.FilteredRows) Project(com.google.refine.model.Project) JSONObject(org.json.JSONObject) Column(com.google.refine.model.Column) Row(com.google.refine.model.Row) RowVisitor(com.google.refine.browsing.RowVisitor)

Example 29 with JSONArray

use of org.json.JSONArray in project OpenRefine by OpenRefine.

the class CreateProjectCommand method doPost.

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ProjectManager.singleton.setBusy(true);
    try {
        Properties parameters = ParsingUtilities.parseUrlParameters(request);
        ImportingJob job = ImportingManager.createJob();
        JSONObject config = job.getOrCreateDefaultConfig();
        ImportingUtilities.loadDataAndPrepareJob(request, response, parameters, job, config);
        String format = parameters.getProperty("format");
        // to check if we have a parser for it. If not, null it out.
        if (format != null && !format.isEmpty()) {
            Format formatRecord = ImportingManager.formatToRecord.get(format);
            if (formatRecord == null || formatRecord.parser == null) {
                format = null;
            }
        }
        // If we don't have a format specified, try to guess it.
        if (format == null || format.isEmpty()) {
            // Use legacy parameters to guess the format.
            if ("false".equals(parameters.getProperty("split-into-columns"))) {
                format = "text/line-based";
            } else if (",".equals(parameters.getProperty("separator")) || "\\t".equals(parameters.getProperty("separator"))) {
                format = "text/line-based/*sv";
            } else {
                JSONArray rankedFormats = JSONUtilities.getArray(config, "rankedFormats");
                if (rankedFormats != null && rankedFormats.length() > 0) {
                    format = rankedFormats.getString(0);
                }
            }
            if (format == null || format.isEmpty()) {
                // If we have failed in guessing, default to something simple.
                format = "text/line-based";
            }
        }
        JSONObject optionObj = null;
        String optionsString = request.getParameter("options");
        if (optionsString != null && !optionsString.isEmpty()) {
            optionObj = ParsingUtilities.evaluateJsonStringToObject(optionsString);
        } else {
            Format formatRecord = ImportingManager.formatToRecord.get(format);
            optionObj = formatRecord.parser.createParserUIInitializationData(job, job.getSelectedFileRecords(), format);
        }
        adjustLegacyOptions(format, parameters, optionObj);
        String projectName = parameters.getProperty("project-name");
        if (projectName != null && !projectName.isEmpty()) {
            JSONUtilities.safePut(optionObj, "projectName", projectName);
        }
        List<Exception> exceptions = new LinkedList<Exception>();
        long projectId = ImportingUtilities.createProject(job, format, optionObj, exceptions, true);
        HttpUtilities.redirect(response, "/project?project=" + projectId);
    } catch (Exception e) {
        respondWithErrorPage(request, response, "Failed to import file", e);
    } finally {
        ProjectManager.singleton.setBusy(false);
    }
}
Also used : Format(com.google.refine.importing.ImportingManager.Format) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ImportingJob(com.google.refine.importing.ImportingJob) Properties(java.util.Properties) LinkedList(java.util.LinkedList) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 30 with JSONArray

use of org.json.JSONArray in project OpenRefine by OpenRefine.

the class ApplyOperationsCommand method doPost.

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Project project = getProject(request);
    String jsonString = request.getParameter("operations");
    try {
        JSONArray a = ParsingUtilities.evaluateJsonStringToArray(jsonString);
        int count = a.length();
        for (int i = 0; i < count; i++) {
            JSONObject obj = a.getJSONObject(i);
            reconstructOperation(project, obj);
        }
        if (project.processManager.hasPending()) {
            respond(response, "{ \"code\" : \"pending\" }");
        } else {
            respond(response, "{ \"code\" : \"ok\" }");
        }
    } catch (JSONException e) {
        respondException(response, e);
    }
}
Also used : Project(com.google.refine.model.Project) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Aggregations

JSONArray (org.json.JSONArray)1596 JSONObject (org.json.JSONObject)1121 JSONException (org.json.JSONException)690 ArrayList (java.util.ArrayList)303 IOException (java.io.IOException)232 Test (org.junit.Test)199 HashMap (java.util.HashMap)105 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)96 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)61 List (java.util.List)59 HashSet (java.util.HashSet)53 File (java.io.File)49 Query (org.b3log.latke.repository.Query)47 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 Date (java.util.Date)44 GraphObject (com.abewy.android.apps.klyph.core.graph.GraphObject)43 Map (java.util.Map)40 FileNotFoundException (java.io.FileNotFoundException)37 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)36 VolleyError (com.android.volley.VolleyError)35