auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void createConfigEvent(ITestResult iTestResult) { String description = iTestResult.getMethod().getDescription(); if (description==null || description.trim().isEmpty()) { description = getConfigMethodType(iTestResult); } TestCaseStartedEvent event = new TestCaseStartedEvent(getSuiteUid(iTestResult.getTestContext()), iTestResult.getName()); event.setDescription(new Description().withValue(description)); AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); }

Target:
private void createConfigEvent(ITestResult iTestResult) { String description = iTestResult.getMethod().getDescription(); if (description == null || description.isEmpty()) { description = getConfigMethodType(iTestResult).getName(); } String suiteUid = getSuiteUid(iTestResult.getTestContext()); TestCaseStartedEvent event = new TestCaseStartedEvent(suiteUid, iTestResult.getName()); event.setDescription(new Description().withValue(description)); AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); }
Source:
public void clear() { commands.clear(); ; items.clear(); getView().clear(); }

Target:
public void clear() { commands.clear(); items.clear(); getView().clear(); }
Source:
public static final Builder v1Builder(String name) { return new Builder(name, V1MarshallerSet.marshallers(), V1MarshallerSet.setMarshallers(), StandardUnmarshallerSet.unmarshallers(), StandardUnmarshallerSet.setUnmarshallers()); }

Target:
public static Builder v1Builder(String name) { return new Builder(name, V1MarshallerSet.marshallers(), V1MarshallerSet.setMarshallers(), StandardUnmarshallerSet.unmarshallers(), StandardUnmarshallerSet.setUnmarshallers()); }
Source:
public static PublicJobState mapState(JobState state) { if (state == null) { return null; } PublicJobState publicJobState; switch (state) { case FINISHED: publicJobState = PublicJobState.FINISHED; break; case CREATED: publicJobState = PublicJobState.CREATED; break; case QUEUED: case RUNNING: case SCHEDULED: case WAITING: publicJobState = PublicJobState.RUNNING; break; case ABORTED: case CANCELED: case FAILED: case FAILED_WITH_RETRY: default: publicJobState = PublicJobState.FAILED; break; } return publicJobState; }

Target:
public static PublicJobState mapState(JobState state) { if (state == null) { return null; } PublicJobState publicJobState; switch (state) { case FINISHED: publicJobState = PublicJobState.FINISHED; break; case CREATED: case QUEUED: publicJobState = PublicJobState.CREATED; break; case CANCELED: publicJobState = PublicJobState.CANCELED; break; case FAILED_WITH_RETRY: case RUNNING: case SCHEDULED: case WAITING: publicJobState = PublicJobState.RUNNING; break; case ABORTED: case FAILED: default: publicJobState = PublicJobState.FAILED; break; } return publicJobState; }
Source:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newLinkedList(); Object item = entry.getDocument(); try { Datasift datasift = mapper.convertValue(item, Datasift.class); result.add(this.converter.convert(datasift)); } catch (Exception e) { e.printStackTrace(); } return result; }

Target:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newLinkedList(); Object item = entry.getDocument(); try { Datasift datasift = mapper.convertValue(item, Datasift.class); result.add(this.converter.convert(datasift)); } catch (Exception e) { LOGGER.error("Exception converting Datasift Interaction to "+this.outClass.getName()+ " : {}", e); } return result; }
Source:
public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { verifyNativeCommandPresent(d.getAnnotation(Native.class)); verifyNativeCommandPresent(d.getTestClass().getAnnotation(Native.class)); base.evaluate(); } private void verifyNativeCommandPresent(Native n) throws IOException, InterruptedException { if (n==null) return; if (!(controller instanceof LocalController)) { throw new AssumptionViolatedException("Test skipped. Native should be used with a local controller, otherwise it cannot be fully trusted to work as expected."); } List<String> supportedCmds = Lists.newLinkedList(); String path = System.getenv("PATH"); if (path != null) { String[] dirsInPath = SystemUtils.IS_OS_WINDOWS ? path.split(";") : path.split(":"); for (String dirName : dirsInPath) { File dir = new File(dirName); if (dir.isDirectory()) { supportedCmds.addAll(Arrays.asList(dir.list())); } } } for (String cmd : n.value()) { if (!supportedCmds.contains(cmd)) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system."); } } } }; }

Target:
public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { verifyNativeCommandPresent(d.getAnnotation(Native.class)); verifyNativeCommandPresent(d.getTestClass().getAnnotation(Native.class)); base.evaluate(); } private void verifyNativeCommandPresent(Native n) throws IOException, InterruptedException { if (n==null) return; for (String cmd : n.value()) { if (SystemUtils.IS_OS_WINDOWS) { if (new CommandBuilder("where",cmd).system()!=0) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system"); } } else { if (new CommandBuilder("which",cmd).system()!=0) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system"); } } } } }; }
Source:
public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications(5, TimeUnit.MINUTES); String appName = clientConfig.getReadClusterAppName(); if (applications != null && appName != null) { Application application = applications.getRegisteredApplications(appName); if (application != null) { List<InstanceInfo> validInstanceInfos = application.getInstances(); for (InstanceInfo instanceInfo : validInstanceInfos) { if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { result.add(ResolverUtils.instanceInfoToEndpoint(clientConfig, instanceInfo)); } } } } logger.debug("Retrieved endpoint list {}", result); return result; }

