Search in sources :

Example 1 with MediaWikiApiErrorException

use of org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException in project OpenRefine by OpenRefine.

the class ConnectionManager method logout.

public void logout(String mediaWikiApiEndpoint) {
    ApiConnection connection = endpointToConnection.get(mediaWikiApiEndpoint);
    if (connection != null) {
        try {
            connection.logout();
            endpointToConnection.remove(mediaWikiApiEndpoint);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (MediaWikiApiErrorException e) {
            if ("assertuserfailed".equals(e.getErrorCode())) {
                // it turns out we were already logged out
                endpointToConnection.remove(mediaWikiApiEndpoint);
            } else {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
Also used : BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection) ApiConnection(org.wikidata.wdtk.wikibaseapi.ApiConnection) OAuthApiConnection(org.wikidata.wdtk.wikibaseapi.OAuthApiConnection) IOException(java.io.IOException) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException)

Example 2 with MediaWikiApiErrorException

use of org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException in project OpenRefine by OpenRefine.

the class EditBatchProcessorTest method testMultipleBatches.

@Test
public void testMultipleBatches() throws MediaWikiApiErrorException, InterruptedException, IOException {
    // Prepare test data
    MonolingualTextValue description = Datamodel.makeMonolingualTextValue("village in Nepal", "en");
    List<String> ids = new ArrayList<>();
    for (int i = 124; i < 190; i++) {
        ids.add("Q" + String.valueOf(i));
    }
    List<ItemIdValue> qids = ids.stream().map(e -> Datamodel.makeWikidataItemIdValue(e)).collect(Collectors.toList());
    List<TermedStatementEntityEdit> batch = qids.stream().map(qid -> new TermedStatementEntityEditBuilder(qid).addDescription(description, true).build()).collect(Collectors.toList());
    int batchSize = 50;
    List<ItemDocument> fullBatch = qids.stream().map(qid -> ItemDocumentBuilder.forItemId(qid).withStatement(TestingData.generateStatement(qid, TestingData.existingId)).build()).collect(Collectors.toList());
    List<ItemDocument> firstBatch = fullBatch.subList(0, batchSize);
    List<ItemDocument> secondBatch = fullBatch.subList(batchSize, fullBatch.size());
    when(fetcher.getEntityDocuments(toQids(firstBatch))).thenReturn(toMap(firstBatch));
    when(fetcher.getEntityDocuments(toQids(secondBatch))).thenReturn(toMap(secondBatch));
    // Run edits
    EditBatchProcessor processor = new EditBatchProcessor(fetcher, editor, batch, library, summary, maxlag, tags, batchSize);
    assertEquals(0, processor.progress());
    for (int i = 124; i < 190; i++) {
        assertEquals(processor.remainingEdits(), 190 - i);
        processor.performEdit();
    }
    assertEquals(0, processor.remainingEdits());
    assertEquals(100, processor.progress());
    // Check result
    assertEquals(new NewEntityLibrary(), library);
    verify(fetcher, times(1)).getEntityDocuments(toQids(firstBatch));
    verify(fetcher, times(1)).getEntityDocuments(toQids(secondBatch));
    for (ItemDocument doc : fullBatch) {
        verify(editor, times(1)).editEntityDocument(Datamodel.makeItemUpdate(doc.getEntityId(), doc.getRevisionId(), Datamodel.makeTermUpdate(Collections.emptyList(), Collections.emptyList()), Datamodel.makeTermUpdate(Collections.singletonList(description), Collections.emptyList()), Collections.emptyMap(), Datamodel.makeStatementUpdate(Collections.emptyList(), Collections.emptyList(), Collections.emptyList()), Collections.emptyList(), Collections.emptyList()), false, summary, tags);
    }
}
Also used : Arrays(java.util.Arrays) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) MediaInfoDocument(org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument) EntityDocument(org.wikidata.wdtk.datamodel.interfaces.EntityDocument) ArrayList(java.util.ArrayList) TermUpdate(org.wikidata.wdtk.datamodel.interfaces.TermUpdate) WikibaseDataFetcher(org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher) ItemIdValue(org.wikidata.wdtk.datamodel.interfaces.ItemIdValue) Map(java.util.Map) MonolingualTextValue(org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue) WikidataRefineTest(org.openrefine.wikidata.testing.WikidataRefineTest) TermedStatementEntityEdit(org.openrefine.wikidata.updates.TermedStatementEntityEdit) BeforeMethod(org.testng.annotations.BeforeMethod) ItemDocumentBuilder(org.wikidata.wdtk.datamodel.helpers.ItemDocumentBuilder) WikibaseDataEditor(org.wikidata.wdtk.wikibaseapi.WikibaseDataEditor) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) MediaInfoIdValue(org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue) Mockito.verify(org.mockito.Mockito.verify) StatementUpdate(org.wikidata.wdtk.datamodel.interfaces.StatementUpdate) List(java.util.List) TermedStatementEntityEditBuilder(org.openrefine.wikidata.updates.TermedStatementEntityEditBuilder) Datamodel(org.wikidata.wdtk.datamodel.helpers.Datamodel) ItemDocument(org.wikidata.wdtk.datamodel.interfaces.ItemDocument) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException) Collections(java.util.Collections) TestingData(org.openrefine.wikidata.testing.TestingData) Mockito.mock(org.mockito.Mockito.mock) TermedStatementEntityEditBuilder(org.openrefine.wikidata.updates.TermedStatementEntityEditBuilder) ArrayList(java.util.ArrayList) MonolingualTextValue(org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue) ItemIdValue(org.wikidata.wdtk.datamodel.interfaces.ItemIdValue) ItemDocument(org.wikidata.wdtk.datamodel.interfaces.ItemDocument) TermedStatementEntityEdit(org.openrefine.wikidata.updates.TermedStatementEntityEdit) Test(org.testng.annotations.Test) WikidataRefineTest(org.openrefine.wikidata.testing.WikidataRefineTest)

