auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SimpleObject update(String uuid, SimpleObject postBody, RequestContext context) { String manualEntryEnabled = postBody.get("manualEntryEnabled").toString(); String automaticGenerationEnabled = postBody.get("automaticGenerationEnabled").toString(); String sourceUuid = postBody.get("source").toString(); String locationUuid = postBody.get("location").toString(); IdentifierSource identifierSource = Context.getService(IdentifierSourceService.class) .getIdentifierSourceByUuid(sourceUuid); PatientIdentifierType patientIdentifierType = Context.getPatientService().getPatientIdentifierTypeByUuid(uuid); Location location = Context.getLocationService().getLocationByUuid(locationUuid); AutoGenerationOption autoGenerationOption = Context.getService(IdentifierSourceService.class) .getAutoGenerationOption(patientIdentifierType); autoGenerationOption.setManualEntryEnabled(Boolean.parseBoolean(manualEntryEnabled)); autoGenerationOption.setAutomaticGenerationEnabled(Boolean.parseBoolean(automaticGenerationEnabled)); autoGenerationOption.setSource(identifierSource); autoGenerationOption.setLocation(location); return (SimpleObject) ConversionUtil.convertToRepresentation(save(autoGenerationOption), Representation.REF); }

Target:
public SimpleObject update(String uuid, SimpleObject postBody, RequestContext context) throws ResponseException { String manualEntryEnabled = ((postBody.get("manualEntryEnabled") != null) && !(postBody.get("manualEntryEnabled").equals(""))) ? postBody.get("manualEntryEnabled").toString() : null; String automaticGenerationEnabled = ((postBody.get("automaticGenerationEnabled") != null) && !(postBody.get("automaticGenerationEnabled").equals(""))) ? postBody.get("automaticGenerationEnabled").toString() : null; String sourceUuid = ((postBody.get("source") != null) && !(postBody.get("source").equals(""))) ? postBody.get("source").toString() : null; String locationUuid = ((postBody.get("location") != null) && !(postBody.get("location").equals(""))) ? postBody.get("location").toString() : null; AutoGenerationOption autoGenerationOption = Context.getService(IdentifierSourceService.class) .getAutoGenerationOption(Integer.parseInt(uuid)); if (manualEntryEnabled != null) { autoGenerationOption.setManualEntryEnabled(Boolean.parseBoolean(manualEntryEnabled)); } if (automaticGenerationEnabled != null) { autoGenerationOption.setAutomaticGenerationEnabled(Boolean.parseBoolean(automaticGenerationEnabled)); } if (sourceUuid != null) { IdentifierSource identifierSource = identifierSourceService.getIdentifierSourceByUuid(sourceUuid); autoGenerationOption.setSource(identifierSource); } if (locationUuid != null) { Location location = Context.getLocationService().getLocationByUuid(locationUuid); autoGenerationOption.setLocation(location); } if (locationUuid == null && sourceUuid == null && automaticGenerationEnabled == null && manualEntryEnabled == null) { throw new ResourceDoesNotSupportOperationException( "updating an autoGenerationOption with missing parameters is not supported"); } return (SimpleObject) ConversionUtil.convertToRepresentation(save(autoGenerationOption), Representation.REF); }
Source:
public T get() { throw new UnsupportedOperationException("#get()"); }

Target:
public T get() { throw new UnsupportedOperationException( "there is nothing here, use has() first, to check" ); }
Source:
public void removeFilter(@NonNull ViewerFilter filter) { fTimeGraphCtrl.removeFilter(filter); refresh(); fTimeGraphCtrl.fireFilterApplied(); }

Target:
public void removeFilter(@NonNull ViewerFilter filter) { fTimeGraphCtrl.removeFilter(filter); refresh(); }
Source:
public static String stringToHtml(String inxml, String infilexsl) { Document doc = null; File stylesheet = null; StringReader inReader = new StringReader(inxml); StringWriter writer = new StringWriter(); try { stylesheet = new File(infilexsl); DocumentBuilder builder = XmlUtils.newXxeDisabledDocumentBuilderFactory().newDocumentBuilder(); doc = builder.parse(new InputSource(inReader)); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) { showDialogForGUI(); logger.error(e.getMessage(), e); return inxml; } finally { } return writer.toString(). replace("&lt;p&gt;", "<p>"). replace("&lt;/p&gt;", "</p>"); }

Target:
public static String stringToHtml(String inxml, String infilexsl) { Document doc = null; File stylesheet = null; StringReader inReader = new StringReader(inxml); StringWriter writer = new StringWriter(); try { stylesheet = new File(infilexsl); DocumentBuilder builder = XmlUtils.newXxeDisabledDocumentBuilderFactory().newDocumentBuilder(); doc = builder.parse(new InputSource(inReader)); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) { showDialogForGUI(); logger.error(e.getMessage(), e); } finally { } return writer.toString(). replace("&lt;p&gt;", "<p>"). replace("&lt;/p&gt;", "</p>"); }
Source:
public Response generateEdges() { List<DeviceOrganizationVisEdge> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); result = dops.generateEdges(); if (result.isEmpty()) { String msg = "No Edge connections available and visible"; log.error(msg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); }

