auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Builder setPathPart(String path) { switch (type) { case PATH: case DIFF: this.path = maybeTrimLeadingAndTrailingSlash(checkNotNull(path)); break; case DESCRIBE: case REFS: case LOG: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null; break; default: checkState(path == null, "cannot set path on %s view", type); this.path = path; break; } return this; }

Target:
public Builder setPathPart(String path) { switch (type) { case PATH: case DIFF: this.path = maybeTrimLeadingAndTrailingSlash(checkNotNull(path)); return this; case DESCRIBE: case REFS: case LOG: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null; return this; default: throw new IllegalStateException(String.format("cannot set path on %s view", type)); } }
Source:
@Override public Iterable<K> loadAllKeys() { logger.info( "Starting load all keys for map {}", mapName ); return new PostgresIterable<>( () -> { try { Connection connection = hds.getConnection(); connection.setAutoCommit( false ); Statement stmt = connection.createStatement(); stmt.setFetchSize( 50_000 ); ResultSet rs = stmt.executeQuery( selectAllKeysQuery ); return new StatementHolder( connection, stmt, rs ); } catch ( SQLException e ) { logger.error( "Unable to load all keys", e ); throw new IllegalStateException( "Unable to load all keys.", e ); } }, rs -> { try { return mapToKey( rs ); } catch ( SQLException e ) { logger.error( "Unable to read keys for map {}.", mapName, e); throw new IllegalStateException( "Unable to read keys.", e ); } } ); }

Target:
@Override public Iterable<K> loadAllKeys() { logger.info( "Starting load all keys for map {}", mapName ); return new BasePostgresIterable<>( new StatementHolderSupplier( hds, selectAllKeysQuery, 50_000, false, 0L), rs -> { try { return mapToKey( rs ); } catch ( SQLException e ) { logger.error( "Unable to read keys for map {}.", mapName, e); throw new IllegalStateException( "Unable to read keys.", e ); } } ); }
Source:
public void testTransferCodingGZIP() { String requestStr = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Transfer-Encoding: gzip\r\n" + "\r\n"; HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor); channel.writeInbound(Unpooled.copiedBuffer(requestStr.getBytes())); channel.writeInbound(Unpooled.copiedBuffer(GZ_HELLO_WORLD)); HttpRequest request = channel.readInbound(); assertTrue(request.decoderResult().isSuccess()); assertFalse(request.headers().contains("Content-Length")); HttpContent content = channel.readInbound(); assertTrue(content.decoderResult().isSuccess()); assertEquals(HELLO_WORLD, content.content().toString(CharsetUtil.US_ASCII)); content.release(); LastHttpContent lastHttpContent = channel.readInbound(); assertTrue(lastHttpContent.decoderResult().isSuccess()); lastHttpContent.release(); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); channel.releaseInbound(); }

Target:
public void testTransferCodingGZIP() { String requestStr = "POST / HTTP/1.1\r\n" + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + "Transfer-Encoding: gzip\r\n" + "\r\n"; HttpRequestDecoder decoder = new HttpRequestDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor); channel.writeInbound(Unpooled.copiedBuffer(requestStr.getBytes())); channel.writeInbound(Unpooled.copiedBuffer(GZ_HELLO_WORLD)); HttpRequest request = channel.readInbound(); assertTrue(request.decoderResult().isSuccess()); assertFalse(request.headers().contains(HttpHeaderNames.CONTENT_LENGTH)); HttpContent content = channel.readInbound(); assertTrue(content.decoderResult().isSuccess()); assertEquals(HELLO_WORLD, content.content().toString(CharsetUtil.US_ASCII)); content.release(); LastHttpContent lastHttpContent = channel.readInbound(); assertTrue(lastHttpContent.decoderResult().isSuccess()); lastHttpContent.release(); assertHasInboundMessages(channel, false); assertHasOutboundMessages(channel, false); assertFalse(channel.finish()); channel.releaseInbound(); }
Source:
public void catchingExceptionDuringAnnotation() { EntryImpl change = new EntryImpl(); change.setParent(ChangeLogSet.createEmpty(null)); boolean notCaught = false; try { change.getMsgAnnotated(); } catch (Throwable t) { notCaught = true; } assertEquals((new EntryImpl()).getMsg(), change.getMsg()); assertFalse(notCaught); }

Target:
public void catchingExceptionDuringAnnotation() { EntryImpl change = new EntryImpl(); change.setParent(ChangeLogSet.createEmpty(null)); try { change.getMsgAnnotated(); } catch (Throwable t) { fail(t.getMessage()); } assertEquals((new EntryImpl()).getMsg(), change.getMsg()); }
Source:
public String getProvisionedEntityNameByLocalId(String localId) throws IdentityApplicationManagementException { Connection dbConnection = null; String sqlStmt = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { dbConnection = JDBCPersistenceManager.getInstance().getDBConnection(); sqlStmt = IdentityProvisioningConstants.SQLQueries.GET_PROVISIONED_ENTITY_NAME_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, localId); rs = prepStmt.executeQuery(); if (rs.next()) { return rs.getString(1); } else { throw new IdentityApplicationManagementException("Given Local ID does not exist"); } } catch (SQLException | IdentityException e) { IdentityApplicationManagementUtil.rollBack(dbConnection); throw new IdentityApplicationManagementException( "Error occurred while loading Provisioned Entity Name from DB", e); } finally { IdentityApplicationManagementUtil.closeResultSet(rs); IdentityApplicationManagementUtil.closeStatement(prepStmt); IdentityApplicationManagementUtil.closeConnection(dbConnection); } }

