auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void searchAudit() { if (NullChecker.isNullish(messageId) && NullChecker.isNullish(relatesTo)) { if (null != eventEndDate && null != eventEndDate && eventStartDate.getTime() > eventEndDate.getTime()) { HelperUtil.addMessageError(null, "The EndTime should be greater than startTime."); return; } auditRecordList = service.searchAuditRecord( selectedEventTypeList, NullChecker.isNotNullishIgnoreSpace(userId) ? userId.trim() : null, getRemoteHCIDFromSelectedOrgs(), eventStartDate, eventEndDate, getRemoteHcidOrgNameMap()); } else { auditRecordList = service.searchAuditRecordBasedOnMsgIdAndRelatesTo( NullChecker.isNotNullishIgnoreSpace(messageId) ? messageId.trim() : null, NullChecker.isNotNullishIgnoreSpace(relatesTo) ? relatesTo.trim() : null, getRemoteHcidOrgNameMap()); } if (NullChecker.isNullish(auditRecordList)) { auditMessage = AUDIT_RECORDS_NOT_FOUND; auditFound = false; } else { auditMessage = AUDIT_RECORDS_FOUND; auditFound = true; } }

Target:
public void searchAudit() { if (NullChecker.isNullish(messageId) && NullChecker.isNullish(relatesTo)) { if (null != eventEndDate && null != eventEndDate && eventStartDate.after(eventEndDate)) { HelperUtil.addMessageError(null, HelperUtil.readPropertyAdminGui(KEY_STARTTIME_ENDTIME_MSG, DEFAULT_STARTTIME_ENDTIME_MSG)); return; } auditRecordList = service.searchAuditRecord( selectedEventTypeList, NullChecker.isNotNullishIgnoreSpace(userId) ? userId.trim() : null, getRemoteHCIDFromSelectedOrgs(), eventStartDate, eventEndDate, getRemoteHcidOrgNameMap()); } else { auditRecordList = service.searchAuditRecordBasedOnMsgIdAndRelatesTo( NullChecker.isNotNullishIgnoreSpace(messageId) ? messageId.trim() : null, NullChecker.isNotNullishIgnoreSpace(relatesTo) ? relatesTo.trim() : null, getRemoteHcidOrgNameMap()); } if (NullChecker.isNullish(auditRecordList)) { auditMessage = AUDIT_RECORDS_NOT_FOUND; auditFound = false; } else { auditMessage = AUDIT_RECORDS_FOUND; auditFound = true; } }
Source:
public void testLoadOrderedPublicEvents_6() throws Throwable { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24") .withAuthorization(Group.FREE_GROUP_NAME, "tempRole", Permission.BACKOFFICE).build(); String accessToken = mockOAuthInterceptor(user); ResultActions result = mockMvc .perform(get("/plugins/cms/contents") .param("status", IContentService.STATUS_ONLINE) .param("sort", IContentManager.CONTENT_MAIN_GROUP_FILTER_KEY) .param("direction", FieldSearchFilter.ASC_ORDER) .param("filters[0].attribute", IContentManager.ENTITY_TYPE_CODE_FILTER_KEY) .param("filters[0].operator", "eq") .param("filters[0].value", "EVN") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); String bodyResult = result.andReturn().getResponse().getContentAsString(); result.andExpect(status().isOk()); String expectedContentId = "EVN25"; int payloadSize = JsonPath.read(bodyResult, "$.payload.size()"); String extractedId = JsonPath.read(bodyResult, "$.payload[" + 0 + "].id"); Assert.assertEquals(expectedContentId, extractedId); }

Target:
public void testLoadOrderedPublicEvents_6() throws Throwable { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24") .withAuthorization(Group.FREE_GROUP_NAME, "tempRole", Permission.BACKOFFICE).build(); String accessToken = mockOAuthInterceptor(user); ResultActions result = mockMvc .perform(get("/plugins/cms/contents") .param("status", IContentService.STATUS_ONLINE) .param("sort", IContentManager.CONTENT_MAIN_GROUP_FILTER_KEY) .param("direction", FieldSearchFilter.ASC_ORDER) .param("filters[0].attribute", IContentManager.ENTITY_TYPE_CODE_FILTER_KEY) .param("filters[0].operator", "eq") .param("filters[0].value", "EVN") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); result.andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.payload.size()", is(9))) .andExpect(jsonPath("$.payload[0].id", is("EVN25"))); }
Source:
protected void execute(final String schema, final String table, final LocalDate startDate, final LocalDate endDate) { final SqlQuery sql = _ebeanServer.createSqlQuery( "select * from create_daily_partition(?::text, ?::text, ?::date, ?::date)") .setParameter(1, schema) .setParameter(2, table) .setParameter(3, startDate) .setParameter(4, endDate); sql.findOneOrEmpty().orElseThrow(() -> new IllegalStateException("Expected a single empty result.")); }

