auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Map<String, String> getExistingAzureUserMapping(RolesResourceApi rolesResourceApi, String clusterName, String rangerUserSyncRoleName) throws ApiException { ApiConfigList roleConfigList = rolesResourceApi.readRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "summary"); ApiConfig azureUserMappingConfig = roleConfigList.getItems().stream() .filter(apiConfig -> apiConfig.getName().equals(AZURE_USER_MAPPING)) .findFirst() .get(); String azureUserMappingStr = azureUserMappingConfig.getValue(); return userMappingStrToMap(azureUserMappingStr); }

Target:
private Map<String, String> getExistingAzureUserMapping(RolesResourceApi rolesResourceApi, String clusterName, String rangerUserSyncRoleName) throws ApiException { ApiConfigList roleConfigList = rolesResourceApi.readRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "summary"); Optional<ApiConfig> azureUserMappingConfig = roleConfigList.getItems().stream() .filter(apiConfig -> apiConfig.getName().equals(AZURE_USER_MAPPING)) .findFirst(); Map<String, String> userMappingMap; if (azureUserMappingConfig.isPresent()) { String azureUserMappingStr = azureUserMappingConfig.get().getValue(); userMappingMap = userMappingStrToMap(azureUserMappingStr); } else { LOGGER.info("No azure cloud mapping config set."); userMappingMap = new HashMap<>(); } return userMappingMap; }
Source:
public void exit() { super.exit(); removeMessages(BREDR_STOP_TIMEOUT); }

Target:
public void exit() { removeMessages(BREDR_STOP_TIMEOUT); super.exit(); }
Source:
public Argument build(Class<?> expectedType, T value, StatementContext ctx) { ArgBuilder<T> p = (ArgBuilder<T>) BUILDERS.get(expectedType); if (value != null && expectedType == Object.class) { ArgBuilder<T> v = (ArgBuilder<T>) BUILDERS.get(value.getClass()); if (v != null) { return v.build(value); } if (value.getClass().isEnum()) { return STR_BUILDER.build((((Enum<?>)value).name())); } } if (p != null) { return p.build(value); } if (expectedType.isEnum()) { return STR_BUILDER.build(value.toString()); } return OBJ_BUILDER.build(value); }

Target:
public Argument build(Class<?> expectedType, T value, StatementContext ctx) { Class<?> buildType = value != null && expectedType == Object.class ? value.getClass() : expectedType; ArgBuilder<T> v = (ArgBuilder<T>) BUILDERS.get(buildType); if (v != null) { return v.build(value); } if (value != null && value.getClass().isEnum()) { return STR_BUILDER.build((((Enum<?>)value).name())); } return OBJ_BUILDER.build(value); }
Source:
private void checkNonAnnotatedVariantsRead(int expectedNonAnnotatedVariants, String study) throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_VARIANTS_NAME, Arrays.asList( VariantData.getVariantWithAnnotation(), VariantData.getVariantWithoutAnnotation(), VariantData.getVariantWithoutAnnotationOtherStudy())); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); NonAnnotatedVariantsMongoReader mongoItemReader = new NonAnnotatedVariantsMongoReader( mongoOperations, COLLECTION_VARIANTS_NAME, study); mongoItemReader.open(executionContext); int itemCount = 0; VariantWrapper variantWrapper; while ((variantWrapper = mongoItemReader.read()) != null) { itemCount++; assertFalse(variantWrapper.getChr().isEmpty()); assertFalse(variantWrapper.getStart() == 0); Field privateVariantField = VariantWrapper.class.getDeclaredField("variant"); privateVariantField.setAccessible(true); VariantAnnotation annotation = ((Variant) privateVariantField.get(variantWrapper)).getAnnotation(); assertNull(annotation.getConsequenceTypes()); } assertEquals(expectedNonAnnotatedVariants, itemCount); mongoItemReader.close(); }

Target:
private void checkNonAnnotatedVariantsRead(int expectedNonAnnotatedVariants, String study) throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_VARIANTS_NAME, Arrays.asList( VariantData.getVariantWithAnnotation(), VariantData.getVariantWithoutAnnotation(), VariantData.getVariantWithoutAnnotationOtherStudy())); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); NonAnnotatedVariantsMongoReader mongoItemReader = new NonAnnotatedVariantsMongoReader( mongoOperations, COLLECTION_VARIANTS_NAME, study); mongoItemReader.open(executionContext); int itemCount = 0; VariantWrapper variantWrapper; while ((variantWrapper = mongoItemReader.read()) != null) { itemCount++; assertFalse(variantWrapper.getChr().isEmpty()); assertNotEquals(0, variantWrapper.getStart()); Field privateVariantField = VariantWrapper.class.getDeclaredField("variant"); privateVariantField.setAccessible(true); VariantAnnotation annotation = ((Variant) privateVariantField.get(variantWrapper)).getAnnotation(); assertNull(annotation.getConsequenceTypes()); } assertEquals(expectedNonAnnotatedVariants, itemCount); mongoItemReader.close(); }
Source:
private void populateRepositoryRefresh() { this.refreshLayout = new GridPane(); this.refreshLayout.setHgap(20); this.refreshLayout.setVgap(10); ColumnConstraints columnConstraints = new ColumnConstraints(); columnConstraints.setFillWidth(true); columnConstraints.setHgrow(Priority.ALWAYS); this.refreshLayout.getColumnConstraints().add(columnConstraints); this.refreshRepositoriesLabel = new Label(translate("Fetch updates for the repositories to retrieve the newest script versions")); this.refreshRepositoriesLabel.setWrapText(true); this.refreshRepositoriesButton = new Button("Refresh Repositories"); refreshRepositoriesButton.getStyleClass().add("buttonWithIcon"); this.refreshRepositoriesButton.setOnAction(event -> { refreshRepositoriesButton.getStyleClass().add("refreshIcon"); refreshRepositoriesButton.setDisable(true); repositoryManager.triggerRepositoryChange(); }); this.refreshLayout.add(refreshRepositoriesLabel, 0, 0); this.refreshLayout.add(refreshRepositoriesButton, 1, 0); }

