auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void showBundleFilter() { final Collection<String> bundleIds; if (getCollector() instanceof TargetPlatformClassContributionCollector) { bundleIds = TargetPlatformClassContributionCollector.getInstance().getBundleIds(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { bundleIds = TargetPlatformIconContributionCollector.getInstance().getBundleIds(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(bundleIds); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the bundle to filter on."); setTitle("Bundle Filter"); getShell().setText("Bundle Filter"); try { <START> setTitleImage(new Image(getShell().getDisplay(), getClass().getResourceAsStream("/icons/full/wizban/plugin_wiz.gif"))); <END> } catch (Exception e) { e.printStackTrace(); } return ret; } }; if (dlg.open() == Dialog.OK) { setFilterBundles((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }</code><technical_language>anonymous "new Image()" is a resource leak. Please some kind of resourcepool</technical_language>

Target:
protected void showBundleFilter() { final Collection<String> bundleIds; if (getCollector() instanceof TargetPlatformClassContributionCollector) { bundleIds = TargetPlatformClassContributionCollector.getInstance().getBundleIds(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { bundleIds = TargetPlatformIconContributionCollector.getInstance().getBundleIds(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(bundleIds); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the bundle to filter on."); setTitle("Bundle Filter"); getShell().setText("Bundle Filter"); try { setTitleImage(imageCache.create("/icons/full/wizban/plugin_wiz.gif")); } catch (Exception e) { e.printStackTrace(); } return ret; } }; if (dlg.open() == Dialog.OK) { setFilterBundles((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }
Source:
<code>private void updateSavePageMenuItem(MenuItem menuItemSavePage) { if (!savedPageCheckComplete) { menuItemSavePage.setEnabled(false); <START> } else if (refreshedIfSaved) { <END> menuItemSavePage.setEnabled(false); menuItemSavePage.setTitle(getString(R.string.menu_page_saved)); } else if (pageSaved) { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_refresh_saved_page)); } else { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_save_page)); } }</code><technical_language>Is this logic correct? I thought refreshIfSaved meant client if page saved wanted update saved page if saved</technical_language>

Target:
public void updateSavePageMenuItem(MenuItem menuItemSavePage) { if (!savedPageCheckComplete) { menuItemSavePage.setEnabled(false); } else if (pageRefreshed) { menuItemSavePage.setEnabled(false); menuItemSavePage.setTitle(getString(R.string.menu_page_saved)); } else if (pageSaved) { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_refresh_saved_page)); } else { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_page_save)); } }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (!(o instanceof ReplicationFactor)) return false; ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }</code><technical_language>missing braces</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ReplicationFactor)) { return false; } ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RosterGroupElement other = (RosterGroupElement) obj; <START> if (!Arrays.equals(children, other.children)) return false; <END> if (groupName == null) { if (other.groupName != null) return false; } else if (!groupName.equals(other.groupName)) return false; return true; }</code><technical_language>check</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RosterGroupElement other = (RosterGroupElement) obj; return Objects.equals(groupName, other.groupName); }
Source:
<code>private static List<Integer> findMatchName(String name, ITmfTrace trace) { Map<Integer, String> executableNames = getExecutableNames(trace); <START> List<Integer> TIDS = new ArrayList<>(); <END> Pattern checkRegex = Pattern.compile(name); for (Entry<Integer, String> entry : executableNames.entrySet()) { Matcher regexMatcher = checkRegex.matcher(entry.getValue()); if (regexMatcher.find()) { TIDS.add(entry.getKey()); } } return TIDS; }</code><technical_language>tids, lowercase</technical_language>

Target:
private static List<Integer> findMatchName(String name, ITmfTrace trace) { Map<Integer, String> executableNames = getExecutableNames(trace); List<Integer> tids = new ArrayList<>(); Pattern checkRegex = Pattern.compile(name); for (Entry<Integer, String> entry : executableNames.entrySet()) { Matcher regexMatcher = checkRegex.matcher(entry.getValue()); if (regexMatcher.find()) { tids.add(entry.getKey()); } } return tids; }
Source:
<code>private Set<DSemanticDecorator> getDElementToClearWithXref(final EObject root, final Set<EObject> semanticElements, final ECrossReferenceAdapter xref) { final Set<DSemanticDecorator> decoratorsToDestroy = new HashSet<DSemanticDecorator>(); for (EObject semElt : semanticElements) { for (Setting setting : xref.getInverseReferences(semElt)) { EObject eObj = setting.getEObject(); EReference targetReference = ViewpointPackage.Literals.DSEMANTIC_DECORATOR__TARGET; <START> EReference semanticElementsReference = ViewpointPackage.Literals.DREPRESENTATION_ELEMENT__SEMANTIC_ELEMENTS; <END> if (eObj instanceof DRepresentationElement && setting.getEStructuralFeature().equals(semanticElementsReference) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } else if (eObj instanceof DSemanticDecorator && setting.getEStructuralFeature().equals(targetReference) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } } } return decoratorsToDestroy; }</code><technical_language>2 constants defined once, of (performance-sensitive) loop</technical_language>

