auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Map<String, Serializable> getMetadata() throws RepositoryException { if ( metadata == null ) { this.executeOperation( new SessionOperation() { @Override public void execute( Session session ) { try { metadata = JcrRepositoryFileUtils.getFileMetadata( session, getId() ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { getLogger().warn( "InvalidItemStateException. Probable cause: File does not exist anymore" ); } catch ( RepositoryException e ) { getLogger().error( "RepositoryException was found: ", e ); } } } ); } return metadata; }

Target:
Map<String, Serializable> getMetadata() throws RepositoryException { if ( metadata == null ) { this.executeOperation( new SessionOperation() { @Override public void execute( Session session ) { try { metadata = JcrRepositoryFileUtils.getFileMetadata( session, getId() ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { getLogger().warn( "InvalidItemStateException in getMetadata. Probable cause: File does not exist anymore" ); } catch ( RepositoryException e ) { getLogger().error( "RepositoryException was found: ", e ); } } } ); } return metadata; }
Source:
public FileSplit[] getSplits(JobConf job, int numSplits) throws IOException { Settings settings = HadoopSettingsManager.loadFrom(job); Log log = LogFactory.getLog(getClass()); InitializationUtils.setValueReaderIfNotSet(settings, HiveValueReader.class, log); if (settings.getOutputAsJson() == false) { settings.setProperty(InternalConfigurationOptions.INTERNAL_ES_TARGET_FIELDS, StringUtils.concatenate(HiveUtils.columnToAlias(settings), ",")); } settings.setResourceRead(settings.getResourceRead()); HiveUtils.init(settings, log); String filterObjectStr = job.get(TableScanDesc.FILTER_OBJECT_CONF_STR); if (filterObjectStr != null && filterObjectStr.length() > 0) { String esQuery = Utilities.deserializeObject(filterObjectStr, String.class); if (esQuery != null && esQuery.length() > 0) { log.info("[EsHiveInputFormat][Pushdown][Es.query] : " + esQuery); settings.setQuery(esQuery); } } InputSplit[] shardSplits = super.getSplits(job, numSplits); FileSplit[] wrappers = new FileSplit[shardSplits.length]; Path path = new Path(job.get(HiveConstants.TABLE_LOCATION)); for (int i = 0; i < wrappers.length; i++) { wrappers[i] = new EsHiveSplit(shardSplits[i], path); } return wrappers; }

Target:
public FileSplit[] getSplits(JobConf job, int numSplits) throws IOException { Settings settings = HadoopSettingsManager.loadFrom(job); Log log = LogFactory.getLog(getClass()); InitializationUtils.setValueReaderIfNotSet(settings, HiveValueReader.class, log); InitializationUtils.setUserProviderIfNotSet(settings, HadoopUserProvider.class, log); if (settings.getOutputAsJson() == false) { settings.setProperty(InternalConfigurationOptions.INTERNAL_ES_TARGET_FIELDS, StringUtils.concatenate(HiveUtils.columnToAlias(settings), ",")); } HiveUtils.init(settings, log); String filterObjectStr = job.get(TableScanDesc.FILTER_OBJECT_CONF_STR); if (filterObjectStr != null && filterObjectStr.length() > 0) { String filters = Utilities.deserializeObject(filterObjectStr, String.class); if (filters != null && filters.length() > 0) { log.info(String.format("[EsHiveInputFormat][Pushdown][Filters] %s", filters)); SettingsUtils.setFilters(settings, filters); } } InputSplit[] shardSplits = super.getSplits(job, numSplits); FileSplit[] wrappers = new FileSplit[shardSplits.length]; Path path = new Path(job.get(HiveConstants.TABLE_LOCATION)); for (int i = 0; i < wrappers.length; i++) { wrappers[i] = new EsHiveSplit(shardSplits[i], path); } return wrappers; }
Source:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); CoordinatorProxyService coordinator = new CoordinatorProxyService(config, storeClientConfigs); services.add(coordinator); if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }

Target:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); services.add(new CoordinatorProxyService(config, storeClientConfigs)); if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }
Source:
public PatientData<Object> load(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException("The patient does not have a PatientClass"); } Map<String, Object> result = new LinkedHashMap<String, Object>(); ListProperty allergiesListProperty = (ListProperty) data.get(ALLERGIES); List<String> allergiesList = allergiesListProperty.getList(); result.put(ALLERGIES, allergiesList); IntegerProperty nkdaProperty = (IntegerProperty) data.get(NKDA); Integer nkdaInteger = (Integer) nkdaProperty.getValue(); Boolean nkda = Boolean.TRUE; if (nkdaInteger != 1) { nkda = Boolean.FALSE; } result.put(NKDA, nkda); return new DictionaryPatientData<>(getName(), result); } catch (Exception e) { this.logger.error( "Could not find requested document or some unforeseen error has occurred during controller loading"); } return null; }

Target:
public PatientData<Object> load(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException("The patient does not have a PatientClass"); } Map<String, Object> result = new LinkedHashMap<String, Object>(); ListProperty allergiesListProperty = (ListProperty) data.get(ALLERGIES); List<String> allergiesList = allergiesListProperty.getList(); result.put(ALLERGIES, allergiesList); IntegerProperty nkdaProperty = (IntegerProperty) data.get(NKDA); Integer nkdaInteger = (Integer) nkdaProperty.getValue(); boolean nkda = nkdaInteger == 1; result.put(NKDA, nkda); return new DictionaryPatientData<>(getName(), result); } catch (Exception e) { this.logger.error( "Could not find requested document or some unforeseen error has occurred during controller loading.", e); } return null; }
Source:
public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }

Target:
private String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }
Source:
private <K, V> RemoteCache<K, V> createRemoteCache(String cacheName, Boolean forceReturnValueOverride) { synchronized (cacheName2RemoteCache) { RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValueOverride); if (!cacheName2RemoteCache.containsKey(key)) { RemoteCacheImpl<K, V> result = createRemoteCache(cacheName); RemoteCacheHolder rcc = new RemoteCacheHolder(result, forceReturnValueOverride == null ? configuration.forceReturnValues() : forceReturnValueOverride); startRemoteCache(rcc); if (configuration.pingOnStartup()) { if (!cacheName.equals(RemoteCacheManager.DEFAULT_CACHE_NAME) && ping(result) == PingResult.CACHE_DOES_NOT_EXIST) { return null; } } result.resolveCompatibility(); result.start(); cacheName2RemoteCache.put(key, rcc); return result; } else { return (RemoteCache<K, V>) cacheName2RemoteCache.get(key).remoteCache; } } }

Target:
private <K, V> RemoteCache<K, V> createRemoteCache(String cacheName, Boolean forceReturnValueOverride) { synchronized (cacheName2RemoteCache) { RemoteCacheKey key = new RemoteCacheKey(cacheName, forceReturnValueOverride); if (!cacheName2RemoteCache.containsKey(key)) { RemoteCacheImpl<K, V> result = createRemoteCache(cacheName); RemoteCacheHolder rcc = new RemoteCacheHolder(result, forceReturnValueOverride == null ? configuration.forceReturnValues() : forceReturnValueOverride); startRemoteCache(rcc); PingResult pingResult = result.resolveCompatibility(); if (!cacheName.equals(RemoteCacheManager.DEFAULT_CACHE_NAME) && pingResult == PingResult.CACHE_DOES_NOT_EXIST) { return null; } result.start(); cacheName2RemoteCache.put(key, rcc); return result; } else { return (RemoteCache<K, V>) cacheName2RemoteCache.get(key).remoteCache; } } }
Source:
private boolean isAllGroupImplicit(XWikiContext context) { return context.getWiki().isAllGroupImplicit(); }

Target:
protected boolean isAllGroupImplicit(XWikiContext context) { return context.getWiki().isAllGroupImplicit(); }
Source:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof AbstractJpaDao) { try { AbstractJpaDao abstractJpaDao = (AbstractJpaDao) createAndInjectMembers(dao); return (T) abstractJpaDao; } catch (Exception e) { log.error("Can't initialize an AbstractJpaDao for entity " + daoType, e); } } else { return (T) dao; } } } log.error("Can't find dao for " + daoType); return null; }

Target:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof AbstractJpaDao) { try { AbstractJpaDao abstractJpaDao = (AbstractJpaDao) createAndInjectMembers(dao); return (T) abstractJpaDao; } catch (Exception e) { log.error("Can't initialize an AbstractJpaDao for entity {}: ", daoType, e.getMessage()); log.debug("Exception: ", e); } } else { return (T) dao; } } } log.error("Can't find dao for " + daoType); return null; }
Source:
protected void executeQueryCommand() { Provider provider = getDbFacade().getProviderDao().get(getParameters().getId()); NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }

Target:
protected void executeQueryCommand() { Provider<?> provider = getDbFacade().getProviderDao().get(getParameters().getId()); NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }
Source:
public static GranularityType fromPeriod(Period period) { int[] vals = period.getValues(); BitSet bs = new BitSet(); for (int i = 0; i < vals.length; i++) { if (vals[i] != 0) { bs.set(i); } } if (bs.cardinality() == 0 || bs.cardinality() > 1) { throw new IAE("Granularity is not supported. [%s]", period); } else { final int index = bs.nextSetBit(0); if (index == 0) { return GranularityType.YEAR; } if (index == 1) { if (vals[index] == 4) { return GranularityType.QUARTER; } else if (vals[index] == 1) { return GranularityType.MONTH; } } if (index == 2) { return GranularityType.WEEK; } if (index == 3) { return GranularityType.DAY; } if (index == 4) { if (vals[index] == 6) { return GranularityType.SIX_HOUR; } else if (vals[index] == 1) { return GranularityType.HOUR; } } if (index == 5) { if (vals[index] == 30) { return GranularityType.THIRTY_MINUTE; } else if (vals[index] == 15) { return GranularityType.FIFTEEN_MINUTE; } else if (vals[index] == 10) { return GranularityType.TEN_MINUTE; } else if (vals[index] == 5) { return GranularityType.FIVE_MINUTE; } else if (vals[index] == 1) { return GranularityType.MINUTE; } } if (index == 6) { return GranularityType.SECOND; } } throw new IAE("Granularity is not supported. [%s]", period); }

Target:
public static GranularityType fromPeriod(Period period) { int[] vals = period.getValues(); int index = -1; for (int i = 0; i < vals.length; i++) { if (vals[i] != 0) { if (index < 0) { index = i; } else { throw new IAE("Granularity is not supported. [%s]", period); } } } switch (index) { case 0: return GranularityType.YEAR; case 1: if (vals[index] == 4) { return GranularityType.QUARTER; } else if (vals[index] == 1) { return GranularityType.MONTH; } break; case 2: return GranularityType.WEEK; case 3: return GranularityType.DAY; case 4: if (vals[index] == 6) { return GranularityType.SIX_HOUR; } else if (vals[index] == 1) { return GranularityType.HOUR; } break; case 5: if (vals[index] == 30) { return GranularityType.THIRTY_MINUTE; } else if (vals[index] == 15) { return GranularityType.FIFTEEN_MINUTE; } else if (vals[index] == 10) { return GranularityType.TEN_MINUTE; } else if (vals[index] == 5) { return GranularityType.FIVE_MINUTE; } else if (vals[index] == 1) { return GranularityType.MINUTE; } break; case 6: return GranularityType.SECOND; default: break; } throw new IAE("Granularity is not supported. [%s]", period); }
Source:
private static String getISO8601FormattedLastSyncTime() { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(SyncDetailCalculations.getLastSyncTime()); }