Target:
private void populateRepositoryRefresh() { this.refreshLayout = new GridPane(); this.refreshLayout.setHgap(20); this.refreshLayout.setVgap(10); ColumnConstraints columnConstraints = new ColumnConstraints(); columnConstraints.setFillWidth(true); columnConstraints.setHgrow(Priority.ALWAYS); this.refreshLayout.getColumnConstraints().add(columnConstraints); this.refreshRepositoriesLabel = new Label(translate("Fetch updates for the repositories to retrieve the newest script versions")); this.refreshRepositoriesLabel.setWrapText(true); this.refreshRepositoriesButton = new Button("Refresh Repositories"); this.refreshRepositoriesButton.getStyleClass().add("buttonWithIcon"); this.refreshRepositoriesButton.setOnAction(event -> { refreshRepositoriesButton.getStyleClass().add("refreshIcon"); refreshRepositoriesButton.setDisable(true); repositoryManager.triggerRepositoryChange(); }); this.refreshLayout.add(refreshRepositoriesLabel, 0, 0); this.refreshLayout.add(refreshRepositoriesButton, 1, 0); }
Source:
private void extractTitles(Element mods, IndexDocumentBean idb) { List<?> titles = mods.getChildren("titleInfo", JDOMNamespaceUtil.MODS_V3_NS); String mainTitle = null; List<String> otherTitles = new ArrayList<>(); for (Object titleInfoObj : titles) { Element titleInfoEl = (Element) titleInfoObj; for (Object titleObj : titleInfoEl.getChildren()) { Element titleEl = (Element) titleObj; if (mainTitle == null && "title".equalsIgnoreCase(titleEl.getName())) { mainTitle = titleEl.getValue(); } else { otherTitles.add(titleEl.getValue()); } } } if (mainTitle != null && !mainTitle.equals("")) { idb.setTitle(mainTitle); } if (otherTitles.size() > 0) { idb.setOtherTitle(otherTitles); } else { idb.setOtherTitle(null); } }

Target:
private void extractTitles(Element mods, IndexDocumentBean idb) { List<?> titles = mods.getChildren("titleInfo", JDOMNamespaceUtil.MODS_V3_NS); String mainTitle = null; List<String> otherTitles = new ArrayList<>(); for (Object titleInfoObj : titles) { Element titleInfoEl = (Element) titleInfoObj; for (Object titleObj : titleInfoEl.getChildren()) { Element titleEl = (Element) titleObj; if (mainTitle == null && "title".equalsIgnoreCase(titleEl.getName())) { mainTitle = titleEl.getValue(); } else { otherTitles.add(titleEl.getValue()); } } } if (!isBlank(mainTitle)) { idb.setTitle(mainTitle); } if (otherTitles.size() > 0) { idb.setOtherTitle(otherTitles); } else { idb.setOtherTitle(null); } }
Source:
public void initializeSpinners() { String[] categoryList = new String[]{SCHOOL, GENERAL}; StringArraySpinnerAdapter categoryAdapter = new StringArraySpinnerAdapter(getActivity(), categoryList, R.layout.simple_spinner_item, R.layout.simple_spinner_item); categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); mAnnouncementCategory.setAdapter(categoryAdapter); mAnnouncementCategory.setSelection(1, true); mSchoolAdapter = new SchoolSpinnerAdapter(getActivity(), mSchools, R.layout.simple_spinner_item, R.layout.simple_spinner_item); mSchoolAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mAnnouncementSchoolList.setAdapter(mSchoolAdapter); mAnnouncementCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (mAnnouncementCategory.getSelectedItemPosition() == 1) { mAnnouncementSchoolList.setVisibility(View.GONE); } else { mAnnouncementSchoolList.setVisibility(View.VISIBLE); } } @Override public void onNothingSelected(AdapterView<?> adapterView) }); }

Target:
public void initializeSpinners() { StringArraySpinnerAdapter categoryAdapter = new StringArraySpinnerAdapter(getActivity(), categoryList, R.layout.simple_spinner_item, R.layout.simple_spinner_item); mAnnouncementCategory.setAdapter(categoryAdapter); mAnnouncementCategory.setSelection(1, true); mSchoolAdapter = new SchoolSpinnerAdapter(getActivity(), mSchools, R.layout.simple_spinner_item, R.layout.simple_spinner_item); mAnnouncementSchoolList.setAdapter(mSchoolAdapter); mAnnouncementCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (mAnnouncementCategory.getSelectedItemPosition() == 1) { mAnnouncementSchoolList.setVisibility(View.GONE); } else { mAnnouncementSchoolList.setVisibility(View.VISIBLE); } } @Override public void onNothingSelected(AdapterView<?> adapterView) }); }
Source:
public boolean isDarkload() { if (!shard.containsKey(DARKLOAD)) { return false; } final String value = shard.get(DARKLOAD); if (!value.equals("true")) { return false; } return true; }

Target:
public boolean isDarkload() { return shard.containsKey(DARKLOAD); }
Source:
public void verify() { int tolerance = (int) (elementCounter.get() * tolerancePercentage); logger.info("Actual Keys added : " + elementCounter.get()); logger.info("Acceptable Count(i.e. tolerance) : " + (elementCounter.get() - tolerance)); logger.info("Cardinality Estimation : " + cardinalityEstimator.estimate()); assertTrue(Math.abs(cardinalityEstimator.estimate() - elementCounter.get()) < tolerance); }

Target:
public void verify() { int tolerance = (int) (elementCounter.get() * tolerancePercentage); logger.info("Actual Keys added : " + elementCounter.get()); logger.info("Acceptable Count(i.e. tolerance) : (" + (elementCounter.get() - tolerance) + " - " + (elementCounter.get() + tolerance) + ")"); logger.info("Cardinality Estimation : " + cardinalityEstimator.estimate()); assertTrue(Math.abs(cardinalityEstimator.estimate() - elementCounter.get()) < tolerance); }
Source:
public ITmfStateValue increment() throws StateValueTypeException { return TmfStateValue.newValueInt(this.unboxInt() + 1); }