Target:
private Set<DSemanticDecorator> getDElementToClearWithXref(final EObject root, final Set<EObject> semanticElements, final ECrossReferenceAdapter xref) { final Set<DSemanticDecorator> decoratorsToDestroy = new HashSet<DSemanticDecorator>(); for (EObject semElt : semanticElements) { for (Setting setting : xref.getInverseReferences(semElt)) { EObject eObj = setting.getEObject(); if (setting.getEStructuralFeature().equals(DSEMANTIC_DECORATOR__TARGET) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } else if (!decoratorsToDestroy.contains(eObj) && setting.getEStructuralFeature().equals(DREPRESENTATION_ELEMENT__SEMANTIC_ELEMENTS) && EcoreUtil.isAncestor(root, eObj)) { DRepresentationElement repElt = (DRepresentationElement) eObj; if (semanticElements.containsAll(repElt.getSemanticElements())) { decoratorsToDestroy.add(repElt); } } } } return decoratorsToDestroy; }
Source:
<code>public static ObjectNode unflattenObjectNode(ObjectNode flatObject, char seperator) { ObjectNode root = mapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> iter = flatObject.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> item = iter.next(); String fullKey = item.getKey(); if( !fullKey.contains(Character.valueOf(seperator).toString())) { root.put(item.getKey(), item.getValue()); } else { ObjectNode currentNode = root; <START> List<String> keyParts = Lists.newArrayList(); <END> Iterables.addAll(keyParts, Splitter.on(seperator).split(item.getKey())); Iterator<String> keyPartIterator = Iterables.limit(Splitter.on(seperator).split(item.getKey()), keyParts.size()-1).iterator(); while( keyPartIterator.hasNext()) { String part = keyPartIterator.next(); if( currentNode.has(part) && currentNode.get(part).isObject() ) { currentNode = (ObjectNode) currentNode.get(part); } else { ObjectNode newNode = mapper.createObjectNode(); currentNode.put(part, newNode); currentNode = newNode; } }; currentNode.put(keyParts.get(keyParts.size()-1), item.getValue()); } } return root; }</code><technical_language>reason for switching Guava here, benefit</technical_language>

Target:
public static ObjectNode unflattenObjectNode(ObjectNode flatObject, char seperator) { ObjectNode root = mapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> iter = flatObject.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> item = iter.next(); String fullKey = item.getKey(); if( !fullKey.contains(Character.valueOf(seperator).toString())) { root.put(item.getKey(), item.getValue()); } else { ObjectNode currentNode = root; List<String> keyParts = new ArrayList<>(Arrays.asList(StringUtils.split(item.getKey(), seperator))); keyParts.remove(keyParts.size()-1); Iterator<String> keyPartIterator = keyParts.iterator(); while( keyPartIterator.hasNext()) { String part = keyPartIterator.next(); if( currentNode.has(part) && currentNode.get(part).isObject() ) { currentNode = (ObjectNode) currentNode.get(part); } else { ObjectNode newNode = mapper.createObjectNode(); currentNode.put(part, newNode); currentNode = newNode; } }; currentNode.put(keyParts.get(keyParts.size()-1), item.getValue()); } } return root; }
Source:
<code>public void returnsNotFoundWhenClientDoesNotExist() throws Exception { when(aclDAO.getBatchSanitizedSecretsFor(client, ImmutableList.of(secret.getName()))).thenReturn(ImmutableList.<SanitizedSecret>of()); when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.empty()); <START> when(secretController.getSecretsByName(ImmutableList.of(secret.getName()))) <END> .thenReturn(ImmutableList.<Secret>of()); batchSecretDeliveryResource.getBatchSecret(client, BatchSecretRequest.create(ImmutableList.of(secret.getName()))); }</code><technical_language>This test set existing secret, missing client--currently client secret missing, hard failure case is triggered</technical_language>

Target:
public void returnsNotFoundWhenClientDoesNotExist() throws Exception { when(aclDAO.getBatchSanitizedSecretsFor(client, ImmutableList.of(secret.getName()))).thenReturn(ImmutableList.of()); when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.empty()); when(secretController.getSecretsByName(ImmutableList.of(secret.getName()))) .thenReturn(ImmutableList.of(secret)); batchSecretDeliveryResource.getBatchSecret(client, BatchSecretRequest.create(ImmutableList.of(secret.getName()))); }
Source:
<code>protected boolean checkIfImageDiskCanBeAdded(VM vm, DiskVmElementValidator diskVmElementValidator) { if (Guid.Empty.equals(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_SPECIFIED); } boolean returnValue; StorageDomainValidator storageDomainValidator = createStorageDomainValidator(); returnValue = (getParameters().isSkipDomainCheck() || validate(storageDomainValidator.isDomainExistAndActive())) && validateShareableDiskOnGlusterDomain() && <START> checkImageConfiguration() && <END> validate(storageDomainValidator.hasSpaceForNewDisk(getDiskImageInfo())) && validate(storageDomainValidator.isDomainWithinThresholds()) && checkExceedingMaxBlockDiskSize() && canAddShareableDisk() && validate(diskVmElementValidator.isVirtIoScsiValid(vm)) && validate(diskVmElementValidator.isDiskInterfaceSupported(getVm())); if (returnValue && vm != null) { StoragePool sp = getStoragePool(); returnValue = validate(new StoragePoolValidator(sp).existsAndUp()) && isStoragePoolMatching(vm) && validate(new VmValidator(getVm()).vmNotLocked()) && isVmNotInPreviewSnapshot(); } return returnValue; }</code><technical_language>In case missed it: this line removed purpose? validate(storageDomainValidator.domainIsValidDestination())</technical_language>