Target:
public Response generateEdges() { List<DeviceOrganizationVisEdge> result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); result = dops.generateEdges(); if (result.isEmpty()) { String msg = "No Edge connections available and visible"; if (log.isDebugEnabled()) { log.debug(msg); } return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); }
Source:
protected boolean isUnsupportedXmlnsAttribute(Attr attribute) { return StringUtils.startsWith(attribute.getName(), XMLNS_ATTRIBUTE_PREFIX) && !ALLOWED_XMLNS_ATTRIBUTES_PATTERN.matcher(attribute.getName()).matches(); }

Target:
protected boolean isUnsupportedXmlnsAttribute(Attr attribute) { String attributeName = StringUtils.lowerCase(attribute.getName()); return StringUtils.startsWith(attributeName, XMLNS_ATTRIBUTE_PREFIX) && !ALLOWED_XMLNS_ATTRIBUTES_PATTERN.matcher(attributeName).matches(); }
Source:
StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = message.getOrCreateSession(channel); if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }

Target:
StreamSession deriveSession(StreamMessage message) { StreamSession streamSession = message.getOrCreateSession(channel); streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }
Source:
private Set<RelationalSymbolicValue> transitiveRelations(Set<RelationalSymbolicValue> knownRelations) { Set<RelationalSymbolicValue> newRelations = new HashSet<>(); Deque<RelationalSymbolicValue> workList = new ArrayDeque<>(); int iterations = 0; workList.add(this); while (!workList.isEmpty()) { if (newRelations.size() > MAX_DEDUCED_RELATIONS || iterations > MAX_ITERATIONS) { throw new RelationalSymbolicValue.TransitiveRelationExceededException("Used relations: " + newRelations.size() + ". Iterations " + iterations); } iterations++; RelationalSymbolicValue relation = workList.pop(); for (RelationalSymbolicValue knownRelation : knownRelations) { RelationalSymbolicValue r = relation.deduceTransitiveOrSimplified(knownRelation); if (r != null && !knownRelations.contains(r) && !newRelations.contains(r)) { newRelations.add(r); workList.add(r); } } } return newRelations; }

Target:
Set<RelationalSymbolicValue> transitiveRelations(Set<RelationalSymbolicValue> knownRelations) { Set<RelationalSymbolicValue> newRelations = new HashSet<>(); Deque<RelationalSymbolicValue> workList = new ArrayDeque<>(); int iterations = 0; workList.add(this); while (!workList.isEmpty()) { if (newRelations.size() > MAX_DEDUCED_RELATIONS || iterations > MAX_ITERATIONS) { throw new RelationalSymbolicValue.TransitiveRelationExceededException("Used relations: " + newRelations.size() + ". Iterations " + iterations); } iterations++; RelationalSymbolicValue relation = workList.pop(); for (RelationalSymbolicValue knownRelation : knownRelations) { RelationalSymbolicValue r = relation.deduceTransitiveOrSimplified(knownRelation); if (r != null && !knownRelations.contains(r) && newRelations.add(r)) { workList.add(r); } } } return newRelations; }
Source:
public void removeMember(PerunSession sess, List<Group> groups, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException { Collections.sort(groups); Collections.reverse(groups); for (Group group : groups) { if (group.getName().equals(VosManager.MEMBERS_GROUP)) { throw new InternalErrorException("Cannot remove member directly from the members group."); } else { try { this.removeDirectMember(sess, group, member); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex){ throw new InternalErrorException(ex); } } } }

Target:
public void removeMember(PerunSession sess, List<Group> groups, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException { Collections.sort(groups, Collections.reverseOrder()); for (Group group : groups) { if (group.getName().equals(VosManager.MEMBERS_GROUP)) { throw new InternalErrorException("Cannot remove member directly from the members group."); } else { try { this.removeDirectMember(sess, group, member); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex){ throw new InternalErrorException(ex); } } } }
Source:
public void retryableConfigurationExceptionsTest() throws Exception { doTestHttpClient(new Runnable() { @Override public void run() { System.setProperty( "maven.wagon.http.retryhandler.class", "default" ); System.setProperty( "maven.wagon.http.retryhandler.nonRetryableClasses", IOException.class.getName() ); final HttpRequestRetryHandler handler = getCurrentHttpClient(); assertNotNull( handler ); assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); assertEquals( 3, impl.getRetryCount() ); assertFalse( impl.isRequestSentRetryEnabled() ); try { final Field nonRetriableClasses = handler.getClass().getSuperclass() .getDeclaredField( "nonRetriableClasses" ); if (!nonRetriableClasses.isAccessible()) { nonRetriableClasses.setAccessible(true); } final Set<?> exceptions = Set.class.cast( nonRetriableClasses.get(handler) ); assertEquals( 1, exceptions.size() ); assertTrue( exceptions.contains( IOException.class ) ); } catch ( final Exception e ) { fail( e.getMessage() ); } } }); }

Target:
public void retryableConfigurationExceptionsTest() throws Exception { doTestHttpClient( new Runnable() { @Override public void run() { System.setProperty( "maven.wagon.http.retryhandler.class", "default" ); System.setProperty( "maven.wagon.http.retryhandler.nonRetryableClasses", IOException.class.getName() ); final HttpRequestRetryHandler handler = getCurrentHandler(); assertNotNull( handler ); assertThat( handler, instanceOf( DefaultHttpRequestRetryHandler.class ) ); final DefaultHttpRequestRetryHandler impl = DefaultHttpRequestRetryHandler.class.cast(handler); assertEquals( 3, impl.getRetryCount() ); assertFalse( impl.isRequestSentRetryEnabled() ); try { final Field nonRetriableClasses = handler.getClass().getSuperclass() .getDeclaredField( "nonRetriableClasses" ); if ( !nonRetriableClasses.isAccessible() ) { nonRetriableClasses.setAccessible(true); } final Set<?> exceptions = Set.class.cast( nonRetriableClasses.get(handler) ); assertEquals( 1, exceptions.size() ); assertTrue( exceptions.contains( IOException.class ) ); } catch ( final Exception e ) { fail( e.getMessage() ); } } }); }
Source:
private Callback<ModelField[]> fieldCompletionsCallback(String factName, Callback<FactModelTree> aggregatorCallback) { return result -> { Map<String, String> simpleProperties = new HashMap<>(); for (ModelField modelField : result) { if (!modelField.getName().equals("this")) { simpleProperties.put(modelField.getName(), modelField.getClassName()); } } String factPackageName; String fullFactClassName = oracle.getFQCNByFactName(factName); if (fullFactClassName != null && fullFactClassName.contains(".")) { factPackageName = fullFactClassName.substring(0, fullFactClassName.lastIndexOf(".")); } else { factPackageName = packageName; } FactModelTree toSend = new FactModelTree(factName, factPackageName, simpleProperties); aggregatorCallback.callback(toSend); }; }

Target:
protected Callback<ModelField[]> fieldCompletionsCallback(String factName, Callback<FactModelTree> aggregatorCallback) { return result -> { FactModelTree toSend = getFactModelTree(factName, result); aggregatorCallback.callback(toSend); }; }
Source:
protected void tearDown() throws Exception { Locale.getDefault(); Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }

Target:
protected void tearDown() throws Exception { Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }
Source:
public Response removeUser(@PathParam("username") String username, @QueryParam("domain") String domain) { if (domain != null) { username = domain + '/' + username; } try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } }

Target:
public Response removeUser(@PathParam("username") String username, @QueryParam("domain") String domain) { if (domain != null && !domain.isEmpty()) { username = domain + '/' + username; } try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } }
Source:
public void run() { int reconnectAttempts = 0; for (; ; ) { if (Thread.currentThread().isInterrupted()) { return; } LOG.debug("Start connection loop channels ", wsUri, channels); try { connect(wsUri, channels); reconnectAttempts = 0; LOG.debug("Connection complete"); return; } catch (IOException | DeploymentException e) { LOG.warn("Not able to connect to because {}. Retrying ", wsUri, e.getLocalizedMessage()); LOG.debug(e.getLocalizedMessage(), e); if (reconnectAttempts++ > MAX_ATTEMPTS) { LOG.error(WORKSPACE_AGENT_STOPPED_MESSAGE); try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception ex) { LOG.info(e.getLocalizedMessage(), ex); } System.exit(0); } synchronized (this) { try { wait(WS_CONNECTION_TIMEOUT * 2 * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } catch (Throwable e) { LOG.error("Unexpected here"); LOG.error(e.getLocalizedMessage(), e); } LOG.debug("Iteration complete"); } }

Target:
public void run() { for (; ; ) { if (Thread.currentThread().isInterrupted()) { return; } LOG.debug("Start connection loop channels ", wsUri, channels); try { connect(wsUri, channels); LOG.debug("Connection complete"); return; } catch (IOException | DeploymentException e) { LOG.warn("Not able to connect to because {}. Retrying ", wsUri, e.getLocalizedMessage()); LOG.debug(e.getLocalizedMessage(), e); synchronized (this) { try { wait(WS_CONNECTION_TIMEOUT * 2 * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } catch (Throwable e) { LOG.error("Unexpected here"); LOG.error(e.getLocalizedMessage(), e); } LOG.debug("Iteration complete"); } }
Source:
public ImageFormat determineImageFormat(final InputStream is) throws IOException { Preconditions.checkNotNull(is); final byte[] imageHeaderBytes = new byte[mMaxHeaderLength]; final int headerSize = readHeaderFromStream(mMaxHeaderLength, is, imageHeaderBytes); ImageFormat format = mDefaultFormatChecker.determineFormat(imageHeaderBytes, headerSize); if (format != null && format != ImageFormat.UNKNOWN) { return format; } if (mCustomImageFormatCheckers != null) { for (ImageFormat.FormatChecker formatChecker : mCustomImageFormatCheckers) { format = formatChecker.determineFormat(imageHeaderBytes, headerSize); if (format != null && format != ImageFormat.UNKNOWN) { return format; } } } return ImageFormat.UNKNOWN; }

Target:
public ImageFormat determineImageFormat(final InputStream is) throws IOException { Preconditions.checkNotNull(is); final byte[] imageHeaderBytes = new byte[mMaxHeaderLength]; final int headerSize = readHeaderFromStream(mMaxHeaderLength, is, imageHeaderBytes); if (mCustomImageFormatCheckers != null) { for (ImageFormat.FormatChecker formatChecker : mCustomImageFormatCheckers) { ImageFormat format = formatChecker.determineFormat(imageHeaderBytes, headerSize); if (format != null && format != ImageFormat.UNKNOWN) { return format; } } } ImageFormat format = mDefaultFormatChecker.determineFormat(imageHeaderBytes, headerSize); if (format == null) { format = ImageFormat.UNKNOWN; } return format; }
Source:
public static GitWebType fromName(final String name) { final GitWebType type; if (name == null || name.isEmpty() || name.equalsIgnoreCase("gitweb")) { type = new GitWebType(); type.setProject("?p=${project}.git;a=summary"); type.setRevision("?p=${project}.git;a=commit;h=${commit}"); type.setBranch("?p=${project}.git;a=shortlog;h=${branch}"); } else if (name.equalsIgnoreCase("gitweb-pathinfo")) { type = new GitWebType(); type.setProject("/${project_path}.git/summary"); type.setRevision("/${project_path}.git/commit/${commit}"); type.setBranch("/${project_path}.git/shortlog/${branch_path}"); } else if (name.equalsIgnoreCase("cgit")) { type = new GitWebType(); type.setProject("${project}/summary"); type.setRevision("${project}/commit/?id=${commit}"); type.setBranch("${project}/log/?h=${branch}"); } else if (name.equalsIgnoreCase("custom")) { type = new GitWebType(); } else { type = null; } return type; }

Target:
public static GitWebType fromName(final String name) { final GitWebType type; if (name == null || name.isEmpty() || name.equalsIgnoreCase("gitweb")) { type = new GitWebType(); type.setProject("?p=${project}.git;a=summary"); type.setRevision("?p=${project}.git;a=commit;h=${commit}"); type.setBranch("?p=${project}.git;a=shortlog;h=${branch}"); } else if (name.equalsIgnoreCase("gitweb-pathinfo")) { type = new GitWebType(); type.setProject("${project}.git/summary"); type.setRevision("${project}.git/commit/${commit}"); type.setBranch("${project}.git/shortlog/${branch}"); type.setPathInfo(true); } else if (name.equalsIgnoreCase("cgit")) { type = new GitWebType(); type.setProject("${project}/summary"); type.setRevision("${project}/commit/?id=${commit}"); type.setBranch("${project}/log/?h=${branch}"); } else if (name.equalsIgnoreCase("custom")) { type = new GitWebType(); } else { type = null; } return type; }
Source:
private void runChecks(SensorContext context, XmlFile xmlFile, NewXmlFile newXmlFile) { XmlSourceCode sourceCode = new XmlSourceCode(xmlFile); if (sourceCode.parseSource()) { checks.all().stream() .filter(AbstractXmlCheck.class::isInstance) .map(AbstractXmlCheck.class::cast) .forEach(check -> runCheck(check, sourceCode)); saveIssues(context, sourceCode); } checks.all().stream() .filter(NewXmlCheck.class::isInstance) .map(NewXmlCheck.class::cast) .forEach(check -> { RuleKey ruleKey = checks.ruleKey(check); if (ruleKey == null) { throw new IllegalStateException("Failed to get rule key for rule " + check.getClass()); } runCheck(context, check, ruleKey, newXmlFile); }); }

Target:
private void runChecks(SensorContext context, XmlFile xmlFile, NewXmlFile newXmlFile) { XmlSourceCode sourceCode = new XmlSourceCode(xmlFile); if (sourceCode.parseSource()) { checks.all().stream() .filter(AbstractXmlCheck.class::isInstance) .map(AbstractXmlCheck.class::cast) .forEach(check -> runCheck(check, sourceCode)); saveIssues(context, sourceCode); } checks.all().stream() .filter(NewXmlCheck.class::isInstance) .map(NewXmlCheck.class::cast) .forEach(check -> runCheck(context, check, checks.ruleKey(check), newXmlFile)); }
Source:
private void validateRetentionPolicy(String retentionPolicy) throws FalconException { if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }

Target:
public static void validateRetentionPolicy(String retentionPolicy) throws FalconException { if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }
Source:
private void handleRegularArgument(RegularArgument regularArgument, SubscriptionContext ctx) { Name keywordArgument = regularArgument.keywordArgument(); if (keywordArgument != null && isCredential(keywordArgument.name(), variablePatterns()) && regularArgument.expression().is(Tree.Kind.STRING_LITERAL) && !isEmptyStringLiteral((StringLiteral) regularArgument.expression())) { ctx.addIssue(regularArgument, MESSAGE); } }

Target:
private void handleRegularArgument(RegularArgument regularArgument, SubscriptionContext ctx) { Name keywordArgument = regularArgument.keywordArgument(); if (keywordArgument != null && isCredential(keywordArgument.name(), variablePatterns()) && isNonEmptyStringLiteral(regularArgument.expression())) { ctx.addIssue(regularArgument, MESSAGE); } }
Source:
public String getMessage() { return "Impossible to delete some children when computing the folder: \n" + String.join("\n", exceptions.stream().map(e -> e.getMessage()).collect(Collectors.toList())); }

Target:
public String getMessage() { return "Impossible to delete some children when computing the folder. The first errors are: \n\t" + String.join("\n\t", exceptions.stream().limit(3).map(e -> e.getMessage()).collect(Collectors.toList())); }
Source:
public void markCompleted() { if(isTXCommit) { InflightMessageList.InflightMessage message = inflightMessages.completeMessage(position); if (message != null) { context.setPosition(message.position); Metrics metrics = context.getMetrics(); Timer timer = metrics.getRegistry().timer(metrics.metricName("message", "publish", "time")); timer.update(message.timeSinceSendMS(), TimeUnit.MILLISECONDS); } } }

Target:
public void markCompleted() { if(isTXCommit) { InflightMessageList.InflightMessage message = inflightMessages.completeMessage(position); if (message != null) { context.setPosition(message.position); metricsTimer.update(message.timeSinceSendMS(), TimeUnit.MILLISECONDS); } } }
Source:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { response = Response.status(Response.Status.OK).entity(DispoUtil.itemArtToItemData(result)).build(); } return response; }

Target:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { response = Response.status(Response.Status.OK).entity(result).build(); } return response; }
Source:
public static String generateServletActionFailureLogMessage(HttpServletRequest req, Exception e) { String[] actionTaken = req.getServletPath().split("/"); String action = req.getServletPath(); if (actionTaken.length > 0) { action = actionTaken[actionTaken.length - 1]; } String url = HttpRequestHelper.getRequestedURL(req); StringBuilder message = new StringBuilder(100); message.append("<span class=\"text-danger\">Servlet Action failure in ").append(action).append("<br>") .append(e.getClass()).append(": ").append(TeammatesException.toStringWithStackTrace(e)).append("<br>") .append(HttpRequestHelper.printRequestParameters(req)).append("</span>"); String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.COURSE_ID); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.STUDENT_EMAIL); ActivityLogEntry exceptionLog = new ActivityLogEntry(action, Const.ACTION_RESULT_FAILURE, null, message.toString(), url, courseId, studentEmail); return exceptionLog.generateLogMessage(); }

Target:
public static String generateServletActionFailureLogMessage(HttpServletRequest req, Exception e) { String[] actionTaken = req.getServletPath().split("/"); String action = req.getServletPath(); if (actionTaken.length > 0) { action = actionTaken[actionTaken.length - 1]; } String url = HttpRequestHelper.getRequestedURL(req); String message = "<span class=\"text-danger\">Servlet Action failure in " + action + "<br>" + e.getClass() + ": " + TeammatesException.toStringWithStackTrace(e) + "<br>" + HttpRequestHelper.printRequestParameters(req) + "</span>"; String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.COURSE_ID); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, Const.ParamsNames.STUDENT_EMAIL); ActivityLogEntry exceptionLog = new ActivityLogEntry(action, Const.ACTION_RESULT_FAILURE, null, message, url, courseId, studentEmail); return exceptionLog.generateLogMessage(); }
Source:
public void setup() { doReturn(viewport).when(gridPanel).getViewport(); doReturn(viewportMediators).when(viewport).getMediators(); doReturn(gridPanelElement).when(gridPanel).getElement(); this.view = new ExpressionEditorViewImpl(exitButton, expressionEditorControls, document, ts, gridPanel, gridLayer, mousePanMediator, sessionManager, sessionCommandManager); }