Target:
private static String getISO8601FormattedLastSyncTime() { long lastSyncTime = SyncDetailCalculations.getLastSyncTime(); if (lastSyncTime == 0) { return ""; } else { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(lastSyncTime); } }
Source:
public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { throw new JadbException(e.getMessage()); } }

Target:
public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { throw new JadbException(e); } }
Source:
private List<String> splitArguments() { final int argLength = arguments.length(); sb = new StringBuffer(argLength); boolean insideQuotas = false; for (int i = 0; i < argLength; i++) { char ch = arguments.charAt(i); if (ch == '"' || ch == '\'') { insideQuotas = !insideQuotas; } if (ch == argumentDelimiter && !insideQuotas) { pushArg(); i++; } sb.append(ch); } pushArg(); return argList; }

Target:
private List<String> splitArguments() { final int argLength = arguments.length(); StringBuilder sb = new StringBuilder(argLength); boolean insideQuotas = false; int bracesBlock = 0; for (int i = 0; i < argLength; i++) { char ch = arguments.charAt(i); if (ch == '"' || ch == '\'') { insideQuotas = !insideQuotas; } else if (ch == '(') { bracesBlock++; } else if (ch == ')') { bracesBlock--; } else if (ch == argumentDelimiter && !insideQuotas && bracesBlock == 0) { pushArg(sb); sb = new StringBuilder(argLength); } sb.append(ch); } pushArg(sb); return argList; }
Source:
public boolean isRecipientOptionDisplayed(FeedbackParticipantType recipientType, int questionNumber) { WebElement recipientOption = browser.driver.findElement( By.cssSelector("#recipienttype-" + questionNumber + " option[value='" + recipientType + "']")); return "block".equals(recipientOption.getCssValue("display")); }

Target:
public boolean isRecipientOptionDisplayed(FeedbackParticipantType recipientType, int questionNumber) { WebElement recipientOption = browser.driver.findElement( By.cssSelector("#recipienttype-" + questionNumber + " option[value='" + recipientType + "']")); return !"none".equals(recipientOption.getCssValue("display")); }
Source:
public InMemoryCircuitBreakerRegistry() { this.defaultCircuitBreakerConfig = CircuitBreakerConfig.ofDefaults(); this.circuitBreakers = new ConcurrentHashMap<>(); this.postCreationConsumers = new ArrayList<>(); }

Target:
public InMemoryCircuitBreakerRegistry() { this(CircuitBreakerConfig.ofDefaults()); }
Source:
public Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { int ebnf = 0; if ( ebnfRoot!=null ) ebnf = ebnfRoot.getType(); Choice c = null; switch ( ebnf ) { case ANTLRParser.OPTIONAL : if ( alts.size()==1 ) c = new LL1OptionalBlockSingleAlt(this, ebnfRoot, alts); else c = new LL1OptionalBlock(this, ebnfRoot, alts); break; case ANTLRParser.CLOSURE : c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts); break; case ANTLRParser.POSITIVE_CLOSURE : c = new LL1PlusBlockSingleAlt(this, ebnfRoot, alts); break; } return c; }

Target:
public Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { int ebnf = 0; if ( ebnfRoot!=null ) ebnf = ebnfRoot.getType(); Choice c = null; switch ( ebnf ) { case ANTLRParser.OPTIONAL : if ( alts.size()==1 ) c = new LL1OptionalBlockSingleAlt(this, ebnfRoot, alts); else c = new LL1OptionalBlock(this, ebnfRoot, alts); break; case ANTLRParser.CLOSURE : if ( alts.size()==1 ) c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts); else c = getComplexEBNFBlock(ebnfRoot, alts); break; case ANTLRParser.POSITIVE_CLOSURE : if ( alts.size()==1 ) c = new LL1PlusBlockSingleAlt(this, ebnfRoot, alts); else c = getComplexEBNFBlock(ebnfRoot, alts); break; } return c; }
Source:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { if (value instanceof EObject) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; }

Target:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } return ret; }
Source:
public SingleDimensionPartitionsSpec( @JsonProperty(DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT) @Nullable Integer targetRowsPerSegment, @JsonProperty(PartitionsSpec.MAX_ROWS_PER_SEGMENT) @Nullable Integer maxRowsPerSegment, @JsonProperty("partitionDimension") @Nullable String partitionDimension, @JsonProperty("assumeGrouped") boolean assumeGrouped, @Deprecated @JsonProperty(DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE) @Nullable Integer targetPartitionSize, @Deprecated @JsonProperty(MAX_PARTITION_SIZE) @Nullable Integer maxPartitionSize ) { Property<Integer> target = checkAtMostOneNotNull( TARGET_ROWS_PER_SEGMENT, targetRowsPerSegment, TARGET_PARTITION_SIZE, targetPartitionSize ); Property<Integer> max = checkAtMostOneNotNull( MAX_ROWS_PER_SEGMENT, maxRowsPerSegment, MAX_PARTITION_SIZE, maxPartitionSize ); Preconditions.checkArgument( (target.value == null) != (max.value == null), "Exactly one of " + target.name + " or " + max.name + " must be present" ); this.partitionDimension = partitionDimension; this.assumeGrouped = assumeGrouped; this.targetRowsPerSegment = target.value; this.maxRowsPerSegment = max.value; this.resolvedMaxRowPerSegment = resolveMaxRowsPerSegment(target, max); }