Target:
protected boolean checkIfImageDiskCanBeAdded(VM vm, DiskVmElementValidator diskVmElementValidator) { if (Guid.Empty.equals(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_SPECIFIED); } boolean returnValue; StorageDomainValidator storageDomainValidator = createStorageDomainValidator(); returnValue = (getParameters().isSkipDomainCheck() || validate(storageDomainValidator.isDomainExistAndActive())) && validateShareableDiskOnGlusterDomain() && checkImageConfiguration() && validate(storageDomainValidator.domainIsValidDestination()) && validate(storageDomainValidator.hasSpaceForNewDisk(getDiskImageInfo())) && validate(storageDomainValidator.isDomainWithinThresholds()) && checkExceedingMaxBlockDiskSize() && canAddShareableDisk() && validate(diskVmElementValidator.isVirtIoScsiValid(vm)) && validate(diskVmElementValidator.isDiskInterfaceSupported(getVm())); if (returnValue && vm != null) { StoragePool sp = getStoragePool(); returnValue = validate(new StoragePoolValidator(sp).existsAndUp()) && isStoragePoolMatching(vm) && validate(new VmValidator(getVm()).vmNotLocked()) && isVmNotInPreviewSnapshot(); } return returnValue; }
Source:
<code>public ZoomThread(long startTime, long endTime, long resolution) { super(AbstractTimeGraphView.this.getName() + " zoom"); fZoomStartTime = startTime; fZoomEndTime = endTime; fResolution = resolution; fMonitor = new NullProgressMonitor(); <START> synchronized (fLastZoomThreadId) { <END> fInstanceId = ++fLastZoomThreadId; } }</code><technical_language>I is incorrect synchronize a Number change, is recommended synchronize a final object</technical_language>

Target:
public ZoomThread(long startTime, long endTime, long resolution) { super(AbstractTimeGraphView.this.getName() + " zoom"); fZoomStartTime = startTime; fZoomEndTime = endTime; fResolution = resolution; fMonitor = new NullProgressMonitor(); }
Source:
<code>public PreparedOperationWithReactiveStream<List<T>> prepare() { if (getResolver == null) { getResolver = DefaultGetResolver.INSTANCE; } <START> Checks.checkNotNull(mapFunc, "Please specify map function"); <END> if (query != null) { return new PreparedGetListOfObjects<>(storIOSQLiteDb, query, getResolver, mapFunc); } else if (rawQuery != null) { return new PreparedGetListOfObjects<>(storIOSQLiteDb, rawQuery, getResolver, mapFunc); } else { throw new IllegalStateException("Please specify query"); } }</code><technical_language>Static import</technical_language>

Target:
public PreparedOperationWithReactiveStream<List<T>> prepare() { if (getResolver == null) { getResolver = DefaultGetResolver.INSTANCE; } checkNotNull(mapFunc, "Please specify map function"); if (query != null) { return new PreparedGetListOfObjects<>(storIOSQLiteDb, query, getResolver, mapFunc); } else if (rawQuery != null) { return new PreparedGetListOfObjects<>(storIOSQLiteDb, rawQuery, getResolver, mapFunc); } else { throw new IllegalStateException("Please specify query"); } }
Source:
<code>public void beforeClass(final @Optional Boolean usingEncryption, final @Optional String testType) throws IOException { <START> if (testType.equals("buckets")) { <END> throw new SkipException("Skipping tests since snaplinks are disabled in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(usingEncryption); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }</code><technical_language>testType null, invert equals() check so: java if ("buckets".equals(testType)) {</technical_language>

Target:
public void beforeClass(final @Optional Boolean usingEncryption, final @Optional String testType) throws IOException { if ("buckets".equals(testType)) { throw new SkipException("Skipping tests since snaplinks are disabled in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(usingEncryption); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
<code>public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); <START> LOG.debug("ALocatorIO.getLocators() executing: select * from \"" + CassandraModel.KEYSPACE + "\"." + CassandraModel.CF_METRICS_LOCATOR + " where key=" + Long.toString(shard)); <END> return query.execute().getResult().getColumnNames(); } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + ")", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } }</code><technical_language>set this trace</technical_language>

Target:
public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); if (LOG.isTraceEnabled()) LOG.trace("ALocatorIO.getLocators() executing: select * from \"" + CassandraModel.KEYSPACE + "\"." + CassandraModel.CF_METRICS_LOCATOR_NAME + " where key=" + Long.toString(shard)); return query.execute().getResult().getColumnNames(); } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + ")", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } }
Source:
<code><START> @Before public void setUp() { <END> client = new LostApiClient.Builder(application).build(); FusedLocationProviderService.FusedLocationProviderBinder stubBinder = mock( FusedLocationProviderService.FusedLocationProviderBinder.class); when(stubBinder.getService()).thenReturn(mock(FusedLocationProviderService.class)); shadowOf(application).setComponentNameAndServiceForBindService( new ComponentName("com.mapzen.lost", "FusedLocationProviderService"), stubBinder); }</code><technical_language>Setup test methods in JUnit include throws Exception convention. This tests brittle ensures if method signatures change for production code test throw exception tests compile</technical_language>