Target:
public String getProvisionedEntityNameByLocalId(String localId) throws IdentityApplicationManagementException { Connection dbConnection = null; String sqlStmt = null; PreparedStatement prepStmt = null; ResultSet rs = null; try { dbConnection = JDBCPersistenceManager.getInstance().getDBConnection(); sqlStmt = IdentityProvisioningConstants.SQLQueries.GET_PROVISIONED_ENTITY_NAME_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, localId); rs = prepStmt.executeQuery(); if (rs.next()) { return rs.getString(1); } else { throw new IdentityApplicationManagementException("Given Local ID :"+localId+" does not exist"); } } catch (SQLException e) { IdentityApplicationManagementUtil.rollBack(dbConnection); throw new IdentityApplicationManagementException( "Error occurred while loading Provisioned Entity Name from DB", e); } finally { IdentityDatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }
Source:
private void showAbortedByHook(final AbortedByHookException cause) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { private String createTitle() { StringBuilder b = new StringBuilder(); b.append(UIText.CommitJob_AbortedByHook); b.append(" \""); b.append(cause.getHookName()); b.append("\""); return b.toString(); } @Override public void run() { MessageDialog.openWarning(PlatformUI.getWorkbench() .getDisplay().getActiveShell(), createTitle(), cause.getHookStdErr()); } }); }

Target:
private void showAbortedByHook(final AbortedByHookException cause) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { private String createTitle() { return MessageFormat.format(UIText.CommitJob_AbortedByHook, cause.getHookName()); } @Override public void run() { MessageDialog.openWarning(PlatformUI.getWorkbench() .getDisplay().getActiveShell(), createTitle(), cause.getHookStdErr()); } }); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (Guid.isNullOrEmpty(getParameters().getHookId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED); return false; } List <VDS> servers = getAllUpServers(getParameters().getClusterId()); if (servers == null || servers.size() == 0) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); return false; } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (Guid.isNullOrEmpty(getParameters().getHookId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED); return false; } if (getGlusterHooksDao().getById(getParameters().getHookId()) == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST); return false; } List <VDS> servers = getAllUpServers(getParameters().getClusterId()); if (servers == null || servers.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); return false; } return true; }
Source:
private boolean hasAlternativeInstructor(String courseId, String instructorToDeleteEmail) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); boolean isAlternativeInstructorWithModifyInstructorPermissionPresent = false; boolean isAlternativeVisibleInstructorPresent = false; for (InstructorAttributes instr : instructors) { isAlternativeInstructorWithModifyInstructorPermissionPresent = instr.isRegistered() && !instr.getEmail().equals(instructorToDeleteEmail) && instr.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR); if (isAlternativeInstructorWithModifyInstructorPermissionPresent) { break; } } for (InstructorAttributes instr : instructors) { isAlternativeVisibleInstructorPresent = instr.isDisplayedToStudents() && !instr.getEmail().equals(instructorToDeleteEmail); if (isAlternativeVisibleInstructorPresent) { break; } } return isAlternativeInstructorWithModifyInstructorPermissionPresent && isAlternativeVisibleInstructorPresent; }

Target:
private boolean hasAlternativeInstructor(String courseId, String instructorToDeleteEmail) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); boolean hasAlternativeModifyInstructor = false; boolean hasAlternativeVisibleInstructor = false; for (InstructorAttributes instr : instructors) { hasAlternativeModifyInstructor = hasAlternativeModifyInstructor || (instr.isRegistered() && !instr.getEmail().equals(instructorToDeleteEmail) && instr.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR)); hasAlternativeVisibleInstructor = hasAlternativeVisibleInstructor || (instr.isDisplayedToStudents() && !instr.getEmail().equals(instructorToDeleteEmail)); if (hasAlternativeModifyInstructor && hasAlternativeVisibleInstructor) { return true; } } return false; }
Source:
static UsbDevice callUsbDeviceConstructor(@NonNull String name, int vendorId, int productId, int usbClass, int subClass, int protocol, @NonNull Parcelable[] interfaces) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<UsbDevice> clazz = (Class<UsbDevice>) Class.forName("android.hardware.usb.UsbDevice"); Constructor<UsbDevice> constructor = clazz.getConstructor(String.class, int.class, int.class, int.class, int.class, int.class, Parcelable[].class); return constructor.newInstance(name, vendorId, productId, usbClass, subClass, protocol); }

Target:
static UsbDevice callUsbDeviceConstructor(@NonNull String name, int vendorId, int productId, int usbClass, int subClass, int protocol, @NonNull Parcelable[] interfaces) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<UsbDevice> clazz = (Class<UsbDevice>) Class.forName("android.hardware.usb.UsbDevice"); Constructor<UsbDevice> constructor = clazz.getConstructor(String.class, int.class, int.class, int.class, int.class, int.class, Parcelable[].class); return constructor.newInstance(name, vendorId, productId, usbClass, subClass, protocol, interfaces); }
Source:
public String getCronExpression(GlusterVolumeSnapshotSchedule schedule) { String retStr = ""; switch (schedule.getRecurrence()) { case INTERVAL: int interval = schedule.getInterval(); retStr = "0 */" + interval + " * * * ? *"; break; case HOURLY: retStr = "0 0 * * * ? *"; break; case DAILY: Time execTime = schedule.getExecutionTime(); retStr = "0 " + execTime.getMinutes() + " " + execTime.getHours() + " * * ? *"; break; case WEEKLY: String days = schedule.getDays(); Time execTime1 = schedule.getExecutionTime(); retStr = "0 " + execTime1.getMinutes() + " " + execTime1.getHours() + " ? * " + days + " *"; break; case MONTHLY: String days1 = schedule.getDays(); Time execTime2 = schedule.getExecutionTime(); retStr = "0 " + execTime2.getMinutes() + " " + execTime2.getHours() + " " + days1 + " * ? *"; break; case UNKNOWN: return null; } return retStr; }