Target:
public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications( transportConfig.getApplicationsResolverDataStalenessThresholdSeconds(), TimeUnit.SECONDS); String vipAddress = transportConfig.getReadClusterVip(); if (applications != null && vipAddress != null) { List<InstanceInfo> validInstanceInfos = applications.getInstancesByVirtualHostName(vipAddress); for (InstanceInfo instanceInfo : validInstanceInfos) { if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { result.add(ResolverUtils.instanceInfoToEndpoint(clientConfig, instanceInfo)); } } } logger.debug("Retrieved endpoint list {}", result); return result; }
Source:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { try (AbfsPerfInfo tracker = new AbfsPerfInfo(client.getAbfsPerfTracker(), "writeCurrentBufferToService", "append")) { tracker.registerResult(client.append(path, offset, bytes, 0, bytesLength).getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); tracker.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
public NestedPropertyMappingMethod build() { List<String> existingVariableNames = new ArrayList<String>(); for ( Parameter parameter : method.getSourceParameters() ) { existingVariableNames.add( parameter.getName() ); } final List<Type> thrownTypes = new ArrayList<Type>(); List<SafePropertyEntry> safePropertyEntries = new ArrayList<SafePropertyEntry>(); for ( PropertyEntry propertyEntry : propertyEntries ) { String safeName = Strings.getSaveVariableName( propertyEntry.getName(), existingVariableNames ); safePropertyEntries.add( new SafePropertyEntry( propertyEntry, safeName ) ); existingVariableNames.add( safeName ); List<Type> declaredExceptions = ctx.getTypeFactory().getThrownTypes( (ExecutableType) propertyEntry.getReadAccessor().getExecutable().asType() ); for (Type declaredException : declaredExceptions) { thrownTypes.add( declaredException ); } } NestedPropertyMappingMethod mappingMethod = new NestedPropertyMappingMethod( method, safePropertyEntries ); for (Type thrownType : thrownTypes) { if (!mappingMethod.getThrownTypes().contains( thrownType )) { mappingMethod.getThrownTypes().add( thrownType ); } } return mappingMethod; }

Target:
public NestedPropertyMappingMethod build() { List<String> existingVariableNames = new ArrayList<String>(); for ( Parameter parameter : method.getSourceParameters() ) { existingVariableNames.add( parameter.getName() ); } final List<Type> thrownTypes = new ArrayList<Type>(); List<SafePropertyEntry> safePropertyEntries = new ArrayList<SafePropertyEntry>(); for ( PropertyEntry propertyEntry : propertyEntries ) { String safeName = Strings.getSaveVariableName( propertyEntry.getName(), existingVariableNames ); safePropertyEntries.add( new SafePropertyEntry( propertyEntry, safeName ) ); existingVariableNames.add( safeName ); thrownTypes.addAll( ctx.getTypeFactory().getThrownTypes( propertyEntry.getReadAccessor() ) ); } method.addThrownTypes( thrownTypes ); return new NestedPropertyMappingMethod( method, safePropertyEntries ); }
Source:
private void ping() throws IOException, InterruptedException { LOGGER.log(Level.FINE, "pinging {0}", channel.getName()); Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); long remaining = end - System.nanoTime(); do { LOGGER.log(Level.FINE, "waiting {0}s on {1}", new Object[] {TimeUnit.NANOSECONDS.toSeconds(remaining), channel.getName()}); try { f.get(Math.max(1,remaining),TimeUnit.NANOSECONDS); LOGGER.log(Level.FINE, "ping succeeded on {0}", channel.getName()); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; throw e; } catch (TimeoutException e) { } remaining = end - System.nanoTime(); } while(remaining>0); throw new TimeoutException( "Ping started at " + start + " hasn't completed by " + System.currentTimeMillis() ); }

Target:
private void ping() throws IOException, InterruptedException { LOGGER.log(Level.FINE, "pinging {0}", channel.getName()); int timeouts = 0; while (true) { Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); long remaining = end - System.nanoTime(); do { LOGGER.log( Level.FINE, "waiting {0}s on {1}", new Object[] {TimeUnit.NANOSECONDS.toSeconds(remaining), channel.getName()} ); try { f.get(Math.max(1,remaining),TimeUnit.NANOSECONDS); LOGGER.log(Level.FINE, "ping succeeded on {0}", channel.getName()); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; onDead(e); return; } catch (TimeoutException e) { } remaining = end - System.nanoTime(); } while(remaining>0); if (++timeouts >= maxTimeouts) { break; } Logger.log(Level.WARNING, "ping timeout {0}/{1} on {2}", new Object[] {timeouts, maxTimeouts, channel.getName()} ); } onDead(new TimeoutException( String.format("Ping started at %d hasn't completed by %d", start, System.currentTimeMillis()) )); }
Source:
public void testCreationOfFakeCommentBlock() throws Exception { final Method createFakeBlockComment = Whitebox.getMethod(CommonUtils.class, "createFakeBlockComment", String.class); final DetailAST testCommentBlock = (DetailAST) createFakeBlockComment.invoke(null, "test_comment"); assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_BEGIN, testCommentBlock.getType()); assertEquals("Invalid text", " ", endCommentBlock.getText()); }