Example 3 with MediaWikiApiErrorException

use of org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException in project OpenRefine by OpenRefine.

the class EditBatchProcessorTest method testMultipleBatchesMediaInfo.

@Test
public void testMultipleBatchesMediaInfo() throws MediaWikiApiErrorException, InterruptedException, IOException {
    // Prepare test data
    MonolingualTextValue label = Datamodel.makeMonolingualTextValue("village in Nepal", "en");
    List<MonolingualTextValue> labels = Collections.singletonList(label);
    TermUpdate labelsUpdate = Datamodel.makeTermUpdate(labels, Collections.emptyList());
    List<String> ids = new ArrayList<>();
    for (int i = 124; i < 190; i++) {
        ids.add("M" + String.valueOf(i));
    }
    List<MediaInfoIdValue> mids = ids.stream().map(e -> Datamodel.makeWikimediaCommonsMediaInfoIdValue(e)).collect(Collectors.toList());
    List<TermedStatementEntityEdit> batch = mids.stream().map(mid -> new TermedStatementEntityEditBuilder(mid).addLabel(label, false).build()).collect(Collectors.toList());
    int batchSize = 50;
    List<MediaInfoDocument> fullBatch = mids.stream().map(mid -> Datamodel.makeMediaInfoDocument(mid)).collect(Collectors.toList());
    List<MediaInfoDocument> firstBatch = fullBatch.subList(0, batchSize);
    List<MediaInfoDocument> secondBatch = fullBatch.subList(batchSize, fullBatch.size());
    when(fetcher.getEntityDocuments(toMids(firstBatch))).thenReturn(toMapMediaInfo(firstBatch));
    when(fetcher.getEntityDocuments(toMids(secondBatch))).thenReturn(toMapMediaInfo(secondBatch));
    // Run edits
    EditBatchProcessor processor = new EditBatchProcessor(fetcher, editor, batch, library, summary, maxlag, tags, batchSize);
    assertEquals(0, processor.progress());
    for (int i = 124; i < 190; i++) {
        assertEquals(processor.remainingEdits(), 190 - i);
        processor.performEdit();
    }
    assertEquals(0, processor.remainingEdits());
    assertEquals(100, processor.progress());
    // Check result
    assertEquals(new NewEntityLibrary(), library);
    verify(fetcher, times(1)).getEntityDocuments(toMids(firstBatch));
    verify(fetcher, times(1)).getEntityDocuments(toMids(secondBatch));
    for (MediaInfoDocument doc : fullBatch) {
        StatementUpdate statementUpdate = Datamodel.makeStatementUpdate(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
        verify(editor, times(1)).editEntityDocument(Datamodel.makeMediaInfoUpdate((MediaInfoIdValue) doc.getEntityId(), doc.getRevisionId(), labelsUpdate, statementUpdate), false, summary, tags);
    }
}
Also used : Arrays(java.util.Arrays) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) MediaInfoDocument(org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument) EntityDocument(org.wikidata.wdtk.datamodel.interfaces.EntityDocument) ArrayList(java.util.ArrayList) TermUpdate(org.wikidata.wdtk.datamodel.interfaces.TermUpdate) WikibaseDataFetcher(org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher) ItemIdValue(org.wikidata.wdtk.datamodel.interfaces.ItemIdValue) Map(java.util.Map) MonolingualTextValue(org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue) WikidataRefineTest(org.openrefine.wikidata.testing.WikidataRefineTest) TermedStatementEntityEdit(org.openrefine.wikidata.updates.TermedStatementEntityEdit) BeforeMethod(org.testng.annotations.BeforeMethod) ItemDocumentBuilder(org.wikidata.wdtk.datamodel.helpers.ItemDocumentBuilder) WikibaseDataEditor(org.wikidata.wdtk.wikibaseapi.WikibaseDataEditor) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) MediaInfoIdValue(org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue) Mockito.verify(org.mockito.Mockito.verify) StatementUpdate(org.wikidata.wdtk.datamodel.interfaces.StatementUpdate) List(java.util.List) TermedStatementEntityEditBuilder(org.openrefine.wikidata.updates.TermedStatementEntityEditBuilder) Datamodel(org.wikidata.wdtk.datamodel.helpers.Datamodel) ItemDocument(org.wikidata.wdtk.datamodel.interfaces.ItemDocument) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException) Collections(java.util.Collections) TestingData(org.openrefine.wikidata.testing.TestingData) Mockito.mock(org.mockito.Mockito.mock) TermedStatementEntityEditBuilder(org.openrefine.wikidata.updates.TermedStatementEntityEditBuilder) MediaInfoIdValue(org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue) MediaInfoDocument(org.wikidata.wdtk.datamodel.interfaces.MediaInfoDocument) StatementUpdate(org.wikidata.wdtk.datamodel.interfaces.StatementUpdate) ArrayList(java.util.ArrayList) MonolingualTextValue(org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue) TermedStatementEntityEdit(org.openrefine.wikidata.updates.TermedStatementEntityEdit) TermUpdate(org.wikidata.wdtk.datamodel.interfaces.TermUpdate) Test(org.testng.annotations.Test) WikidataRefineTest(org.openrefine.wikidata.testing.WikidataRefineTest)