Target:
public void setup() { doReturn(viewport).when(gridPanel).getViewport(); doReturn(viewportMediators).when(viewport).getMediators(); doReturn(gridPanelElement).when(gridPanel).getElement(); this.view = new ExpressionEditorViewImpl(exitButton, expressionEditorControls, document, translationService, gridPanel, gridLayer, mousePanMediator, sessionManager, sessionCommandManager); }
Source:
private boolean needAck(Message message) { if (message.getSequence() == message.getBatch().getWindowSize()) { return true; } else { return false; } }

Target:
private boolean needAck(Message message) { return message.getSequence() == message.getBatch().getBatchSize(); }
Source:
private ButtonFieldActionDescriptor extractButtonFieldActionDescriptor(final String tableName, final String fieldName, final int adProcessId) { if (adProcessId > 0) { if (WindowConstants.FIELDNAME_DocAction.equals(fieldName) || WindowConstants.FIELDNAME_Processing.equals(fieldName)) { return null; } return ButtonFieldActionDescriptor.processCall(ProcessId.ofAD_Process_ID(adProcessId)); } if (tableName != null) { if (adColumnBL.isRecordIdColumnName(fieldName)) { final String zoomIntoTableIdFieldName = adColumnBL.getTableIdColumnName(tableName, fieldName).orElse(null); if (zoomIntoTableIdFieldName != null) { return ButtonFieldActionDescriptor.genericZoomInto(zoomIntoTableIdFieldName); } } } return null; }