Target:
public SingleDimensionPartitionsSpec( @JsonProperty(DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT) @Nullable Integer targetRowsPerSegment, @JsonProperty(PartitionsSpec.MAX_ROWS_PER_SEGMENT) @Nullable Integer maxRowsPerSegment, @JsonProperty("partitionDimension") @Nullable String partitionDimension, @JsonProperty("assumeGrouped") boolean assumeGrouped, @Deprecated @JsonProperty(DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE) @Nullable Integer targetPartitionSize, @Deprecated @JsonProperty(MAX_PARTITION_SIZE) @Nullable Integer maxPartitionSize ) { Property<Integer> target = Checks.checkAtMostOneNotNull( DimensionBasedPartitionsSpec.TARGET_ROWS_PER_SEGMENT, targetRowsPerSegment, DimensionBasedPartitionsSpec.TARGET_PARTITION_SIZE, targetPartitionSize ); Property<Integer> max = Checks.checkAtMostOneNotNull( PartitionsSpec.MAX_ROWS_PER_SEGMENT, maxRowsPerSegment, MAX_PARTITION_SIZE, maxPartitionSize ); Preconditions.checkArgument( (target.getValue() == null) != (max.getValue() == null), "Exactly one of " + target.getName() + " or " + max.getName() + " must be present" ); this.partitionDimension = partitionDimension; this.assumeGrouped = assumeGrouped; this.targetRowsPerSegment = target.getValue(); this.maxRowsPerSegment = max.getValue(); this.resolvedMaxRowPerSegment = resolveMaxRowsPerSegment(target, max); }
Source:
public URL getResource(String name) { try { return new URL("jar", "", name); } catch(MalformedURLException e) { e.printStackTrace(); fail("Could not even create disfunct library URL."); return null; } }

Target:
public URL getResource(String name) { try { return new URL("jar", "", name); } catch(MalformedURLException e) { fail("Could not even create disfunct library URL: " + e.getMessage()); return null; } }
Source:
public void testBindFilteredEventsToMethod() { final MultipleEventSource src = new MultipleEventSource(); final EventCounter counter = new EventCounter(); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1"); assertEquals(0, counter.getCount()); src.listeners.fire().event1(new PropertyChangeEvent(new Date(), "Day", 0, 1)); assertEquals(1, counter.getCount()); src.listeners.fire().event2(new PropertyChangeEvent(new Date(), "Day", 1, 2)); assertEquals(1, counter.getCount()); }

Target:
public void testBindFilteredEventsToMethod() { final MultipleEventSource src = new MultipleEventSource(); final EventCounter counter = new EventCounter(); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1"); assertEquals(0, counter.getCount()); src.listeners.fire().event1(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(0), Integer.valueOf(1))); assertEquals(1, counter.getCount()); src.listeners.fire().event2(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(1), Integer.valueOf(2))); assertEquals(1, counter.getCount()); }
Source:
public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(); ProducerRecord<String, String> record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, this.numPartitions), key, value); if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); KafkaCallback callback; if ( KafkaCallback.LOGGER.isDebugEnabled() ) callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); else callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, null, null); kafka.send(record, callback); }

Target:
public void push(RowMap r) throws Exception { String key = r.pkToJson(keyFormat); String value = r.toJSON(); ProducerRecord<String, String> record = new ProducerRecord<>(topic, this.partitioner.kafkaPartition(r, this.numPartitions), key, value); if ( r.isTXCommit() ) inflightMessages.addMessage(r.getPosition()); if ( !KafkaCallback.LOGGER.isDebugEnabled() ) value = null; KafkaCallback callback = new KafkaCallback(inflightMessages, r.getPosition(), r.isTXCommit(), this.context, key, value); kafka.send(record, callback); }
Source:
private void onSendCallback(DatastreamRecordMetadata metadata, Exception exception, SendCallback sendCallback, DatastreamTask task, DatastreamProducerRecord record) { SendFailedException sendFailedException = null; if (exception != null) { sendFailedException = new SendFailedException(_safeCheckpoints); if (_onUnrecoverableError != null) { _onUnrecoverableError.accept(this); } } else { for (Pair<byte[], byte[]> event : record.getEvents()) { try { DatastreamEvent datastreamEvent = AvroUtils.decodeAvroSpecificRecord(DatastreamEvent.class, event.getValue()); DatastreamUtils.processEventMetadata(datastreamEvent); Optional<Long> eventLatency = Optional.ofNullable(datastreamEvent.metadata.get(DatastreamEventMetadata.EVENT_TIMESTAMP)) .map(metaVal -> metaVal.toString()) .map(eventTimestamp -> System.currentTimeMillis() - Long.valueOf(eventTimestamp)); eventLatency.ifPresent(latency -> { if (latency <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } TOTAL_EVENTS_PRODUCED.inc(); }); } catch (IOException e) { _logger.warn("Unable to decode DatastreamEvent " + event.getValue(), e); } } try { _checkpointRWLock.readLock().lock(); if (!_safeCheckpoints.containsKey(task)) { _logger.warn(String.format("Event of unknown task is being acknowledged: task=%s, record=%s", task, record)); } else { _safeCheckpoints.get(task).put(metadata.getPartition(), record.getCheckpoint()); _pendingCheckpoints.set(true); } } finally { _checkpointRWLock.readLock().unlock(); } } if (sendCallback != null) { sendCallback.onCompletion(metadata, sendFailedException); } if (exception != null) { shutdown(); } }