Example 4 with MediaWikiApiErrorException

use of org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException in project OpenRefine by OpenRefine.

the class EditBatchProcessor method performEdit.

/**
 * Performs the next edit in the batch.
 *
 * @throws InterruptedException
 */
public void performEdit() throws InterruptedException {
    if (remainingEdits() == 0) {
        return;
    }
    if (batchCursor == currentBatch.size()) {
        prepareNewBatch();
    }
    TermedStatementEntityEdit update = currentBatch.get(batchCursor);
    // Rewrite mentions to new entities
    ReconEntityRewriter rewriter = new ReconEntityRewriter(library, update.getEntityId());
    try {
        update = rewriter.rewrite(update);
    } catch (NewEntityNotCreatedYetException e) {
        logger.warn("Failed to rewrite update on entity " + update.getEntityId() + ". Missing entity: " + e.getMissingEntity() + ". Skipping update.");
        batchCursor++;
        return;
    }
    try {
        // New entities
        if (update.isNew()) {
            ReconEntityIdValue newCell = (ReconEntityIdValue) update.getEntityId();
            // TODO Antonin, 2022-02-11: remove this casting once we have https://github.com/Wikidata/Wikidata-Toolkit/issues/651
            if (newCell instanceof ItemIdValue) {
                update = update.normalizeLabelsAndAliases();
                ItemDocument itemDocument = (ItemDocument) update.toNewEntity();
                ItemDocument createdDoc = editor.createItemDocument(itemDocument, summary, tags);
                library.setId(newCell.getReconInternalId(), createdDoc.getEntityId().getId());
            } else if (newCell instanceof MediaInfoIdValue) {
                update = update.normalizeLabelsAndAliases();
                throw new NotImplementedException();
            }
        } else {
            // Existing entities
            EntityUpdate entityUpdate = update.toEntityUpdate(currentDocs.get(update.getEntityId().getId()));
            editor.editEntityDocument(entityUpdate, false, summary, tags);
        }
    } catch (MediaWikiApiErrorException e) {
        // TODO find a way to report these errors to the user in a nice way
        logger.warn("MediaWiki error while editing [" + e.getErrorCode() + "]: " + e.getErrorMessage());
    } catch (IOException e) {
        logger.warn("IO error while editing: " + e.getMessage());
    }
    batchCursor++;
}
Also used : ItemIdValue(org.wikidata.wdtk.datamodel.interfaces.ItemIdValue) EntityUpdate(org.wikidata.wdtk.datamodel.interfaces.EntityUpdate) ItemDocument(org.wikidata.wdtk.datamodel.interfaces.ItemDocument) NewEntityNotCreatedYetException(org.openrefine.wikidata.schema.exceptions.NewEntityNotCreatedYetException) MediaInfoIdValue(org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue) ReconEntityIdValue(org.openrefine.wikidata.schema.entityvalues.ReconEntityIdValue) NotImplementedException(org.apache.commons.lang.NotImplementedException) TermedStatementEntityEdit(org.openrefine.wikidata.updates.TermedStatementEntityEdit) IOException(java.io.IOException) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException)

