Search in sources :

Example 21 with JSONException

use of org.json.JSONException in project flux by eclipse.

the class Repository method getProject.

public void getProject(JSONObject request) {
    try {
        final int callbackID = request.getInt("callback_id");
        final String sender = request.getString("requestSenderID");
        final String projectName = request.getString("project");
        final String username = request.getString("username");
        final ConnectedProject connectedProject = this.syncedProjects.get(projectName);
        if (this.username.equals(username) && connectedProject != null) {
            final JSONArray files = new JSONArray();
            IProject project = connectedProject.getProject();
            try {
                project.accept(new IResourceVisitor() {

                    @Override
                    public boolean visit(IResource resource) throws CoreException {
                        JSONObject projectResource = new JSONObject();
                        String path = resource.getProjectRelativePath().toString();
                        try {
                            projectResource.put("path", path);
                            projectResource.put("timestamp", connectedProject.getTimestamp(path));
                            projectResource.put("hash", connectedProject.getHash(path));
                            if (resource instanceof IFile) {
                                projectResource.put("type", "file");
                            } else if (resource instanceof IFolder) {
                                projectResource.put("type", "folder");
                            }
                            files.put(projectResource);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return true;
                    }
                }, IResource.DEPTH_INFINITE, IContainer.EXCLUDE_DERIVED);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject message = new JSONObject();
            message.put("callback_id", callbackID);
            message.put("requestSenderID", sender);
            message.put("username", this.username);
            message.put("project", projectName);
            message.put("username", this.username);
            message.put("files", files);
            messagingConnector.send("getProjectResponse", message);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : IResourceVisitor(org.eclipse.core.resources.IResourceVisitor) IFile(org.eclipse.core.resources.IFile) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IProject(org.eclipse.core.resources.IProject) CoreException(org.eclipse.core.runtime.CoreException) JSONException(org.json.JSONException) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) JSONObject(org.json.JSONObject) IResource(org.eclipse.core.resources.IResource) IFolder(org.eclipse.core.resources.IFolder)

Example 22 with JSONException

use of org.json.JSONException 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 23 with JSONException

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

the class GetRowsCommand method internalRespond.

protected void internalRespond(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Project project = null;
        // This command also supports retrieving rows for an importing job.
        String importingJobID = request.getParameter("importingJobID");
        if (importingJobID != null) {
            long jobID = Long.parseLong(importingJobID);
            ImportingJob job = ImportingManager.getJob(jobID);
            if (job != null) {
                project = job.project;
            }
        }
        if (project == null) {
            project = getProject(request);
        }
        Engine engine = getEngine(request, project);
        String callback = request.getParameter("callback");
        int start = Math.min(project.rows.size(), Math.max(0, getIntegerParameter(request, "start", 0)));
        int limit = Math.min(project.rows.size() - start, Math.max(0, getIntegerParameter(request, "limit", 20)));
        Pool pool = new Pool();
        Properties options = new Properties();
        options.put("project", project);
        options.put("reconCandidateOmitTypes", true);
        options.put("pool", pool);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", callback == null ? "application/json" : "text/javascript");
        PrintWriter writer = response.getWriter();
        if (callback != null) {
            writer.write(callback);
            writer.write("(");
        }
        JSONWriter jsonWriter = new JSONWriter(writer);
        jsonWriter.object();
        RowWritingVisitor rwv = new RowWritingVisitor(start, limit, jsonWriter, options);
        JSONObject sortingJson = null;
        try {
            String json = request.getParameter("sorting");
            sortingJson = (json == null) ? null : ParsingUtilities.evaluateJsonStringToObject(json);
        } catch (JSONException e) {
        }
        if (engine.getMode() == Mode.RowBased) {
            FilteredRows filteredRows = engine.getAllFilteredRows();
            RowVisitor visitor = rwv;
            if (sortingJson != null) {
                SortingRowVisitor srv = new SortingRowVisitor(visitor);
                srv.initializeFromJSON(project, sortingJson);
                if (srv.hasCriteria()) {
                    visitor = srv;
                }
            }
            jsonWriter.key("mode");
            jsonWriter.value("row-based");
            jsonWriter.key("rows");
            jsonWriter.array();
            filteredRows.accept(project, visitor);
            jsonWriter.endArray();
            jsonWriter.key("filtered");
            jsonWriter.value(rwv.total);
            jsonWriter.key("total");
            jsonWriter.value(project.rows.size());
        } else {
            FilteredRecords filteredRecords = engine.getFilteredRecords();
            RecordVisitor visitor = rwv;
            if (sortingJson != null) {
                SortingRecordVisitor srv = new SortingRecordVisitor(visitor);
                srv.initializeFromJSON(project, sortingJson);
                if (srv.hasCriteria()) {
                    visitor = srv;
                }
            }
            jsonWriter.key("mode");
            jsonWriter.value("record-based");
            jsonWriter.key("rows");
            jsonWriter.array();
            filteredRecords.accept(project, visitor);
            jsonWriter.endArray();
            jsonWriter.key("filtered");
            jsonWriter.value(rwv.total);
            jsonWriter.key("total");
            jsonWriter.value(project.recordModel.getRecordCount());
        }
        jsonWriter.key("start");
        jsonWriter.value(start);
        jsonWriter.key("limit");
        jsonWriter.value(limit);
        jsonWriter.key("pool");
        pool.write(jsonWriter, options);
        jsonWriter.endObject();
        if (callback != null) {
            writer.write(")");
        }
    } catch (Exception e) {
        respondException(response, e);
    }
}
Also used : JSONWriter(org.json.JSONWriter) SortingRecordVisitor(com.google.refine.sorting.SortingRecordVisitor) JSONException(org.json.JSONException) FilteredRecords(com.google.refine.browsing.FilteredRecords) Properties(java.util.Properties) RecordVisitor(com.google.refine.browsing.RecordVisitor) SortingRecordVisitor(com.google.refine.sorting.SortingRecordVisitor) FilteredRows(com.google.refine.browsing.FilteredRows) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) Project(com.google.refine.model.Project) JSONObject(org.json.JSONObject) ImportingJob(com.google.refine.importing.ImportingJob) Pool(com.google.refine.util.Pool) RowVisitor(com.google.refine.browsing.RowVisitor) SortingRowVisitor(com.google.refine.sorting.SortingRowVisitor) Engine(com.google.refine.browsing.Engine) SortingRowVisitor(com.google.refine.sorting.SortingRowVisitor) PrintWriter(java.io.PrintWriter)

Example 24 with JSONException

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

the class GetAllProjectMetadataCommand method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json");
        JSONWriter writer = new JSONWriter(response.getWriter());
        Properties options = new Properties();
        writer.object();
        writer.key("projects");
        writer.object();
        Map<Long, ProjectMetadata> m = ProjectManager.singleton.getAllProjectMetadata();
        for (Entry<Long, ProjectMetadata> e : m.entrySet()) {
            ProjectMetadata pm = e.getValue();
            if (pm != null) {
                writer.key(e.getKey().toString());
                e.getValue().write(writer, options);
            }
        }
        writer.endObject();
        writer.endObject();
    } catch (JSONException e) {
        respondException(response, e);
    }
}
Also used : JSONWriter(org.json.JSONWriter) ProjectMetadata(com.google.refine.ProjectMetadata) JSONException(org.json.JSONException) Properties(java.util.Properties)

Example 25 with JSONException

use of org.json.JSONException 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)

Aggregations

JSONException (org.json.JSONException)1760 JSONObject (org.json.JSONObject)1346 JSONArray (org.json.JSONArray)593 IOException (java.io.IOException)315 ArrayList (java.util.ArrayList)194 HashMap (java.util.HashMap)139 Test (org.junit.Test)108 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)98 Bundle (android.os.Bundle)67 VolleyError (com.android.volley.VolleyError)66 File (java.io.File)63 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)62 Response (com.android.volley.Response)58 URL (java.net.URL)54 Map (java.util.Map)45 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 MalformedURLException (java.net.MalformedURLException)43 UnsupportedEncodingException (java.io.UnsupportedEncodingException)41 Intent (android.content.Intent)40 JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)40