Target:
public String getCronExpression(GlusterVolumeSnapshotSchedule schedule) { String retStr = ""; switch (schedule.getRecurrence()) { case INTERVAL: int interval = schedule.getInterval(); retStr = "0 */" + interval + " * * * ? *"; break; case HOURLY: retStr = "0 0 0/1 1/1 * ? *"; break; case DAILY: Time execTime = schedule.getExecutionTime(); retStr = "0 " + execTime.getMinutes() + " " + execTime.getHours() + " * * ? *"; break; case WEEKLY: String days = schedule.getDays(); Time execTime1 = schedule.getExecutionTime(); retStr = "0 " + execTime1.getMinutes() + " " + execTime1.getHours() + " ? * " + days + " *"; break; case MONTHLY: String days1 = schedule.getDays(); Time execTime2 = schedule.getExecutionTime(); retStr = "0 " + execTime2.getMinutes() + " " + execTime2.getHours() + " " + days1 + " * ? *"; break; case UNKNOWN: return null; } return retStr; }
Source:
public boolean imageExists(String image) { if (dockerConnection == null || StringUtils.isBlank(image)) { return false; } DockerImageURI imageName = new DockerImageURI(image); String repo = imageName.getUriWithoutTag(); String tag = imageName.getTag() == null?"latest":imageName.getTag(); return dockerConnection.hasImage(repo, tag); }

Target:
public boolean imageExists(String image) { if (dockerConnection == null || StringUtils.isBlank(image)) { return false; } DockerImageURI imageName = new DockerImageURI(image); String repo = imageName.getUriWithoutTag(); String tag = StringUtils.defaultIfBlank(imageName.getTag(),"latest"); return dockerConnection.hasImage(repo, tag); }
Source:
public synchronized void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { if (!recogniser.isAvailable()) { LOG.warn("{} is not available for service", recogniser.getClass()); return; } metadata.set("object.rec.impl", recogniser.getClass().getSimpleName()); long start = System.currentTimeMillis(); List<RecognisedObject> objects = recogniser.recognise(stream, handler, metadata, context); LOG.debug("Found objects", objects != null ? objects.size() : 0); LOG.debug("Time taken {}ms", System.currentTimeMillis() - start); if (objects != null && !objects.isEmpty()){ XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startElement("ol", "id", "objects"); Collections.sort(objects, DESC_CONFIDENCE_SORTER); int count = 0; for (RecognisedObject object : objects) { if (object.getConfidence() >= minConfidence) { LOG.debug("Add {}", object); count++; metadata.add(MD_KEY, object.getLabel()); xhtml.startElement("li", "id", object.getId()); String text = String.format(Locale.ENGLISH, " %s [%s](confidence = %f )", object.getLabel(), object.getLabelLang(), object.getConfidence()); xhtml.characters(text); xhtml.endElement("li"); if (count >= topN) { break; } } } xhtml.endElement("ol"); } else { LOG.warn("NO objects"); metadata.add("no.objects", Boolean.TRUE.toString()); } }

Target:
public synchronized void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { if (!recogniser.isAvailable()) { LOG.warn("{} is not available for service", recogniser.getClass()); return; } metadata.set(MD_REC_IMPL_KEY, recogniser.getClass().getName()); long start = System.currentTimeMillis(); List<RecognisedObject> objects = recogniser.recognise(stream, handler, metadata, context); LOG.debug("Found objects", objects != null ? objects.size() : 0); LOG.debug("Time taken {}ms", System.currentTimeMillis() - start); if (objects != null && !objects.isEmpty()) { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startElement("ol", "id", "objects"); Collections.sort(objects, DESC_CONFIDENCE_SORTER); int count = 0; for (RecognisedObject object : objects) { if (object.getConfidence() >= minConfidence) { LOG.debug("Add {}", object); count++; String mdValue = String.format(Locale.ENGLISH, "%s (%.5f)", object.getLabel(), object.getConfidence()); metadata.add(MD_KEY, mdValue); xhtml.startElement("li", "id", object.getId()); String text = String.format(Locale.ENGLISH, " %s [%s](confidence = %f )", object.getLabel(), object.getLabelLang(), object.getConfidence()); xhtml.characters(text); xhtml.endElement("li"); if (count >= topN) { break; } } } xhtml.endElement("ol"); } else { LOG.warn("NO objects"); metadata.add("no.objects", Boolean.TRUE.toString()); } }
Source:
public void reportTaskStatus(int id, Task.TaskStatus status, long miliseconds) throws JMSException { TextMessage message = session.createTextMessage("task:" + propertiesBean.getProperty("engine.unique.id") + ":" + id + ":" + status + ":" + miliseconds); producer.send(message, DeliveryMode.PERSISTENT, 6, 0); log.debug("[{}] Task state sent to dispatcher.", id, status); }

Target:
public void reportTaskStatus(int id, Task.TaskStatus status, long miliseconds) throws JMSException { TextMessage message = session.createTextMessage("task:" + propertiesBean.getProperty("engine.unique.id") + ":" + id + ":" + status + ":" + miliseconds); producer.send(message, DeliveryMode.PERSISTENT, 6, 0); log.info("[{}] Task state sent to dispatcher.", id, status); }
Source:
protected String getText() { return "Default properties view description"; }

Target:
protected String getText() { return Messages.ImportingDefaultPropertiesViewDescriptionCommand_text; }
Source:
LockResponse lock(LockRequest request) { return timeoutRetryer.attemptUntilTimeLimitOrException( request, req -> Duration.ofMillis(req.getAcquireTimeoutMs()), BlockEnforcingLockService::clampLockRequestToDeadline, this::performSingleLockRequest, LockResponse::wasSuccessful, LockResponse.timedOut()); }

Target:
LockResponse lock(LockRequest request) { return timeoutRetryer.attemptUntilTimeLimitOrException( ConjureLockRequests.toConjure(request), Duration.ofMillis(request.getAcquireTimeoutMs()), BlockEnforcingLockService::clampLockRequestToDeadline, this::performSingleLockRequest, response -> !response.wasSuccessful()); }
Source:
public boolean evaluate( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent ) { Pageview pageview_inst = Pageview.getInstance(); return pageview_inst.isPageview( uriHost, uriPath, uriQuery, httpStatus, contentType, userAgent ); }