Target:
public void testCreationOfFakeCommentBlock() { final DetailAST testCommentBlock = CommonUtils.createBlockCommentNode("test_comment"); assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_BEGIN, testCommentBlock.getType()); assertEquals("Invalid text", " ", endCommentBlock.getText()); }
Source:
protected void relearnAdditionalParameters(final ExpectationStep eStep) { final Function<Double, Double> emissionLogLikelihood = width -> { double logLikelihood = 0.0; for (int position = 0; position < positions.size(); position++) { for (int state = 0; state < weights.length; state++) { final double eStepPosterior = eStep.pStateAtPosition(state, position); logLikelihood += eStepPosterior < NEGLIGIBLE_POSTERIOR_FOR_M_STEP ? 0 :eStepPosterior * CopyRatioHiddenMarkovModel.logEmissionProbability(data.get(position), hiddenStateValues[state], width); } } return logLikelihood; }; logCoverageCauchyWidth = OptimizationUtils.quickArgmax(emissionLogLikelihood, 0, MAX_REASONABLE_CAUCHY_WIDTH, logCoverageCauchyWidth); logger.info("New coverage standard deviation learned: " + logCoverageCauchyWidth); }

Target:
protected void relearnAdditionalParameters(final ExpectationStep eStep) { final Function<Double, Double> emissionLogLikelihood = width -> { double logLikelihood = 0.0; for (int position = 0; position < positions.size(); position++) { for (int state = 0; state < weights.length; state++) { final double eStepPosterior = eStep.pStateAtPosition(state, position); logLikelihood += eStepPosterior < NEGLIGIBLE_POSTERIOR_FOR_M_STEP ? 0 :eStepPosterior * CopyRatioHiddenMarkovModel.logEmissionProbability(data.get(position), hiddenStateValues[state], width); } } return logLikelihood; }; logCoverageCauchyWidth = OptimizationUtils.argmax(emissionLogLikelihood, 0, MAX_REASONABLE_CAUCHY_WIDTH, logCoverageCauchyWidth, RELATIVE_TOLERANCE_FOR_OPTIMIZATION, ABSOLUTE_TOLERANCE_FOR_OPTIMIZATION, MAX_EVALUATIONS_FOR_OPTIMIZATION); logger.info("New coverage standard deviation learned: " + logCoverageCauchyWidth); }
Source:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { logger.debug("Error closing an autorecovered channel"); } finally { hasListener.remove(recoverable); } }

Target:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { logger.error("Error closing an autorecovered channel", e); } finally { hasListener.remove(recoverable); } }
Source:
private boolean canScanNode(StructuralNode node) { if (node == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null node"); } return false; } HistoryReference hRef = node.getHistoryReference(); if (hRef == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null history reference for node: " + node.getName()); } return false; } if (HistoryReference.TYPE_SCANNER == hRef.getHistoryType()) { if (log.isDebugEnabled()) { log.debug( "Ignoring \"scanner\" type href [id=" + hRef.getHistoryId() + ", URL=" + hRef.getURI() + "]"); } return false; } if (!nodeInScope(node.getName())) { if (log.isDebugEnabled()) { log.debug("Ignoring node not in scope: " + node.getName()); } return false; } Set<FilterResult> filterResult = filterNode(node); if (filterResult.size() > 0) { if (log.isDebugEnabled()) { log.debug("Ignoring filtered node: " + node.getName() + " Reasons for Ignoring: " + filterResult.toString()); } return false; } return true; }

Target:
private boolean canScanNode(StructuralNode node) { if (node == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null node"); } return false; } HistoryReference hRef = node.getHistoryReference(); if (hRef == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null history reference for node: " + node.getName()); } return false; } if (HistoryReference.TYPE_SCANNER == hRef.getHistoryType()) { if (log.isDebugEnabled()) { log.debug( "Ignoring \"scanner\" type href [id=" + hRef.getHistoryId() + ", URL=" + hRef.getURI() + "]"); } return false; } if (!nodeInScope(node.getName())) { if (log.isDebugEnabled()) { log.debug("Ignoring node not in scope: " + node.getName()); } return false; } if (filterNode(node)) { return false; } return true; }
Source:
public void zoomOut() { double maxRange = layoutPanel.getFirstChild().getPlotRepresentation().getMaxRange(); for (PlotContainer pc : layoutPanel.getAllChildren()) { SimplePlot plot = pc.getPlotRepresentation().getSimplePlot(); Zoom zoom = Zoom.create().setAmount(1.1); plot.zoomOut(zoom); pc.getPlotRepresentation().calculateScrollWidth(); } PlotRepresentation plotRepresentation = layoutPanel.getFirstChild().getPlotRepresentation(); double minVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMinimumValue(); double maxVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMaximumValue(); if (maxVisible > maxRange && minVisible < 0) { return; } double percent; if (maxVisible >= maxRange) { percent = 1; } else if (minVisible <= 0) { percent = 0; } else { percent = minVisible / (maxRange - maxVisible + minVisible); } plotRepresentation.panToPercent(percent); }