Example 5 with MediaWikiApiErrorException

use of org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException in project OpenRefine by OpenRefine.

the class ConnectionManager method login.

/**
 * Logs in to the Wikibase instance, using cookies.
 * <p>
 * If failed to login, the connection will be set to null.
 *
 * @param mediaWikiApiEndpoint the api endpoint of the target Wikibase instance
 * @param username the username
 * @param cookies  the cookies used to login
 * @return true if logged in successfully, false otherwise
 */
public boolean login(String mediaWikiApiEndpoint, String username, List<Cookie> cookies) {
    cookies.forEach(cookie -> cookie.setPath("/"));
    Map<String, Object> map = new HashMap<>();
    map.put("baseUrl", mediaWikiApiEndpoint);
    map.put("cookies", cookies);
    map.put("username", username);
    map.put("loggedIn", true);
    map.put("tokens", Collections.emptyMap());
    map.put("connectTimeout", CONNECT_TIMEOUT);
    map.put("readTimeout", READ_TIMEOUT);
    try {
        BasicApiConnection connection = convertToBasicApiConnection(map);
        connection.checkCredentials();
        endpointToConnection.put(mediaWikiApiEndpoint, connection);
        return true;
    } catch (IOException | MediaWikiApiErrorException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection)

Aggregations

IOException (java.io.IOException)5 MediaWikiApiErrorException (org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException)5 TermedStatementEntityEdit (org.openrefine.wikidata.updates.TermedStatementEntityEdit)3 ItemDocument (org.wikidata.wdtk.datamodel.interfaces.ItemDocument)3 ItemIdValue (org.wikidata.wdtk.datamodel.interfaces.ItemIdValue)3 MediaInfoIdValue (org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Mockito.mock (org.mockito.Mockito.mock)2 Mockito.times (org.mockito.Mockito.times)2 Mockito.verify (org.mockito.Mockito.verify)2 Mockito.when (org.mockito.Mockito.when)2 TestingData (org.openrefine.wikidata.testing.TestingData)2 WikidataRefineTest (org.openrefine.wikidata.testing.WikidataRefineTest)2 TermedStatementEntityEditBuilder (org.openrefine.wikidata.updates.TermedStatementEntityEditBuilder)2 Assert.assertEquals (org.testng.Assert.assertEquals)2