Target:
public ITmfStateValue increment() throws StateValueTypeException { return TmfStateValue.newValueInt(valueInt + 1); }
Source:
public void test_get_String() { assertEquals("d1", Paths.get("d1").toString()); assertEquals("", Paths.get("").toString()); assertEquals("/", Paths.get(" assertEquals("d1/d2/d3", Paths.get("d1 assertEquals("d1/d2", Paths.get("d1", "", "d2").toString()); try { Paths.get("'\u0000'"); fail(); } catch (InvalidPathException expected) }

Target:
public void test_get_String() { assertEquals("d1", Paths.get("d1").toString()); assertEquals("", Paths.get("").toString()); assertEquals("/", Paths.get(" assertEquals("d1/d2/d3", Paths.get("d1 assertEquals("d1/d2", Paths.get("d1", "", "d2").toString()); assertEquals("foo", Paths.get("", "foo").toString()); assertEquals("/foo/bar/gus", Paths.get("/foo", "bar", "gus").toString()); try { Paths.get("'\u0000'"); fail(); } catch (InvalidPathException expected) }
Source:
public void run() { try { startupComplete(); while (isRunning()) { configureNewConnections(); processNewResponses(); long startSelectTime = SystemTime.getInstance().milliseconds(); int ready = selector.select(300); logger.trace("Processor id selection time = ms number of ready channels = {}", id, (SystemTime.getInstance().milliseconds() - startSelectTime), ready); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); long startTimeInMs = SystemTime.getInstance().milliseconds(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } else if (!key.isValid()) { close(key); } else { throw new IllegalStateException("Unrecognized key state for processor thread."); } } catch (EOFException e) { close(key); logger.error("closing key on EOFException {}", e); } catch (Throwable e) { logger.error("closing key on exception remote host " + ((SocketChannel) key.channel()).socket() .getRemoteSocketAddress(), e); close(key); } } long roundTime = SystemTime.getInstance().milliseconds() - startTimeInMs; logger.trace("Processor id one round of processing time = {}", id, roundTime); } } logger.debug("Closing server socket and selector."); closeAll(); selector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error while shutting down processor thread {}", e); } }

Target:
public void run() { try { startupComplete(); while (isRunning()) { configureNewConnections(); processNewResponses(); long startSelectTime = SystemTime.getInstance().milliseconds(); int ready = selector.select(300); logger.trace("Processor id selection time = ms number of ready channels = {}", id, (SystemTime.getInstance().milliseconds() - startSelectTime), ready); if (ready > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); long startTimeInMs = SystemTime.getInstance().milliseconds(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isReadable()) { read(key); } else if (key.isWritable()) { write(key); } else if (!key.isValid()) { close(key); } else { throw new IllegalStateException("Unrecognized key state for processor thread."); } } catch (EOFException e) { close(key); logger.error("closing key on EOFException {}", e); } catch (Throwable e) { logger.error("closing key on exception remote host " + ((SocketChannel) key.channel()).socket() .getRemoteSocketAddress(), e); close(key); } } long selectedKeysProcessingTime = SystemTime.getInstance().milliseconds() - startTimeInMs; logger.trace("Processor id one selector iteration processing time = {}", id, selectedKeysProcessingTime); } } logger.debug("Closing server socket and selector."); closeAll(); selector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error while shutting down processor thread {}", e); } }
Source:
private static AmazonS3 getClient(String driverId) { if(driverClientMap.containsKey(driverId)) { return driverClientMap.get(driverId); } else { AmazonS3ClientBuilder s3CB = AmazonS3ClientBuilder.standard(); ClientConfiguration cc = new ClientConfiguration(); Integer poolSize = Integer.getInteger("dataverse.files." + driverId + ".connection-pool-size"); if(poolSize==null) { poolSize = 256; } cc.setMaxConnections(poolSize); s3CB.setClientConfiguration(cc); String s3CEUrl = System.getProperty("dataverse.files." + driverId + ".custom-endpoint-url", ""); String s3CERegion = System.getProperty("dataverse.files." + driverId + ".custom-endpoint-region", "dataverse"); if (!s3CEUrl.isEmpty()) { s3CB.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3CEUrl, s3CERegion)); } Boolean s3pathStyleAccess = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".path-style-access", "false")); s3CB.withPathStyleAccessEnabled(s3pathStyleAccess); Boolean s3payloadSigning = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".payload-signing","false")); Boolean s3chunkedEncoding = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".chunked-encoding","true")); s3CB.setPayloadSigningEnabled(s3payloadSigning); s3CB.setChunkedEncodingDisabled(!s3chunkedEncoding); String s3profile = System.getProperty("dataverse.files." + driverId + ".profile","default"); s3CB.setCredentials(new ProfileCredentialsProvider(s3profile)); AmazonS3 client = s3CB.build(); driverClientMap.put(driverId, client); return client; } }

Target:
private static AmazonS3 getClient(String driverId) { if(driverClientMap.containsKey(driverId)) { return driverClientMap.get(driverId); } else { AmazonS3ClientBuilder s3CB = AmazonS3ClientBuilder.standard(); ClientConfiguration cc = new ClientConfiguration(); Integer poolSize = Integer.getInteger("dataverse.files." + driverId + ".connection-pool-size", 256); cc.setMaxConnections(poolSize); s3CB.setClientConfiguration(cc); String s3CEUrl = System.getProperty("dataverse.files." + driverId + ".custom-endpoint-url", ""); String s3CERegion = System.getProperty("dataverse.files." + driverId + ".custom-endpoint-region", "dataverse"); if (!s3CEUrl.isEmpty()) { s3CB.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3CEUrl, s3CERegion)); } Boolean s3pathStyleAccess = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".path-style-access", "false")); s3CB.withPathStyleAccessEnabled(s3pathStyleAccess); Boolean s3payloadSigning = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".payload-signing","false")); Boolean s3chunkedEncoding = Boolean.parseBoolean(System.getProperty("dataverse.files." + driverId + ".chunked-encoding","true")); s3CB.setPayloadSigningEnabled(s3payloadSigning); s3CB.setChunkedEncodingDisabled(!s3chunkedEncoding); String s3profile = System.getProperty("dataverse.files." + driverId + ".profile","default"); s3CB.setCredentials(new ProfileCredentialsProvider(s3profile)); AmazonS3 client = s3CB.build(); driverClientMap.put(driverId, client); return client; } }
Source:
public void leftHandAssignmentCanBeInBraces() { ParseResult<Expression> result = new JavaParser().parse(EXPRESSION, provider("(i) += (i) += 1")); assertProblems(result); }