Target:
public void zoomOut() { zoom(true); }
Source:
private void failWithTimeout(long now, Throwable cause) { if (log.isDebugEnabled()) { log.debug("{} timed out at after attempt(s)", this, now, retryContext.getTries() + 1, new Exception(prettyPrintException(cause))); } handleFailure(new TimeoutException(this + " timed out at " + now + " after " + getRetryContext().getTries() + " attempt(s)", cause)); }

Target:
private void failWithTimeout(long now, Throwable cause) { if (log.isDebugEnabled()) { log.debug("{} timed out at after attempt(s)", this, now, callRetryContext.tries() + 1, new Exception(prettyPrintException(cause))); } handleFailure(new TimeoutException(this + " timed out at " + now + " after " + callRetryContext().tries() + " attempt(s)", cause)); }
Source:
public void init() { setPackage(securityPackage); setLabel(SIMPLE_NAME); setDescription("A number of people that work together or share certain beliefs."); addAttribute(ID, ROLE_ID).setAuto(true).setVisible(false).setLabel("Identifier"); addAttribute(NAME, ROLE_LOOKUP) .setLabel("Name") .setDescription("Name of the group. Use kebab-case, e.g. my-group.") .setNillable(false) .setUnique(true) .setValidationExpression("$('name').matches(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/).value()"); addAttribute(LABEL, ROLE_LABEL, ROLE_LOOKUP).setLabel("Label").setNillable(false); getLanguageCodes() .map(languageCode -> getI18nAttributeName(LABEL, languageCode)) .forEach(this::addAttribute); addAttribute(DESCRIPTION).setLabel("Description").setDataType(TEXT); getLanguageCodes() .map(languageCode -> getI18nAttributeName(DESCRIPTION, languageCode)) .map(this::addAttribute) .forEach(attribute -> attribute.setDataType(TEXT)); addAttribute(PUBLIC) .setDataType(BOOL) .setLabel("Publicly visible") .setDescription("Indication if this group is publicly visible.") .setNillable(false) .setDefaultValue("true"); addAttribute(ROLES) .setDataType(ONE_TO_MANY) .setRefEntity(roleMetadata) .setMappedBy(roleMetadata.getAttribute(RoleMetadata.GROUP)) .setLabel("Roles") .setDescription("Roles a User can have within this Group") .setCascadeDelete(true); addAttribute(ROOT_PACKAGE) .setLabel("Root package") .setDescription("Id of the package where this Group's resources reside.") .setDataType(XREF) .setRefEntity(packageMetadata) .setNillable(false) .setReadOnly(true) .setCascadeDelete(true); }

Target:
public void init() { setPackage(securityPackage); setLabel(SIMPLE_NAME); setDescription("A number of people that work together or share certain beliefs."); addAttribute(ID, ROLE_ID).setAuto(true).setVisible(false).setLabel("Identifier"); addAttribute(NAME, ROLE_LOOKUP) .setLabel("Name") .setDescription("Name of the group. Use kebab-case, e.g. my-group.") .setNillable(false) .setUnique(true) .setValidationExpression("$('name').matches(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/).value()"); addAttribute(LABEL, ROLE_LABEL, ROLE_LOOKUP).setLabel("Label").setNillable(false); getLanguageCodes() .map(languageCode -> getI18nAttributeName(LABEL, languageCode)) .forEach(this::addAttribute); addAttribute(DESCRIPTION).setLabel("Description").setDataType(TEXT); getLanguageCodes() .map(languageCode -> getI18nAttributeName(DESCRIPTION, languageCode)) .map(this::addAttribute) .forEach(attribute -> attribute.setDataType(TEXT)); addAttribute(PUBLIC) .setDataType(BOOL) .setLabel("Publicly visible") .setDescription("Indication if this group is publicly visible.") .setNillable(false) .setDefaultValue("true"); addAttribute(ROLES) .setDataType(ONE_TO_MANY) .setRefEntity(roleMetadata) .setMappedBy(roleMetadata.getAttribute(RoleMetadata.GROUP)) .setLabel("Roles") .setDescription("Roles a User can have within this Group") .setCascadeDelete(true); addAttribute(ROOT_PACKAGE) .setLabel("Root package") .setDescription("Package where this Group's resources reside.") .setDataType(XREF) .setRefEntity(packageMetadata) .setNillable(false) .setReadOnly(true) .setCascadeDelete(true) .setUnique(true); }
Source:
public static boolean authorizeUpdatePassword(Context context, String email) { try { EPerson eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(context, email); if (eperson != null && eperson.canLogIn()) { return true; } } catch (SQLException e) { log.error("Something went wrong trying to retrieve EPerson for email: " + email, e); } return false; }