Target:
private void onSendCallback(DatastreamRecordMetadata metadata, Exception exception, SendCallback sendCallback, DatastreamTask task, DatastreamProducerRecord record) { SendFailedException sendFailedException = null; if (exception != null) { sendFailedException = new SendFailedException(_safeCheckpoints); if (_onUnrecoverableError != null) { _onUnrecoverableError.accept(this); } } else { if (System.currentTimeMillis() - record.getEventsTimestamp() <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } TOTAL_EVENTS_PRODUCED.inc(); try { _checkpointRWLock.readLock().lock(); if (!_safeCheckpoints.containsKey(task)) { _logger.warn(String.format("Event of unknown task is being acknowledged: task=%s, record=%s", task, record)); } else { _safeCheckpoints.get(task).put(metadata.getPartition(), record.getCheckpoint()); _pendingCheckpoints.set(true); } } finally { _checkpointRWLock.readLock().unlock(); } } if (sendCallback != null) { sendCallback.onCompletion(metadata, sendFailedException); } if (exception != null) { shutdown(); } }
Source:
public Parser<String, Object> makeParser() { parser = parser == null ? new JavaScriptParser(function) : parser; return parser; }

Target:
public Parser<String, Object> makeParser() { Preconditions.checkState(config.isEnabled(), "JavaScript is disabled"); parser = parser == null ? new JavaScriptParser(function) : parser; return parser; }
Source:
public RestApp() { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); register(new SuggesterAppBinder()); register(CorsFilter.class); packages("org.opengrok.web.api.constraints", "org.opengrok.web.api.error"); packages(true, "org.opengrok.web.api.v1"); }

Target:
public RestApp() { register(new SuggesterAppBinder()); packages("org.opengrok.web.api.constraints", "org.opengrok.web.api.error"); packages(true, "org.opengrok.web.api.v1"); }
Source:
public Collection<SnomedConceptIndexEntry> getProximalPrimitiveParents(String nodeId) { final Set<String> proximalPrimitiveParentIds = newHashSet(); for (SnomedConceptIndexEntry ancestor : getAncestors(nodeId)) { if (ancestor.isPrimitive()) { final String primitiveAncestorId = ancestor.getId(); if (proximalPrimitiveParentIds.isEmpty()) { proximalPrimitiveParentIds.add(primitiveAncestorId); } else { boolean doAdd = true; for (String id : newHashSet(proximalPrimitiveParentIds)) { if (isSubTypeOf(primitiveAncestorId, id)) { proximalPrimitiveParentIds.remove(id); proximalPrimitiveParentIds.add(primitiveAncestorId); doAdd = false; } else if (doAdd && isSuperTypeOf(primitiveAncestorId, id)) { doAdd = false; } } if (doAdd) { proximalPrimitiveParentIds.add(primitiveAncestorId); } } } } return getNodes(proximalPrimitiveParentIds); }

Target:
public Collection<SnomedConceptIndexEntry> getProximalPrimitiveParents(String nodeId) { return getNodes(getProximalPrimitiveParentIds(nodeId)); }
Source:
public Position center() { int halfWidth = width() >> 1; int centerX = southWestX + halfWidth; int centerY = southWestY + halfWidth; return new Position(centerX, centerY); }

Target:
public Position center() { int halfWidth = width() / 2; int centerX = southWestX + halfWidth; int centerY = southWestY + halfWidth; return new Position(centerX, centerY); }
Source:
public synchronized File getTemporaryDirectory() { if ( temporaryDirectory == null ) { final File file = new File( System.getProperty( "java.io.tmpdir" ) ); if ( !file.exists() ) { file.mkdirs(); } temporaryDirectory = canonicalize( file ); } return temporaryDirectory; }

Target:
public synchronized File getTemporaryDirectory() { if ( temporaryDirectory == null ) { final File file = new File( System.getProperty( "java.io.tmpdir" ) ); forceMkdir( file ); temporaryDirectory = canonicalize( file ); } return temporaryDirectory; }
Source:
private EndpointIterator(final List<Endpoint> endpoints) { this.endpoints = checkNotNull(endpoints); size = endpoints.size(); cursor = size == 0 ? 0 : new Random().nextInt(size); }

Target:
private EndpointIterator(final List<Endpoint> endpoints) { this.endpoints = ImmutableList.copyOf(checkNotNull(endpoints)); size = this.endpoints.size(); cursor = size == 0 ? 0 : new Random().nextInt(size); }
Source:
public Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { ImmutableMap.Builder<SchemaTableName, ConnectorViewDefinition> views = ImmutableMap.builder(); List<SchemaTableName> tableNames; if (prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listViews(session, prefix.getSchemaName()); } for (SchemaTableName schemaTableName : tableNames) { Optional<Table> table = metastore.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent() && HiveUtil.isPrestoView(table.get())) { views.put(schemaTableName, new ConnectorViewDefinition( schemaTableName, Optional.ofNullable(table.get().getOwner()), decodeViewData(table.get().getViewOriginalText().get()), Optional.empty())); } } return views.build(); }