Target:
public void leftHandAssignmentCanBeInBraces() { ParseResult<Expression> result = new JavaParser().parse(EXPRESSION, provider("(i) += (i) += 1")); assertNoProblems(result); }
Source:
public Status update(final String table, final String key, final Map<String, ByteIterator> values) { try { final Response searchResponse = search(table, key); final int statusCode = searchResponse.getStatusLine().getStatusCode(); if (statusCode == 404) { return Status.NOT_FOUND; } else if (statusCode != 200) { return Status.ERROR; } final Map<String, Object> map = map(searchResponse); @SuppressWarnings("unchecked") final Map<String, Object> hits = (Map<String, Object>) map.get("hits"); final int total = (int) hits.get("total"); if (total == 0) { return Status.NOT_FOUND; } @SuppressWarnings("unchecked") final Map<String, Object> hit = (Map<String, Object>) ((List<Object>) hits.get("hits")).get(0); @SuppressWarnings("unchecked") final Map<String, Object> source = (Map<String, Object>) hit.get("_source"); for (final Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { source.put(entry.getKey(), entry.getValue()); } final Map<String, String> params = emptyMap(); final Response response = restClient.performRequest( "PUT", "/" + indexKey + "/" + table + "/" + hit.get("_id"), params, new NStringEntity(new ObjectMapper().writeValueAsString(source), ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != 200) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } }

Target:
public Status update(final String table, final String key, final Map<String, ByteIterator> values) { try { final Response searchResponse = search(table, key); final int statusCode = searchResponse.getStatusLine().getStatusCode(); if (statusCode == 404) { return Status.NOT_FOUND; } else if (statusCode != HttpStatus.SC_OK) { return Status.ERROR; } final Map<String, Object> map = map(searchResponse); @SuppressWarnings("unchecked") final Map<String, Object> hits = (Map<String, Object>) map.get("hits"); final int total = (int) hits.get("total"); if (total == 0) { return Status.NOT_FOUND; } @SuppressWarnings("unchecked") final Map<String, Object> hit = (Map<String, Object>) ((List<Object>) hits.get("hits")).get(0); @SuppressWarnings("unchecked") final Map<String, Object> source = (Map<String, Object>) hit.get("_source"); for (final Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { source.put(entry.getKey(), entry.getValue()); } final Map<String, String> params = emptyMap(); final Response response = restClient.performRequest( "PUT", "/" + indexKey + "/" + table + "/" + hit.get("_id"), params, new NStringEntity(new ObjectMapper().writeValueAsString(source), ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } }
Source:
public DeCoupleMbusDeviceResponseDto execute(final DlmsConnectionHolder conn, final DlmsDevice device, final DeCoupleMbusDeviceDto decoupleMbusDto) throws ProtocolAdapterException { LOGGER.debug("DeCouple mbus device from gateway device"); final DeCoupleMbusDeviceResponseDto response = this.writeUpdatedMbus(conn, decoupleMbusDto); final CosemObjectAccessor mBusSetup = new CosemObjectAccessor(conn, this.getObisCode(decoupleMbusDto), CLASS_ID); final DataObject parameter = DataObject.newUInteger8Data((byte) 0); mBusSetup.callMethod(Method.SLAVE_DE_INSTALL, parameter); return response; }

Target:
public DeCoupleMbusDeviceResponseDto execute(final DlmsConnectionHolder conn, final DlmsDevice device, final DeCoupleMbusDeviceDto decoupleMbusDto) throws ProtocolAdapterException { LOGGER.debug("DeCouple mbus device from gateway device"); final DeCoupleMbusDeviceResponseDto response = this.writeUpdatedMbus(conn, decoupleMbusDto); final CosemObjectAccessor mBusSetup = new CosemObjectAccessor(conn, this.getObisCode(decoupleMbusDto), CLASS_ID); final DataObject parameter = DataObject.newUInteger8Data((byte) 0); final MethodResultCode slaveDeinstall = mBusSetup.callMethod(Method.SLAVE_DEINSTALL, parameter); if (slaveDeinstall != MethodResultCode.SUCCESS) { LOGGER.warn("Slave deinstall was not successfull on device for mbus device {}", device.getDeviceIdentification(), decoupleMbusDto.getmBusDeviceIdentification()); } return response; }
Source:
public boolean isActive(boolean performTimeoutCheck) { if (active && performTimeoutCheck) { if (lastReceivedFrame == null) { return false; } else { long silentIntervalMs = System.currentTimeMillis() - lastReceivedFrame.getReceivedMs(); return silentIntervalMs <= MediaStreamTrackDesc.SUSPENSION_THRESHOLD_MS; } } else { return active; } }

Target:
public boolean isActive(boolean performTimeoutCheck) { if (active && performTimeoutCheck) { if (lastReceivedFrame == null) { return false; } else { long timeSinceLastReceivedFrameMs = System.currentTimeMillis() - lastReceivedFrame.getReceivedMs(); return timeSinceLastReceivedFrameMs <= MediaStreamTrackDesc.SUSPENSION_THRESHOLD_MS; } } else { return active; } }
Source:
void clearWALEntryBatch() { long timeout = System.currentTimeMillis() + this.shipEditsTimeout; while(this.isAlive() || this.entryReader.isAlive()){ try { if (System.currentTimeMillis() >= timeout) { LOG.warn("Interrupting source thread for peer without cleaning buffer usage " + "because clearWALEntryBatch method timed out whilst waiting reader/shipper " + "thread to stop.", this.source.getPeerId()); Thread.currentThread().interrupt(); } else { Thread.sleep(this.sleepForRetries); } } catch (InterruptedException e) { LOG.warn("{} Interrupted while waiting to stop on clearWALEntryBatch: {}", this.source.getPeerId(), this.getName(), e); Thread.currentThread().interrupt(); } } LongAccumulator totalToDecrement = new LongAccumulator((a,b) -> a + b, 0); entryReader.entryBatchQueue.forEach(w -> { entryReader.entryBatchQueue.remove(w); w.getWalEntries().forEach(e -> { long entrySizeExcludeBulkLoad = entryReader.getEntrySizeExcludeBulkLoad(e); totalToDecrement.accumulate(entrySizeExcludeBulkLoad); }); }); LOG.trace("Decrementing totalBufferUsed by {}B while stopping Replication WAL Readers.", totalToDecrement.longValue()); source.getSourceManager().getTotalBufferUsed().addAndGet(-totalToDecrement.longValue()); }

Target:
void clearWALEntryBatch() { long timeout = EnvironmentEdgeManager.currentTime() + this.shipEditsTimeout; while(this.isAlive() || this.entryReader.isAlive()){ try { if (System.currentTimeMillis() >= timeout) { LOG.warn("Interrupting source thread for peer without cleaning buffer usage " + "because clearWALEntryBatch method timed out whilst waiting reader/shipper " + "thread to stop.", this.source.getPeerId()); Thread.currentThread().interrupt(); } else { Thread.sleep(this.sleepForRetries); } } catch (InterruptedException e) { LOG.warn("{} Interrupted while waiting to stop on clearWALEntryBatch: {}", this.source.getPeerId(), this.getName(), e); Thread.currentThread().interrupt(); } } LongAccumulator totalToDecrement = new LongAccumulator((a,b) -> a + b, 0); entryReader.entryBatchQueue.forEach(w -> { entryReader.entryBatchQueue.remove(w); w.getWalEntries().forEach(e -> { long entrySizeExcludeBulkLoad = entryReader.getEntrySizeExcludeBulkLoad(e); totalToDecrement.accumulate(entrySizeExcludeBulkLoad); }); }); LOG.trace("Decrementing totalBufferUsed by {}B while stopping Replication WAL Readers.", totalToDecrement.longValue()); source.getSourceManager().getTotalBufferUsed().addAndGet(-totalToDecrement.longValue()); }
Source:
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { checkOpen(); if ((x == null) || (targetSqlType == Types.NULL)) { setNull(parameterIndex, targetSqlType); return; } switch (targetSqlType) { case Types.TINYINT: setByte(parameterIndex, castToByte(x, targetSqlType)); return; case Types.SMALLINT: setShort(parameterIndex, castToShort(x, targetSqlType)); return; case Types.INTEGER: setInt(parameterIndex, castToInt(x, targetSqlType)); return; case Types.BIGINT: setLong(parameterIndex, castToLong(x, targetSqlType)); return; case Types.FLOAT: case Types.REAL: setFloat(parameterIndex, castToFloat(x, targetSqlType)); return; case Types.DOUBLE: setDouble(parameterIndex, castToDouble(x, targetSqlType)); return; case Types.DECIMAL: case Types.NUMERIC: setBigDecimal(parameterIndex, castToBigDecimal(x, targetSqlType)); return; case Types.CHAR: case Types.NCHAR: case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: setString(parameterIndex, x.toString()); return; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: setBytes(parameterIndex, castToBinary(x, targetSqlType)); return; case Types.DATE: setDate(parameterIndex, castToDate(x, targetSqlType)); return; case Types.TIME: setTime(parameterIndex, castToTime(x, targetSqlType)); return; case Types.TIMESTAMP: setTimestamp(parameterIndex, castToTimestamp(x, targetSqlType)); return; } throw new SQLException("Unsupported target SQL type: " + targetSqlType); }

Target:
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { checkOpen(); if (x == null) { setNull(parameterIndex, targetSqlType); return; } switch (targetSqlType) { case Types.BOOLEAN: case Types.BIT: setBoolean(parameterIndex, castToBoolean(x, targetSqlType)); return; case Types.TINYINT: setByte(parameterIndex, castToByte(x, targetSqlType)); return; case Types.SMALLINT: setShort(parameterIndex, castToShort(x, targetSqlType)); return; case Types.INTEGER: setInt(parameterIndex, castToInt(x, targetSqlType)); return; case Types.BIGINT: setLong(parameterIndex, castToLong(x, targetSqlType)); return; case Types.FLOAT: case Types.REAL: setFloat(parameterIndex, castToFloat(x, targetSqlType)); return; case Types.DOUBLE: setDouble(parameterIndex, castToDouble(x, targetSqlType)); return; case Types.DECIMAL: case Types.NUMERIC: setBigDecimal(parameterIndex, castToBigDecimal(x, targetSqlType)); return; case Types.CHAR: case Types.NCHAR: case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: setString(parameterIndex, x.toString()); return; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: setBytes(parameterIndex, castToBinary(x, targetSqlType)); return; case Types.DATE: setDate(parameterIndex, castToDate(x, targetSqlType)); return; case Types.TIME: setTime(parameterIndex, castToTime(x, targetSqlType)); return; case Types.TIMESTAMP: setTimestamp(parameterIndex, castToTimestamp(x, targetSqlType)); return; } throw new SQLException("Unsupported target SQL type: " + targetSqlType); }
Source:
public FfmpegDecoderException decode(DecoderInputBuffer inputBuffer, SimpleOutputBuffer outputBuffer, boolean reset) { if (reset) { nativeContext = ffmpegReset(nativeContext, extraData); if (nativeContext == 0) { return new FfmpegDecoderException("Error resetting (see logcat)."); } } ByteBuffer inputData = inputBuffer.data; int inputSize = inputData.limit(); ByteBuffer outputData = outputBuffer.init(inputBuffer.timeUs, OUTPUT_BUFFER_SIZE); int result = ffmpegDecode(nativeContext, inputData, inputSize, outputData, OUTPUT_BUFFER_SIZE); if (result < 0) { return new FfmpegDecoderException("Error decoding (see logcat). Code: " + result); } if (!hasOutputFormat) { channelCount = ffmpegGetChannelCount(nativeContext); if ("alac".equals(codecName)) { sampleRate = ByteBuffer.wrap(extraData, extraData.length - 4, 4).getInt(); } else { sampleRate = ffmpegGetSampleRate(nativeContext); } hasOutputFormat = true; } outputBuffer.data.position(0); outputBuffer.data.limit(result); return null; }

Target:
public FfmpegDecoderException decode(DecoderInputBuffer inputBuffer, SimpleOutputBuffer outputBuffer, boolean reset) { if (reset) { nativeContext = ffmpegReset(nativeContext, extraData); if (nativeContext == 0) { return new FfmpegDecoderException("Error resetting (see logcat)."); } } ByteBuffer inputData = inputBuffer.data; int inputSize = inputData.limit(); ByteBuffer outputData = outputBuffer.init(inputBuffer.timeUs, OUTPUT_BUFFER_SIZE); int result = ffmpegDecode(nativeContext, inputData, inputSize, outputData, OUTPUT_BUFFER_SIZE); if (result < 0) { return new FfmpegDecoderException("Error decoding (see logcat). Code: " + result); } if (!hasOutputFormat) { channelCount = ffmpegGetChannelCount(nativeContext); sampleRate = ffmpegGetSampleRate(nativeContext); if (sampleRate == 0 && "alac".equals(codecName)) { ParsableByteArray parsableExtraData = new ParsableByteArray(extraData); parsableExtraData.setPosition(extraData.length - 4); sampleRate = parsableExtraData.readUnsignedIntToInt(); } hasOutputFormat = true; } outputBuffer.data.position(0); outputBuffer.data.limit(result); return null; }
Source:
public IncludedInDetail call() throws OrmException, NoSuchChangeException, IOException, InvalidRevisionException { control = changeControlFactory.validateFor(changeId); final PatchSet patch = db.patchSets().get(control.getChange().currentPatchSetId()); final Repository repo = repoManager.openRepository(control.getProject().getNameKey()); try { final RevWalk rw = new RevWalk(repo); try { rw.setRetainBody(false); final RevCommit rev; try { rev = rw.parseCommit(ObjectId.fromString(patch.getRevision().get())); } catch (IncorrectObjectTypeException err) { throw new InvalidRevisionException(); } catch (MissingObjectException err) { throw new InvalidRevisionException(); } Set<Ref> tags = new HashSet<Ref>(repo.getRefDatabase().getRefs(Constants.R_TAGS) .values()); Set<Ref> branches = new HashSet<Ref>(repo.getRefDatabase().getRefs(Constants.R_HEADS) .values()); Set<Ref> allRefs = new HashSet<Ref>(); allRefs.addAll(tags); allRefs.addAll(branches); Set<Ref> allMatchingRefs = includedIn(repo, rw, rev, allRefs); detail = new IncludedInDetail(); detail.setBranches(getMatchingRefNames(allMatchingRefs, branches)); detail.setTags(getMatchingRefNames(allMatchingRefs, tags)); return detail; } finally { rw.release(); } } finally { repo.close(); } }

Target:
public IncludedInDetail call() throws OrmException, NoSuchChangeException, IOException, InvalidRevisionException { control = changeControlFactory.validateFor(changeId); final PatchSet patch = db.patchSets().get(control.getChange().currentPatchSetId()); final Repository repo = repoManager.openRepository(control.getProject().getNameKey()); try { final RevWalk rw = new RevWalk(repo); try { rw.setRetainBody(false); final RevCommit rev; try { rev = rw.parseCommit(ObjectId.fromString(patch.getRevision().get())); } catch (IncorrectObjectTypeException err) { throw new InvalidRevisionException(); } catch (MissingObjectException err) { throw new InvalidRevisionException(); } Set<Ref> tags = new HashSet<Ref>(repo.getRefDatabase().getRefs(Constants.R_TAGS) .values()); Set<Ref> branches = new HashSet<Ref>(repo.getRefDatabase().getRefs(Constants.R_HEADS) .values()); Set<Ref> allTagsAndBranches = new HashSet<Ref>(); allTagsAndBranches.addAll(tags); allTagsAndBranches.addAll(branches); Set<Ref> allMatchingTagsAndBranches = includedIn(repo, rw, rev, allTagsAndBranches); detail = new IncludedInDetail(); detail.setBranches(getMatchingRefNames(allMatchingTagsAndBranches, branches)); detail.setTags(getMatchingRefNames(allMatchingTagsAndBranches, tags)); return detail; } finally { rw.release(); } } finally { repo.close(); } }
Source:
public int hashCode() { if (carriesUnmergeableSack()) { return System.identityHashCode(this); } return super.hashCode() ^ this.path.hashCode(); }

Target:
public int hashCode() { return carriesUnmergeableSack() ? System.identityHashCode(this) : (super.hashCode() ^ this.path.hashCode()); }
Source:
public void applyState(final ShapeState shapeState) { if (!this.state.equals(shapeState)) { this.state = shapeState; if (ShapeState.SELECTED.equals(shapeState)) { runState(ShapeState.SELECTED); } else if (ShapeState.HIGHLIGHT.equals(shapeState)) { runState(ShapeState.HIGHLIGHT); } else if (ShapeState.INVALID.equals(shapeState)) { runState(ShapeState.INVALID); } else { runStrokeStateHandler(strokeState); } } }

Target:
public void applyState(final ShapeState shapeState) { if (!this.state.equals(shapeState)) { this.state = shapeState; switch (shapeState) { case SELECTED: case HIGHLIGHT: case INVALID: runState(shapeState); break; default: runStrokeStateHandler(strokeState); break; } } }
Source:
private void generateCallFile(Config config, Map<String, String> params, Map<String, String> completeParams, String motechCallId) throws URISyntaxException, IOException { String myUri = mergeUriAndRemoveParams(config.getOutgoingCallUriTemplate(), completeParams); Path path = Paths.get(new URI(myUri)); Path tempDirectory = Files.createTempDirectory(path.getParent(), "motech"); Path tempPath = Files.createTempFile(tempDirectory, "motech", ".tmp"); BufferedWriter bufferedWriter = Files.newBufferedWriter(tempPath); for (Map.Entry<String, String> entry : completeParams.entrySet()) { bufferedWriter.write(String.format("%s: %s", entry.getKey(), entry.getValue())); bufferedWriter.newLine(); } bufferedWriter.close(); Files.move(tempPath, path, StandardCopyOption.ATOMIC_MOVE); tempDirectory.toFile().delete(); addCallDetailRecord(CallDetailRecord.CALL_INITIATED, config, params, motechCallId); }

Target:
private void generateCallFile(Config config, Map<String, String> params, Map<String, String> completeParams, String motechCallId) { String myUri = mergeUriAndRemoveParams(config.getOutgoingCallUriTemplate(), completeParams); try { Path path = Paths.get(new URI(myUri)); Path tempDirectory = Files.createTempDirectory(path.getParent(), "motech-ivr"); Path tempPath = Files.createTempFile(tempDirectory, "callfile", ".txt"); try (BufferedWriter bufferedWriter = Files.newBufferedWriter(tempPath)) { for (Map.Entry<String, String> entry : completeParams.entrySet()) { bufferedWriter.write(String.format("%s: %s", entry.getKey(), entry.getValue())); bufferedWriter.newLine(); } } Files.move(tempPath, path, StandardCopyOption.ATOMIC_MOVE); tempDirectory.toFile().delete(); } catch (URISyntaxException | IOException e) { String message = String.format("Could not initiate call, unexpected exception: %s", e.toString()); statusMessageService.warn(message, MODULE_NAME); params.put("ErrorMessage", message); addCallDetailRecord(CallDetailRecord.CALL_FAILED, config, params, motechCallId); throw new CallInitiationException(message, e); } addCallDetailRecord(CallDetailRecord.CALL_INITIATED, config, params, motechCallId); }
Source:
void annotate(final GithubUrl url, final MarkupText text, final Entry change) { final String base = url.baseUrl(); for (LinkMarkup markup : MARKUPS) { markup.process(text, base); } if (change instanceof GitChangeSet) { GitChangeSet cs = (GitChangeSet) change; final String id = cs.getId(); text.wrapBy("", " (<a href='" + url.commitId(id) + "'>commit: " + id.substring(0, Math.min(id.length(), 7)) + "</a>)"); } }

Target:
void annotate(final GithubUrl url, final MarkupText text, final Entry change) { final String base = url.baseUrl(); for (LinkMarkup markup : MARKUPS) { markup.process(text, base); } if (change instanceof GitChangeSet) { GitChangeSet cs = (GitChangeSet) change; final String id = cs.getId(); text.wrapBy("", format(" (<a href='%s'>commit: %s</a>)", url.commitId(id), id.substring(0, Math.min(id.length(), 7)))); } }
Source:
private void updateDevice() { if ((getParameters().getAction() == PlugAction.PLUG) && hotPlugVmNicRequired(getVm().getStatus())) { VmDevicesMonitoring.Change change = vmDevicesMonitoring.createChange(getVdsId(), System.nanoTime()); change.updateVm(getVmId(), VmDevicesMonitoring.UPDATE_HASH); change.flush(); } else { vmDevice.setPlugged(getParameters().getAction() == PlugAction.PLUG); vmDeviceDao.update(vmDevice); } }

Target:
private void updateDevice() { if (getParameters().getAction() == PlugAction.PLUG && hotPlugVmNicRequired(getVm().getStatus())) { VmDevicesMonitoring.Change change = vmDevicesMonitoring.createChange(getVdsId(), System.nanoTime()); change.updateVm(getVmId(), VmDevicesMonitoring.UPDATE_HASH); change.flush(); } else { vmDevice.setPlugged(getParameters().getAction() == PlugAction.PLUG); vmDeviceDao.update(vmDevice); } }
Source:
private Mono<Payload> handleRequestResponse(final Payload payload) { Throwable err = checkAvailable(); if (err != null) { payload.release(); return Mono.error(err); } if (!PayloadValidationUtils.isValid(this.mtu, payload)) { payload.release(); return Mono.error(new IllegalArgumentException(INVALID_PAYLOAD_ERROR_MESSAGE)); } final UnboundedProcessor<ByteBuf> sendProcessor = this.sendProcessor; final UnicastProcessor<Payload> receiver = UnicastProcessor.create(Queues.<Payload>one().get()); final AtomicBoolean once = new AtomicBoolean(); return Mono.defer( () -> { if (once.getAndSet(true)) { return Mono.error( new IllegalStateException("RequestResponseMono allows only a single subscriber")); } return receiver .next() .transform( Operators.<Payload, Payload>lift( (s, actual) -> new RequestOperator(actual) { int streamId; @Override void hookOnFirstRequest(long n) { int streamId = streamIdSupplier.nextStreamId(receivers); this.streamId = streamId; ByteBuf requestResponseFrame = RequestResponseFrameFlyweight.encodeReleasingPayload( allocator, streamId, payload); receivers.put(streamId, receiver); sendProcessor.onNext(requestResponseFrame); } @Override void hookOnCancel() { if (receivers.remove(streamId, receiver)) { sendProcessor.onNext( CancelFrameFlyweight.encode(allocator, streamId)); } else { payload.release(); } } @Override public void hookOnTerminal(SignalType signalType) { receivers.remove(streamId, receiver); } })) .doOnDiscard(ReferenceCounted.class, DROPPED_ELEMENTS_CONSUMER); }); }

Target:
private Mono<Payload> handleRequestResponse(final Payload payload) { Throwable err = checkAvailable(); if (err != null) { payload.release(); return Mono.error(err); } if (!PayloadValidationUtils.isValid(this.mtu, payload)) { payload.release(); return Mono.error(new IllegalArgumentException(INVALID_PAYLOAD_ERROR_MESSAGE)); } final UnboundedProcessor<ByteBuf> sendProcessor = this.sendProcessor; final UnicastProcessor<Payload> receiver = UnicastProcessor.create(Queues.<Payload>one().get()); final AtomicBoolean once = new AtomicBoolean(); return Mono.defer( () -> { if (once.getAndSet(true)) { return Mono.error( new IllegalStateException("RequestResponseMono allows only a single subscriber")); } return receiver .next() .transform( Operators.<Payload, Payload>lift( (s, actual) -> new RequestOperator(actual) { @Override void hookOnFirstRequest(long n) { int streamId = streamIdSupplier.nextStreamId(receivers); this.streamId = streamId; ByteBuf requestResponseFrame = RequestResponseFrameFlyweight.encodeReleasingPayload( allocator, streamId, payload); receivers.put(streamId, receiver); sendProcessor.onNext(requestResponseFrame); } @Override void hookOnCancel() { if (receivers.remove(streamId, receiver)) { sendProcessor.onNext( CancelFrameFlyweight.encode(allocator, streamId)); } else { payload.release(); } } @Override public void hookOnTerminal(SignalType signalType) { receivers.remove(streamId, receiver); } })) .doOnDiscard(ReferenceCounted.class, DROPPED_ELEMENTS_CONSUMER); }); }
Source:
public String decapitalize(String word) { if ((word == null) || (word.length() < 1)) { return word; } char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } return String.valueOf(Character.toLowerCase(first)) + word.substring(1); }

Target:
public String decapitalize(String word) { if ((word == null) || (word.length() < 1)) { return word; } char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } StringBuilder sb = new StringBuilder(word.length()); sb.append(Character.toLowerCase(first)); sb.append(word.substring(1)); return sb.toString(); }
Source:
public String displayCollectedMetaTags() { return metaTag.displayCollectedMetaTags(); }

Target:
public @NotNull String displayCollectedMetaTags() { return metaTag.displayCollectedMetaTags(); }
Source:
protected String obfuscateId(TimeoutException ex) { String error = ex.getMessage(); if (ex.getMessage().contains(ResourceMonitor.ERROR_MSG)) { String[] msg = ex.getMessage().split("\\]"); String[] splittedForId = msg[0].split(":"); String[] splittedForResourceType = splittedForId[0].split("\\["); String resourceId = splittedForId[1]; String resourceType = splittedForResourceType[1]; Object obfuscatedId = null; if (Instance.class.getSimpleName().equalsIgnoreCase(resourceType)) { Instance instance = objectManager.loadResource(Instance.class, resourceId); if (instance != null && instance.getName() != null) { obfuscatedId = instance.getName(); } } if (obfuscatedId == null) { idFormatter.formatId(resourceType, resourceId); } Object predicateResource = objectManager.loadResource(resourceType, resourceId); error = "Waiting for [" + resourceType + ":" + obfuscatedId + "]"; if (predicateResource != null) { String transitioningMsg = DataAccessor.fieldString(predicateResource, "transitioningMessage"); StringBuffer sb = new StringBuffer(resourceType); sb.replace(0, 1, resourceType.substring(0, 1).toUpperCase()); if (!StringUtils.isEmpty(sb)) { error = error + ". " + sb + " status: " + transitioningMsg; } } } return error; }

Target:
protected String obfuscateId(TimeoutException ex) { String error = ex.getMessage(); if (ex.getMessage().contains(ResourceMonitor.ERROR_MSG)) { String[] msg = ex.getMessage().split("\\]"); String[] splittedForId = msg[0].split(":"); String[] splittedForResourceType = splittedForId[0].split("\\["); String resourceId = splittedForId[1]; String resourceType = splittedForResourceType[1]; Object obfuscatedId = null; if (Instance.class.getSimpleName().equalsIgnoreCase(resourceType)) { Instance instance = objectManager.loadResource(Instance.class, resourceId); if (instance != null && instance.getName() != null) { obfuscatedId = instance.getName(); } } if (obfuscatedId == null) { obfuscatedId = idFormatter.formatId(resourceType, resourceId); } Object predicateResource = objectManager.loadResource(resourceType, resourceId); error = "Waiting for [" + resourceType + ":" + obfuscatedId + "]"; if (predicateResource != null) { String transitioningMsg = DataAccessor.fieldString(predicateResource, "transitioningMessage"); StringBuffer sb = new StringBuffer(resourceType); sb.replace(0, 1, resourceType.substring(0, 1).toUpperCase()); if (!StringUtils.isEmpty(sb)) { error = error + ". " + sb + " status: " + transitioningMsg; } } } return error; }
Source:
private static String removeConditionsClause(String importQuerySring) { if (importQuerySring.toUpperCase().contains("WHERE $CONDITIONS AND")) { importQuerySring = importQuerySring.toUpperCase().replace(" $CONDITIONS AND", ""); } else if (importQuerySring.toUpperCase().contains("WHERE $CONDITIONS")) { importQuerySring = importQuerySring.toUpperCase().replace(" WHERE $CONDITIONS", ""); } else if (importQuerySring.toUpperCase().contains("AND $CONDITIONS")) { importQuerySring = importQuerySring.toUpperCase().replace(" AND $CONDITIONS", ""); } return importQuerySring; }

Target:
private static String removeConditionsClause(String importQuerySring) { importQuerySring = importQuerySring.replaceAll("\\s{2,}", " ").toUpperCase(); if (importQuerySring.contains("WHERE $CONDITIONS AND")) { importQuerySring = importQuerySring.replace("$CONDITIONS AND", ""); } else if (importQuerySring.contains("WHERE $CONDITIONS")) { importQuerySring = importQuerySring.replace("WHERE $CONDITIONS", ""); } else if (importQuerySring.contains("AND $CONDITIONS")) { importQuerySring = importQuerySring.replace("AND $CONDITIONS", ""); } return importQuerySring; }
Source:
private Map<String, List> getRelationshipFieldMap(final Contentlet con, final Entry<String, List> records) { Optional<com.dotcms.contenttype.model.field.Field> field = null; try { field = APILocator.getContentTypeFieldAPI() .byContentTypeAndFieldRelationType(con.getContentTypeId(), records.getKey()); } catch (DotDataException e) { Logger.warn(this, "Error getting field for relation type " + records.getKey(), e); } if (field.isPresent()) { Map<String, List> results = new HashMap<>(); results.put(new StringBuilder(con.getContentType().variable()).append(".") .append(field.get().variable()).toString(), records.getValue()); return results; } return Collections.emptyMap(); }

Target:
private Map<String, List> getRelationshipFieldMap(final Contentlet con, final Entry<String, List> records) { Optional<com.dotcms.contenttype.model.field.Field> field = null; try { field = APILocator.getContentTypeFieldAPI() .byContentTypeAndFieldRelationType(con.getContentTypeId(), records.getKey()); } catch (DotDataException e) { Logger.warn(this, "Error getting field for relation type " + records.getKey(), e); } return field.isPresent()? CollectionsUtils.map(new StringBuilder(con.getContentType().variable()).append(".") .append(field.get().variable()).toString(), records.getValue()):Collections.emptyMap(); }