Target:
private ButtonFieldActionDescriptor extractButtonFieldActionDescriptor(final String tableName, final String fieldName, final int adProcessId) { if (adProcessId > 0) { if ( WindowConstants.FIELDNAME_Processing.equals(fieldName)) { return null; } return ButtonFieldActionDescriptor.processCall(ProcessId.ofAD_Process_ID(adProcessId)); } if (tableName != null) { if (adColumnBL.isRecordIdColumnName(fieldName)) { final String zoomIntoTableIdFieldName = adColumnBL.getTableIdColumnName(tableName, fieldName).orElse(null); if (zoomIntoTableIdFieldName != null) { return ButtonFieldActionDescriptor.genericZoomInto(zoomIntoTableIdFieldName); } } } return null; }
Source:
public static <V> CompletionStage<V> continueOnExecutor(CompletionStage<V> delay, Executor continuationExecutor, Object traceId) { if (isCompletedSuccessfully(delay)) { if (trace) { log.tracef("Stage for %s was already completed, returning in same thread", traceId); } return delay; } CompletionStage<V> returnedFuture = delay.thenApplyAsync(v -> { if (trace) { log.tracef("Continuing execution of id %s", traceId); } return v; }, continuationExecutor); if (trace) { returnedFuture.exceptionally(t -> { log.tracef("Continuing execution of id %s with exception %s", traceId, t.getMessage()); return null; }); } return returnedFuture; }