Target:
@Before public void setUp() throws Exception { client = new LostApiClient.Builder(application).build(); FusedLocationProviderService.FusedLocationProviderBinder stubBinder = mock( FusedLocationProviderService.FusedLocationProviderBinder.class); when(stubBinder.getService()).thenReturn(mock(FusedLocationProviderService.class)); shadowOf(application).setComponentNameAndServiceForBindService( new ComponentName("com.mapzen.lost", "FusedLocationProviderService"), stubBinder); }
Source:
<code>private synchronized Graph buildGraph() { String implementationVersion = IntegrationGraphServer.class.getPackage().getImplementationVersion(); if (implementationVersion == null) { implementationVersion = "unknown - is Spring Integration running from the distribution jar?"; } Map<String, Object> descriptor = new HashMap<String, Object>(); descriptor.put("provider", "spring-integration"); descriptor.put("providerVersion", implementationVersion); descriptor.put("providerFormatVersion", GRAPH_VERSION); <START> if (this.applicationContext.containsBean("applicationNameAndVersion")) { <END> descriptor.put("name", this.applicationContext.getBean("applicationNameAndVersion")); } this.nodeFactory.reset(); Collection<IntegrationNode> nodes = new ArrayList<IntegrationNode>(); Collection<LinkNode> links = new ArrayList<LinkNode>(); Map<String, MessageChannelNode> channelNodes = channels(nodes); pollingAdapters(nodes, links, channelNodes); gateways(nodes, links, channelNodes); producers(nodes, links, channelNodes); consumers(nodes, links, channelNodes); this.graph = new Graph(descriptor, nodes, links); return this.graph; }</code><technical_language>weird. allow inject appName version IntegrationGraphServer bean</technical_language>

Target:
private synchronized Graph buildGraph() { String implementationVersion = IntegrationGraphServer.class.getPackage().getImplementationVersion(); if (implementationVersion == null) { implementationVersion = "unknown - is Spring Integration running from the distribution jar?"; } Map<String, Object> descriptor = new HashMap<String, Object>(); descriptor.put("provider", "spring-integration"); descriptor.put("providerVersion", implementationVersion); descriptor.put("providerFormatVersion", GRAPH_VERSION); String name = this.applicationName; if (name == null) { name = this.applicationContext.getEnvironment().getProperty("spring.application.name"); } if (name != null) { descriptor.put("name", name); } this.nodeFactory.reset(); Collection<IntegrationNode> nodes = new ArrayList<IntegrationNode>(); Collection<LinkNode> links = new ArrayList<LinkNode>(); Map<String, MessageChannelNode> channelNodes = channels(nodes); pollingAdapters(nodes, links, channelNodes); gateways(nodes, links, channelNodes); producers(nodes, links, channelNodes); consumers(nodes, links, channelNodes); this.graph = new Graph(descriptor, nodes, links); return this.graph; }
Source:
<code>private void saveAttachedHost(VmDevice vmDevice, Guid vdsId, boolean isLiveMigration) { TransactionSupport.executeInNewTransaction(() -> { Map<String, Object> specParams = new HashMap<>(); if <START> (!isLiveMigration) { <END> specParams.put(ManagedBlockStorageDisk.ATTACHED_VDS_ID, vdsId); } else { specParams.put(ManagedBlockStorageDisk.DEST_VDS_ID, vdsId); } if (vmDevice.getSpecParams() != null) { vmDevice.getSpecParams().putAll(specParams); } else { vmDevice.setSpecParams(specParams); } vmDeviceDao.update(vmDevice); return null; }); }</code><technical_language>replace !isLiveMigration isLiveMigration avoid operator</technical_language>

Target:
private void saveAttachedHost(VmDevice vmDevice, Guid vdsId, boolean isLiveMigration) { TransactionSupport.executeInNewTransaction(() -> { Map<String, Object> specParams = new HashMap<>(); if (isLiveMigration) { specParams.put(ManagedBlockStorageDisk.DEST_VDS_ID, vdsId); } else { specParams.put(ManagedBlockStorageDisk.ATTACHED_VDS_ID, vdsId); } if (vmDevice.getSpecParams() != null) { vmDevice.getSpecParams().putAll(specParams); } else { vmDevice.setSpecParams(specParams); } vmDeviceDao.update(vmDevice); return null; }); }
Source:
<code>private boolean buildMicroservicePath(String pa_home, String microservices_path) { String microservice_file = pa_home + separator + microservices_path + separator + microservice_name; if (new File(microservice_file).exists()) { command.add(microservice_file); return true; } else { <START> System.out.println("IAM microservice is not deployed"); <END> return false; } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Replace this of System.out System.err a logger. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static boolean buildMicroservicePath(String pa_home, String microservices_path) { String microservice_file = pa_home + SEPARATOR + microservices_path + SEPARATOR + MICROSERVICE_NAME; if (new File(microservice_file).exists()) { command.add(microservice_file); return true; } else { System.out.println("IAM microservice is not deployed"); return false; } }
Source:
<code>private static Coordinate[] readCoordinates(SliceInput input, int count) { requireNonNull(input, "input is null"); Coordinate[] coordinates = new Coordinate[count]; <START> for (int j = 0; j < count; j++) { <END> coordinates[j] = readCoordinate(input); } return coordinates; }</code><technical_language>assert count is non-negative</technical_language>

Target:
private static Coordinate[] readCoordinates(SliceInput input, int count) { requireNonNull(input, "input is null"); verify(count > 0); Coordinate[] coordinates = new Coordinate[count]; for (int i = 0; i < count; i++) { coordinates[i] = readCoordinate(input); } return coordinates; }
Source:
<code>private Table createSimpleTable(SchemaTableName schemaTableName, List<Column> columns, ConnectorSession session, Path targetPath, String queryId) { String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); Table.Builder tableBuilder = Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, queryId)) .setDataColumns(columns); <START> tableBuilder.getStorageBuilder() <END> .setLocation(targetPath.toString()) .setStorageFormat(StorageFormat.create(ORC.getSerDe(), ORC.getInputFormat(), ORC.getOutputFormat())) .setSerdeParameters(ImmutableMap.of()); return tableBuilder.build(); }</code><technical_language>Add a withStorage() method Table.Builder Partition.Builder has, do java return Table.builder() ... .withStorage(storage -> storage .setLocation(targetPath.toString()) .setStorageFormat(...) .setSerdeParameters(ImmutableMap.of())) .build();</technical_language>