Target:
public boolean evaluate( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent ) { PageviewDefinition pageviewDefinitionInstance = PageviewDefinition.getInstance(); return pageviewDefinitionInstance.isPageview( uriHost, uriPath, uriQuery, httpStatus, contentType, userAgent ); }
Source:
private void purgeHistory(HistoryReference ref) { if (ref == null) { return; } extension.removeFromHistoryList(ref); extension.clearLogPanelDisplayQueue(); ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionAlert.NAME); if (extAlert != null) { extAlert.deleteHistoryReferenceAlerts(ref); } extension.delete(ref); SiteNode node = ref.getSiteNode(); if (node == null) { return; } SiteMap map = Model.getSingleton().getSession().getSiteTree(); if (node.getHistoryReference() == ref) { ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class); if (extHistory != null) { extHistory.purge(map, node); } } else { node.getPastHistoryReference().remove(ref); map.removeHistoryReference(ref.getHistoryId()); } }

Target:
private void purgeHistory(HistoryReference ref) { if (ref == null) { return; } extension.removeFromHistoryList(ref); extension.clearLogPanelDisplayQueue(); ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionAlert.NAME); if (extAlert != null) { extAlert.deleteHistoryReferenceAlerts(ref); } extension.delete(ref); SiteNode node = ref.getSiteNode(); if (node == null) { return; } SiteMap map = Model.getSingleton().getSession().getSiteTree(); if (node.getHistoryReference() == ref) { extension.purge(map, node); } else { node.getPastHistoryReference().remove(ref); map.removeHistoryReference(ref.getHistoryId()); } }
Source:
public NoValidCRCException(byte receivedCrc, byte expectedCrc) { super(String.format("CRC not valid. Receive/expected 0x%02X/0x%02X,", receivedCrc, expectedCrc)); }

Target:
public NoValidCRCException(byte receivedCrc, byte expectedCrc) { super(String.format("CRC not valid. Receive/expected 0x%02X/0x%02X", receivedCrc, expectedCrc)); }
Source:
public static List<String> getBrokersFromURI(URI uri) { List<String> brokerList = new ArrayList<>(); brokerList.add(String.format("%s:%d", uri.getHost(), uri.getPort())); return brokerList; }

Target:
public static List<String> getBrokersFromURI(URI uri) { String brokerUrl = String.format("%s:%d", uri.getHost(), uri.getPort()); List<String> brokerList = Collections.singletonList(brokerUrl); return brokerList; }
Source:
public void queryWithAFilter() throws Exception { final Path path = mockPath("file://the_project"); final Project project = mock(Project.class); when(project.getRootPath()).thenReturn(path); doReturn(true).when(ioService).exists(any()); final ProjectAssetsQuery query = new ProjectAssetsQuery(project, "helloo", 10, 20, Collections.emptyList()); final PageResponse<RefactoringPageRow> pageRowPageResponse = new PageResponse<>(); pageRowPageResponse.setPageRowList(new ArrayList<>()); when(refactoringQueryService.query(any(RefactoringPageRequest.class))).thenReturn(pageRowPageResponse); libraryService.getProjectAssets(query); verify(refactoringQueryService).query(pageRequestArgumentCaptor.capture()); final RefactoringPageRequest pageRequest = pageRequestArgumentCaptor.getValue(); assertEquals(FindAllLibraryAssetsQuery.NAME, pageRequest.getQueryName()); assertEquals(2, pageRequest.getQueryTerms().size()); assertQueryTermsContains(pageRequest.getQueryTerms(), "file://the_project"); assertQueryTermsContains(pageRequest.getQueryTerms(), "*helloo*"); assertEquals(10, pageRequest.getStartRowIndex()); assertEquals(20, (int) pageRequest.getPageSize()); }

Target:
public void queryWithAFilter() throws Exception { final WorkspaceProject project = spy(WorkspaceProject.class); final Branch branch = mock(Branch.class); final Path path = mockPath("file://the_project"); when(branch.getPath()).thenReturn(path); when(project.getBranch()).thenReturn(branch); doReturn(true).when(ioService).exists(any()); final ProjectAssetsQuery query = new ProjectAssetsQuery(project, "helloo", 10, 20, Arrays.asList("xml")); final PageResponse<RefactoringPageRow> pageRowPageResponse = new PageResponse<>(); pageRowPageResponse.setPageRowList(new ArrayList<>()); when(refactoringQueryService.query(any(RefactoringPageRequest.class))).thenReturn(pageRowPageResponse); libraryService.getProjectAssets(query); verify(refactoringQueryService).query(pageRequestArgumentCaptor.capture()); final RefactoringPageRequest pageRequest = pageRequestArgumentCaptor.getValue(); assertEquals(FindAllLibraryAssetsQuery.NAME, pageRequest.getQueryName()); assertEquals(3, pageRequest.getQueryTerms().size()); assertQueryTermsContains(pageRequest.getQueryTerms(), "file://the_project"); assertQueryTermsContains(pageRequest.getQueryTerms(), "*helloo*"); assertQueryTermsContains(pageRequest.getQueryTerms(), ".*(xml)"); assertEquals(10, pageRequest.getStartRowIndex()); assertEquals(20, (int) pageRequest.getPageSize()); }
Source:
private void verifyBodyCloseBraceStyle(ParserRuleContext bodyCtx, String constructName) { ParseTree closeBrace = ParseTreeUtil.getLastChild(bodyCtx); Location closeBraceLocation = ListenerUtil.getParseTreeStartLocation(closeBrace); ParseTree closeBraceLeftSibling = ParseTreeUtil.getLeftSibling(closeBrace); Location closeBraceLeftSiblingLocation = ListenerUtil.getParseTreeStopLocation(closeBraceLeftSibling); if (closeBraceLocation.line == closeBraceLeftSiblingLocation.line) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); } }