Target:
public static <V> CompletionStage<V> continueOnExecutor(CompletionStage<V> delay, Executor continuationExecutor, Object traceId) { if (isCompletedSuccessfully(delay)) { if (trace) { log.tracef("Stage for %s was already completed, returning in same thread", traceId); } return delay; } return delay.whenCompleteAsync((v, t) -> { if (t != null) { if (trace) { log.tracef("Continuing execution of id %s with exception %s", traceId, t.getMessage()); } } else if (trace) { log.tracef("Continuing execution of id %s", traceId); } }, continuationExecutor); }
Source:
public void listPatchesAgainstBase() throws Exception { add(git, FILE_D, "4"); createCommit(git, admin.getIdent(), SUBJECT_1); pushHead(git, "refs/heads/master", false); add(git, FILE_A, "1"); rm(git, FILE_D); Commit c = createCommit(git, admin.getIdent(), SUBJECT_2); pushHead(git, "refs/for/master", false); List<PatchListEntry> entries = getCurrentPatches(c.getChangeId()); assertThat(entries.size()).isEqualTo(3); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertDeleted(FILE_D, entries.get(2)); add(git, FILE_B, "2"); c = amendCommit(git, admin.getIdent(), SUBJECT_2, c.getChangeId()); pushHead(git, "refs/for/master", false); entries = getCurrentPatches(c.getChangeId()); assertThat(entries.size()).isEqualTo(4); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertAdded(FILE_B, entries.get(2)); assertDeleted(FILE_D, entries.get(3)); }

Target:
public void listPatchesAgainstBase() throws Exception { add(git, FILE_D, "4"); createCommit(git, admin.getIdent(), SUBJECT_1); pushHead(git, "refs/heads/master", false); add(git, FILE_A, "1"); rm(git, FILE_D); Commit c = createCommit(git, admin.getIdent(), SUBJECT_2); pushHead(git, "refs/for/master", false); List<PatchListEntry> entries = getCurrentPatches(c.getChangeId()); assertThat(entries).hasSize(3); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertDeleted(FILE_D, entries.get(2)); add(git, FILE_B, "2"); c = amendCommit(git, admin.getIdent(), SUBJECT_2, c.getChangeId()); pushHead(git, "refs/for/master", false); entries = getCurrentPatches(c.getChangeId()); assertThat(entries).hasSize(4); assertAdded(Patch.COMMIT_MSG, entries.get(0)); assertAdded(FILE_A, entries.get(1)); assertAdded(FILE_B, entries.get(2)); assertDeleted(FILE_D, entries.get(3)); }
Source:
public boolean copyInitialTasksForRetry(List<Long> recursiveChildrenIdList) { List<StoredTask> tasks = handle.createQuery( selectTaskDetailsQuery() + " where t.id " + inLargeIdListExpression(recursiveChildrenIdList) + " and " + bitAnd("t.state_flags", Integer.toString(TaskStateFlags.INITIAL_TASK)) + " != 0" + " order by t.id asc" ) .map(stm) .list(); if (tasks.isEmpty()) { return false; } DatabaseTaskControlStore store = new DatabaseTaskControlStore(handle); Map<Long, Long> oldIdToNewId = new HashMap<>(); for (StoredTask task : tasks) { Task newTask = Task.taskBuilder() .from(task) .parentId(task.getParentId().transform(it -> oldIdToNewId.containsKey(it) ? oldIdToNewId.get(it) : it)) .state(TaskStateCode.BLOCKED) .stateFlags(TaskStateFlags.empty()) .build(); long newTaskId = addSubtask(tasks.get(0).getAttemptId(), newTask); oldIdToNewId.put(task.getId(), newTaskId); for (long oldUpstreamId : task.getUpstreams()) { dao.insertTaskDependency(newTaskId, oldIdToNewId.get(oldUpstreamId)); } } return true; }

Target:
public boolean copyInitialTasksForRetry(List<Long> recursiveChildrenIdList) { List<StoredTask> tasks = handle.createQuery( selectTaskDetailsQuery() + " where t.id " + inLargeIdListExpression(recursiveChildrenIdList) + " and " + bitAnd("t.state_flags", Integer.toString(TaskStateFlags.INITIAL_TASK)) + " != 0" + " order by t.id asc" ) .map(stm) .list(); if (tasks.isEmpty()) { return false; } DatabaseTaskControlStore store = new DatabaseTaskControlStore(handle); Map<Long, Long> oldIdToNewId = new HashMap<>(); for (StoredTask task : tasks) { Task newTask = Task.taskBuilder() .from(task) .parentId(task.getParentId().transform(it -> oldIdToNewId.getOrDefault(it, it))) .state(TaskStateCode.BLOCKED) .stateFlags(TaskStateFlags.empty()) .build(); long newTaskId = addSubtask(tasks.get(0).getAttemptId(), newTask); oldIdToNewId.put(task.getId(), newTaskId); for (long oldUpstreamId : task.getUpstreams()) { dao.insertTaskDependency(newTaskId, oldIdToNewId.get(oldUpstreamId)); } } return true; }
Source:
private static String assemble(String easting, String northing) { StringBuilder numericBuilder = new StringBuilder(); Runnable appendZero = () -> numericBuilder.append("0"); if (easting.length() < MAX_EASTING_LENGTH) { int numberOfZerosNeeded = MAX_EASTING_LENGTH - easting.length(); repeat(numberOfZerosNeeded, appendZero); } numericBuilder.append(easting); if (northing.length() < MAX_NORTHING_LENGTH) { int numberOfZerosNeeded = MAX_NORTHING_LENGTH - northing.length(); repeat(numberOfZerosNeeded, appendZero); } numericBuilder.append(northing); return numericBuilder.toString(); }