Target:
protected void execute( final String schema, final String table, final LocalDate startDate, final LocalDate endDate ) { final SqlQuery sql = _ebeanServer.createSqlQuery( "select * from create_daily_partition(?::text, ?::text, ?::date, ?::date)") .setParameter(1, schema) .setParameter(2, table) .setParameter(3, startDate) .setParameter(4, endDate); sql.findOneOrEmpty().orElseThrow(() -> new PersistenceException("Expected a single empty result.")); }
Source:
public long getCardinality() { try { response = searchBuilder .execute() .actionGet(); return response.getHits().getTotalHits(); } catch (Exception e) { return 0; } }

Target:
public long getCardinality() { if (pos > 0) { return totalHits; } try { EsResponse res = client.search(index, type, query); Document hits = (Document) res.get("hits"); totalHits = hits.getInteger("total"); return totalHits; } catch (Exception e) { throw new EsIndexException(e); } }
Source:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: case ACTIVE_ASYNC: case NOT_STARTED: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; default: if (!cmdEntity.isCallBackNotified()) { addToCallBackMap(cmdEntity); } break; } } cmdExecutorInitialized = true; } }

Target:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { if (!cmdEntity.isExecuted()) { coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); } else if (!cmdEntity.isCallBackNotified()) { addToCallBackMap(cmdEntity); } } cmdExecutorInitialized = true; } }
Source:
public Element encode(Object object, Document document, Element value) throws Exception { EObject eobject = (EObject) object; if (EMFUtils.has(eobject, "data")) { Object v = EMFUtils.get(((EObject) object), "data"); if (v != null && v instanceof EList) { EList data = (EList) v; if (!data.isEmpty() && data.get(0) instanceof EncoderDelegate) { EncoderDelegate encoder = (EncoderDelegate) data.get(0); StringWriter output = new StringWriter(); Transformer transformer = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformer(); SerializationHandler outputHandler = ((TransformerImpl)transformer).getOutputHandler(new StreamResult(output)); encoder.encode(outputHandler); value.appendChild(document.createTextNode(cleanUpHeader(output.toString()))); } } } return value; }

Target:
public Element encode(Object object, Document document, Element value) throws Exception { EObject eobject = (EObject) object; if (EMFUtils.has(eobject, "data")) { Object v = EMFUtils.get(((EObject) object), "data"); if (v != null && v instanceof EList) { EList data = (EList) v; if (!data.isEmpty() && data.get(0) instanceof EncoderDelegate) { EncoderDelegate encoder = (EncoderDelegate) data.get(0); StringWriter output = new StringWriter(); TransformerHandler serializer = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler(); serializer.setResult(new StreamResult(output)); encoder.encode(serializer); CDATASection cData = document.createCDATASection(WPS.cleanUpHeader(output.toString())); cData.normalize(); value.appendChild(cData); } } } return value; }
Source:
protected final void setDatabaseUrl(final List<ServerAddress> databaseUrl) { if (!setup) { throw new IllegalStateException("Can only set this variable during valid times"); } this.databaseUrl = databaseUrl; }

Target:
protected final void setDatabaseUrl(final List<ServerAddress> databaseUrl) { if (!setup) { throw new IllegalStateException("Can only set this variable during setup"); } this.databaseUrl = databaseUrl; }
Source:
@Override public byte[] encode(ClientListenerResponse resp) { assert resp != null; BinaryHeapOutputStream outStream = new BinaryHeapOutputStream(32); BinaryRawWriterEx writer = marsh.writer(outStream); assert resp instanceof ClientResponse || resp instanceof ClientNotification : "Unexpected response type: " + resp.getClass(); if (resp instanceof ClientResponse) ((ClientResponse)resp).encode(ctx, writer); else if (resp instanceof ClientNotification) ((ClientNotification)resp).encode(ctx, writer); return outStream.arrayCopy(); }

Target:
@Override public byte[] encode(ClientListenerResponse resp) { assert resp != null; BinaryHeapOutputStream outStream = new BinaryHeapOutputStream(32); BinaryRawWriterEx writer = marsh.writer(outStream); assert resp instanceof ClientOutgoingMessage : "Unexpected response type: " + resp.getClass(); ((ClientOutgoingMessage)resp).encode(ctx, writer); return outStream.arrayCopy(); }
Source:
public PreparedAttachment(Attachment attachment, String attachmentsDir) throws AttachmentException { this.attachment = attachment; this.tempFile = new File(attachmentsDir, "temp" + UUID.randomUUID()); InputStream attachmentInStream = null; OutputStream tempFileOutStream = null; MessageDigest sha1 = null; try { attachmentInStream = attachment.getInputStream(); tempFileOutStream = FileUtils.openOutputStream(this.tempFile); sha1 = MessageDigest.getInstance("SHA-1"); int bufSiz = 1024; byte buf[] = new byte[bufSiz]; int bytesRead; int totalRead = 0; while ((bytesRead = attachmentInStream.read(buf)) != -1) { sha1.update(buf, 0, bytesRead); tempFileOutStream.write(buf, 0, bytesRead); totalRead += bytesRead; } this.length = totalRead; } catch (IOException e) { logger.log(Level.WARNING,"Problem reading input or output stream ",e); throw new AttachmentNotSavedException(e); } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING,"Problem calculating SHA1 for attachment stream ",e); throw new AttachmentNotSavedException(e); } finally { IOUtils.closeQuietly(attachmentInStream); IOUtils.closeQuietly(tempFileOutStream); } this.sha1 = sha1.digest(); }