Target:
public Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { ImmutableMap.Builder<SchemaTableName, ConnectorViewDefinition> views = ImmutableMap.builder(); List<SchemaTableName> tableNames; if (prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listViews(session, prefix.getSchemaName()); } for (SchemaTableName schemaTableName : tableNames) { Optional<Table> table = metastore.getTable(schemaTableName.getSchemaName(), schemaTableName.getTableName()); if (table.isPresent() && HiveUtil.isPrestoView(table.get())) { views.put(schemaTableName, new ConnectorViewDefinition( schemaTableName, Optional.ofNullable(table.get().getOwner()), decodeViewData(table.get().getViewOriginalText().get()), Optional.ofNullable(table.get().getParameters().get(TABLE_COMMENT)))); } } return views.build(); }
Source:
public CosemDateTimeDto getDaylightSavingsBegin() { return new CosemDateTimeDto(this.daylightSavingsBegin); }

Target:
public CosemDateTimeDto getDaylightSavingsBegin() { return this.daylightSavingsBegin; }
Source:
public RepositoryVersion(@NonNull String version) { Matcher matcher1 = MAJOR_MINOR_MICRO_VERSION_PATTERN.matcher(version); Matcher matcher2 = MAJOR_MINOR_QUALIFIER_VERSION_PATTERN.matcher(version); Matcher matcher3 = MAJOR_MINOR_MICRO_QUALIFIER_VERSION_PATTERN.matcher(version); if (matcher1.matches()) { major = parseInt(matcher1.group(1)); minor = parseInt(matcher1.group(2)); if (matcher1.group(4) != null) { micro = parseInt(matcher1.group(4)); } else { micro = null; } qualifier = null; } else if (matcher3.matches()) { major = parseInt(matcher3.group(1)); minor = parseInt(matcher3.group(2)); micro = parseInt(matcher3.group(3)); qualifier = (matcher3.group(4)); } else if (matcher2.matches()) { major = parseInt(matcher2.group(1)); minor = parseInt(matcher2.group(2)); micro = null; qualifier = matcher2.group(3); } else { qualifier = version; } }

Target:
public RepositoryVersion(@NonNull String version) { orgVersion = version; Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (versionMatcher.matches()) { major = parseInt(versionMatcher.group(2)); if (versionMatcher.group(5) != null) { minor = parseInt(versionMatcher.group(5)); } else { minor = null; } if (versionMatcher.group(7) != null) { micro = parseInt(versionMatcher.group(7)); } else { micro = null; } if (versionMatcher.group(8) != null) { qualifier = (versionMatcher.group(8)); } else { qualifier = null; } } else { qualifier = version; } }
Source:
private void forAll(List<Traversable<?>> traversables, boolean value) { for (Traversable<?> traversable1 : traversables) { for (Traversable<?> traversable2 : traversables) { if (traversable1 != traversable2) { assertThat(traversable1.equals(traversable2)).isEqualTo(value); } } } }

Target:
private void forAll(List<Traversable<?>> traversables, boolean value) { for (Traversable<?> traversable1 : traversables) { for (Traversable<?> traversable2 : traversables) { if (traversable1 != traversable2) { assertThat(traversable1.equals(traversable2)).isEqualTo(value); if (value) { assertThat(traversable1.hashCode() == traversable2.hashCode()).isTrue(); } } } } }
Source:
private boolean isHighPriority(IInvokedMethod method) { try { checkForTestAnnotation(method); } catch (IllegalStateException e) { return true; } int high = method.getTestMethod().getPriority(); for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) { if (test.getEnabled() && test.getPriority() > high) { return false; } } Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class); if (!(t.dataProvider().isEmpty())) { int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount(); int parameterInvocationCount = method.getTestMethod().getParameterInvocationCount(); return (currentInvocationCount == parameterInvocationCount); } return true; }

Target:
private boolean isHighPriority(IInvokedMethod method) { if (!isAnnotatedWithTest(method)) { return true; } int high = method.getTestMethod().getPriority(); for (ITestNGMethod test : method.getTestMethod().getTestClass().getTestMethods()) { if (test.getEnabled() && test.getPriority() > high) { return false; } } Test t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class); if (!(t.dataProvider().isEmpty())) { int currentInvocationCount = method.getTestMethod().getCurrentInvocationCount(); int parameterInvocationCount = method.getTestMethod().getParameterInvocationCount(); return (currentInvocationCount == parameterInvocationCount); } return true; }
Source:
public void testLeaderMetrics() throws Exception { System.setProperty(Leader.ACK_LOGGING_FREQUENCY, "1"); ServerMetrics.resetAll(); QuorumUtil util = new QuorumUtil(1); util.startAll(); ZooKeeper zk = ClientBase.createZKClient(util.getConnString()); createdLatch = new CountDownLatch(1); zk.exists("/test", new MyWatcher()); zk.create("/test", new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); createdLatch.await(); Map<String, Object> values = ServerMetrics.getAllValues(); Assert.assertEquals(2L, values.get("proposal_count")); Assert.assertEquals(2L, values.get("cnt_quorum_ack_latency")); Assert.assertThat((long)values.get("min_quorum_ack_latency"), greaterThan(0L)); int numberOfAckServers = 0; for (int sid = 1; sid<=3; sid++) { String metricName = "min_" + sid + "_ack_latency"; if (values.get(metricName) != null) { numberOfAckServers++; Assert.assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L)); } } Assert.assertThat(numberOfAckServers, greaterThanOrEqualTo(2)); zk.close(); util.shutdownAll(); }

