@Test void createDocTest() { BaseIndexer indexer = new SolrIndexer("", TEST1); List<String> languages = Lists.newArrayList(); languages.add(LOCALE); Map<String, Object> createdDoc = indexer.createDoc(ID, ENGLISH_TITLE, SPANISH_TITLE, ALT_TITLE, languages); Map<String, Object> expectedDoc = Maps.newHashMap(); expectedDoc.put(Properties.idField.get(), ID + "_" + TEST1); expectedDoc.put(Properties.titleFields.get().get(0) + "_en", ENGLISH_TITLE); Set<Object> localizedTitles = Sets.newHashSet(); localizedTitles.add(SPANISH_TITLE); expectedDoc.put(Properties.titleFields.get().get(0) + "_es", localizedTitles); expectedDoc.put(Properties.docTypeFieldName.get(), TEST1); Assert.assertEquals(createdDoc, expectedDoc); StringBuilder jsonStringOfDoc = indexer.getJsonStringOfDoc(new ObjectMapper().valueToTree(createdDoc)); Assert.assertEquals(jsonStringOfDoc.toString(), "[{\"query_testing_type\":\"test1\",\"title_en\":\"title en\",\"id\":\"123_test1\",\"title_es\":[\"title es\"]}]"); String urlForAddingDoc = indexer.getUrlForAddingDoc(createdDoc); Assert.assertEquals(urlForAddingDoc, "http://localhost:8983/solr/qtest/update"); String urlForCommitting = indexer.getUrlForCommitting(); Assert.assertEquals(urlForCommitting, "http://localhost:8983/solr/qtest/update?commit=true"); }
@Override protected void setup() throws Exception { super.internalSetup(); super.producerBaseSetup(); pulsarSpoutConf = new PulsarSpoutConfiguration(); pulsarSpoutConf.setServiceUrl(serviceUrl); pulsarSpoutConf.setTopic(topic); pulsarSpoutConf.setSubscriptionName(subscriptionName); pulsarSpoutConf.setMessageToValuesMapper(messageToValuesMapper); pulsarSpoutConf.setFailedRetriesTimeout(1, TimeUnit.SECONDS); pulsarSpoutConf.setMaxFailedRetries(2); pulsarSpoutConf.setSharedConsumerEnabled(true); pulsarSpoutConf.setMetricsTimeIntervalInSecs(60); consumerConf = new ConsumerConfiguration(); consumerConf.setSubscriptionType(SubscriptionType.Shared); spout = new PulsarSpout(pulsarSpoutConf, new ClientConfiguration(), consumerConf); mockCollector = new MockSpoutOutputCollector(); SpoutOutputCollector collector = new SpoutOutputCollector(mockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("test-spout-" + methodName); when(context.getThisTaskId()).thenReturn(0); spout.open(Maps.newHashMap(), context, collector); producer = pulsarClient.createProducer(topic); }
@Test public void testSharedConsumer() throws Exception { PersistentTopicStats topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); PulsarSpout otherSpout = new PulsarSpout(pulsarSpoutConf, new ClientConfiguration(), consumerConf); MockSpoutOutputCollector otherMockCollector = new MockSpoutOutputCollector(); SpoutOutputCollector collector = new SpoutOutputCollector(otherMockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("test-spout-" + methodName); when(context.getThisTaskId()).thenReturn(1); otherSpout.open(Maps.newHashMap(), context, collector); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); otherSpout.close(); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); }
@Test public void testNoSharedConsumer() throws Exception { PersistentTopicStats topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); pulsarSpoutConf.setSharedConsumerEnabled(false); PulsarSpout otherSpout = new PulsarSpout(pulsarSpoutConf, new ClientConfiguration(), consumerConf); MockSpoutOutputCollector otherMockCollector = new MockSpoutOutputCollector(); SpoutOutputCollector collector = new SpoutOutputCollector(otherMockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("test-spout-" + methodName); when(context.getThisTaskId()).thenReturn(1); otherSpout.open(Maps.newHashMap(), context, collector); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 2); otherSpout.close(); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); }
@Test public void testFailedConsumer() throws Exception { PulsarSpoutConfiguration pulsarSpoutConf = new PulsarSpoutConfiguration(); pulsarSpoutConf.setServiceUrl(serviceUrl); pulsarSpoutConf.setTopic("persistent://invalidTopic"); pulsarSpoutConf.setSubscriptionName(subscriptionName); pulsarSpoutConf.setMessageToValuesMapper(messageToValuesMapper); pulsarSpoutConf.setFailedRetriesTimeout(1, TimeUnit.SECONDS); pulsarSpoutConf.setMaxFailedRetries(2); pulsarSpoutConf.setSharedConsumerEnabled(false); pulsarSpoutConf.setMetricsTimeIntervalInSecs(60); ConsumerConfiguration consumerConf = new ConsumerConfiguration(); consumerConf.setSubscriptionType(SubscriptionType.Shared); PulsarSpout spout = new PulsarSpout(pulsarSpoutConf, new ClientConfiguration(), consumerConf); MockSpoutOutputCollector mockCollector = new MockSpoutOutputCollector(); SpoutOutputCollector collector = new SpoutOutputCollector(mockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("new-test" + methodName); when(context.getThisTaskId()).thenReturn(0); try { spout.open(Maps.newHashMap(), context, collector); fail("should have failed as consumer creation failed"); } catch (IllegalStateException e) { // Ok } }
@Override protected void setup() throws Exception { super.internalSetup(); super.producerBaseSetup(); pulsarBoltConf = new PulsarBoltConfiguration(); pulsarBoltConf.setServiceUrl(serviceUrl); pulsarBoltConf.setTopic(topic); pulsarBoltConf.setTupleToMessageMapper(tupleToMessageMapper); pulsarBoltConf.setMetricsTimeIntervalInSecs(60); bolt = new PulsarBolt(pulsarBoltConf, new ClientConfiguration()); mockCollector = new MockOutputCollector(); OutputCollector collector = new OutputCollector(mockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("test-bolt-" + methodName); when(context.getThisTaskId()).thenReturn(0); bolt.prepare(Maps.newHashMap(), context, collector); consumer = pulsarClient.subscribe(topic, subscriptionName); }
@Test public void testSharedProducer() throws Exception { PersistentTopicStats topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.publishers.size(), 1); PulsarBolt otherBolt = new PulsarBolt(pulsarBoltConf, new ClientConfiguration()); MockOutputCollector otherMockCollector = new MockOutputCollector(); OutputCollector collector = new OutputCollector(otherMockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("test-bolt-" + methodName); when(context.getThisTaskId()).thenReturn(1); otherBolt.prepare(Maps.newHashMap(), context, collector); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.publishers.size(), 1); otherBolt.close(); topicStats = admin.persistentTopics().getStats(topic); Assert.assertEquals(topicStats.publishers.size(), 1); }
@Test public void testFailedProducer() { PulsarBoltConfiguration pulsarBoltConf = new PulsarBoltConfiguration(); pulsarBoltConf.setServiceUrl(serviceUrl); pulsarBoltConf.setTopic("persistent://invalid"); pulsarBoltConf.setTupleToMessageMapper(tupleToMessageMapper); pulsarBoltConf.setMetricsTimeIntervalInSecs(60); PulsarBolt bolt = new PulsarBolt(pulsarBoltConf, new ClientConfiguration()); MockOutputCollector mockCollector = new MockOutputCollector(); OutputCollector collector = new OutputCollector(mockCollector); TopologyContext context = mock(TopologyContext.class); when(context.getThisComponentId()).thenReturn("new" + methodName); when(context.getThisTaskId()).thenReturn(0); try { bolt.prepare(Maps.newHashMap(), context, collector); fail("should have failed as producer creation failed"); } catch (IllegalStateException ie) { // Ok. } }
private List<List<IMethodInstance>> createInstances(List<IMethodInstance> methodInstances) { Map<Object, List<IMethodInstance>> map = Maps.newHashMap(); // MapList<IMethodInstance[], Object> map = new MapList<IMethodInstance[], Object>(); for (IMethodInstance imi : methodInstances) { for (Object o : imi.getInstances()) { System.out.println(o); List<IMethodInstance> l = map.get(o); if (l == null) { l = Lists.newArrayList(); map.put(o, l); } l.add(imi); } // for (Object instance : imi.getInstances()) { // map.put(imi, instance); // } } // return map.getKeys(); // System.out.println(map); return new ArrayList<List<IMethodInstance>>(map.values()); }
/** Returns all replicas per node. */ private Map<String, List<ReplicaInfo>> getNodeReplicas() { final ClusterState clusterState = getClusterState(); final Map<String, List<ReplicaInfo>> result = Maps.newHashMap(); for (final DocCollection collection : clusterState.getCollectionsMap().values()) { for (final Slice slice : collection.getSlices()) { for (final Replica replica : slice.getReplicas()) { List<ReplicaInfo> nodeReplicas = result.get(replica.getNodeName()); if (nodeReplicas == null) { nodeReplicas = Lists.newArrayList(); result.put(replica.getNodeName(), nodeReplicas); } nodeReplicas.add(new ReplicaInfo(replica, collection.getName(), slice.getName())); } } } return result; }
@Test(dependsOnMethods = "getAndClearNotifications", groups = "eps") public void checkDeletions() throws Exception { waitForIndex(0, "nonExistantCountsAsAll?"); JsonNode results = doNotificationsSearch("dontfindanything", null, Maps.newHashMap(), getToken()); assertEquals(results.get("available").asInt(), 0, "Should be no notifications"); }
@Test public void testInsertMany() throws Exception { List<Map<String, Object>> dataList = Lists.newArrayList(); for (int i =0; i< 10; i++){ Map<String, Object> map = Maps.newHashMap(); map.put("number", i); dataList.add(map); } dataAccess.insertMany("testNumber", dataList); }
@Test void createDocTest() { BaseIndexer indexer = new ElasticsearchIndexer("", TEST1); List<String> languages = Lists.newArrayList(); languages.add(LOCALE); Map<String, Object> createdDoc = indexer.createDoc(ID, ENGLISH_TITLE, SPANISH_TITLE, ALT_TITLE, languages); Map<String, Object> expectedDoc = Maps.newHashMap(); expectedDoc.put(Properties.idField.get(), ID + "_" + TEST1); expectedDoc.put(Properties.titleFields.get().get(0) + "_en", ENGLISH_TITLE); Set<Object> localizedTitles = Sets.newHashSet(); localizedTitles.add(SPANISH_TITLE); expectedDoc.put(Properties.titleFields.get().get(0) + "_es", localizedTitles); expectedDoc.put(Properties.docTypeFieldName.get(), TEST1); Assert.assertEquals(createdDoc, expectedDoc); StringBuilder jsonStringOfDoc = indexer.getJsonStringOfDoc(new ObjectMapper().valueToTree(createdDoc)); Assert.assertEquals(jsonStringOfDoc.toString(), "{\"query_testing_type\":\"test1\",\"title_en\":\"title en\",\"id\":\"123_test1\",\"title_es\":[\"title es\"]}"); String urlForAddingDoc = indexer.getUrlForAddingDoc(createdDoc); Assert.assertEquals(urlForAddingDoc, "http://localhost:8983/solr/qtest/test_doc/123_test1"); String urlForCommitting = indexer.getUrlForCommitting(); Assert.assertEquals(urlForCommitting, "http://localhost:8983/solr/qtest/_flush"); }
@Test void createDocTest() { GoogleDataExtractor titleExtractor = Mockito.mock(GoogleDataExtractor.class); Map<String, Map<Integer, TitleWithQueries>> mapOfQueriesToTitles = Maps.newHashMap(); Map<Integer, TitleWithQueries> titlesWithQueries = Maps.newHashMap(); TitleWithQueries titleWithQueries = new TitleWithQueries(DATASET_ID); titleWithQueries.setValue(TitleWithQueries.ID, ID1); titleWithQueries.setValue(TitleWithQueries.TITLE_EN, ENGLISH_TITLE); titleWithQueries.setValue(TitleWithQueries.TITLE_LOCALE, SPANISH_TITLE); titleWithQueries.setValue(TitleWithQueries.Q_ + "regular", Q1); titlesWithQueries.put(1, titleWithQueries); TitleWithQueries titleWithQueries2 = new TitleWithQueries(DATASET_ID); titleWithQueries2.setValue(TitleWithQueries.ID, ID2); titleWithQueries2.setValue(TitleWithQueries.TITLE_EN, ENGLISH_TITLE); titleWithQueries2.setValue(TitleWithQueries.TITLE_LOCALE, SPANISH_TITLE); titleWithQueries2.setValue(TitleWithQueries.Q_ + "regular", Q1); titlesWithQueries.put(2, titleWithQueries2); mapOfQueriesToTitles.put(DATASET_ID, titlesWithQueries); Mockito.when(titleExtractor.getTitlesWithQueriesPerDataset()).thenReturn(mapOfQueriesToTitles); Queries queries = new Queries(DATASET_ID, TEST1, titleExtractor); queries.populateFromGoogleSpreadsheets(); Map<String, Set<String>> queryToIdMap = queries.getQueryToIdMap(); Map<String, Set<String>> expectedQueryToIdMap = Maps.newHashMap(); Set<String> titles = Sets.newHashSet(); titles.add(ID1+"_"+DATASET_ID); titles.add(ID2+"_"+DATASET_ID); expectedQueryToIdMap.put(Q1, titles); Assert.assertEquals(queryToIdMap, expectedQueryToIdMap); }
private Map<String, String> createGroups(String[] groups) { Map<String, String> result = Maps.newHashMap(); // Groups that were passed on the command line for (String group : groups) { result.put(group, group); } // See if we have any MetaGroups and // expand them if they match one of the groups // we have just been passed List<String> unfinishedGroups = Lists.newArrayList(); if (m_metaGroups.size() > 0) { collectGroups(groups, unfinishedGroups, result); // Do we need to loop over unfinished groups? while (unfinishedGroups.size() > 0) { String[] uGroups = unfinishedGroups.toArray(new String[unfinishedGroups.size()]); unfinishedGroups = Lists.newArrayList(); collectGroups(uGroups, unfinishedGroups, result); } } // Utils.dumpMap(result); return result; }
private ListMultiMap<ITestNGMethod, ITestNGMethod> createInstanceDependencies(ITestNGMethod[] methods) { ListMultiMap<Object, ITestNGMethod> instanceMap = Maps.newSortedListMultiMap(); for (ITestNGMethod m : methods) { instanceMap.put(m.getInstance(), m); } ListMultiMap<ITestNGMethod, ITestNGMethod> result = Maps.newListMultiMap(); Object previousInstance = null; for (Map.Entry<Object, List<ITestNGMethod>> es : instanceMap.entrySet()) { if (previousInstance == null) { previousInstance = es.getKey(); } else { List<ITestNGMethod> previousMethods = instanceMap.get(previousInstance); Object currentInstance = es.getKey(); List<ITestNGMethod> currentMethods = instanceMap.get(currentInstance); // Make all the methods from the current instance depend on the methods of // the previous instance for (ITestNGMethod cm : currentMethods) { for (ITestNGMethod pm : previousMethods) { result.put(cm, pm); } } previousInstance = currentInstance; } } return result; }
@Override public Collection<ITestNGMethod> getExcludedMethods() { Map<ITestNGMethod, ITestNGMethod> vResult = Maps.newHashMap(); for (ITestNGMethod m : m_excludedMethods) { vResult.put(m, m); } return vResult.keySet(); }
@DataProvider(name="dp-with-testngmethod-contex") public Object[][] dataProviderForBDD(ITestNGMethod method, ITestContext contex){ Map<Object, Object> m = Maps.newHashMap(); m.put("method", method.getMethodName()); m.put("contex", contex.getName()); return new Object[][]{{m}}; }
public SuiteMessage(final ISuite suite, final boolean startSuiteRun) { m_suiteName = suite.getName(); m_testMethodCount =suite.getInvokedMethods().size(); m_startSuite = startSuiteRun; Collection<ITestNGMethod> excludedMethods = suite.getExcludedMethods(); if (excludedMethods != null && excludedMethods.size() > 0) { m_excludedMethods = Lists.newArrayList(); m_descriptions = Maps.newHashMap(); for (ITestNGMethod m : excludedMethods) { String methodName = m.getTestClass().getName() + "." + m.getMethodName(); m_excludedMethods.add(methodName); if (m.getDescription() != null) m_descriptions.put(methodName, m.getDescription()); } } }
@Test(dataProvider = "envPropMap") public void testResolveDashedProperties(String key, String value, String keyENV, String valueENV) throws Exception { Properties props = new Properties(); props.put(key, value); props = EnvironmentPropertyConfigurer.resolveDashedProperties(props); assertEquals(props.size(), 1); assertEquals(props.get(key), value); Map<String, String> envMap = Maps.newHashMap(System.getenv()); envMap.put(keyENV, valueENV); props = EnvironmentPropertyConfigurer.resolveDashedProperties(props, envMap); assertEquals(props.size(), 1); assertEquals(props.get(key), valueENV); }
@Test public void copyTableQueryTest() throws Exception { Map<String, String> partitionsDMLInfo = Maps.newHashMap(); String partitionName = "datepartition"; String partitionValue = "2017-07-15-08"; partitionsDMLInfo.put(partitionName, partitionValue); String expectedQuery = "INSERT OVERWRITE TABLE `" + outputDatabaseName + "`.`" + outputTableName + "` \n" + "PARTITION (`" + partitionName + "`) \n" + "SELECT * FROM `" + inputDbName + "`.`" + inputTableName + "` WHERE " + "`" + partitionName + "`='" + partitionsDMLInfo.get(partitionName) + "'"; String actualQuery = HiveConverterUtils.generateTableCopy(inputTableName, outputTableName, inputDbName, outputDatabaseName, Optional.of(partitionsDMLInfo)); Assert.assertEquals(expectedQuery, actualQuery); }
/** * Returns all the nodes with down replicas. Note that some replicas for a node may not be marked DOWN, however per * node returned there is at least one replica that was marked DOWN. */ public Map<String, List<ReplicaInfo>> getDownReplicas() { final Map<String, List<ReplicaInfo>> nodeReplicas = getNodeReplicas(); final Map<String, List<ReplicaInfo>> result = Maps.newHashMap(); for (final Entry<String, List<ReplicaInfo>> entry : nodeReplicas.entrySet()) { for (final ReplicaInfo replicaInfo : entry.getValue()) { if (isReplicaDown(replicaInfo.getReplica())) { result.put(entry.getKey(), entry.getValue()); } } } return result; }
private Map<String, List<ITestResult>> buildTestClassGroups(Set<ITestResult> testResults) { Map<String, List<ITestResult>> map = Maps.newHashMap(); for (ITestResult result : testResults) { String className = result.getTestClass().getName(); List<ITestResult> list = map.get(className); if (list == null) { list = Lists.newArrayList(); map.put(className, list); } list.add(result); } return map; }
/** * <pre> * It verifies e2e tls + Authentication + Authorization (client -> proxy -> broker> * * 1. client connects to proxy over tls and pass auth-data * 2. proxy authenticate client and retrieve client-role * and send it to broker as originalPrincipal over tls * 3. client creates producer/consumer via proxy * 4. broker authorize producer/consumer create request using originalPrincipal * * </pre> * * @throws Exception */ @Test public void testTlsSyncProducerAndConsumer() throws Exception { log.info("-- Starting {} test --", methodName); final String proxyServiceUrl = "pulsar://localhost:" + proxyConfig.getServicePortTls(); Map<String, String> authParams = Maps.newHashMap(); authParams.put("tlsCertFile", TLS_CLIENT_CERT_FILE_PATH); authParams.put("tlsKeyFile", TLS_CLIENT_KEY_FILE_PATH); Authentication authTls = new AuthenticationTls(); authTls.configure(authParams); // create a client which connects to proxy over tls and pass authData PulsarClient proxyClient = createPulsarClient(authTls, proxyServiceUrl); admin.clusters().createCluster("use", new ClusterData(brokerUrl.toString(), brokerUrlTls.toString(), "pulsar://localhost:" + BROKER_PORT, "pulsar+ssl://localhost:" + BROKER_PORT_TLS)); admin.properties().createProperty("my-property", new PropertyAdmin(Lists.newArrayList("appid1", "appid2"), Sets.newHashSet("use"))); admin.namespaces().createNamespace("my-property/use/my-ns"); ConsumerConfiguration conf = new ConsumerConfiguration(); conf.setSubscriptionType(SubscriptionType.Exclusive); Consumer consumer = proxyClient.subscribe("persistent://my-property/use/my-ns/my-topic1", "my-subscriber-name", conf); ProducerConfiguration producerConf = new ProducerConfiguration(); Producer producer = proxyClient.createProducer("persistent://my-property/use/my-ns/my-topic1", producerConf); final int msgs = 10; for (int i = 0; i < msgs; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); } Message msg = null; Set<String> messageSet = Sets.newHashSet(); int count = 0; for (int i = 0; i < 10; i++) { msg = consumer.receive(5, TimeUnit.SECONDS); String receivedMessage = new String(msg.getData()); log.debug("Received message: [{}]", receivedMessage); String expectedMessage = "my-message-" + i; testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage); count++; } // Acknowledge the consumption of all messages at once Assert.assertEquals(msgs, count); consumer.acknowledgeCumulative(msg); consumer.close(); log.info("-- Exiting {} test --", methodName); }
@DataProvider(name="dp-without-injection") public static Object[][] dataProviderForBDD(){ Map<Object, Object> m = Maps.newHashMap(); m.put("value", "OK"); return new Object[][]{{m}}; }
@DataProvider(name="dp-with-testngmethod") public Object[][] dataProviderForBDD(ITestNGMethod method){ Map<Object, Object> m = Maps.newHashMap(); m.put("method", method.getMethodName()); return new Object[][]{{m}}; }
@DataProvider(name="dp-with-method") public Object[][] dataProviderForBDD(Method method){ Map<Object, Object> m = Maps.newHashMap(); m.put("method", method.getName()); return new Object[][]{{m}}; }
private void migrateV6toV7() throws SQLException { SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class); Connection connection = session.getJdbcConnectionAccess().obtainConnection(); String contestModuleTable = "uriel_contest_module"; Statement statement = connection.createStatement(); String scoreboardModuleQuery = "SELECT * FROM " + contestModuleTable + " WHERE name = \"SCOREBOARD\";"; ResultSet resultSet = statement.executeQuery(scoreboardModuleQuery); while (resultSet.next()) { long scoreboardId = resultSet.getLong("id"); String jid = resultSet.getString("contestJid"); String scoreboardConfig = resultSet.getString("config"); Map<String, Object> scoreboardConfigMap = new Gson().fromJson(scoreboardConfig, new TypeToken<HashMap<String, Object>>() { }.getType()); Map<String, Object> newScoreboardConfigMap = Maps.newHashMap(scoreboardConfigMap); boolean isOfficialScoreboardAllowed = (boolean) scoreboardConfigMap.get("isOfficialScoreboardAllowed"); newScoreboardConfigMap.remove("isOfficialScoreboardAllowed"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + contestModuleTable + " SET config = ? WHERE id = " + scoreboardId + ";"); preparedStatement.setString(1, new Gson().toJson(newScoreboardConfigMap)); preparedStatement.executeUpdate(); String frozenScoreboardModuleQuery = "SELECT * FROM " + contestModuleTable + " WHERE name = \"FROZEN_SCOREBOARD\" AND contestJid = \"" + jid + "\";"; Statement statement1 = connection.createStatement(); ResultSet resultSet1 = statement1.executeQuery(frozenScoreboardModuleQuery); if (resultSet1.next()) { long frozenScoreboardId = resultSet1.getLong("id"); String frozenScoreboardConfig = resultSet1.getString("config"); Map<String, Object> frozenScoreboardConfigMap = new Gson().fromJson(frozenScoreboardConfig, new TypeToken<HashMap<String, Object>>() { }.getType()); Map<String, Object> newFrozenScoreboardConfigMap = Maps.newHashMap(frozenScoreboardConfigMap); newFrozenScoreboardConfigMap.put("isOfficialScoreboardAllowed", isOfficialScoreboardAllowed); preparedStatement = connection.prepareStatement("UPDATE " + contestModuleTable + " SET config = ? WHERE id = " + frozenScoreboardId + ";"); preparedStatement.setString(1, new Gson().toJson(newFrozenScoreboardConfigMap)); preparedStatement.executeUpdate(); } } }
private void migrateV5toV6() throws SQLException { SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class); Connection connection = session.getJdbcConnectionAccess().obtainConnection(); String contestModuleTable = "uriel_contest_module"; Statement statement = connection.createStatement(); String contestQuery = "SELECT * FROM " + contestModuleTable + " WHERE name = \"CLARIFICATION\" OR name = \"SCOREBOARD\";"; ResultSet resultSet = statement.executeQuery(contestQuery); while (resultSet.next()) { long id = resultSet.getLong("id"); String jid = resultSet.getString("contestJid"); String name = resultSet.getString("name"); String config = resultSet.getString("config"); String userCreate = resultSet.getString("userCreate"); long timeCreate = resultSet.getLong("timeCreate"); String ipCreate = resultSet.getString("ipCreate"); String userUpdate = resultSet.getString("userUpdate"); long timeUpdate = resultSet.getLong("timeUpdate"); String ipUpdate = resultSet.getString("ipUpdate"); Map<String, Object> configMap = new Gson().fromJson(config, new TypeToken<HashMap<String, Object>>() { }.getType()); Map<String, Object> newConfigMap = Maps.newHashMap(configMap); if ("CLARIFICATION".equals(name)) { long clarificationDuration = (long) (double) configMap.get("clarificationDuration"); Map<String, Long> clarificationTimeLimitConfigMap = ImmutableMap.of("clarificationDuration", clarificationDuration); newConfigMap.remove("clarificationDuration"); insertIntoModule(connection, contestModuleTable, jid, "CLARIFICATION_TIME_LIMIT", new Gson().toJson(clarificationTimeLimitConfigMap), userCreate, timeCreate, ipCreate, userUpdate, timeUpdate, ipUpdate); } else if ("SCOREBOARD".equals(name)) { long scoreboardFreezeTime = (long) (double) configMap.get("scoreboardFreezeTime"); Map<String, Long> scoreboardFreezeTimeConfigMap = ImmutableMap.of("scoreboardFreezeTime", scoreboardFreezeTime); newConfigMap.remove("scoreboardFreezeTime"); insertIntoModule(connection, contestModuleTable, jid, "FROZEN_SCOREBOARD", new Gson().toJson(scoreboardFreezeTimeConfigMap), userCreate, timeCreate, ipCreate, userUpdate, timeUpdate, ipUpdate); } PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + contestModuleTable + " SET config = ? WHERE id = " + id + ";"); preparedStatement.setString(1, new Gson().toJson(newConfigMap)); preparedStatement.executeUpdate(); } }