Target:
public PreparedAttachment(Attachment attachment, String attachmentsDir) throws AttachmentException { this.attachment = attachment; this.tempFile = new File(attachmentsDir, "temp" + UUID.randomUUID()); InputStream attachmentInStream = null; OutputStream tempFileOutStream = null; MessageDigest calculateSha1 = null; int totalRead = 0; try { attachmentInStream = attachment.getInputStream(); tempFileOutStream = FileUtils.openOutputStream(this.tempFile); calculateSha1 = MessageDigest.getInstance("SHA-1"); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = attachmentInStream.read(buffer)) != -1) { calculateSha1.update(buffer, 0, bytesRead); tempFileOutStream.write(buffer, 0, bytesRead); totalRead += bytesRead; } } catch (IOException e) { logger.log(Level.WARNING, "Problem reading from input or writing to output stream ", e); throw new AttachmentNotSavedException(e); } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING, "Problem calculating SHA1 for attachment stream ", e); throw new AttachmentNotSavedException(e); } finally { IOUtils.closeQuietly(attachmentInStream); IOUtils.closeQuietly(tempFileOutStream); } this.length = totalRead; this.sha1 = calculateSha1.digest(); }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTION_WIFI_CODE) { if (resultCode == RESULT_OK) { info("wifi turned on"); } else { info("wifi NOT turned on"); } } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTION_WIFI_CODE) { if (resultCode == RESULT_OK) { info("wifi turned on"); } else { info("wifi NOT turned on, resultCode: " + resultCode); } } else { info("MainActivity: Unhandled requestCode: " + requestCode + " resultCode: " + resultCode); } }
Source:
protected FilterChainResolver createInstance(ServletContext servletContext) throws Exception { PathMatchingFilterChainResolver resolver = new PathMatchingFilterChainResolver(servletContext); FilterChainManager mgr = getConfig().getFilterChainManager(); resolver.setFilterChainManager(mgr); AccountResolverFilterFactory factory = new AccountResolverFilterFactory(); factory.init(servletContext); Filter accountFilter = factory.getInstance(); final List<Filter> priorityFilters = new ArrayList<>(); priorityFilters.add(accountFilter); if (getConfig().isCorsEnabled()) { CORSFilterFactory corsFilterFactory = new CORSFilterFactory(); corsFilterFactory.init(servletContext); priorityFilters.add(corsFilterFactory.getInstance()); } return new PrioritizedFilterChainResolver(resolver, priorityFilters); }

Target:
protected FilterChainResolver createInstance(ServletContext servletContext) throws Exception { PathMatchingFilterChainResolver resolver = new PathMatchingFilterChainResolver(servletContext); FilterChainManager mgr = getConfig().getFilterChainManager(); resolver.setFilterChainManager(mgr); AccountResolverFilterFactory factory = new AccountResolverFilterFactory(); factory.init(servletContext); Filter accountFilter = factory.getInstance(); final List<Filter> priorityFilters = new ArrayList<>(); priorityFilters.add(accountFilter); if (getConfig().isCorsEnabled()) { CorsFilterFactory corsFilterFactory = new CorsFilterFactory(); corsFilterFactory.init(servletContext); priorityFilters.add(corsFilterFactory.getInstance()); } return new PrioritizedFilterChainResolver(resolver, priorityFilters); }
Source:
private static IASTInitializerClause getInitializerClauseForDecltypeAuto(IASTDeclarator declarator) { IASTInitializer initializer = declarator.getInitializer(); if (initializer == null) { ICPPASTNewExpression newExpression = CPPVisitor.findAncestorWithType(declarator, ICPPASTNewExpression.class); if (newExpression != null) { initializer = newExpression.getInitializer(); } } if (initializer instanceof IASTEqualsInitializer) { return ((IASTEqualsInitializer) initializer).getInitializerClause(); } else if (initializer instanceof ICPPASTConstructorInitializer) { ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; IASTInitializerClause[] arguments = constructorInitializer.getArguments(); if (arguments.length == 1) { return arguments[0]; } } if (initializer instanceof IASTInitializerList) { IASTInitializerList initializerList = (IASTInitializerList) initializer; IASTInitializerClause[] clauses = initializerList.getClauses(); if (clauses.length == 1) { return clauses[0]; } } return null; }