Target:
private Table createSimpleTable(SchemaTableName schemaTableName, List<Column> columns, ConnectorSession session, Path targetPath, String queryId) { String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); return Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, queryId)) .setDataColumns(columns) .withStorage(storage -> storage .setLocation(targetPath.toString()) .setStorageFormat(fromHiveStorageFormat(ORC)) .setSerdeParameters(ImmutableMap.of())) .build(); }
Source:
<code>public void checkTest3() { projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/test3"); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/test3/fred"); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/test3/fred/A.java"); editor.waitActive(); editor.waitTextNotPresentIntoEditor(TEST3_R_OUT); projectExplorer.waitAndSelectItem(PROJECT_NAME + "/src/main/java/test3/fred"); projectExplorer.launchRefactorByKeyboard(); refactor.waitRenamePackageFormIsOpen(); refactor.sendKeysIntoField("test3.r"); refactor.waitTextIntoNewNameField("test3.r"); loader.waitOnClosed(); refactor.setAndWaitStateUpdateReferencesCheckbox(true); refactor.setAndWaitStateRenameSubpackagesCheckbox(false); refactor.setAndWaitStateUpdateNonJavaFilesCheckbox(false); <START> refactor.waitTextInErrorMessage("Package already exists"); <END> refactor.clickCancelButtonRefactorForm(); refactor.waitRenameFieldFormIsClosed(); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/test3/r/r"); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/test3/r/r/B.java"); editor.waitTextIntoEditor(TEST3_R_R_OUT); editor.closeFileByNameWithSaving("B"); }</code><technical_language>If I understand correctly, this rename work, anymore. Is this behvavior get Eclipse refactoring</technical_language>

Target:
public void checkTest3() { projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/mine/pack"); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/mine/pack/Textfile.txt"); editor.waitActive(); editor.waitTextIntoEditor(TEST12_RENAME_WITH_RESOURCE_IN); editor.closeFileByNameWithSaving("Textfile.txt"); projectExplorer.waitAndSelectItem(PROJECT_NAME + "/src/main/java/mine/pack"); projectExplorer.launchRefactorByKeyboard(); refactor.waitRenamePackageFormIsOpen(); loader.waitOnClosed(); refactor.sendKeysIntoField("main"); refactor.waitTextIntoNewNameField("main"); refactor.setAndWaitStateUpdateReferencesCheckbox(true); refactor.setAndWaitStateRenameSubpackagesCheckbox(false); refactor.setAndWaitStateUpdateNonJavaFilesCheckbox(true); refactor.typeAndWaitFileNamePatterns("*.txt"); loader.waitOnClosed(); refactor.clickOkButtonRefactorForm(); refactor.waitRenamePackageFormIsClosed(); loader.waitOnClosed(); projectExplorer.waitItem(PROJECT_NAME + "/src/main/java/main"); projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/main/Textfile.txt"); editor.waitTextIntoEditor(TEST12_RENAME_WITH_RESOURCE_OUT); editor.closeFileByNameWithSaving("Textfile.txt"); }
Source:
<code>private long doForceInsertNewDocumentWithHistory(DocumentRevision rev, List<String> revHistory) { Log.v(LOG_TAG, "doForceInsertNewDocumentWithHistory()"); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } long seq = insertRevision(docNumericID, revHistory.get(revHistory.size() - 1), parentSequence, rev.isDeleted(), true, rev.getBody().asBytes(), true); <START> return seq; <END> }</code><technical_language>Rename sequence match var names in other methods changed</technical_language>