Target:
private void verifyBodyCloseBraceStyle(ParserRuleContext bodyCtx, String constructName) { ParseTree closeBrace = ParseTreeUtil.getLastChild(bodyCtx); Token closeBraceToken = ((TerminalNodeImpl)closeBrace).getSymbol(); Location closeBraceLocation = ListenerUtil.getTokenLocation(closeBraceToken); List<Token> tokens = tokenStream.getHiddenTokensToLeft(closeBraceToken.getTokenIndex()); if (tokens != null) { Token commentToken = getLastCommentToken(tokens); if (commentToken != null) { int commentEndLine = ListenerUtil.getEndLineOfToken(commentToken); if (commentEndLine == closeBraceLocation.line) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); return; } } } ParseTree closeBraceLeftSibling = ParseTreeUtil.getLeftSibling(closeBrace); Location closeBraceLeftSiblingLocation = ListenerUtil.getParseTreeStopLocation(closeBraceLeftSibling); if (closeBraceLocation.line == closeBraceLeftSiblingLocation.line) { if (!closeBraceLeftSibling.getText().equals("{")) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); } else if (closeBraceLocation.column - closeBraceLeftSiblingLocation.column != 1) { this.printer.warn(Messages.EMPTY_BODY, closeBraceLeftSiblingLocation); } } }
Source:
public Entry<Integer,String> execMapreduceWithStdout(Class<?> clz, String[] args) throws IOException { String host = "localhost"; String[] cmd = new String[4 + args.length]; cmd[0] = getAccumuloUtilPath(); cmd[1] = "hadoop-jar"; cmd[2] = getJarFromClass(clz); cmd[3] = clz.getName(); for (int i = 0, j = 4; i < args.length; i++, j++) { cmd[j] = "'" + args[i] + "'"; } log.info("Running: '{}' on {}", StringUtils.join(cmd, " "), host); return exec(host, cmd); }

Target:
public Entry<Integer,String> execMapreduceWithStdout(Class<?> clz, String[] args) throws IOException { String host = "localhost"; List<String> cmd = new ArrayList<>(); cmd.add(getAccumuloUtilPath()); cmd.add("hadoop-jar"); cmd.add(getJarFromClass(clz)); cmd.add(clz.getName()); for (String arg : args) { cmd.add("'" + arg + "'"); } log.info("Running: '{}' on {}", StringUtils.join(cmd, " "), host); return exec(host, cmd.toArray(new String[cmd.size()])); }
Source:
private static void updateHTMLPageVersionTS(String id) throws DotDataException, DotSecurityException { Identifier identifier = APILocator.getIdentifierAPI().find(id); List<Contentlet> allContentletVersions = APILocator.getContentletAPI() .findAllVersions(identifier, APILocator.getUserAPI().getSystemUser(), false); for (Contentlet contentlet : allContentletVersions) { ContentletVersionInfo versionInfo = APILocator.getVersionableAPI() .getContentletVersionInfo(id, contentlet.getLanguageId()); if(versionInfo!=null) { versionInfo.setVersionTs(new Date()); APILocator.getVersionableAPI().saveContentletVersionInfo(versionInfo); } } }

Target:
private static void updateHTMLPageVersionTS(String id) throws DotDataException, DotSecurityException { List<ContentletVersionInfo> infos = APILocator.getVersionableAPI().findContentletVersionInfos(id); for (ContentletVersionInfo versionInfo : infos) { if(versionInfo!=null) { versionInfo.setVersionTs(new Date()); APILocator.getVersionableAPI().saveContentletVersionInfo(versionInfo); } } }
Source:
public PatientProgram getPatientProgramByUuid(String uuid) { return (PatientProgram) sessionFactory.getCurrentSession().createCriteria(PatientProgram.class).add( Restrictions.eq("uuid", uuid)).uniqueResult(); }