Target:
private static IASTInitializerClause getInitializerClauseForDecltypeAuto(IASTDeclarator declarator) { IASTInitializer initializer = declarator.getInitializer(); if (initializer == null) { ICPPASTNewExpression newExpression = CPPVisitor.findAncestorWithType(declarator, ICPPASTNewExpression.class); if (newExpression != null) { initializer = newExpression.getInitializer(); } } if (initializer instanceof IASTEqualsInitializer) { return ((IASTEqualsInitializer) initializer).getInitializerClause(); } else if (initializer instanceof ICPPASTConstructorInitializer) { ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; IASTInitializerClause[] arguments = constructorInitializer.getArguments(); if (arguments.length == 1) { return arguments[0]; } } else if (initializer instanceof IASTInitializerList) { IASTInitializerList initializerList = (IASTInitializerList) initializer; IASTInitializerClause[] clauses = initializerList.getClauses(); if (clauses.length == 1) { return clauses[0]; } } return null; }
Source:
public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { set(kind, value); fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }

Target:
public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { fKind = kind; fSuffix = getSuffix(kind, value, fSuffix); fLiteral = getLiteral(value, fSuffix); fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }
Source:
public boolean getRequestParamAsBoolean(String paramName) { String paramValue = getRequestParamValue(paramName); if (paramValue == null || paramValue.equals("off")) { return false; } else if (paramValue.equals("on")) { return true; } else { return Boolean.parseBoolean(getRequestParamValue(paramName)); } }

Target:
public boolean getRequestParamAsBoolean(String paramName) { return Boolean.parseBoolean(getRequestParamValue(paramName)); }
Source:
public RevertResult revert(String commit) throws GitException { RevCommit revCommit; RevertCommand revertCommand = getGit().revert(); try { revertCommand.include(this.repository.resolve(commit)); revCommit = revertCommand.call(); } catch (IOException | GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } Map<String, RevertResult.RevertStatus> conflicts = new HashMap<>(); if (revertCommand.getFailingResult() != null) { Map<String, MergeFailureReason> failingPaths = revertCommand.getFailingResult().getFailingPaths(); if (failingPaths != null && !failingPaths.isEmpty()) { failingPaths .entrySet() .forEach( failure -> conflicts.put( failure.getKey(), getRevertStatusFromMergeFailureReason(failure.getValue()))); } } List<String> unmergedPaths = revertCommand.getUnmergedPaths(); if (unmergedPaths != null && !unmergedPaths.isEmpty()) { unmergedPaths .stream() .filter(unmergedPath -> !conflicts.containsKey(unmergedPath)) .forEach(unmergedPath -> conflicts.put(unmergedPath, RevertResult.RevertStatus.FAILED)); } List<Ref> jGitRevertedCommits = revertCommand.getRevertedRefs(); List<String> revertedCommits = new ArrayList<String>(); if (jGitRevertedCommits != null) { jGitRevertedCommits.forEach(ref -> revertedCommits.add(ref.getObjectId().name())); } String newHead = null; if (revCommit != null) { newHead = revCommit.getId().getName(); } return newDto(RevertResult.class) .withRevertedCommits(revertedCommits) .withConflicts(conflicts) .withNewHead(newHead); }