Target:
private long doForceInsertNewDocumentWithHistory(DocumentRevision rev, List<String> revHistory) { Log.v(LOG_TAG, "doForceInsertNewDocumentWithHistory()"); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } long sequence = insertRevision(docNumericID, revHistory.get(revHistory.size() - 1), parentSequence, rev.isDeleted(), true, rev.getBody().asBytes(), true); return sequence; }
Source:
<code>private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver( grpcWriteChannel, uploadId, chunkData, writeOffset, objectHasher); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) .insertObject(responseObserver); responseObserver.done.await(); if (responseObserver.hasError()) { <START> this.pushbackPipeSource = new PushbackInputStream(pipeSource, MAX_BYTES_PER_MESSAGE); <END> long commitedSize = getCommittedWriteSize(uploadId); if (commitedSize <= writeOffset) { pushbackPipeSource.unread(pushbackBuffer, 0, pushbackBuffer.length); } else { int missedChunkLength = (int) (pushbackBuffer.length - (commitedSize - writeOffset)); pushbackPipeSource.unread( pushbackBuffer, pushbackBuffer.length - missedChunkLength, missedChunkLength); writeOffset += commitedSize - writeOffset; } ++retriesAttempted; } else { writeOffset += responseObserver.bytesWritten(); retriesAttempted = 0; } if (retriesAttempted == maxRetries) { throw new IOException( String.format("Insert failed for '%s'", resourceId), responseObserver.getError()); } } while (!responseObserver.isFinished()); return responseObserver.getResponse(); }</code><technical_language>I simpler error-prone [BufferedInputStream](<LINK_0> [mark](<LINK_2>[reset](<LINK_1> methods instead of manually maintaining retry cache PushbackInputStream</technical_language>

Target:
private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver(uploadId, chunkData, writeOffset, objectHasher); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) .insertObject(responseObserver); responseObserver.done.await(); if (responseObserver.hasError()) { long committedSize = getCommittedWriteSize(uploadId); pipeSource.reset(); if (committedSize > writeOffset) { int uploadedDataChunkSize = Math.toIntExact(committedSize - writeOffset); pipeSource.skip(uploadedDataChunkSize); writeOffset += uploadedDataChunkSize; } ++retriesAttempted; } else { writeOffset += responseObserver.bytesWritten(); retriesAttempted = 0; } if (retriesAttempted >= WRITE_CHUNK_RETRIES) { throw new IOException( String.format("Insert failed for '%s'", resourceId), responseObserver.getError()); } } while (!responseObserver.isFinished()); return responseObserver.getResponse(); }
Source:
<code>public void enableFirewall(boolean enabled) { if(this.enabled != enabled) { logger.info("Setting firewall to {}", enabled); this.enabled = enabled; List<Masked<U64>> changes = new ArrayList<Masked<U64>>(); <START> changes.add(Masked.of(DEFAULT_COOKIE, AppCookie.getAppFieldMask())); <END> routingService.handleRoutingDecisionChange(changes); } }</code><technical_language>ImmutableSet instead? is list necessary instead of set</technical_language>

Target:
public void enableFirewall(boolean enabled) { if(this.enabled != enabled) { logger.info("Setting firewall to {}", enabled); this.enabled = enabled; List<Masked<U64>> changes = ImmutableList.of( Masked.of(DEFAULT_COOKIE, AppCookie.getAppFieldMask()) ); routingService.handleRoutingDecisionChange(changes); } }
Source:
<code>private String serialize(Expression<?> expression) { CollectionAnyVisitor visitor = new CollectionAnyVisitor() { @Override protected Predicate exists(Context c, Predicate condition) { return condition; } }; <START> Expression<?> transformed = expression.accept(visitor, new Context()); <END> return transformed.toString(); }</code><technical_language>in mind, collectionAnyVisitor is stateful. tests reflect well</technical_language>

Target:
private String serialize(Expression<?> expression) { return serialize(expression, new CollectionAnyVisitor()); }
Source:
<code>public AeternityRPCClient(String rpcUrl) throws MalformedURLException { super(CryptoCurrency.AE.getCode(), baseUrl); if (rpcUrl == null) rpcUrl = baseUrl; <START> api = RestProxyFactory.createProxy(AeternityV2API.class, "<LINK_1>"); END> serviceConf = ServiceConfiguration.configure().baseUrl(rpcUrl).compile(); accountService = new AccountServiceFactory().getService(serviceConf); chainService = new ChainServiceFactory().getService(serviceConf); transactionService = new TransactionServiceFactory().getService(TransactionServiceConfiguration.configure().baseUrl(rpcUrl).network(mainnet).compile()); }</code><technical_language>Please centralized service track transactions. Please wallet provide this information, BCH</technical_language>

Target:
public AeternityRPCClient(String rpcUrl) throws MalformedURLException { super(CryptoCurrency.AE.getCode(), baseUrl); if (rpcUrl == null) rpcUrl = baseUrl; String sdkUrl = rpcUrl + "/v2"; api = RestProxyFactory.createProxy(AeternityV2API.class, rpcUrl); serviceConf = ServiceConfiguration.configure().baseUrl(sdkUrl).compile(); accountService = new AccountServiceFactory().getService(serviceConf); chainService = new ChainServiceFactory().getService(serviceConf); transactionService = new TransactionServiceFactory().getService(TransactionServiceConfiguration.configure().baseUrl(rpcUrl).network(mainnet).compile()); }
Source:
<code>public void provision(RuntimeIdentity id, InternalEnvironment internalEnvironment) throws InfrastructureException { if (hasInstallers(internalEnvironment)) { for (EnvVarProvider envVarProvider : envVarProviders) { Pair<String, String> envVar = envVarProvider.get(id); if (envVar != null) { <START> LOG.info( <END> "Provisioning legacy environment variables for workspace '{}' from with variable", id.getWorkspaceId(), envVarProvider, envVar.first); internalEnvironment .getMachines() .values() .forEach(m -> m.getEnv().putIfAbsent(envVar.first, envVar.second)); } } LOG.info( "Environment legacy variables provisioning done for workspace '{}'", id.getWorkspaceId()); } else { LOG.debug( "Legacy environment variables not provisioned to workspace '{}'.", id.getWorkspaceId()); } }</code><technical_language>debug logs info, WDYT</technical_language>