Target:
private static String assemble(String easting, String northing) { return leftPad(easting, MAX_COORDINATE_LENGTH, ZERO) + leftPad(northing, MAX_COORDINATE_LENGTH, ZERO); }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.IDP_RESPONSE); mHandler.getOperation().observe(this, new Observer<Resource<Void>>() { @Override public void onChanged(@Nullable Resource<Void> resource) { if (resource == null) { Log.w(TAG, "getSaveOperation:onChanged:null"); return; } if (!resource.isUsed()) { onSaveOperation(resource); } } }); Resource<Void> currentOp = mHandler.getOperation().getValue(); if (currentOp == null) { Log.d(TAG, "Launching save operation."); mHandler.saveCredentials(credential); } else { Log.d(TAG, "Save operation in progress, doing nothing."); } }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.IDP_RESPONSE); mHandler.getOperation().observe(this, new VoidResourceObserver( this, R.string.fui_progress_dialog_loading) { @Override protected void onSuccess() { finish(RESULT_OK, mIdpResponse.toIntent()); } @Override protected void onFailure(@NonNull Exception e) { finish(RESULT_OK, mIdpResponse.toIntent()); } }); Resource<Void> currentOp = mHandler.getOperation().getValue(); if (currentOp == null) { Log.d(TAG, "Launching save operation."); mHandler.saveCredentials(credential); } else { Log.d(TAG, "Save operation in progress, doing nothing."); } }
Source:
private void synchronizeJavaProjectInTransaction(final EclipseProject model, final IProject project, PersistentModelBuilder persistentModel, SubMonitor progress) throws JavaModelException, CoreException { progress.setWorkRemaining(8); CorePlugin.workspaceOperations().addNature(project, JavaCore.NATURE_ID, progress.newChild(1)); IJavaProject javaProject = JavaCore.create(project); OutputLocationUpdater.update(javaProject, model.getOutputLocation(), progress.newChild(1)); SourceFolderUpdater.update(javaProject, ImmutableList.copyOf(model.getSourceDirectories()), progress.newChild(1)); LibraryFilter.update(javaProject, model, progress.newChild(1)); ClasspathContainerUpdater.update(javaProject, model, progress.newChild(1)); JavaSourceSettingsUpdater.update(javaProject, model, progress.newChild(1)); GradleClasspathContainerUpdater.updateFromModel(javaProject, model, this.locationToProject.values(), persistentModel, progress.newChild(1)); WtpClasspathUpdater.update(javaProject, model, this.internalGradleBuild, progress.newChild(1)); CorePlugin.externalLaunchConfigurationManager().updateClasspathProviders(project); }

Target:
private void synchronizeJavaProjectInTransaction(final EclipseProject model, final IProject project, PersistentModelBuilder persistentModel, SubMonitor progress) throws JavaModelException, CoreException { progress.setWorkRemaining(7); CorePlugin.workspaceOperations().addNature(project, JavaCore.NATURE_ID, progress.newChild(1)); IJavaProject javaProject = JavaCore.create(project); OutputLocationUpdater.update(javaProject, model.getOutputLocation(), progress.newChild(1)); SourceFolderUpdater.update(javaProject, ImmutableList.copyOf(model.getSourceDirectories()), progress.newChild(1)); LibraryFilter.update(javaProject, model, progress.newChild(1)); ClasspathContainerUpdater.update(javaProject, model, progress.newChild(1)); JavaSourceSettingsUpdater.update(javaProject, model, progress.newChild(1)); GradleClasspathContainerUpdater.updateFromModel(javaProject, model, this.locationToProject.values(), persistentModel, progress.newChild(1)); CorePlugin.externalLaunchConfigurationManager().updateClasspathProviders(project); }
Source:
public static Map<Comparable, Double> getRankingPositionMap(final List<Comparable> unsortedArray, final boolean orderByDescending){ final Comparable[] sorted = unsortedArray.toArray(new Comparable[0]); Arrays.sort(sorted, new Comparator<Comparable>() { @Override public int compare(Comparable o1, Comparable o2) { if(!orderByDescending){ return o1.compareTo(o2); }else{ return -o1.compareTo(o2); } } }); final LinkedHashMap<Comparable, Double> rankingPositions = new LinkedHashMap<>(); for(int i = 0; i < sorted.length; i++){ rankingPositions.put(sorted[i], Double.valueOf(i) / unsortedArray.size()); } return rankingPositions; }