Target:
public static boolean authorizeUpdatePassword(Context context, String email) { try { EPerson eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(context, email); if (eperson != null && eperson.canLogIn()) { HttpServletRequest request = new DSpace().getRequestService().getCurrentRequest() .getHttpServletRequest(); return AuthenticateServiceFactory.getInstance().getAuthenticationService() .allowSetPassword(context, request, null); } } catch (SQLException e) { log.error("Something went wrong trying to retrieve EPerson for email: " + email, e); } return false; }
Source:
public void validate(PatientRecord patientRecord) throws ImportResourceException { if (patientRecord.getPatient() == null) { throw new ImportResourceException("Patient must be defined"); } if (patientRecord.getPatient().getPatientNumbers() == null) { throw new ImportResourceException("PatientNumbers must be defined"); } if (CollectionUtils.isEmpty(patientRecord.getPatient().getPatientNumbers().getPatientNumber())) { throw new ImportResourceException("PatientNumbers must have at least one Number"); } findIdentifier(patientRecord); if (patientRecord.getSurveys() != null && !CollectionUtils.isEmpty(patientRecord.getSurveys().getSurvey())) { for (uk.org.rixg.Survey survey : patientRecord.getSurveys().getSurvey()) { validateSurvey(survey); } } if (patientRecord.getDocuments() != null && !CollectionUtils.isEmpty(patientRecord.getDocuments().getDocument())) { if (StringUtils.isEmpty(patientRecord.getSendingFacility().toString())) { throw new ImportResourceException("SendingFacility must be defined (for Documents)"); } if (groupRepository.findByCode(patientRecord.getSendingFacility().toString()) == null) { throw new ImportResourceException("SendingFacility PatientView Group not found (for Documents)"); } for (Document document : patientRecord.getDocuments().getDocument()) { validateDocument(document); } } }

Target:
public void validate(PatientRecord patientRecord) throws ImportResourceException { if (patientRecord.getPatient() == null) { throw new ImportResourceException("Patient must be defined"); } if (patientRecord.getPatient().getPatientNumbers() == null) { throw new ImportResourceException("PatientNumbers must be defined"); } if (CollectionUtils.isEmpty(patientRecord.getPatient().getPatientNumbers().getPatientNumber())) { throw new ImportResourceException("PatientNumbers must have at least one Number"); } findIdentifier(patientRecord); if (patientRecord.getSurveys() != null && !CollectionUtils.isEmpty(patientRecord.getSurveys().getSurvey())) { for (uk.org.rixg.Survey survey : patientRecord.getSurveys().getSurvey()) { validateSurvey(survey); } } if (patientRecord.getDocuments() != null && !CollectionUtils.isEmpty(patientRecord.getDocuments().getDocument())) { if (patientRecord.getSendingFacility() == null || StringUtils.isEmpty(patientRecord.getSendingFacility().toString())) { throw new ImportResourceException("SendingFacility must be defined (for Documents)"); } if (groupRepository.findByCode(patientRecord.getSendingFacility().toString()) == null) { throw new ImportResourceException("SendingFacility PatientView Group not found (for Documents)"); } for (Document document : patientRecord.getDocuments().getDocument()) { validateDocument(document); } } }
Source:
public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug(e.getMessage(), e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug(e.getMessage(), e); result.use(Results.http()).sendError(SC_BAD_REQUEST, e.getMessage()); } }

Target:
public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug(e.getMessage(), e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug(e.getMessage(), e); invalidInputHandler.deny(e); } }
Source:
generateX509Certificate( X500Name subject, AsymmetricCipherKeyPair keyPair) { String signatureAlgorithm = ConfigUtils.getString( LibJitsi.getConfigurationService(), PROP_SIGNATURE_ALGORITHM, "SHA1withRSA"); if (logger.isDebugEnabled()) logger.debug("Signature algorithm: " + signatureAlgorithm); try { long now = System.currentTimeMillis(); Date notBefore = new Date(now - ONE_DAY); Date notAfter = new Date(now + CERT_VALIDITY_TIME); X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject, BigInteger.valueOf(now), notBefore, notAfter, subject, SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo( keyPair.getPublic())); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find(signatureAlgorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keyPair.getPrivate()); return builder.build(signer).toASN1Structure(); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } else { logger.error( "Failed to generate self-signed X.509 certificate", t); if (t instanceof RuntimeException) throw (RuntimeException) t; else throw new RuntimeException(t); } } }

Target:
generateX509Certificate( X500Name subject, AsymmetricCipherKeyPair keyPair) { String signatureAlgorithm = ConfigUtils.getString( LibJitsi.getConfigurationService(), PROP_SIGNATURE_ALGORITHM, "SHA1withRSA"); if (logger.isDebugEnabled()) logger.debug("Signature algorithm: " + signatureAlgorithm); try { long now = System.currentTimeMillis(); Date notBefore = new Date(now - ONE_DAY); Date notAfter = new Date(now + ONE_DAY * 6 + CERT_CACHE_EXPIRE_TIME); X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject, BigInteger.valueOf(now), notBefore, notAfter, subject, SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo( keyPair.getPublic())); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find(signatureAlgorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keyPair.getPrivate()); return builder.build(signer).toASN1Structure(); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } else { logger.error( "Failed to generate self-signed X.509 certificate", t); if (t instanceof RuntimeException) throw (RuntimeException) t; else throw new RuntimeException(t); } } }
Source:
public boolean hasRadiologyOrderClaimedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.like("radiologyOrder", radiologyOrder)).add( Restrictions.like("radiologyReportStatus", RadiologyReportStatus.CLAIMED)).list(); if (radiologyReports.size() == 1) { return true; } else { return false; } }