Target:
public void testLeaderMetrics() throws Exception { Leader.setAckLoggingFrequency(1); ServerMetrics.getMetrics().resetAll(); QuorumUtil util = new QuorumUtil(1); util.startAll(); ZooKeeper zk = ClientBase.createZKClient(util.getConnString()); createdLatch = new CountDownLatch(1); zk.exists("/test", new MyWatcher()); zk.create("/test", new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); createdLatch.await(); Map<String, Object> values = MetricsUtils.currentServerMetrics(); Assert.assertEquals(2L, values.get("proposal_count")); Assert.assertEquals(2L, values.get("cnt_quorum_ack_latency")); Assert.assertThat((long)values.get("min_quorum_ack_latency"), greaterThan(0L)); int numberOfAckServers = 0; for (int sid = 1; sid<=3; sid++) { String metricName = "min_" + sid + "_ack_latency"; if (values.get(metricName) != null) { numberOfAckServers++; Assert.assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L)); } } Assert.assertThat(numberOfAckServers, greaterThanOrEqualTo(2)); zk.close(); util.shutdownAll(); }
Source:
protected BinaryObject(PID pid, Repository repository, RepositoryObjectDataLoader dataLoader) { super(pid, repository, dataLoader); metadataUri = URI.create(pid.getRepositoryUri().toString() + RepositoryPathConstants.FCR_METADATA); }

Target:
protected BinaryObject(PID pid, Repository repository, RepositoryObjectDataLoader dataLoader) { super(pid, repository, dataLoader); metadataUri = URI.create(URIUtil.join(pid.getRepositoryUri(), RepositoryPathConstants.FCR_METADATA)); }
Source:
public Connection getConnection() throws SQLException { Connection connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } connection.close(); for (int i = 0; i < MAX_TRIES_NEW_CONNECTION; i++) { if(logger.isEnabledFor(Priority.WARN)){ logger.warn("Connection failed: Trying to get new connection. Attempt:" + i); } connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } connection.close(); } logger.warn("Connection failed: Trying to get a connection from a new ConnectionManager"); SqlConfiguration config = SqlConfiguration.getInstance(); this.cm = new ConnectionManager(config); connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } logger.error("Connection failed!"); return connection; }

Target:
public Connection getConnection() throws SQLException { Connection connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } for (int i = 0; i < MAX_TRIES_NEW_CONNECTION; i++) { if(logger.isEnabledFor(Priority.WARN)){ logger.warn("Connection failed: Trying to get new connection. Attempt:" + i); } connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } } logger.warn("Connection failed: Trying to get a connection from a new ConnectionManager"); SqlConfiguration config = SqlConfiguration.getInstance(); this.cm = new ConnectionManager(config); connection = this.cm.getDataSource().getConnection(); if (connection.isValid(TIME_FOR_CONNECTION_VALID_CHECK)) { return connection; } logger.error("Connection failed!"); return connection; }
Source:
public boolean ingestableAsTabular(DataFile dataFile) { String mimeType = dataFile.getContentType(); if (mimeType == null) { return false; } switch (mimeType) { case MIME_TYPE_STATA: return true; case MIME_TYPE_STATA13: return true; case MIME_TYPE_RDATA: return true; case MIME_TYPE_CSV: case MIME_TYPE_CSV_ALT: return true; case MIME_TYPE_XLSX: return true; case MIME_TYPE_SPSS_SAV: return true; case MIME_TYPE_SPSS_POR: return true; } return false; }

Target:
public boolean ingestableAsTabular(DataFile dataFile) { String mimeType = dataFile.getContentType(); if (mimeType == null) { return false; } switch (mimeType) { case MIME_TYPE_STATA: case MIME_TYPE_STATA13: case MIME_TYPE_RDATA: case MIME_TYPE_CSV: case MIME_TYPE_CSV_ALT: case MIME_TYPE_XLSX: case MIME_TYPE_SPSS_SAV: case MIME_TYPE_SPSS_POR: return true; } return false; }
Source:
public Collection<Object> getAttributeValues(IAtsObject atsObject, IAttributeType attributeType) { return getAttributeValues(atsObject.getStoreObject(), attributeType); }

Target:
public Collection<Object> getAttributeValues(IAtsObject atsObject, IAttributeType attributeType) { Assert.isNotNull(atsObject, "ATS Object can not be null"); Assert.isNotNull(attributeType, "Attribute Type can not be null"); return getAttributeValues(atsObject.getStoreObject(), attributeType); }
Source:
void setMaximumPoolSize(int maximumPoolSize) { if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).setMaximumPoolSize(maximumPoolSize); } else { throw new UnsupportedOperationException(); } }

Target:
void setMaximumPoolSize(int maximumPoolSize) { if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).setMaximumPoolSize(maximumPoolSize); if (!(((ThreadPoolExecutor)executor).getQueue() instanceof SynchronousQueue)) { ((ThreadPoolExecutor) executor).setCorePoolSize(maximumPoolSize); } } else { throw new UnsupportedOperationException(); } }
Source:
public void sendMessage(String registrationToken, nu.yona.server.messaging.entities.Message message) { Message firebaseMessage = Message.builder().putData("messageId", Long.toString(message.getId())) .setToken(registrationToken).build(); try { FirebaseMessaging.getInstance().send(firebaseMessage); } catch (FirebaseMessagingException e) { logger.error("Error sending message to Firebase server", e); } }