Target:
public RevertResult revert(String commit) throws GitException { RevCommit revCommit; RevertCommand revertCommand = getGit().revert(); try { revertCommand.include(this.repository.resolve(commit)); revCommit = revertCommand.call(); } catch (IOException | GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } return newDto(RevertResult.class) .withRevertedCommits(getRevertedCommits(revertCommand)) .withConflicts(getRevertConflicts(revertCommand)) .withNewHead(revCommit != null ? revCommit.getId().getName() : null); }
Source:
public void testValidateLabelsForVlan(){ Nic nic = new Nic(); nic.setName("eth0"); NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, "eth0", "labelOnUnmanaged"); Set<NicLabel> labels = new HashSet<>(Arrays.asList(label, labelWithUnmanagedNetwork)); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100); ValidationResult result = validator.validateLabels(vlanNic, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Set<NicLabel> labelsNotOnUnmanagedNetwork = new HashSet<>(Arrays.asList(labelWithoutUnmanaged)); result = validator.validateLabels(vlanNic, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }

Target:
public void testValidateLabelsForVlan(){ Nic nic = createNic("eth0"); NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, "eth0", "labelOnUnmanaged"); Collection<NicLabel> labels = Arrays.asList(label, labelWithUnmanagedNetwork); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100, false); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(vlanNic); Set<String> nicsWithUnmanagedNetworks = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, Collections.emptySet()); assertEquals(1, nicsWithUnmanagedNetworks.size()); String vlanNicName = nicsWithUnmanagedNetworks.iterator().next(); ValidationResult result = validator.validateLabels(vlanNicName, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Collection<NicLabel> labelsNotOnUnmanagedNetwork = Arrays.asList(labelWithoutUnmanaged); result = validator.validateLabels(vlanNicName, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }
Source:
protected void validate() { super.validate(); if (recordReader == null) { throw new SamzaException("Record reader is required."); } }

Target:
protected void validate() { super.validate(); Preconditions.checkNotNull(readFn, "TableReadFunction is required."); Preconditions.checkArgument(rateLimiter == null || tagCreditsMap.isEmpty(), "Only one of rateLimiter instance or read/write limits can be specified"); }
Source:
private static void closeContext(BoundedContext boundedContext) { checkNotNull(boundedContext); try { boundedContext.close(); } catch (Exception e) { throw Exceptions.illegalStateWithCauseOf(e); } }

Target:
private static void closeContext(BoundedContext boundedContext) { checkNotNull(boundedContext); try { boundedContext.close(); } catch (Exception e) { throw illegalStateWithCauseOf(e); } }
Source:
static InetSocketAddress getBindAddress(final ModelNode operation, final OperationContext context) throws OperationFailedException { return new InetSocketAddress(Inet.parseInetAddress( OutboundBindAddressResourceDefinition.BIND_ADDRESS.resolveModelAttribute(context, operation).asString()), OutboundBindAddressResourceDefinition.BIND_PORT.resolveModelAttribute(context, operation).asInt() ); }

Target:
static InetSocketAddress getBindAddress(final ModelNode operation, final OperationContext context) throws OperationFailedException { return new InetSocketAddress(Inet.parseInetAddress( OutboundBindAddressResourceDefinition.BIND_ADDRESS.resolveModelAttribute(context, operation).asString()), OutboundBindAddressResourceDefinition.BIND_PORT.resolveModelAttribute(context, operation).asInt(0) ); }
Source:
public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { if(server.isStarted()) ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(failedOver); synchronized (connectionGuard) { keepConnecting = true; } try { if (producer != null) { producer.close(); } cleanUpSessionFactory(csf); } catch (Throwable dontCare) { } try { session.cleanUp(false); } catch (Throwable dontCare) { } if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID.toString())) { synchronized (this) { try { logger.debug("Moving " + queue.getMessageCount() + " messages from " + queue.getName() + " to " + scaleDownTargetNodeID); ((QueueImpl) queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); fail(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } else if (scaleDownTargetNodeID != null) { logger.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect."); fail(true); } else { logger.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID); fail(me.getType() == ActiveMQExceptionType.DISCONNECTED); } tryScheduleRetryReconnect(me.getType()); }

Target:
public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { if (server.isStarted()) { ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(failedOver); } synchronized (connectionGuard) { keepConnecting = true; } try { if (producer != null) { producer.close(); } cleanUpSessionFactory(csf); } catch (Throwable dontCare) { } try { session.cleanUp(false); } catch (Throwable dontCare) { } if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID.toString())) { synchronized (this) { try { logger.debug("Moving " + queue.getMessageCount() + " messages from " + queue.getName() + " to " + scaleDownTargetNodeID); ((QueueImpl) queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); fail(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } else if (scaleDownTargetNodeID != null) { logger.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect."); fail(true); } else { logger.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID); fail(me.getType() == ActiveMQExceptionType.DISCONNECTED); } tryScheduleRetryReconnect(me.getType()); }
Source:
public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); Assert.assertThat(passiveMessageHandler.getTrackedClients().count(), is(1L)); Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }

Target:
public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); assertThat(passiveMessageHandler.getTrackedClients().count()).isEqualTo(1L); Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(KEY_ENDS_UP_IN_SEGMENT_11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }
Source:
protected File writeMergedFile(MergeResult<RawText> result) throws FileNotFoundException, IOException { MergeFormatter fmt = new MergeFormatter(); File of = null; FileOutputStream fos; if (!inCore) { File workTree = db.getWorkTree(); if (workTree == null) throw new UnsupportedOperationException(); of = new File(workTree, tw.getPathString()); File parentFolder = of.getParentFile(); if (!parentFolder.exists()) parentFolder.mkdirs(); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } else if (!result.containsConflicts()) { of = File.createTempFile("merge_", "_temp", null); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } return of; }

Target:
private File writeMergedFile(MergeResult<RawText> result) throws FileNotFoundException, IOException { MergeFormatter fmt = new MergeFormatter(); File of = null; FileOutputStream fos; if (!inCore) { File workTree = db.getWorkTree(); if (workTree == null) throw new UnsupportedOperationException(); of = new File(workTree, tw.getPathString()); File parentFolder = of.getParentFile(); if (!parentFolder.exists()) parentFolder.mkdirs(); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } else if (!result.containsConflicts()) { of = File.createTempFile("merge_", "_temp", null); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } return of; }
Source:
private DataAccessRequest updateDarWithDocumentContents( DarDocumentType type, User user, DataAccessRequest dar, InputStream uploadInputStream, FormDataContentDisposition fileDetail) throws IOException { String fileName = fileDetail.getFileName(); String toStoreFileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(fileName); BlobId blobId = gcsService.storeDocument(uploadInputStream, fileDetail.getType(), toStoreFileName); switch (type) { case IRB: if (Objects.nonNull(dar.getData().getIrbDocumentLocation())) { deleteDarDocument(dar, dar.getData().getIrbDocumentLocation()); } dar.getData().setIrbDocumentLocation(blobId.getName()); dar.getData().setIrbDocumentName(fileName); break; case COLLABORATION: if (Objects.nonNull(dar.getData().getCollaborationLetterLocation())) { deleteDarDocument(dar, dar.getData().getCollaborationLetterLocation()); } dar.getData().setCollaborationLetterLocation(blobId.getName()); dar.getData().setCollaborationLetterName(fileName); break; default: break; } dataAccessRequestService.updateByReferenceIdVersion2(user, dar); return dataAccessRequestService.findByReferenceId(dar.getReferenceId()); }

Target:
private DataAccessRequest updateDarWithDocumentContents( DarDocumentType type, User user, DataAccessRequest dar, InputStream uploadInputStream, FormDataContentDisposition fileDetail) throws IOException { validateFileDetails(fileDetail); String fileName = fileDetail.getFileName(); String blobFileName = UUID.randomUUID().toString(); BlobId blobId = gcsService.storeDocument(uploadInputStream, fileDetail.getType(), blobFileName); switch (type) { case IRB: if (Objects.nonNull(dar.getData().getIrbDocumentLocation())) { deleteDarDocument(dar, dar.getData().getIrbDocumentLocation()); } dar.getData().setIrbDocumentLocation(blobId.getName()); dar.getData().setIrbDocumentName(fileName); break; case COLLABORATION: if (Objects.nonNull(dar.getData().getCollaborationLetterLocation())) { deleteDarDocument(dar, dar.getData().getCollaborationLetterLocation()); } dar.getData().setCollaborationLetterLocation(blobId.getName()); dar.getData().setCollaborationLetterName(fileName); break; default: break; } return dataAccessRequestService.updateByReferenceIdVersion2(user, dar); }
Source:
protected String getMinGDBVersionSupported() { return GdbDebugServicesFactory.GDB_7_7_VERSION; }

Target:
protected String getMinGDBVersionSupported() { return GdbDebugServicesFactory.GDB_7_12_VERSION; }
Source:
private DatabaseType getDatabaseType() { if (databaseType == null) { Connection conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDatabaseProductName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC metadata.", e); } finally { if (conn != null) { connectionFactory.releaseConnection(conn); } } if (databaseType == null) { log.debug("Unable to detect database type using connection metadata. Attempting to guess on driver name."); conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDriverName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC driver name.", e); } finally { if (conn != null) { connectionFactory.releaseConnection(conn); } } } if (databaseType == null) { throw new ConfigurationException("Unable to detect database type from JDBC driver name or connection metadata. Please provide this manually using the 'databaseType' property in your configuration. Supported database type strings are " + Arrays.toString(DatabaseType.values())); } else { log.debugf("Guessing database type as '%s'. If this is incorrect, please specify the correct type using the 'databaseType' property in your configuration. Supported database type strings are %s", databaseType, Arrays.toString(DatabaseType.values())); } } return databaseType; }

Target:
private DatabaseType getDatabaseType() { if (databaseType == null) { Connection conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDatabaseProductName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC metadata.", e); } finally { connectionFactory.releaseConnection(conn); } if (databaseType == null) { log.debug("Unable to detect database type using connection metadata. Attempting to guess on driver name."); conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDriverName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC driver name.", e); } finally { connectionFactory.releaseConnection(conn); } } if (databaseType == null) { throw new ConfigurationException("Unable to detect database type from JDBC driver name or connection metadata. Please provide this manually using the 'databaseType' property in your configuration. Supported database type strings are " + Arrays.toString(DatabaseType.values())); } else { log.debugf("Guessing database type as '%s'. If this is incorrect, please specify the correct type using the 'databaseType' property in your configuration. Supported database type strings are %s", databaseType, Arrays.toString(DatabaseType.values())); } } return databaseType; }
Source:
public void collectionWithDifferentJobNamesProducesUnqiueEntries() { List<BuildResult> results = new ArrayList<BuildResult>(); results.add(new BuildResult(0, "", BuildStatus.STARTED, 1, "SameJob")); results.add(new BuildResult(1, "", BuildStatus.STARTED, 1, "DifferentJob")); TaskBuildStatusMapper mapper = new TaskBuildStatusMapper(results); TaskAttribute root = createRootAttribute(); mapper.applyTo(root); assertEquals(2, root.getAttributes().size()); assertNotNull(root.getAttribute("BUILD_RESULT-0")); assertNotNull(root.getAttribute("BUILD_RESULT-1")); }