Target:
public static Map<Comparable, Double> getRankingPositionMap(final List<Comparable> unsortedArray, final boolean orderByDescending){ List<Comparable> sortedCopy = Ordering.natural().immutableSortedCopy(unsortedArray); if(orderByDescending){ sortedCopy = Ordering.natural().reverse().immutableSortedCopy(unsortedArray); } final LinkedHashMap<Comparable, Double> rankingPositions = new LinkedHashMap<>(); for(int i = 0; i < sortedCopy.size(); i++){ rankingPositions.put(sortedCopy.get(i), Double.valueOf(i) / unsortedArray.size()); } return rankingPositions; }
Source:
public void testSyncInOnly() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"request\")}")) .to("mock:result"); } }; context.addRoutes(builder); try { ServiceRegistry.get().register("GlobalCamelService", context); String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("camel-endpoint-id", "start"); workItem.setParameter("request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); WorkItemHandler handler = new InOnlyCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(0)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }

Target:
public void testSyncInOnly() throws Exception { String routeId = "testSyncInOnlyExceptionRoute"; RouteBuilder builder = new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId(routeId) .setBody(simple("${body.getParameter(\"Request\")}")) .to("mock:result"); } }; context.addRoutes(builder); try { ServiceRegistry.get().register(JBPMConstants.GLOBAL_CAMEL_CONTEXT_SERVICE_KEY, context); String expectedBody = "helloRequest"; resultEndpoint.expectedBodiesReceived(expectedBody); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM, "start"); workItem.setParameter("Request", expectedBody); TestWorkItemManager manager = new TestWorkItemManager(); WorkItemHandler handler = new InOnlyCamelWorkItemHandler(); handler.executeWorkItem(workItem, manager); assertThat(manager.getResults().size(), equalTo(0)); resultEndpoint.assertIsSatisfied(); } finally { context.removeRoute(routeId); } }
Source:
public Request init(Request request) { String context = request.getContext(); if (context == null || !context.toLowerCase().contains("gwc/service")) { return null; } Map<String, String> kvp = new HashMap<>(); kvp.put("service", "gwc"); kvp.put("version", "1.0.0"); kvp.put("request", "dispatch"); WorkspaceInfo localWorkspace = LocalWorkspace.get(); if (localWorkspace != null) { String layerName = (String) request.getKvp().get("LAYER"); if (layerName == null) { layerName = (String) request.getKvp().get("layer"); } if (layerName != null) { layerName = CatalogConfiguration.removeWorkspacePrefix(layerName, catalog); layerName = localWorkspace.getName() + ":" + layerName; kvp.put("LAYER", layerName); } request.setHttpRequest(new VirtualServiceRequest(request.getHttpRequest(), localWorkspace.getName(), layerName)); } request.setKvp(kvp); request.setRawKvp(kvp); return request; }

Target:
public Request init(Request request) { String context = request.getContext(); if (context == null || !isGwcServiceTargeted(context)) { return null; } GWC_OPERATION.set((String) request.getKvp().get("REQUEST")); Map<String, String> kvp = new HashMap<>(); kvp.put("service", "gwc"); kvp.put("version", "1.0.0"); kvp.put("request", "dispatch"); WorkspaceInfo localWorkspace = LocalWorkspace.get(); if (localWorkspace != null) { String layerName = (String) request.getKvp().get("LAYER"); if (layerName == null) { layerName = (String) request.getKvp().get("layer"); } if (layerName != null) { layerName = CatalogConfiguration.removeWorkspacePrefix(layerName, catalog); layerName = localWorkspace.getName() + ":" + layerName; kvp.put("LAYER", layerName); } request.setHttpRequest(new VirtualServiceRequest(request.getHttpRequest(), localWorkspace.getName(), layerName)); } request.setKvp(kvp); request.setRawKvp(kvp); return request; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); blockDrawerFromOpening(); String screenName; String actionItem; Map<String, String> values = new HashMap<>(); if (searchQuery != null) { screenName = ISegment.Screens.FORUM_SEARCH_THREADS; values.put(ISegment.Keys.SEARCH_STRING, searchQuery); actionItem = searchQuery; } else { screenName = ISegment.Screens.FORUM_VIEW_TOPIC_THREADS; String topicId = discussionTopic.getIdentifier(); if (DiscussionTopic.ALL_TOPICS_ID.equals(topicId)) { topicId = ISegment.Values.POSTS_ALL; actionItem = topicId.toLowerCase(); } else if (DiscussionTopic.FOLLOWING_TOPICS_ID.equals(topicId)) { topicId = ISegment.Values.POSTS_FOLLOWING; actionItem = topicId.toLowerCase(); } else { actionItem = discussionTopic.getName(); } values.put(ISegment.Keys.TOPIC_ID, topicId); } environment.getSegment().trackScreenView(screenName, courseData.getCourse().getId(), actionItem, values); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); blockDrawerFromOpening(); String screenName; String actionItem; Map<String, String> values = new HashMap<>(); if (searchQuery != null) { screenName = ISegment.Screens.FORUM_SEARCH_THREADS; values.put(ISegment.Keys.SEARCH_STRING, searchQuery); actionItem = searchQuery; } else { screenName = ISegment.Screens.FORUM_VIEW_TOPIC_THREADS; String topicId = discussionTopic.getIdentifier(); if (DiscussionTopic.ALL_TOPICS_ID.equals(topicId)) { topicId = actionItem = ISegment.Values.POSTS_ALL; } else if (DiscussionTopic.FOLLOWING_TOPICS_ID.equals(topicId)) { topicId = actionItem = ISegment.Values.POSTS_FOLLOWING; } else { actionItem = discussionTopic.getName(); } values.put(ISegment.Keys.TOPIC_ID, topicId); } environment.getSegment().trackScreenView(screenName, courseData.getCourse().getId(), actionItem, values); }