Target:
public boolean hasRadiologyOrderClaimedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)).add( Restrictions.eq("reportStatus", RadiologyReportStatus.CLAIMED)).list(); return radiologyReports.size() == 1 ? true : false; }
Source:
private Direction getParamDirection(int columnType, boolean isFunction) { Direction dir = null; if (isFunction) { switch (columnType) { case DatabaseMetaData.functionColumnIn: dir = Direction.INPUT; break; case DatabaseMetaData.functionReturn: dir = Direction.RETURN_VALUE; break; } } else { switch (columnType) { case DatabaseMetaData.procedureColumnIn: dir = Direction.INPUT; break; case DatabaseMetaData.procedureColumnInOut: dir = Direction.INPUT_OUTPUT; break; case DatabaseMetaData.procedureColumnOut: dir = Direction.OUTPUT; break; } } if (dir == null) { throw new UnsupportedOperationException( "Type " + columnType + " is not a supported type for " + (isFunction ? "function" : "procedure") + " parameters"); } return dir; }

Target:
private Direction getParamDirection(int columnType, boolean isFunction) { if (isFunction) { switch (columnType) { case DatabaseMetaData.functionColumnIn: return Direction.INPUT; case DatabaseMetaData.functionReturn: return Direction.RETURN_VALUE; } } else { switch (columnType) { case DatabaseMetaData.procedureColumnIn: return Direction.INPUT; case DatabaseMetaData.procedureColumnInOut: return Direction.INPUT_OUTPUT; case DatabaseMetaData.procedureColumnOut: return Direction.OUTPUT; } } throw new UnsupportedOperationException("Type " + columnType + " is not a supported type for " + (isFunction ? "function" : "procedure") + " parameters"); }
Source:
public static final <T> StoreQueryParams<T> fromNameAndType(final String storeName, final QueryableStoreType<T> queryableStoreType) { return new<T> StoreQueryParams<T>(storeName, queryableStoreType); }

Target:
public static <T> StoreQueryParams<T> fromNameAndType(final String storeName, final QueryableStoreType<T> queryableStoreType) { return new StoreQueryParams<T>(storeName, queryableStoreType); }
Source:
public static String getLeaseKey(ShardInfo shardInfo) { return shardInfo.streamName().isPresent() ? MultiStreamLease.getLeaseKey(shardInfo.streamName().get(), shardInfo.shardId()) : shardInfo.shardId(); }

Target:
public static String getLeaseKey(ShardInfo shardInfo) { return shardInfo.streamIdentifierSerOpt().isPresent() ? MultiStreamLease.getLeaseKey(shardInfo.streamIdentifierSerOpt().get(), shardInfo.shardId()) : shardInfo.shardId(); }
Source:
public VM update(VM incoming) { if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if(!clusterId.toString().equals(get().getCluster().getId())){ performAction(VdcActionType.ChangeVMCluster, new ChangeVMClusterParameters(clusterId, guid)); } } if (incoming.isSetPlacementPolicy() && incoming.getPlacementPolicy().isSetHost() && incoming.getPlacementPolicy().getHost().isSetName() && !incoming.getPlacementPolicy().getHost().isSetId()) { incoming.getPlacementPolicy().getHost().setId(getHostId(incoming.getPlacementPolicy().getHost().getName())); } VM retVal = performUpdate(incoming, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class), VdcActionType.UpdateVm, new UpdateParametersProvider()); setPayload(retVal); return retVal; }

Target:
public VM update(VM incoming) { if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if(!clusterId.toString().equals(get().getCluster().getId())){ performAction(VdcActionType.ChangeVMCluster, new ChangeVMClusterParameters(clusterId, guid)); } } if (incoming.isSetPlacementPolicy() && incoming.getPlacementPolicy().isSetHost() && incoming.getPlacementPolicy().getHost().isSetName() && !incoming.getPlacementPolicy().getHost().isSetId()) { incoming.getPlacementPolicy().getHost().setId(getHostId(incoming.getPlacementPolicy().getHost().getName())); } VM retVal = performUpdate(incoming, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class), VdcActionType.UpdateVm, new UpdateParametersProvider()); return retVal; }
Source:
public String getPathRelativeToSourceRoot(File file, int stripCount) throws IOException, FileNotFoundException { String canonicalPath = file.getCanonicalPath(); String sourceRoot = getSourceRootPath(); if(sourceRoot == null){ throw new FileNotFoundException("Source Root Not Found"); } if (canonicalPath.startsWith(sourceRoot)) { return canonicalPath.substring(sourceRoot.length() + stripCount); } for (String allowedSymlink : getAllowedSymlinks()) { String allowedTarget = new File(allowedSymlink).getCanonicalPath(); if (canonicalPath.startsWith(allowedTarget)) { return canonicalPath.substring(allowedTarget.length() + stripCount); } } throw new FileNotFoundException("Failed to resolve [" + canonicalPath + "] relative to source root [" + sourceRoot + "]"); }