Target:
public void sendMessage(String registrationToken, nu.yona.server.messaging.entities.Message message) { if (!yonaProperties.getFirebase().isEnabled()) { return; } Message firebaseMessage = Message.builder().putData("messageId", Long.toString(message.getId())) .setToken(registrationToken).build(); try { FirebaseMessaging.getInstance().send(firebaseMessage); } catch (FirebaseMessagingException e) { throw FirebaseServiceException.couldNotSendMessage(e); } }
Source:
public void setReplicationRoleLocal(String role) { SIDriver.driver().lifecycleManager().setReplicationRole(role); Collection<Context> allContexts= ContextService.getFactory().getAllContexts(LanguageConnectionContext.CONTEXT_ID); for(Context context : allContexts){ ((LanguageConnectionContext)context).setReplicationRole(role); } SpliceLogUtils.info(LOG, "Set replication role to %s", role); }

Target:
private void setReplicationRoleLocal(String role) { SIDriver.driver().lifecycleManager().setReplicationRole(role); Collection<Context> allContexts= ContextService.getFactory().getAllContexts(LanguageConnectionContext.CONTEXT_ID); for(Context context : allContexts){ ((LanguageConnectionContext)context).setReplicationRole(role); } SpliceLogUtils.info(LOG, "Set replication role to %s", role); }
Source:
protected Object columnValue(Object value) { switch (type) { case PATH: case NAME: case STRING: case REFERENCE: case SIMPLEREFERENCE: case WEAKREFERENCE: case URI: return valueFactories.getStringFactory().create(value); case DATE : return ((DateTime) value).getMilliseconds(); } return value; }

Target:
protected Object columnValue(Object value) { switch (type) { case PATH: case NAME: case STRING: case REFERENCE: case SIMPLEREFERENCE: case WEAKREFERENCE: case URI: return valueFactories.getStringFactory().create(value); case DATE : return ((DateTime) value).getMilliseconds(); default : return value; } }
Source:
void runConsumers() { for (int i = 0; i < numThreads; i++) { workers.execute(() -> { try { long start = System.nanoTime(); Operation op = operationQueue.take(); op.execute(); long latency = System.nanoTime() - start; System.out.println("nextToken request latency: " + latency); } catch (Exception e) { log.error("Operation failed with", e); } }); } }

Target:
void runConsumers() { for (int i = 0; i < numThreads; i++) { workers.execute(() -> { try { long start = System.nanoTime(); Operation op = operationQueue.take(); op.execute(); long latency = System.nanoTime() - start; log.info("nextToken request latency: " + latency); } catch (Exception e) { log.error("Operation failed with", e); } }); } }
Source:
public AbstractExportRepresentationsAsImagesDialog(final Shell shell, final IPath path) { super(shell); initDialogSettings(path); this.autoScaleDiagram = getDialogSettings().getBoolean("autoScaleDiagram"); }

Target:
public AbstractExportRepresentationsAsImagesDialog(final Shell shell, final IPath path) { super(shell); initDialogSettings(path); this.autoScaleDiagram = getDialogSettings().getBoolean(AUTO_SCALE_SETTING_PROPERTY); }
Source:
public String installPush( @Nullable String deviceToken, @NonNull PushBackend pushBackend, boolean development ) throws ThingIFException{ return thingIfApi.installPush(deviceToken, pushBackend, development); }

Target:
public String installPush( @Nullable String deviceToken, @NonNull PushBackend pushBackend, boolean development ) throws ThingIFException{ return this.thingIfApi.installPush(deviceToken, pushBackend, development); }
Source:
public void testDriverRegistration() throws Exception { Class.forName("io.crate.client.jdbc.CrateDriver"); String hostPort = String.format(Locale.ENGLISH, "%s:%d", IntegrationTestSuite.crateTestServer.crateHost, IntegrationTestSuite.crateTestServer.transportPort ); Connection c1 = DriverManager.getConnection("crate://" + hostPort); assertThat(c1, instanceOf(CrateConnection.class)); Connection c2 = DriverManager.getConnection("jdbc:crate://" + hostPort); assertThat(c2, instanceOf(CrateConnection.class)); expectedException.expect(SQLException.class); expectedException.expectMessage("Protocol url jdbc-crate:// not supported. Must be one of crate:// or jdbc:crate://"); DriverManager.getConnection("jdbc-crate://" + hostPort); }

Target:
public void testDriverRegistration() throws Exception { Class.forName("io.crate.client.jdbc.CrateDriver"); String hostAndPort = String.format(Locale.ENGLISH, "%s:%d", IntegrationTestSuite.crateTestServer.crateHost, IntegrationTestSuite.crateTestServer.transportPort ); Connection c1 = DriverManager.getConnection("crate://" + hostAndPort); assertThat(c1, instanceOf(CrateConnection.class)); Connection c2 = DriverManager.getConnection("jdbc:crate://" + hostAndPort); assertThat(c2, instanceOf(CrateConnection.class)); expectedException.expect(SQLException.class); expectedException.expectMessage("Protocol url jdbc-crate:// not supported. Must be one of crate:// or jdbc:crate://"); DriverManager.getConnection("jdbc-crate://" + hostAndPort); }
Source:
public static Integer extractYearOrNull(String date, Logger log) { if (StringUtils.isNotBlank(date) && date.indexOf('-') == 4) { try { return Integer.valueOf(date.substring(0, date.indexOf('-'))); } catch (NumberFormatException e) { log.warn("unsupported, non integer, format of year value: " + date); return null; } } else { return null; } }

Target:
public static Year extractYearOrNull(String date, Logger log) { if (StringUtils.isNotBlank(date)) { if (date.indexOf('-') == 4) { try { return Year.parse(date.substring(0, date.indexOf('-')), DateTimeFormatter.ofPattern("yyyy")); } catch (DateTimeParseException e) { log.warn("unsupported, non integer, format of year value: " + date); return null; } } else { log.warn("unsupported format of year value: " + date); } } return null; }