Target:
public PatientProgram getPatientProgramByUuid(String uuid) { return (PatientProgram) sessionFactory.getCurrentSession().createQuery( "from PatientProgram pp where pp.uuid = :uuid").setString("uuid", uuid).uniqueResult(); }
Source:
private void checkThrowingUnsupportedException(PrimitiveComparator<?> comparator, Class<?> exclude) { if (Integer.TYPE != exclude) { try { comparator.compare(0, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Long.TYPE != exclude) { try { comparator.compare(0L, 0L); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Float.TYPE != exclude) { try { comparator.compare(0F, 0F); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Double.TYPE != exclude) { try { comparator.compare(0D, 0D); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Boolean.TYPE != exclude) { try { comparator.compare(false, false); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } }

Target:
private void checkThrowingUnsupportedException(PrimitiveComparator<?> comparator, Class<?> exclude) { if (Integer.TYPE != exclude) { try { comparator.compare(0, 0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Long.TYPE != exclude) { try { comparator.compare(0L, 0L); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Float.TYPE != exclude) { try { comparator.compare(0.0F, 0.0F); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Double.TYPE != exclude) { try { comparator.compare(0.0, 0.0); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } if (Boolean.TYPE != exclude) { try { comparator.compare(false, false); fail("An UnsupportedOperationException should have been thrown"); } catch (UnsupportedOperationException e) { } } }
Source:
private synchronized void process(final double in) { if (!propEnabled && buffer.size() == propBufferSize) { if (System.currentTimeMillis() - disableTime < propAutoReenableTime || propAutoReenableTime == 0) { return; } propEnabled = true; } if (propMode == MODE_AVERAGE) { buffer.addFirst(in); sum += in; if (buffer.size() > propBufferSize) { sum -= buffer.removeLast(); } opOutput.sendData(ConversionUtils.doubleToBytes(sum / buffer.size())); } else if (propMode == MODE_AVERAGE_ROUND) { buffer.addFirst(in); sum += in; if (buffer.size() > propBufferSize) { sum -= buffer.removeLast(); } opOutput.sendData(ConversionUtils.doubleToBytes(Math.round(sum / buffer.size()))); } else if (propMode == MODE_ACCUMULATE) { accu += in; if (System.currentTimeMillis() - lastUpdate > propBufferSize) { lastUpdate = System.currentTimeMillis(); opOutput.sendData(ConversionUtils.doubleToBytes(accu)); accu = 0; } } else if (propMode == MODE_MEDIAN) { buffer.addFirst(in); if (buffer.size() > propBufferSize) { buffer.removeLast(); } double[] array = new double[buffer.size()]; for (int i = 0; i < array.length; ++i) { array[i] = buffer.get(i); } opOutput.sendData(ConversionUtils.doubleToBytes(StatUtils.percentile(array, 50))); } }

Target:
private synchronized void process(final double in) { if (!propEnabled) { if (System.currentTimeMillis() - disableTime < propAutoReenableTime || propAutoReenableTime == 0) { return; } propEnabled = true; } if (propMode == MODE_AVERAGE) { buffer.addFirst(in); sum += in; if (buffer.size() > propBufferSize) { sum -= buffer.removeLast(); } opOutput.sendData(ConversionUtils.doubleToBytes(sum / buffer.size())); } else if (propMode == MODE_AVERAGE_ROUND) { buffer.addFirst(in); sum += in; if (buffer.size() > propBufferSize) { sum -= buffer.removeLast(); } opOutput.sendData(ConversionUtils.doubleToBytes(Math.round(sum / buffer.size()))); } else if (propMode == MODE_ACCUMULATE) { accu += in; if (System.currentTimeMillis() - lastUpdate > propBufferSize) { lastUpdate = System.currentTimeMillis(); opOutput.sendData(ConversionUtils.doubleToBytes(accu)); accu = 0; } } else if (propMode == MODE_MEDIAN) { buffer.addFirst(in); if (buffer.size() > propBufferSize) { buffer.removeLast(); } double[] array = new double[buffer.size()]; for (int i = 0; i < array.length; ++i) { array[i] = buffer.get(i); } opOutput.sendData(ConversionUtils.doubleToBytes(StatUtils.percentile(array, 50))); } }
Source:
private String getParameter(String parameterId) { String value = parameters.getProperty(parameterId); String decode = parameters.getProperty(KEY_DECODE); if (value != null) try { if (decode != null && decode.equalsIgnoreCase(VALUE_TRUE)) return decode(value, "UTF-8"); return value; } catch (Exception e) { CheatSheetPlugin.logError("Failed to decode URL: " + parameterId, e); } return value; }

Target:
private String getParameter(String parameterId) { String value = parameters.getProperty(parameterId); String decode = parameters.getProperty(KEY_DECODE); if (value != null) { try { if (decode != null && decode.equalsIgnoreCase(VALUE_TRUE)) { return decode(value, "UTF-8"); } return value; } catch (Exception e) { CheatSheetPlugin.logError("Failed to decode URL: " + parameterId, e); } } return value; }
Source:
private RevCommit getCommit(Repository repository, String objectId) { RevWalk revWalk = null; try { revWalk = new RevWalk(repository); return revWalk.parseCommit(ObjectId.fromString(objectId)); } catch (MissingObjectException e) { return null; } catch (IncorrectObjectTypeException e) { return null; } catch (IOException e) { return null; } finally { if (revWalk != null) { revWalk.release(); } } }

Target:
private RevCommit getCommit(Repository repository, String objectId) { RevWalk revWalk = null; try { revWalk = new RevWalk(repository); return revWalk.parseCommit(ObjectId.fromString(objectId)); } catch (Exception e) { return null; } finally { if (revWalk != null) { revWalk.release(); } } }
Source:
private void clearContentAccessCerts(Environment env) { ownerEnvContentAccessCurator.removeAllForEnvironment(env.getId()); ownerEnvContentAccessCurator.refresh(); }

Target:
private void clearContentAccessCerts(Environment env) { ownerEnvContentAccessCurator.removeAllForEnvironment(env.getId()); }
Source:
protected void testExecute_noGoogleIdButEmailPresent_shouldPass() { loginAsAdmin(); InstructorAttributes instructorToDelete = typicalBundle.instructors.get("instructor1OfCourse1"); String[] onlyEmailParams = new String[] { Const.ParamsNames.COURSE_ID, instructorToDelete.courseId, Const.ParamsNames.INSTRUCTOR_EMAIL, instructorToDelete.email, Const.ParamsNames.INSTRUCTOR_ID, null, }; DeleteInstructorAction deleteInstructorAction = getAction(onlyEmailParams); JsonResult response = getJsonResult(deleteInstructorAction); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); MessageOutput msg = (MessageOutput) response.getOutput(); assertEquals("Instructor is successfully deleted.", msg.getMessage()); assertFalse(instructorsLogic.isEmailOfInstructorOfCourse(instructorToDelete.email, instructorToDelete.courseId)); }

Target:
protected void testExecute_noGoogleIdButEmailPresent_shouldPass() { loginAsAdmin(); InstructorAttributes instructorToDelete = typicalBundle.instructors.get("instructor1OfCourse1"); String[] onlyEmailParams = new String[] { Const.ParamsNames.COURSE_ID, instructorToDelete.courseId, Const.ParamsNames.INSTRUCTOR_EMAIL, instructorToDelete.email, }; DeleteInstructorAction deleteInstructorAction = getAction(onlyEmailParams); JsonResult response = getJsonResult(deleteInstructorAction); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); MessageOutput msg = (MessageOutput) response.getOutput(); assertEquals("Instructor is successfully deleted.", msg.getMessage()); assertFalse(instructorsLogic.isEmailOfInstructorOfCourse(instructorToDelete.email, instructorToDelete.courseId)); }
Source:
public GenericOAuth20Profile extractUserProfile(String body) throws HttpAction { final GenericOAuth20Profile profile = new GenericOAuth20Profile(); final JsonNode json = JsonHelper.getFirstNode(body, getFirstNodePath()); if (json != null) { for (final String attribute : getPrimaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final String attribute : getSecondaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final Map.Entry<String, String> entry : getProfileAttributes().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); convertAndAdd(profile, key, JsonHelper.getElement(json, value)); } } return profile; }

Target:
public OAuth20Profile extractUserProfile(String body) throws HttpAction { final OAuth20Profile profile = new OAuth20Profile(); final JsonNode json = JsonHelper.getFirstNode(body, getFirstNodePath()); if (json != null) { for (final String attribute : getPrimaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final String attribute : getSecondaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final Map.Entry<String, String> entry : getProfileAttributes().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); convertAndAdd(profile, key, JsonHelper.getElement(json, value)); } } return profile; }
Source:
public Response checkMessagingConnectionWithAgent( String applicationName, String rootInstanceName, String message, long timeout ) { if ( message == null ) { message = UUID.randomUUID().toString(); } if ( timeout > MAXIMUM_TIMEOUT ) { this.logger.warning( "Timeout " + timeout + "ms is above maximum limit " + MAXIMUM_TIMEOUT + "ms. Normalizing" ); timeout = MAXIMUM_TIMEOUT; } boolean hasReceived; try { hasReceived = this.manager.pingAgent( applicationName, rootInstanceName, message, timeout ); } catch ( IOException e ) { final String eMessage = "Unable to ping agent " + rootInstanceName + " with message " + message; logger.log( Level.SEVERE, eMessage, e ); return Response.status( Status.INTERNAL_SERVER_ERROR ).entity( eMessage ).build(); } catch ( InterruptedException e ) { final String eMessage = "Interrupted while waiting for ping response from agent " + rootInstanceName + " message " + message; logger.log( Level.WARNING, eMessage, e ); return Response.status( Status.INTERNAL_SERVER_ERROR ).entity( eMessage ).build(); } if ( hasReceived ) { final String rMessage = "Has received ping response " + message + " from agent " + rootInstanceName; logger.fine( rMessage ); return Response.status( Status.OK ).entity( rMessage ).build(); } else { final String rMessage = "Did not receive ping response " + message + " from agent " + rootInstanceName + " before timeout (" + timeout + "ms)"; logger.warning( rMessage ); return Response.status( 408 ).entity( rMessage ).build(); } }

Target:
public Response checkMessagingConnectionWithAgent( String applicationName, String rootInstanceName, String message, long timeout ) { if ( message == null ) { message = UUID.randomUUID().toString(); } if ( timeout > MAXIMUM_TIMEOUT ) { this.logger.warning( "Timeout " + timeout + "ms is above maximum limit " + MAXIMUM_TIMEOUT + "ms. Normalizing" ); timeout = MAXIMUM_TIMEOUT; } Response response; String responseMessage; try { if ( this.manager.pingAgent( applicationName, rootInstanceName, message, timeout ) ) { responseMessage = "Has received ping response " + message + " from agent " + rootInstanceName; logger.fine( responseMessage ); response = Response.status( Status.OK ).entity( responseMessage ).build(); } else { responseMessage = "Did not receive ping response " + message + " from agent " + rootInstanceName + " before timeout (" + timeout + "ms)"; logger.warning( responseMessage ); response = Response.status( 408 ).entity( responseMessage ).build(); } } catch ( IOException e ) { responseMessage = "Unable to ping agent " + rootInstanceName + " with message " + message; this.logger.severe( responseMessage ); Utils.logException( this.logger, Level.FINEST, e); response = Response.status( Status.INTERNAL_SERVER_ERROR ).entity( responseMessage ).build(); } catch ( InterruptedException e ) { responseMessage = "Interrupted while waiting for ping response from agent " + rootInstanceName + " message " + message; this.logger.severe( responseMessage ); Utils.logException( this.logger, Level.FINEST, e); response = Response.status( Status.INTERNAL_SERVER_ERROR ).entity( responseMessage ).build(); } return response; }
Source:
static TypeElement extractTypeFromAnnotation(Elements elementUtils, AutoDelegate annotation) { TypeElement type; try { Class typeClass = annotation.typeToExtend(); type = elementUtils.getTypeElement(typeClass.getCanonicalName()); } catch (MirroredTypeException mte) { DeclaredType typeMirror = (DeclaredType) mte.getTypeMirror(); type = (TypeElement) typeMirror.asElement(); } return type; }

Target:
static TypeElement extractTypeFromAnnotation(Elements elementUtils, AutoDelegate annotation) { try { Class typeClass = annotation.typeToExtend(); return elementUtils.getTypeElement(typeClass.getCanonicalName()); } catch (MirroredTypeException mte) { DeclaredType typeMirror = (DeclaredType) mte.getTypeMirror(); return (TypeElement) typeMirror.asElement(); } }
Source:
public void testTimestampNanosStringifier() { PrimitiveStringifier stringifier = PrimitiveStringifier.TIMESTAMP_NANOS_STRINGIFIER; assertEquals("1970-01-01T00:00:00.000000000", stringifier.stringify(0l)); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2053, Calendar.JULY, 10, 22, 13, 24); cal.set(Calendar.MILLISECOND, 84); long micros = cal.getTimeInMillis() * 1000_000 + 1900; assertEquals("2053-07-10T22:13:24.084001900", stringifier.stringify(micros)); cal.clear(); cal.set(1848, Calendar.MARCH, 15, 9, 23, 59); cal.set(Calendar.MILLISECOND, 765); micros = cal.getTimeInMillis() * 1000_000 - 1; assertEquals("1848-03-15T09:23:59.765000001", stringifier.stringify(micros)); checkThrowingUnsupportedException(stringifier, Long.TYPE); }

Target:
public void testTimestampNanosStringifier() { PrimitiveStringifier stringifier = PrimitiveStringifier.TIMESTAMP_NANOS_STRINGIFIER; assertEquals("1970-01-01T00:00:00.000000000", stringifier.stringify(0l)); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2053, Calendar.JULY, 10, 22, 13, 24); cal.set(Calendar.MILLISECOND, 84); long nanos = cal.getTimeInMillis() * 1_000_000 + 536; assertEquals("2053-07-10T22:13:24.084000536", stringifier.stringify(nanos)); cal.clear(); cal.set(1848, Calendar.MARCH, 15, 9, 23, 59); cal.set(Calendar.MILLISECOND, 765); nanos = cal.getTimeInMillis() * 1_000_000 - 1; assertEquals("1848-03-15T09:23:59.765000001", stringifier.stringify(nanos)); checkThrowingUnsupportedException(stringifier, Long.TYPE); }
Source:
public IStatus validate(IValidationContext ctx) { final EObject target = ctx.getTarget(); Collection<IStatus> statuses = Sets.newLinkedHashSet(); if (target instanceof RepresentationDescription || target instanceof RepresentationExtensionDescription) { Collection<EPackage> availableMetamodels = getAvailableMetamodels(target); if (availableMetamodels.isEmpty()) { statuses.add(ctx.createFailureStatus(Messages.RepresentationDescriptionMetaModelsConstraint_noMetaModel)); } else { Resource vsmResource = target.eResource(); if (vsmResource != null) { URI vsmURI = vsmResource.getURI(); String projectName = vsmURI.segment(1); if (isOdesignOwnedByVSP(projectName)) { statuses.addAll(checkMetamodelAsVSPDependency(ctx, projectName, availableMetamodels)); } } } } final IStatus returnStatus = getCompositeStatus(ctx, statuses); return returnStatus; }

Target:
public IStatus validate(IValidationContext ctx) { final EObject target = ctx.getTarget(); if (target instanceof RepresentationDescription || target instanceof RepresentationExtensionDescription) { Collection<EPackage> availableMetamodels = getAvailableMetamodels(target); if (availableMetamodels.isEmpty()) { return ctx.createFailureStatus(Messages.RepresentationDescriptionMetaModelsConstraint_noMetaModel); } } return ctx.createSuccessStatus(); }
Source:
public static String getBlobstoreHDFSPrincipal(Map conf) throws UnknownHostException { String principal = (String)conf.get(Config.BLOBSTORE_HDFS_PRINCIPAL); if (principal != null) { principal = principal.replace("HOSTNAME", Utils.localHostname()); } return principal; }

Target:
public static String getBlobstoreHDFSPrincipal(Map conf) throws UnknownHostException { String principal = (String) conf.get(Config.BLOBSTORE_HDFS_PRINCIPAL); if (principal != null) { String[] components = principal.split("[/@]"); if (components.length == 3 && components[1].equals(HOSTNAME_PATTERN)) { principal = components[0] + "/" + Utils.localHostname() + "@" + components[2]; } } return principal; }
Source:
public static <T> T operation(String operationId, Map<String, Object> parameters) { return CLIENT.operation(operationId).parameters(parameters).execute(); }

Target:
public static void operation(String operationId, Map<String, Object> parameters) { CLIENT.operation(operationId).parameters(parameters).execute(); }
Source:
public void generate(final List<TradeOffer> tradeOffers) { if (tradeOffers instanceof MerchantRecipeList) { modifyMerchantRecipeList((MerchantRecipeList) tradeOffers, RANDOM); } else { final MerchantRecipeList list = new MerchantRecipeList(); for (final TradeOffer offer : tradeOffers) { list.add(offer); } modifyMerchantRecipeList(list, RANDOM); tradeOffers.clear(); for (final Object offer : list) { tradeOffers.add(new SpongeTradeOfferBuilder().from((TradeOffer) offer).build()); } } }

Target:
public void generate(final List<TradeOffer> tradeOffers) { if (tradeOffers instanceof MerchantRecipeList) { modifyMerchantRecipeList((MerchantRecipeList) tradeOffers, RANDOM); } else { final MerchantRecipeList list = new MerchantRecipeList(); list.addAll(tradeOffers); modifyMerchantRecipeList(list, RANDOM); tradeOffers.clear(); for (final Object offer : list) { tradeOffers.add(new SpongeTradeOfferBuilder().from((TradeOffer) offer).build()); } } }
Source:
public boolean addItems(Collection<T> items) { boolean result; mAlgorithm.lock(); try { result = mAlgorithm.addItems(items); } finally { mAlgorithm.unlock(); } return result; }

Target:
public boolean addItems(Collection<T> items) { mAlgorithm.lock(); try { return mAlgorithm.addItems(items); } finally { mAlgorithm.unlock(); } }
Source:
public String getCustomParam(String name) { if (customParams != null) { return customParams.get(name); } else { return null; } }

Target:
public String getCustomParam(String name) { return customParams.get(name); }
Source:
public List<OskariLayer> findByDataProviderId(int dataProviderId) { LOG.debug("Find by data provider id: " + dataProviderId); final SqlSession session = factory.openSession(); try { final OskariLayerMapper mapper = session.getMapper(OskariLayerMapper.class); List<Map<String,Object>> result = mapper.findByDataProviderId(dataProviderId); return mapDataList(result); } catch (Exception e) { LOG.warn(e, "Exception while getting oskari layers with dataprovider id"); } finally { session.close(); } return Collections.emptyList(); }

Target:
public List<OskariLayer> findByDataProviderId(int dataProviderId) { LOG.debug("Find by data provider id: " + dataProviderId); try (SqlSession session = factory.openSession()){ final OskariLayerMapper mapper = session.getMapper(OskariLayerMapper.class); List<Map<String,Object>> result = mapper.findByDataProviderId(dataProviderId); return mapDataList(result); } catch (Exception e) { LOG.warn(e, "Exception while getting oskari layers with dataprovider id"); } return Collections.emptyList(); }