Target:
public void provision(RuntimeIdentity id, InternalEnvironment internalEnvironment) throws InfrastructureException { if (!hasInstallers(internalEnvironment)) { LOG.debug( "Legacy environment variables not provisioned to workspace '{}'.", id.getWorkspaceId()); return; } for (EnvVarProvider envVarProvider : envVarProviders) { Pair<String, String> envVar = envVarProvider.get(id); if (envVar != null) { LOG.debug( "Provisioning legacy environment variables for workspace '{}' from with variable", id.getWorkspaceId(), envVarProvider.getClass().getSimpleName(), envVar.first); internalEnvironment .getMachines() .values() .forEach(m -> m.getEnv().putIfAbsent(envVar.first, envVar.second)); } } LOG.info( "Environment legacy variables provisioning done for workspace '{}'", id.getWorkspaceId()); }
Source:
<code>public String getSourceResponseString() { if (srcs != null && srcs.length != 0) { <START> return Arrays.toString(srcs); <END> } else { return src; } }</code><technical_language>Arrays.toString string representation is defined. <LINK_1> a collection String.join control format. <LINK_0></technical_language>

Target:
public String getSourceResponseString() { if (!CollectionUtils.isEmpty(srcs)) { return String.join(", ", srcs); } else { return src; } }
Source:
<code>public MatchingApplicabilityTagsRule(IAtsClient atsClient) { this.atsClient = atsClient; featureDefinitionData = null; <START> validFeatureValues = null; <END> }</code><technical_language>necessary JVM initializes object fields null</technical_language>

Target:
public MatchingApplicabilityTagsRule(IAtsClient atsClient) { this.atsClient = atsClient; }
Source:
<code>public synchronized boolean generateStructure(World world, Random rand, CubePos cubePos) { this.initializeStructureData(world); int centerX = cubeToCenterBlock(cubePos.getX()); int centerY = cubeToCenterBlock(cubePos.getY()); int centerZ = cubeToCenterBlock(cubePos.getZ()); boolean generated = false; for (ICubicStructureStart cubicStructureStart : this.structureMap) { StructureStart structStart = (StructureStart) cubicStructureStart; if (structStart.isSizeableStructure() && structStart.isValidForPostProcess(cubePos.chunkPos()) && structStart.getBoundingBox().intersectsWith( new StructureBoundingBox(centerX, centerY, centerZ, centerX + 15, centerY + 15, centerZ + 15))) { structStart.generateStructure(world, rand, <START> new StructureBoundingBox(centerX, centerY, centerZ, centerX + 15, centerY + 15, centerZ + 15)); END> structStart.notifyPostProcessAt(cubePos.chunkPos()); generated = true; this.setStructureStart(structStart.getChunkPosX(), cubicStructureStart.getChunkPosY(), structStart.getChunkPosZ(), structStart); } } return generated; }</code><technical_language>Yes, this changed Cube.SIZE - 1</technical_language>

Target:
public synchronized boolean generateStructure(World world, Random rand, CubePos cubePos) { this.initializeStructureData(world); int centerX = cubeToCenterBlock(cubePos.getX()); int centerY = cubeToCenterBlock(cubePos.getY()); int centerZ = cubeToCenterBlock(cubePos.getZ()); boolean generated = false; for (ICubicStructureStart cubicStructureStart : this.structureMap) { StructureStart structStart = (StructureStart) cubicStructureStart; if (structStart.isSizeableStructure() && structStart.isValidForPostProcess(cubePos.chunkPos()) && structStart.getBoundingBox().intersectsWith( new StructureBoundingBox(centerX, centerY, centerZ, centerX + Cube.SIZE - 1, centerY + Cube.SIZE - 1, centerZ + Cube.SIZE - 1))) { structStart.generateStructure(world, rand, new StructureBoundingBox(centerX, centerY, centerZ, centerX + Cube.SIZE - 1, centerY + Cube.SIZE - 1, centerZ + Cube.SIZE - 1)); structStart.notifyPostProcessAt(cubePos.chunkPos()); generated = true; this.setStructureStart(structStart.getChunkPosX(), cubicStructureStart.getChunkPosY(), structStart.getChunkPosZ(), structStart); } } return generated; }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedPartitionableRecord<?, ?> that = (OrderedPartitionableRecord<?, ?>) o; <START> return Objects.equals(stream, that.stream) && <END> Objects.equals(partitionId, that.partitionId) && Objects.equals(sequenceNumber, that.sequenceNumber); }</code><technical_language>data is missing in equals hashCode</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedPartitionableRecord<?, ?> that = (OrderedPartitionableRecord<?, ?>) o; if (data.size() != that.data.size()) { return false; } for (int i = 0; i < data.size(); i++) { if (!Arrays.equals(data.get(i), that.data.get(i))) { return false; } } return Objects.equals(stream, that.stream) && Objects.equals(partitionId, that.partitionId) && Objects.equals(sequenceNumber, that.sequenceNumber); }
Source:
<code>public void testDestroyCacheManagerWithMultipleClients() throws CachePersistenceException { PersistentCacheManager persistentCacheManager1 = clusteredCacheManagerBuilder.build(true); PersistentCacheManager persistentCacheManager2 = clusteredCacheManagerBuilder.build(true); persistentCacheManager1.close(); try { persistentCacheManager1.destroy(); <START> } catch (StateTransitionException e) { <END> assertThat(e.getMessage(), is("Couldn't acquire cluster-wide maintenance lease")); } assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED)); assertThat(persistentCacheManager2.getStatus(), is(Status.AVAILABLE)); Cache<Long, String> cache = persistentCacheManager2.createCache("test", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.fixed("primary-server-resource", 32, MemoryUnit.MB)))); cache.put(1L, "One"); assertThat(cache.get(1L), is("One")); }</code><technical_language>safer add Assert.fail line 81</technical_language>