Target:
public void collectionWithDifferentJobNamesProducesUnqiueEntries() { List<BuildResult> results = new ArrayList<BuildResult>(); results.add(new BuildResult(0, "", BuildStatus.STARTED, 1, "SameJob")); results.add(new BuildResult(1, "", BuildStatus.STARTED, 1, "DifferentJob")); TaskBuildStatusMapper mapper = new TaskBuildStatusMapper(results); TaskAttribute root = createRootAttribute(); mapper.applyTo(root); assertEquals(2, root.getAttributes().size()); TaskAttribute firstBuildResultAttribute = root.getAttribute("BUILD_RESULT-0"); assertNotNull(firstBuildResultAttribute); assertEquals(0, firstBuildResultAttribute.getAttribute("NUMBER")); TaskAttribute secondBuildResultAttribute = root.getAttribute("BUILD_RESULT-1"); assertNotNull(secondBuildResultAttribute); assertEquals(1, secondBuildResultAttribute.getAttribute("NUMBER")); }
Source:
private void waitForFinishedNotification() { waitForTransportState("PLAYING"); String notificationTitle = stateMap.get("CurrentTitle"); long playstart = System.currentTimeMillis(); while (System.currentTimeMillis() - playstart < (this.notificationTimeout.longValue() * 1000)) { try { Thread.sleep(50); if (!notificationTitle.equals(stateMap.get("CurrentTitle")) || !"PLAYING".equals(stateMap.get("TransportState"))) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } }

Target:
private void waitForFinishedNotification() { waitForTransportState("PLAYING"); String notificationTitle = stateMap.get("CurrentTitle"); long playstart = System.currentTimeMillis(); while (System.currentTimeMillis() - playstart < this.notificationTimeout.longValue() * 1000) { try { Thread.sleep(50); if (!notificationTitle.equals(stateMap.get("CurrentTitle")) || !"PLAYING".equals(stateMap.get("TransportState"))) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } }
Source:
public void propertyChange(PropertyChangeEvent event) { for (final SelectLocationPage page : getNotVisitedLocationPages()) { final GenerationInfo generationInfo = page.getGenerationInfo(); generationInfo.removePropertyChangeListener(this); if ("location".equals(event.getPropertyName())) { final URI newLocation = getNewLocationProposal((URI) event.getNewValue(), generationInfo.getNameProposal()); generationInfo.setLocation(newLocation); } if ("wrap".equals(event.getPropertyName())) { generationInfo.setWrap((Boolean) event.getNewValue()); } generationInfo.addPropertyChangeListener(this); page.getBindingContext().updateTargets(); } }

Target:
public void propertyChange(PropertyChangeEvent event) { for (final SelectLocationPage page : getNotVisitedLocationPages()) { final GenerationInfo generationInfo = page.getGenerationInfo(); generationInfo.removePropertyChangeListener(this); if ("location".equals(event.getPropertyName())) { final URI newLocation = getNewLocationProposal(URI.class.cast(event.getNewValue()), generationInfo.getNameProposal()); generationInfo.setLocation(newLocation); } if ("wrap".equals(event.getPropertyName())) { generationInfo.setWrap(Boolean.class.cast(event.getNewValue())); } generationInfo.addPropertyChangeListener(this); page.getBindingContext().updateTargets(); } }
Source:
protected String selectSQL(SimpleFeatureType featureType, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, query.getHints()); Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); filter(featureType, filter, sql); } else { removeWhereClausePlaceHolder(sql); } sort(featureType, query.getSortBy(), null, sql); applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); applySearchHints(featureType, query, sql); return sql.toString(); }

