Search in sources :

Example 1 with ServiceException

use of com.google.gdata.util.ServiceException in project OpenRefine by OpenRefine.

the class GDataImportingController method doInitializeParserUI.

private void doInitializeParserUI(HttpServletRequest request, HttpServletResponse response, Properties parameters) throws ServletException, IOException {
    String token = TokenCookie.getToken(request);
    String type = parameters.getProperty("docType");
    String urlString = parameters.getProperty("docUrl");
    URL url = new URL(urlString);
    try {
        JSONObject result = new JSONObject();
        JSONObject options = new JSONObject();
        JSONUtilities.safePut(result, "status", "ok");
        JSONUtilities.safePut(result, "options", options);
        // number of initial data lines to skip
        JSONUtilities.safePut(options, "skipDataLines", 0);
        JSONUtilities.safePut(options, "storeBlankRows", true);
        JSONUtilities.safePut(options, "storeBlankCellsAsNulls", true);
        if ("spreadsheet".equals(type)) {
            // number of blank lines at the beginning to ignore
            JSONUtilities.safePut(options, "ignoreLines", -1);
            // number of header lines
            JSONUtilities.safePut(options, "headerLines", 1);
            JSONArray worksheets = new JSONArray();
            JSONUtilities.safePut(options, "worksheets", worksheets);
            List<WorksheetEntry> worksheetEntries = reallyTryToGetWorksheetEntriesForDoc(url, token);
            for (WorksheetEntry worksheetEntry : worksheetEntries) {
                JSONObject worksheetO = new JSONObject();
                JSONUtilities.safePut(worksheetO, "name", worksheetEntry.getTitle().getPlainText());
                JSONUtilities.safePut(worksheetO, "rows", worksheetEntry.getRowCount());
                JSONUtilities.safePut(worksheetO, "link", worksheetEntry.getSelfLink().getHref());
                JSONUtilities.append(worksheets, worksheetO);
            }
        } else if ("table".equals(type)) {
        // No metadata for a fusion table.
        }
        /* TODO: else */
        HttpUtilities.respond(response, result.toString());
    } catch (ServiceException e) {
        e.printStackTrace();
        HttpUtilities.respond(response, "error", "Internal error: " + e.getLocalizedMessage());
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(com.google.gdata.util.ServiceException) JSONArray(org.json.JSONArray) URL(java.net.URL) WorksheetEntry(com.google.gdata.data.spreadsheet.WorksheetEntry)

Example 2 with ServiceException

use of com.google.gdata.util.ServiceException in project OpenRefine by OpenRefine.

the class GDataImportingController method doListDocuments.

private void doListDocuments(HttpServletRequest request, HttpServletResponse response, Properties parameters) throws ServletException, IOException {
    String token = TokenCookie.getToken(request);
    if (token == null) {
        HttpUtilities.respond(response, "error", "Not authorized");
        return;
    }
    Writer w = response.getWriter();
    JSONWriter writer = new JSONWriter(w);
    try {
        writer.object();
        writer.key("documents");
        writer.array();
        try {
            listSpreadsheets(GDataExtension.getDocsService(token), writer);
            listFusionTables(FusionTableHandler.getFusionTablesService(token), writer);
        } catch (AuthenticationException e) {
            TokenCookie.deleteToken(request, response);
        } catch (ServiceException e) {
            e.printStackTrace();
        } finally {
            writer.endArray();
            writer.endObject();
        }
    } catch (JSONException e) {
        throw new ServletException(e);
    } finally {
        w.flush();
        w.close();
    }
}
Also used : JSONWriter(org.json.JSONWriter) ServletException(javax.servlet.ServletException) ServiceException(com.google.gdata.util.ServiceException) AuthenticationException(com.google.gdata.util.AuthenticationException) JSONException(org.json.JSONException) JSONWriter(org.json.JSONWriter) Writer(java.io.Writer)

Example 3 with ServiceException

use of com.google.gdata.util.ServiceException in project OpenRefine by OpenRefine.

the class UploadCommand method uploadSpreadsheet.

private static String uploadSpreadsheet(final Project project, final Engine engine, final Properties params, String token, String name, List<Exception> exceptions) {
    Drive driveService = GDataExtension.getDriveService(token);
    final SpreadsheetService spreadsheetService = GDataExtension.getSpreadsheetService(token);
    try {
        File body = new File();
        body.setTitle(name);
        body.setDescription("Spreadsheet uploaded from OpenRefine project: " + name);
        body.setMimeType("application/vnd.google-apps.spreadsheet");
        File file = driveService.files().insert(body).execute();
        String fileID = file.getId();
        // Iterate through all spreadsheets to find one with our ID
        SpreadsheetEntry spreadsheetEntry2 = null;
        SpreadsheetFeed feed = spreadsheetService.getFeed(new URL(SPREADSHEET_FEED), SpreadsheetFeed.class);
        List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries();
        for (com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet : spreadsheets) {
            if (spreadsheet.getId().endsWith(fileID)) {
                spreadsheetEntry2 = spreadsheet;
            }
        }
        // Bail if we didn't find our spreadsheet (shouldn't happen)
        if (spreadsheetEntry2 == null) {
            logger.error("Failed to find match for ID: " + fileID);
            return null;
        }
        int[] size = CustomizableTabularExporterUtilities.countColumnsRows(project, engine, params);
        URL worksheetFeedUrl = spreadsheetEntry2.getWorksheetFeedUrl();
        WorksheetEntry worksheetEntry = new WorksheetEntry(size[1], size[0]);
        worksheetEntry.setTitle(new PlainTextConstruct("Uploaded Data"));
        final WorksheetEntry worksheetEntry2 = spreadsheetService.insert(worksheetFeedUrl, worksheetEntry);
        spreadsheetEntry2.getDefaultWorksheet().delete();
        final SpreadsheetEntry spreadsheetEntry3 = spreadsheetEntry2;
        new Thread() {

            @Override
            public void run() {
                spreadsheetService.setProtocolVersion(SpreadsheetService.Versions.V3);
                try {
                    uploadToCellFeed(project, engine, params, spreadsheetService, spreadsheetEntry3, worksheetEntry2);
                } catch (Exception e) {
                    logger.error("Error uploading data to Google Spreadsheets", e);
                }
            }
        }.start();
        return spreadsheetEntry2.getSpreadsheetLink().getHref();
    } catch (IOException | ServiceException e) {
        exceptions.add(e);
    }
    return null;
}
Also used : SpreadsheetService(com.google.gdata.client.spreadsheet.SpreadsheetService) SpreadsheetEntry(com.google.gdata.data.spreadsheet.SpreadsheetEntry) IOException(java.io.IOException) URL(java.net.URL) WorksheetEntry(com.google.gdata.data.spreadsheet.WorksheetEntry) PlainTextConstruct(com.google.gdata.data.PlainTextConstruct) ServletException(javax.servlet.ServletException) ServiceException(com.google.gdata.util.ServiceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SpreadsheetEntry(com.google.gdata.data.spreadsheet.SpreadsheetEntry) ServiceException(com.google.gdata.util.ServiceException) SpreadsheetFeed(com.google.gdata.data.spreadsheet.SpreadsheetFeed) Drive(com.google.api.services.drive.Drive) File(com.google.api.services.drive.model.File)

Example 4 with ServiceException

use of com.google.gdata.util.ServiceException in project OpenRefine by OpenRefine.

the class UploadCommand method uploadToCellFeed.

private static void uploadToCellFeed(Project project, Engine engine, Properties params, final SpreadsheetService service, final SpreadsheetEntry spreadsheetEntry, final WorksheetEntry worksheetEntry) throws IOException, ServiceException {
    final URL cellFeedUrl = worksheetEntry.getCellFeedUrl();
    final CellEntry[][] cellEntries = new CellEntry[worksheetEntry.getRowCount()][worksheetEntry.getColCount()];
    {
        CellQuery cellQuery = new CellQuery(cellFeedUrl);
        cellQuery.setReturnEmpty(true);
        CellFeed fetchingCellFeed = service.getFeed(cellQuery, CellFeed.class);
        for (CellEntry cellEntry : fetchingCellFeed.getEntries()) {
            Cell cell = cellEntry.getCell();
            cellEntries[cell.getRow() - 1][cell.getCol() - 1] = cellEntry;
        }
    }
    TabularSerializer serializer = new TabularSerializer() {

        CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);

        CellFeed batchRequest = null;

        int row = 0;

        @Override
        public void startFile(JSONObject options) {
        }

        @Override
        public void endFile() {
            if (batchRequest != null) {
                sendBatch();
            }
        }

        private void sendBatch() {
            try {
                Link batchLink = cellFeed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
                CellFeed batchResponse = service.batch(new URL(batchLink.getHref()), batchRequest);
                for (CellEntry entry : batchResponse.getEntries()) {
                    String batchId = BatchUtils.getBatchId(entry);
                    if (!BatchUtils.isSuccess(entry)) {
                        BatchStatus status = BatchUtils.getBatchStatus(entry);
                        logger.warn(String.format("Error: %s failed (%s) %s\n", batchId, status.getReason(), status.getContent()));
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            batchRequest = null;
        }

        @Override
        public void addRow(List<CellData> cells, boolean isHeader) {
            if (batchRequest == null) {
                batchRequest = new CellFeed();
            }
            for (int c = 0; c < cells.size(); c++) {
                CellData cellData = cells.get(c);
                if (cellData != null && cellData.text != null) {
                    String cellId = String.format("R%sC%s", row + 1, c + 1);
                    CellEntry cellEntry = cellEntries[row][c];
                    cellEntry.changeInputValueLocal(cellData.text);
                    if (cellData.link != null) {
                        cellEntry.addHtmlLink(cellData.link, null, cellData.text);
                    }
                    cellEntry.setId(cellId);
                    BatchUtils.setBatchId(cellEntry, cellId);
                    BatchUtils.setBatchOperationType(cellEntry, BatchOperationType.UPDATE);
                    batchRequest.getEntries().add(cellEntry);
                }
            }
            row++;
            if (row % 20 == 0) {
                sendBatch();
            }
        }
    };
    CustomizableTabularExporterUtilities.exportRows(project, engine, params, serializer);
}
Also used : CellFeed(com.google.gdata.data.spreadsheet.CellFeed) URL(java.net.URL) ServletException(javax.servlet.ServletException) ServiceException(com.google.gdata.util.ServiceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) TabularSerializer(com.google.refine.exporters.TabularSerializer) BatchStatus(com.google.gdata.data.batch.BatchStatus) LinkedList(java.util.LinkedList) List(java.util.List) CellEntry(com.google.gdata.data.spreadsheet.CellEntry) Cell(com.google.gdata.data.spreadsheet.Cell) CellQuery(com.google.gdata.client.spreadsheet.CellQuery) Link(com.google.gdata.data.Link)

Example 5 with ServiceException

use of com.google.gdata.util.ServiceException in project OpenRefine by OpenRefine.

the class GDataImporter method parseOneWorkSheet.

public static void parseOneWorkSheet(SpreadsheetService service, Project project, ProjectMetadata metadata, final ImportingJob job, URL docURL, URL worksheetURL, int limit, JSONObject options, List<Exception> exceptions) {
    try {
        WorksheetEntry worksheetEntry = service.getEntry(worksheetURL, WorksheetEntry.class);
        String spreadsheetName = docURL.toExternalForm();
        try {
            SpreadsheetEntry spreadsheetEntry = service.getEntry(docURL, SpreadsheetEntry.class);
            spreadsheetName = spreadsheetEntry.getTitle().getPlainText();
        } catch (ServiceException e) {
        // RedirectRequiredException among others
        // fall back to just using the URL (better for traceability anyway?)
        }
        String fileSource = spreadsheetName + " # " + worksheetEntry.getTitle().getPlainText();
        setProgress(job, fileSource, 0);
        TabularImportingParserBase.readTable(project, metadata, job, new WorksheetBatchRowReader(job, fileSource, service, worksheetEntry, 20), fileSource, limit, options, exceptions);
        setProgress(job, fileSource, 100);
    } catch (IOException e) {
        e.printStackTrace();
        exceptions.add(e);
    } catch (ServiceException e) {
        e.printStackTrace();
        exceptions.add(e);
    }
}
Also used : ServiceException(com.google.gdata.util.ServiceException) SpreadsheetEntry(com.google.gdata.data.spreadsheet.SpreadsheetEntry) IOException(java.io.IOException) WorksheetEntry(com.google.gdata.data.spreadsheet.WorksheetEntry)

Aggregations

ServiceException (com.google.gdata.util.ServiceException)6 SpreadsheetEntry (com.google.gdata.data.spreadsheet.SpreadsheetEntry)3 WorksheetEntry (com.google.gdata.data.spreadsheet.WorksheetEntry)3 IOException (java.io.IOException)3 URL (java.net.URL)3 ServletException (javax.servlet.ServletException)3 SpreadsheetService (com.google.gdata.client.spreadsheet.SpreadsheetService)2 MalformedURLException (java.net.MalformedURLException)2 JSONObject (org.json.JSONObject)2 Drive (com.google.api.services.drive.Drive)1 File (com.google.api.services.drive.model.File)1 CellQuery (com.google.gdata.client.spreadsheet.CellQuery)1 Link (com.google.gdata.data.Link)1 PlainTextConstruct (com.google.gdata.data.PlainTextConstruct)1 BatchStatus (com.google.gdata.data.batch.BatchStatus)1 Cell (com.google.gdata.data.spreadsheet.Cell)1 CellEntry (com.google.gdata.data.spreadsheet.CellEntry)1 CellFeed (com.google.gdata.data.spreadsheet.CellFeed)1 SpreadsheetFeed (com.google.gdata.data.spreadsheet.SpreadsheetFeed)1 AuthenticationException (com.google.gdata.util.AuthenticationException)1