Target:
public void testDestroyCacheManagerWithMultipleClients() throws CachePersistenceException { PersistentCacheManager persistentCacheManager1 = clusteredCacheManagerBuilder.build(true); PersistentCacheManager persistentCacheManager2 = clusteredCacheManagerBuilder.build(true); persistentCacheManager1.close(); try { persistentCacheManager1.destroy(); fail("StateTransitionException expected"); } catch (StateTransitionException e) { assertThat(e.getMessage(), is("Couldn't acquire cluster-wide maintenance lease")); } assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED)); assertThat(persistentCacheManager2.getStatus(), is(Status.AVAILABLE)); Cache<Long, String> cache = persistentCacheManager2.createCache("test", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.fixed("primary-server-resource", 32, MemoryUnit.MB)))); cache.put(1L, "One"); assertThat(cache.get(1L), is("One")); }
Source:
<code>public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); CurrencyAmount base = product.getUnderlyingOption().getUnderlying().getBaseCurrencyAmount(); CurrencyAmount counter = product.getUnderlyingOption().getUnderlying().getCounterCurrencyAmount(); buf.append(product.getUnderlyingOption().getLongShort()); buf.append(" Barrier "); buf.append(SummarizerUtils.fx(base, counter)); buf.append(" : "); buf.append(SummarizerUtils.date(product.getUnderlyingOption().getExpiryDate())); CurrencyPair currencyPair = product.getCurrencyPair(); return SummarizerUtils.summary( this, ProductType.FX_SINGLE_BARRIER_OPTION, buf.toString(), currencyPair.getBase(), currencyPair.getCounter()); <START> } <END></code><technical_language>Capture premium do for IR options</technical_language>

Target:
public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); CurrencyAmount base = product.getUnderlyingOption().getUnderlying().getBaseCurrencyAmount(); CurrencyAmount counter = product.getUnderlyingOption().getUnderlying().getCounterCurrencyAmount(); buf.append(product.getUnderlyingOption().getLongShort()); buf.append(" Barrier "); buf.append(SummarizerUtils.fx(base, counter)); buf.append(" Premium "); buf.append(SummarizerUtils.amount(premium.getValue().mapAmount(v -> Math.abs(v)))); buf.append(" : "); buf.append(SummarizerUtils.date(product.getUnderlyingOption().getExpiryDate())); CurrencyPair currencyPair = product.getCurrencyPair(); return SummarizerUtils.summary( this, ProductType.FX_SINGLE_BARRIER_OPTION, buf.toString(), currencyPair.getBase(), currencyPair.getCounter()); }
Source:
<code>public static Timestamp getCurrentTimeOnDB( Connection conn, Calendar cal ) throws SQLException, ConnectException { String query; String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) { query = "select CURRENT_TIMESTAMP from dual"; <START> } else if ("Apache Derby".equals(dbProduct) || dbProduct.startsWith("DB2")) { <END> query = "values(CURRENT_TIMESTAMP)"; } else { query = "select CURRENT_TIMESTAMP;"; } try (Statement stmt = conn.createStatement()) { log.debug("executing query " + query + " to get current time from database"); ResultSet rs = stmt.executeQuery(query); if (rs.next()) { return rs.getTimestamp(1, cal); } else { throw new ConnectException( "Unable to get current time from DB using query " + query + " on database " + dbProduct ); } } catch (SQLException e) { log.error( "Failed to get current time from DB using query " + query + " on database " + dbProduct, e ); throw e; } }</code><technical_language>super cautious add: (dbProduct != null && dbProduct.startsWith("DB2")) instead? A matter of style more else, a possibility of implementation of getDatabaseProductName returning null</technical_language>

Target:
public static Timestamp getCurrentTimeOnDB( Connection conn, Calendar cal ) throws SQLException, ConnectException { String query; String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) { query = "select CURRENT_TIMESTAMP from dual"; } else if ("Apache Derby".equals(dbProduct) || "DB2 UDB for AS/400".equals(dbProduct)) { query = "values(CURRENT_TIMESTAMP)"; } else { query = "select CURRENT_TIMESTAMP;"; } try (Statement stmt = conn.createStatement()) { log.debug("executing query " + query + " to get current time from database"); ResultSet rs = stmt.executeQuery(query); if (rs.next()) { return rs.getTimestamp(1, cal); } else { throw new ConnectException( "Unable to get current time from DB using query " + query + " on database " + dbProduct ); } } catch (SQLException e) { log.error( "Failed to get current time from DB using query " + query + " on database " + dbProduct, e ); throw e; } }