Target:
protected String selectSQL(SimpleFeatureType featureType, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); filter(featureType, filter, sql); } sort(featureType, query.getSortBy(), null, sql); applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); applySearchHints(featureType, query, sql); return sql.toString(); }
Source:
public void updateWorkflowInstanceAfterExecution(WorkflowInstance instance, WorkflowInstanceAction action, List<WorkflowInstance> childWorkflows) { Assert.isTrue(action != null, "action can not be null"); Assert.isTrue(action != null, "childWorkflows can not be null"); if (sqlVariants.hasUpdateableCTE() && childWorkflows.isEmpty()) { updateWorkflowInstanceWithCTE(instance, action); } else { updateWorkflowInstanceWithTransaction(instance, action, childWorkflows); } }

Target:
public void updateWorkflowInstanceAfterExecution(WorkflowInstance instance, WorkflowInstanceAction action, List<WorkflowInstance> childWorkflows) { Assert.isTrue(action != null, "action can not be null"); Assert.isTrue(childWorkflows != null, "childWorkflows can not be null"); if (sqlVariants.hasUpdateableCTE() && childWorkflows.isEmpty()) { updateWorkflowInstanceWithCTE(instance, action); } else { updateWorkflowInstanceWithTransaction(instance, action, childWorkflows); } }
Source:
public String toPath(Class<?> classOfPackagingContainingFile, String filename) { String path = classOfPackagingContainingFile.getResource(filename).getPath(); if (path.endsWith(".java.template")) { String javaPath = path.substring(0, path.length() - 9); File target = new File(javaPath); if (!target.exists()) { try { Files.copy(new File(path).toPath(), target.toPath()); } catch (IOException e) { throw new IllegalStateException("unable to copy file", e); } } return javaPath; } return path; }