Target:
public String getPathRelativeToSourceRoot(File file, int stripCount) throws IOException { String canonicalPath = file.getCanonicalPath(); String sourceRoot = getSourceRootPath(); if(sourceRoot == null){ throw new FileNotFoundException("Source Root Not Found"); } if (canonicalPath.startsWith(sourceRoot)) { return canonicalPath.substring(sourceRoot.length() + stripCount); } for (String allowedSymlink : getAllowedSymlinks()) { String allowedTarget = new File(allowedSymlink).getCanonicalPath(); if (canonicalPath.startsWith(allowedTarget)) { return canonicalPath.substring(allowedTarget.length() + stripCount); } } throw new FileNotFoundException("Failed to resolve [" + canonicalPath + "] relative to source root [" + sourceRoot + "]"); }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { String noteId = context.getJobDetail().getJobDataMap().getString("noteId"); Note note = notebook.getNote(noteId); if (note.isRunningOrPending()) { logger.info("execution of the cron job is skipped because there is a running or pending " + "paragraph (note id: {})", noteId); return; } note.runAll(); boolean releaseResource = false; String cronExecutingUser = null; try { Map<String, Object> config = note.getConfig(); if (config != null) { if (config.containsKey("releaseresource")) { releaseResource = (boolean) config.get("releaseresource"); } cronExecutingUser = (String) config.get("cronExecutingUser"); } } catch (ClassCastException e) { logger.error(e.getMessage(), e); } if (releaseResource) { for (InterpreterSetting setting : notebook.getInterpreterSettingManager() .getInterpreterSettings(note.getId())) { try { notebook.getInterpreterSettingManager().restart(setting.getId(), noteId, cronExecutingUser != null ? cronExecutingUser : "anonymous"); } catch (InterpreterException e) { logger.error("Fail to restart interpreter: " + setting.getId(), e); } } } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { String noteId = context.getJobDetail().getJobDataMap().getString("noteId"); Note note = notebook.getNote(noteId); if (note.isRunningOrPending()) { logger.warn("execution of the cron job is skipped because there is a running or pending " + "paragraph (note id: {})", noteId); return; } note.runAll(); boolean releaseResource = false; String cronExecutingUser = null; try { Map<String, Object> config = note.getConfig(); if (config != null) { if (config.containsKey("releaseresource")) { releaseResource = (boolean) config.get("releaseresource"); } cronExecutingUser = (String) config.get("cronExecutingUser"); } } catch (ClassCastException e) { logger.error(e.getMessage(), e); } if (releaseResource) { for (InterpreterSetting setting : notebook.getInterpreterSettingManager() .getInterpreterSettings(note.getId())) { try { notebook.getInterpreterSettingManager().restart(setting.getId(), noteId, cronExecutingUser != null ? cronExecutingUser : "anonymous"); } catch (InterpreterException e) { logger.error("Fail to restart interpreter: " + setting.getId(), e); } } } }
Source:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); builder.append(actionType); builder.append(", Parameters: "); builder.append(params); } }

Target:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); builder.append(actionType); builder.append(", Parameters: "); builder.append(params); log.debug(builder.toString()); } }
Source:
protected void collectColumns() throws IOException { TermFactory factory = TermFactory.instance(); int index = 0; String[] header = reader.readNext(); if (header == null || header.length == 0) throw new IndexBuilderException("No header in CSV file"); this.termLocations = new HashMap<>(header.length); this.terms = new ArrayList<>(header.length); for (String heading: header) { heading = heading.trim(); Term term = factory.findTerm(heading); if (term == null) term = ALATerm.valueOf(heading); if (term != null) this.termLocations.put(term, index); this.terms.add(term); index++; } }

Target:
protected void collectColumns() throws IOException { TermFactory factory = TermFactory.instance(); int index = 0; String[] header = reader.readNext(); if (header == null || header.length == 0) throw new IndexBuilderException("No header in CSV file"); this.termLocations = new LinkedHashMap<>(header.length); this.terms = new ArrayList<>(header.length); for (String heading: header) { heading = heading.trim(); Term term = factory.findTerm(heading); if (term == null) term = ALATerm.valueOf(heading); if (term != null) this.termLocations.put(term, index); else logger.warn("Unable to map " + heading + " onto a term"); this.terms.add(term); index++; } }
Source:
public final U assertValueAt(int index, T value) { int s = values.size(); if (s == 0) { throw fail("No values"); } if (index >= values.size()) { throw fail("Invalid index: " + index); } T v = values.get(index); if (!ObjectHelper.equals(value, v)) { throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); } return (U)this; }

Target:
public final U assertValueAt(int index, T value) { int s = values.size(); if (s == 0) { throw fail("No values"); } if (index >= s) { throw fail("Invalid index: " + index); } T v = values.get(index); if (!ObjectHelper.equals(value, v)) { throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); } return (U)this; }
Source:
public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, LockingStrategyException { TypeTranslator typeTranslator = lockable.getFactory().getServiceRegistry().getService( TypeTranslator.class ); GridType idGridType = typeTranslator.getType( lockable.getIdentifierType() ); EntityKey key = EntityKeyBuilder.fromData( ( (OgmEntityPersister) lockable ).getRootEntityKeyMetadata(), idGridType, id, session ); IgniteCache<Object, BinaryObject> cache = provider.getEntityCache( key.getMetadata() ); if ( cache == null ) { throw new IgniteHibernateException( "Cache " + key.getMetadata().getTable() + " is not found" ); } Lock lock = cache.lock( provider.createKeyObject( key ) ); try { lock.tryLock( timeout, TimeUnit.MILLISECONDS ); } catch (InterruptedException e) { throw new IgniteLockingStrategyException( object, e.getMessage(), e ); } }

Target:
public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, LockingStrategyException { TypeTranslator typeTranslator = lockable.getFactory().getServiceRegistry().getService( TypeTranslator.class ); GridType idGridType = typeTranslator.getType( lockable.getIdentifierType() ); EntityKey key = EntityKeyBuilder.fromData( ( (OgmEntityPersister) lockable ).getRootEntityKeyMetadata(), idGridType, id, session ); IgniteCache<Object, BinaryObject> cache = provider.getEntityCache( key.getMetadata() ); Lock lock = cache.lock( provider.createKeyObject( key ) ); try { lock.tryLock( timeout, TimeUnit.MILLISECONDS ); } catch (InterruptedException e) { throw new IgniteLockingStrategyException( object, e.getMessage(), e ); } }
Source:
protected void buildOpenMergeRequests(final GitLabPushTrigger trigger, final Integer projectId, String projectRef) { try { GitLabConnectionProperty property = project.getProperty(GitLabConnectionProperty.class); if (property != null && property.getClient() != null) { GitlabAPI client = property.getClient(); for (final GitlabMergeRequest mergeRequest : client.getOpenMergeRequests(projectId)) { String sourceBranch = mergeRequest.getSourceBranch(); String targetBranch = mergeRequest.getTargetBranch(); if (projectRef.endsWith(sourceBranch) || (trigger.getTriggerOpenMergeRequestOnPush().equals("both") && projectRef.endsWith(targetBranch))) { if (trigger.getCiSkip() && mergeRequest.getDescription().contains("[ci-skip]")) { LOGGER.log(Level.INFO, "Skipping MR " + mergeRequest.getTitle() + " due to ci-skip."); continue; } final LastCommit lastCommit = createLastCommit(projectId, client.getBranch(createProject(projectId), sourceBranch)); ACL.impersonate(ACL.SYSTEM, new Runnable() { public void run() { trigger.onPost(createMergeRequest(projectId, mergeRequest, lastCommit)); } }); } } } } catch (Exception e) { LOGGER.warning("failed to communicate with gitlab server to determine is this is an update for a merge request: " + e.getMessage()); e.printStackTrace(); } }

Target:
protected void buildOpenMergeRequests(final GitLabPushTrigger trigger, final Integer projectId, String projectRef) { try { GitLabConnectionProperty property = project.getProperty(GitLabConnectionProperty.class); if (property != null && property.getClient() != null) { GitlabAPI client = property.getClient(); for (final GitlabMergeRequest mergeRequest : client.getOpenMergeRequests(projectId)) { String sourceBranch = mergeRequest.getSourceBranch(); String targetBranch = mergeRequest.getTargetBranch(); if (projectRef.endsWith(sourceBranch) || (trigger.getTriggerOpenMergeRequestOnPush().equals("both") && projectRef.endsWith(targetBranch))) { if (trigger.getCiSkip() && mergeRequest.getDescription().contains("[ci-skip]")) { LOGGER.log(Level.INFO, "Skipping MR " + mergeRequest.getTitle() + " due to ci-skip."); continue; } final LastCommit lastCommit = createLastCommit(projectId, client.getBranch(createProject(projectId), sourceBranch)); ACL.impersonate(ACL.SYSTEM, new Runnable() { public void run() { trigger.onPost(createMergeRequest(projectId, mergeRequest, lastCommit)); } }); } } } } catch (Exception e) { LOGGER.warning("Failed to communicate with gitlab server to determine if this is an update for a merge request: " + e.getMessage()); e.printStackTrace(); } }
Source:
private static String encodeParameters(final Map<String, List<String>> params) { List<String> parameters = new ArrayList<>(); for (final Map.Entry<String, List<String>> entry : params.entrySet()) { try { String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); for (final String value : entry.getValue()) { if (value == null) { continue; } String encodedValue; if (value.startsWith("+")) { encodedValue = value; } else { encodedValue = URLEncoder.encode(value, "UTF-8"); } parameters.add(encodedName + "=" + encodedValue); } } catch (final UnsupportedEncodingException e) { throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); } } return joinIgnoreNull("&", parameters); }

Target:
private static String encodeParameters(final Map<String, List<String>> params) { List<String> parameters = new ArrayList<>(); for (final Map.Entry<String, List<String>> entry : params.entrySet()) { try { String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); for (final String value : entry.getValue()) { if (value == null) { continue; } String encodedValue = URLEncoder.encode(value, "UTF-8"); parameters.add(encodedName + "=" + encodedValue); } } catch (final UnsupportedEncodingException e) { throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); } } return joinIgnoreNull("&", parameters); }