Target:
public String toPath(Class<?> classOfPackagingContainingFile, String filename) { return classOfPackagingContainingFile.getResource(filename).getPath(); }
Source:
public void initRepo() throws Exception { session.removeChildren(session.getRootDocument().getRef()); session.save(); folder = session.createDocumentModel("/", "Folder", "Folder"); folder.setPropertyValue("dc:title", "Folder"); folder = session.createDocument(folder); session.save(); folder = session.getDocument(folder.getRef()); docNoFacet = session.createDocumentModel("/Folder", "DocNoFacet", "File"); docNoFacet.setPropertyValue("dc:title", "DocNotFacet"); docNoFacet = session.createDocument(docNoFacet); session.save(); docNoFacet = session.getDocument(docNoFacet.getRef()); docWithFacet = session.createDocumentModel("/Folder", "DocWithFacet", "File"); docWithFacet.setPropertyValue("dc:title", "DocWithFacet"); docWithFacet = session.createDocument(docWithFacet); session.save(); docWithFacet = session.getDocument(docWithFacet.getRef()); docWithFacet.addFacet(THE_FACET); docWithFacet = session.saveDocument(docWithFacet); session.save(); }

Target:
public void initRepo() throws Exception { folder = session.createDocumentModel("/", "Folder", "Folder"); folder.setPropertyValue("dc:title", "Folder"); folder = session.createDocument(folder); session.save(); docNoFacet = session.createDocumentModel("/Folder", "DocNoFacet", "File"); docNoFacet.setPropertyValue("dc:title", "DocNotFacet"); docNoFacet = session.createDocument(docNoFacet); session.save(); docNoFacet = session.getDocument(docNoFacet.getRef()); docWithFacet = session.createDocumentModel("/Folder", "DocWithFacet", "File"); docWithFacet.setPropertyValue("dc:title", "DocWithFacet"); docWithFacet = session.createDocument(docWithFacet); session.save(); docWithFacet = session.getDocument(docWithFacet.getRef()); docWithFacet.addFacet(THE_FACET); docWithFacet = session.saveDocument(docWithFacet); session.save(); }
Source:
public List<Map> getStageReachedCounts(Context context) throws SQLException { return workspaceItemDAO.getStageReachedCounts(context); }

Target:
public List<Map.Entry<Integer, Long>> getStageReachedCounts(Context context) throws SQLException { return workspaceItemDAO.getStageReachedCounts(context); }
Source:
public String getHref() { return "/entitlements/" + getId(); }

Target:
public String getHref() { return this.getId() != null ? String.format("/entitlements/%s", this.getId()) : null; }
Source:
private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); if (memberList.isEmpty()) { break; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } Connection ownerConnection = this.ownerConnection; if (ownerConnection == null) { continue; } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null, ownerConnection).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }

Target:
private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); Connection ownerConnection = this.ownerConnection; if (memberList.isEmpty() || ownerConnection == null) { sleepBeforeNextTry(); continue; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null, ownerConnection).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }
Source:
private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException { String srcExt = FileUtils.getFileExtension(srcFile.getName()); String dstExt = FileUtils.getFileExtension(dstFile.getName()); if (!StringUtils.equalsIgnoreCase(srcExt, dstExt)) { throw new IOException("Source and destination files have different extensions."); } switch (srcExt != null ? srcExt.toLowerCase() : "") { case "json": ObjectMapper m = new ObjectMapper(); ObjectNode destNode = m.readValue(dstFile, ObjectNode.class); ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class); destNode.setAll(srcNode); m.writeValue(dstFile, destNode); break; default: FileUtils.append(srcFile, dstFile, appendNewLine); } }

Target:
private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException { String srcExt = FileUtils.getFileExtension(srcFile.getName()); String dstExt = FileUtils.getFileExtension(dstFile.getName()); if (StringUtils.equalsIgnoreCase(srcExt, dstExt) && "json".equalsIgnoreCase(srcExt)) { ObjectMapper m = new ObjectMapper(); ObjectNode destNode = m.readValue(dstFile, ObjectNode.class); ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class); destNode.setAll(srcNode); m.writeValue(dstFile, destNode); } else { FileUtils.append(srcFile, dstFile, appendNewLine); } }