auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); feature.setDescription("Ability to delete gluster bricks with data migration using the actions migrate and commit. Action migrate in combination with stop migrates the data and brick can be reused further."); features.getFeature().add(feature); }

Target:
private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); feature.setDescription("Ability to delete gluster bricks with data migration using the actions migrate and DELETE. Action migrate in combination with stopmigrate, migrates the data and brick can be reused further."); features.getFeature().add(feature); }
Source:
public void updateCapabilities(GutenbergPropsBuilder gutenbergPropsBuilder) { if (getActivity() != null) { GutenbergProps gutenbergProps = gutenbergPropsBuilder.build(getActivity(), mHtmlModeEnabled); mWPAndroidGlueCode.updateCapabilities(gutenbergProps); } }

Target:
public void updateCapabilities(GutenbergPropsBuilder gutenbergPropsBuilder) { final Activity activity = getActivity(); if (activity != null) { GutenbergProps gutenbergProps = gutenbergPropsBuilder.build(activity, mHtmlModeEnabled); mWPAndroidGlueCode.updateCapabilities(gutenbergProps); } }
Source:
void init() { ch.closeFuture().addListener(f -> addListenerExecutor.submit(() -> { log.debug("Channel disconnected, removing event sender listener for id: " + Util.printArray(listenerId)); cache.removeListenerAsync(this); unblockCommands(); })); }

Target:
void init() { ch.closeFuture().addListener(f -> { log.debug("Channel disconnected, removing event sender listener for id: " + Util.printArray(listenerId)); cache.removeListenerAsync(this) .whenComplete((ignore, t) -> unblockCommands()); }); }
Source:
private <K extends Exception> void handleExceptionInternal( RetryableCassandraRequest<?, K> req, InetSocketAddress host, Exception ex) throws K { if (isRetriableException(ex) || isRetriableWithBackoffException(ex) || isFastFailoverException(ex)) { if (req.getNumberOfAttempts() >= maxTriesTotal.get()) { if (ex instanceof TTransportException && ex.getCause() != null && (ex.getCause().getClass() == SocketException.class)) { log.error(CONNECTION_FAILURE_MSG, req.getNumberOfAttempts(), ex); String errorMsg = MessageFormatter.format(CONNECTION_FAILURE_MSG, req.getNumberOfAttempts()).getMessage(); throw (K) new TTransportException(((TTransportException) ex).getType(), errorMsg, ex); } else { log.error("Tried to connect to cassandra times.", SafeArg.of("numTries", req.getNumberOfAttempts()), ex); throw (K) ex; } } else { if (req.getNumberOfAttempts() > 1) { log.warn("Error occurred talking to cassandra. Attempt of {}. Exception message was: : {}", SafeArg.of("numTries", req.getNumberOfAttempts()), SafeArg.of("maxTotalTries", maxTriesTotal), SafeArg.of("exceptionClass", ex.getClass().getTypeName()), UnsafeArg.of("exceptionMessage", ex.getMessage())); } else { log.warn("Error occurred talking to cassandra. Attempt of {}.", SafeArg.of("numTries", req.getNumberOfAttempts()), SafeArg.of("maxTotalTries", maxTriesTotal), ex); } if (isConnectionException(ex) && req.getNumberOfAttempts() >= maxTriesSameHost.get()) { blacklist.add(host); } } } else { throw (K) ex; } }

Target:
private <K extends Exception> void handleExceptionInternal( RetryableCassandraRequest<?, K> req, InetSocketAddress host, Exception ex) throws K { if (isRetriableException(ex) || isRetriableWithBackoffException(ex) || isFastFailoverException(ex)) { if (req.getNumberOfAttempts() >= maxTriesTotal.get()) { if (ex instanceof TTransportException && ex.getCause() != null && (ex.getCause().getClass() == SocketException.class)) { log.error(CONNECTION_FAILURE_MSG, req.getNumberOfAttempts(), ex); String errorMsg = MessageFormatter.format(CONNECTION_FAILURE_MSG, req.getNumberOfAttempts()).getMessage(); throw (K) new TTransportException(((TTransportException) ex).getType(), errorMsg, ex); } else { log.error("Tried to connect to cassandra times.", SafeArg.of("numTries", req.getNumberOfAttempts()), ex); throw (K) ex; } } else { if (req.getNumberOfAttempts() > 1) { log.info("Error occurred talking to cassandra. Attempt of {}. Exception message was: : {}", SafeArg.of("numTries", req.getNumberOfAttempts()), SafeArg.of("maxTotalTries", maxTriesTotal), SafeArg.of("exceptionClass", ex.getClass().getTypeName()), UnsafeArg.of("exceptionMessage", ex.getMessage())); } else { log.info("Error occurred talking to cassandra. Attempt of {}.", SafeArg.of("numTries", req.getNumberOfAttempts()), SafeArg.of("maxTotalTries", maxTriesTotal), ex); } if (isConnectionException(ex) && req.getNumberOfAttempts() >= maxTriesSameHost.get()) { blacklist.add(host); } } } else { throw (K) ex; } }
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.channel == null) ? 0 : this.channel.hashCode()); result = prime * result + ((this.supplier == null) ? 0 : this.supplier.hashCode()); return result; }

Target:
public int hashCode() { return super.hashCode() + Objects.hash(this.supplier, this.channel); }
Source:
public void setUpload(String upload) { if (upload != null && (upload.length() == 0 || "false".equals(upload))) upload = null; if (!Objects.equals(upload, _auxinf != null ? _auxinf.upload : null)) { initAuxInfo().upload = upload; if (upload != null) { Matcher matcher = Pattern.compile("maxsize=([^,]+)").matcher(upload); if (matcher.find()) { try { Integer maxsz = Integer.parseInt(matcher.group(1)); setAttribute(org.zkoss.zk.ui.impl.Attributes.UPLOAD_MAX_SIZE, maxsz); } catch (NumberFormatException e) { throw new UiException("The upload max size should be a positive integer."); } } if (Pattern.compile("(?:^|,)\\s*native\\s*(?:$|,)").matcher(upload).find()) { setAttribute(org.zkoss.zk.ui.impl.Attributes.UPLOAD_NATIVE, true); } else { removeAttribute(org.zkoss.zk.ui.impl.Attributes.UPLOAD_NATIVE); } } smartUpdate("upload", getRealUpload()); } }

Target:
public void setUpload(String upload) { if (upload != null && (upload.length() == 0 || "false".equals(upload))) upload = null; if (!Objects.equals(upload, _auxinf != null ? _auxinf.upload : null)) { initAuxInfo().upload = upload; Uploads.parseUpload(this, upload); smartUpdate("upload", Uploads.getRealUpload(this, getUpload())); } }
Source:
public void start() { _daemonThreadExecutorService.scheduleAtFixedRate(() -> { try { if (!_runningTasks.isEmpty()) { _logger.info("Checking status of running kafka connector tasks."); synchronized (_runningTasks) { _runningTasks.keySet().forEach(this::restartIfNotRunning); } } else { _logger.warn("connector received no datastreams tasks yet."); } } catch (Exception e) { _logger.warn("Failed to check status of kafka connector tasks.", e); } }, _config.getDaemonThreadIntervalSeconds(), _config.getDaemonThreadIntervalSeconds(), TimeUnit.SECONDS); }

Target:
public void start() { _daemonThreadExecutorService.scheduleAtFixedRate(() -> { try { if (!_runningTasks.isEmpty()) { _logger.info("Checking status of running kafka connector tasks."); _runningTasks.keySet().forEach(this::restartIfNotRunning); } else { _logger.warn("connector received no datastreams tasks yet."); } } catch (Exception e) { _logger.warn("Failed to check status of kafka connector tasks.", e); } }, _config.getDaemonThreadIntervalSeconds(), _config.getDaemonThreadIntervalSeconds(), TimeUnit.SECONDS); }
Source:
private void purgeOldPackageBits(){ ContentManagerLocal cm = LookupUtil.getContentManager(); cm.removeHistoryDeploymentsBits(); }

Target:
private void purgeOldPackageBits(){ long timeStart = System.currentTimeMillis(); LOG.info("Package bits purge starting at " + new Date(timeStart)); contentManager.removeHistoryDeploymentsBits(); long duration = System.currentTimeMillis() - timeStart; LOG.info("Purged old package bits completed in [" + duration + "]ms"); }
Source:
public void add(final Byte value, final int inc) { MutableInt counter = countMap.get(value & 0xFF); if (counter == null) { counter = new MutableInt(); countMap.put(value & 0xFF, counter); } counter.value += inc; }

Target:
public void add(final Byte value, final int inc) { add(value& 0xFF, inc); }
Source:
private IStatus validateTool(final EObject eObj, final IValidationContext ctx, final IStatus statusInput) { final ToolSwitchValidator toolSwitchValidator = new ToolSwitchValidator(ctx, statusInput); final IStatus status = toolSwitchValidator.doSwitch(eObj); return status; }

Target:
private IStatus validateTool(final EObject eObj, final IValidationContext ctx, final IStatus statusInput) { final ToolSwitchValidator toolSwitchValidator = new ToolSwitchValidator(ctx, statusInput); final IStatus statusCoreTool = toolSwitchValidator.doSwitch(eObj); final DiagramToolSwitchValidator diagramToolSwitchValidator = new DiagramToolSwitchValidator(ctx, statusInput); final IStatus statusDiagramTool = diagramToolSwitchValidator.doSwitch(eObj); MultiStatus status = null; if (statusCoreTool != null || statusDiagramTool != null) { if (statusCoreTool != null) { status = new MultiStatus(statusCoreTool.getPlugin(), statusCoreTool.getCode(), null, null); status.add(statusCoreTool); } if (statusDiagramTool != null) { if (status == null) { status = new MultiStatus(statusDiagramTool.getPlugin(), statusDiagramTool.getCode(), null, null); } status.add(statusDiagramTool); } } return status; }
Source:
private void restoreSavedLayout() { for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); maximizedWindow_.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); ArrayList<Double> leftStart = new ArrayList<>(); ArrayList<Double> leftEnd = new ArrayList<>(); if (leftList_.size() > 0) { for (int i = 0; i < leftList_.size(); i++) leftStart.add(0.0); if (leftWidgetSizePriorToZoom_.size() != leftList_.size()) leftEnd = getValidColumnWidths(leftList_, leftWidgetSizePriorToZoom_, false); else { for (Double size : leftWidgetSizePriorToZoom_) leftEnd.add(size); } } resizeHorizontally(panel_.getWidgetSize(right_), widgetSizePriorToZoom_, leftStart, leftEnd); invalidateSavedLayoutState(true); }

Target:
private void restoreSavedLayout() { for (LogicalWindow window : panes_) window.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); maximizedWindow_.onWindowStateChange(new WindowStateChangeEvent(WindowState.NORMAL, true)); ArrayList<Double> leftStart = new ArrayList<>(); ArrayList<Double> leftEnd = new ArrayList<>(); if (leftList_.size() > 0) { for (int i = 0; i < leftList_.size(); i++) leftStart.add(0.0); if (leftWidgetSizePriorToZoom_.size() != leftList_.size()) leftEnd = getValidColumnWidths(leftList_, leftWidgetSizePriorToZoom_, false); else leftEnd.addAll(leftWidgetSizePriorToZoom_); } resizeHorizontally(panel_.getWidgetSize(right_), widgetSizePriorToZoom_, leftStart, leftEnd); invalidateSavedLayoutState(true); }
Source:
public void close() throws IOException { if (!closed.get()) { flush(); closed.set(true); } }

Target:
public void close() throws IOException { WriteLock lock = mutationLock.writeLock(); lock.lock(); try { if (!closed) { doFlush(); closed = true; } } finally { lock.unlock(); } }
Source:
CircuitBreakerFuture(CircuitBreaker circuitBreaker, Future<T> future) { this(circuitBreaker, future, Clock.systemUTC()); }

Target:
CircuitBreakerFuture(CircuitBreaker circuitBreaker, Future<T> future) { this(circuitBreaker, future, circuitBreaker.getCurrentTimestamp()); }
Source:
public synchronized void start() { checkValidLoadBalancingSettings(); random = ThreadLocalRandom.current(); if (httpClient != null) { log.warn("Service already started"); return; } httpClient = new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()) .establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS) .socketTimeout(socketTimeout, TimeUnit.MILLISECONDS).connectionPoolSize(maxConnections) .maxPooledPerRoute(maxConnectionsPerHost).hostnameVerification(HostnameVerificationPolicy.ANY).build(); if (username != null) { BasicAuthentication auth = new BasicAuthentication(username, password); httpClient.register(auth); } }

Target:
public synchronized void start() { if (httpClient != null) { log.warn("Service already started"); return; } httpClient = new ResteasyClientBuilder().httpEngine(new URLConnectionEngine()) .establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS) .socketTimeout(socketTimeout, TimeUnit.MILLISECONDS).connectionPoolSize(maxConnections) .maxPooledPerRoute(maxConnectionsPerHost).hostnameVerification(HostnameVerificationPolicy.ANY).build(); if (username != null) { BasicAuthentication auth = new BasicAuthentication(username, password); httpClient.register(auth); } }
Source:
public static int scoreAddr(NetworkInterface iface, InetAddress addr) { int score = 0; if (addr instanceof Inet4Address) { score += 300; } try { if (!iface.isLoopback() && !addr.isLoopbackAddress()) { score += 100; if (iface.isUp()) { score += 100; } } } catch (SocketException e) { ; } return score; }

Target:
public static int scoreAddr(NetworkInterface iface, InetAddress addr) { int score = 0; if (addr instanceof Inet4Address) { score += 300; } try { if (!iface.isLoopback() && !addr.isLoopbackAddress()) { score += 100; if (iface.isUp()) { score += 100; } } } catch (SocketException e) { logger.error("Unable to score IP of interface {}", addr, iface, e); } return score; }
Source:
private List<String> getExcludedAttrs() { List<String> attrs = new ArrayList<>(); return attrs; }

Target:
private List<String> getExcludedAttrs() { return new ArrayList<>(); }
Source:
public String read(int fileId) { try { InputStream in = context.getResources().openRawResource(fileId); return getFileContent(in); } catch (Exception e) { e.printStackTrace(); return ""; } }

Target:
public String read(int fileId) { try { InputStream in = context.getResources().openRawResource(fileId); return getFileContent(in); } catch (Exception e) { return ""; } }
Source:
public List<Deployment> listDeployments(String namespace) { DeploymentList list = kubernetesClient.extensions().deployments().inNamespace(namespace) .withLabel(WSO2_DEPLOYMENT_LABEL).list(); if (list == null || list.getItems() == null || list.getItems().isEmpty()) { return new ArrayList<>(); } return list.getItems().stream() .map(deployment -> { Map<String, String> labels = deployment.getSpec().getTemplate().getMetadata().getLabels(); return new Deployment( deployment.getMetadata().getUid(), labels.get(PRODUCT), labels.get(VERSION), Integer.parseInt(labels.get(PATTERN))); }) .collect(Collectors.toList()); }

Target:
public List<Deployment> listDeployments(String namespace) { DeploymentList list = kubernetesClient.extensions().deployments().inNamespace(namespace) .withLabel(WSO2_DEPLOYMENT_LABEL).list(); if (list == null || list.getItems() == null || list.getItems().isEmpty()) { return Collections.emptyList(); } return list.getItems().stream() .map(deployment -> { Map<String, String> labels = deployment.getSpec().getTemplate().getMetadata().getLabels(); return new Deployment( deployment.getMetadata().getUid(), labels.get(PRODUCT), labels.get(VERSION), Integer.parseInt(labels.get(PATTERN))); }) .collect(Collectors.toList()); }
Source:
private void reportTripleCount(AtomicLong tripleCount, boolean force, Consumer<String> statusUpdate) { final long curCount = tripleCount.incrementAndGet(); if (force || curCount % 100 == 0) { final String message = String.format("Processed %d triples", curCount); statusUpdate.accept(message); LOG.info(message); } }

Target:
private void reportTripleCount(AtomicLong tripleCount, boolean force, Consumer<String> statusUpdate) { final long curCount = tripleCount.incrementAndGet(); if (force || curCount % 100 == 0) { final String message = String.format("Processed %d triples", curCount); statusUpdate.accept(message); LOG.debug(message); } }
Source:
public JobIdData reSubmit(String sessionId, String jobId, PathSegment pathSegment, UriInfo contextInfos) throws JobCreationRestException, NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, IOException { Scheduler scheduler = checkAccess(sessionId, "reSubmit"); File tmpJobFile = File.createTempFile("job", "d"); JobId newJobId; try { final String jobContent = scheduler.getJobContent(JobIdImpl.makeJobId(jobId)); FileUtils.write(tmpJobFile, jobContent, Charset.forName("UTF-8")); } catch (NotConnectedException e) { e.printStackTrace(); } catch (UnknownJobException e) { e.printStackTrace(); } catch (PermissionException e) { e.printStackTrace(); } catch (SubmissionClosedException e) { e.printStackTrace(); } catch (JobCreationException e) { e.printStackTrace(); } Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment); Map<String, String> genericInfos = null; if (contextInfos != null) genericInfos = getMapWithFirstValues(contextInfos.getQueryParameters()); WorkflowSubmitter workflowSubmitter = new WorkflowSubmitter(scheduler); newJobId = workflowSubmitter.submit(tmpJobFile, jobVariables, genericInfos); return mapper.map(newJobId, JobIdData.class); }

Target:
public JobIdData reSubmit(String sessionId, String jobId, PathSegment pathSegment, UriInfo contextInfos) throws JobCreationRestException, NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, IOException, UnknownJobRestException { Scheduler scheduler = checkAccess(sessionId, "reSubmit"); File tmpJobFile = File.createTempFile("job", "d"); JobId newJobId; try { String jobContent = scheduler.getJobContent(JobIdImpl.makeJobId(jobId)); FileUtils.write(tmpJobFile, jobContent, Charset.forName("UTF-8")); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (UnknownJobException e) { throw new UnknownJobRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment); Map<String, String> genericInfos = null; if (contextInfos != null) { genericInfos = getMapWithFirstValues(contextInfos.getQueryParameters()); } WorkflowSubmitter workflowSubmitter = new WorkflowSubmitter(scheduler); newJobId = workflowSubmitter.submit(tmpJobFile, jobVariables, genericInfos); return mapper.map(newJobId, JobIdData.class); }
Source:
public void updateSelectedCertificateKS() { LOG.info("updateSelectedCertificate"); if (selectedTSCertificate != null) { String alias = selectedTSCertificate.getAlias(); if (StringUtils.isNotBlank(alias) && !service.isAliasInUse(alias, service.fetchKeyStores())) { try { boolean updateStatus = service.updateCertificateKS(oldAlias, selectedTSCertificate); postUpdateAction(updateStatus, VIEW_CERT_ERROR_MSG_KS); } catch (CertificateManagerException ex) { LOG.error("Unable to update certificate {}", ex.getLocalizedMessage(), ex); HelperUtil.addMessageError(VIEW_CERT_ERROR_MSG_KS, ex.getLocalizedMessage()); } } else { selectedTSCertificate.setAlias(oldAlias); HelperUtil.addMessageError(VIEW_CERT_ERROR_MSG_KS, "Alias already in use"); } } }

Target:
public void updateSelectedCertificateKS() { if (selectedTSCertificate != null) { updateCertificate(service.fetchKeyStores(), VIEW_CERT_ERROR_MSG_KS, RefreshAction.KEYSTORE); } }
Source:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes fs = logic.getFeedbackSession(feedbackSessionName, courseId); if (fs == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session is not found")); } Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case INSTRUCTOR_RESULT: if (userInfo == null) { throw new UnauthorizedAccessException("Instructor account is required to access this resource"); } else { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, fs); } break; case STUDENT_RESULT: StudentAttributes student = getStudent(courseId); gateKeeper.verifyAccessible(student, fs); if (!fs.isPublished()) { throw new UnauthorizedAccessException("This feedback session is not yet published."); } break; case INSTRUCTOR_SUBMISSION: case STUDENT_SUBMISSION: throw new InvalidHttpParameterException("Invalid intent for this action"); default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }

Target:
public void checkSpecificAccessControl() { if (userInfo != null && userInfo.isAdmin) { return; } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes fs = logic.getFeedbackSession(feedbackSessionName, courseId); if (fs == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session is not found")); } Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case INSTRUCTOR_RESULT: if (userInfo == null) { throw new UnauthorizedAccessException("Instructor account is required to access this resource"); } else { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, fs); } break; case STUDENT_RESULT: if (userInfo == null && StringHelper.isEmpty(getRequestParamValue(Const.ParamsNames.REGKEY))) { throw new UnauthorizedAccessException("Student account is required to access this resource."); } StudentAttributes student = getStudent(courseId); gateKeeper.verifyAccessible(student, fs); if (!fs.isPublished()) { throw new UnauthorizedAccessException("This feedback session is not yet published."); } break; case INSTRUCTOR_SUBMISSION: case STUDENT_SUBMISSION: throw new InvalidHttpParameterException("Invalid intent for this action"); default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }
Source:
public void testTimeTravelWorks() throws Exception { String tbl = GenerateTableName(); watcher.executeUpdate("CREATE TABLE " + tbl + "(a INT)"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 1"); long txId = GetTxId(); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 2"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 3"); ResultSet rs = watcher.executeQuery("SELECT * FROM " + tbl + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(2, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(3, rs.getInt(1)); Assert.assertFalse(rs.next()); rs = watcher.executeQuery("SELECT * FROM " + tbl + " AS OF " + txId + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertFalse(rs.next()); }

Target:
public void testTimeTravelWorks() throws Exception { String tbl = generateTableName(); watcher.executeUpdate("CREATE TABLE " + tbl + "(a INT)"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 1"); long txId = getTxId(); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 2"); watcher.executeUpdate("INSERT INTO " + tbl + " VALUES 3"); ResultSet rs = watcher.executeQuery("SELECT * FROM " + tbl + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(2, rs.getInt(1)); Assert.assertTrue(rs.next()); Assert.assertEquals(3, rs.getInt(1)); Assert.assertFalse(rs.next()); rs = watcher.executeQuery("SELECT * FROM " + tbl + " AS OF " + txId + " ORDER BY a ASC"); Assert.assertTrue(rs.next()); Assert.assertEquals(1, rs.getInt(1)); Assert.assertFalse(rs.next()); }
Source:
private void setOATag(SAMRecord rec) { if (rec.getReferenceName().contains(",")) { throw new PicardException(String.format("Reference name for record %s contains a comma character.", rec.getReadName())); } final String OAValue; if (rec.getReadUnmappedFlag()) { OAValue = String.format("*,0,%s,*,255,;", rec.getReadNegativeStrandFlag() ? "-" : "+"); } else { OAValue = String.format("%s,%s,%s,%s,%s,%s;", (rec.getReferenceName()), (rec.getAlignmentStart()), ((rec.getReadNegativeStrandFlag() ? "-" : "+")), (rec.getCigarString()), (rec.getMappingQuality()), (Optional.ofNullable(rec.getAttribute(SAMTag.NM.name())).orElse("").toString())); } rec.setAttribute(OA,Optional.ofNullable(rec.getAttribute(OA)).orElse("") + OAValue); }

Target:
private void setOATag(SAMRecord rec) { if (rec.getReferenceName().contains(",")) { throw new PicardException(String.format("Reference name for record %s contains a comma character.", rec.getReadName())); } final String oaValue; if (rec.getReadUnmappedFlag()) { oaValue = String.format("*,0,%s,*,255,;", rec.getReadNegativeStrandFlag() ? "-" : "+"); } else { oaValue = String.format("%s,%s,%s,%s,%s,%s;", rec.getReferenceName(), rec.getAlignmentStart(), rec.getReadNegativeStrandFlag() ? "-" : "+", rec.getCigarString(), rec.getMappingQuality(), Optional.ofNullable(rec.getAttribute(SAMTag.NM.name())).orElse("")); } rec.setAttribute(OA, Optional.ofNullable(rec.getAttribute(OA)).orElse("") + oaValue); }
Source:
private static ImmutableList<String> filterMetricNames( final List<String> metricNames, final Optional<String> containing, final boolean filterRollups) { final Predicate<String> baseFilter; if (filterRollups) { baseFilter = IS_ROLLUP.negate(); } else { baseFilter = s -> true; } final Predicate<String> containsFilter; if (containing.isPresent() && !containing.get().isEmpty()) { final String lowerContaining = containing.get().toLowerCase(Locale.ENGLISH); containsFilter = s -> s.toLowerCase(Locale.getDefault()).contains(lowerContaining); } else { containsFilter = s -> true; } return metricNames.stream() .filter(baseFilter) .filter(IS_PT1M.negate()) .filter(containsFilter) .collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf)); }

Target:
private static ImmutableList<String> filterMetricNames( final List<String> metricNames, final Optional<String> containing, final boolean filterRollups) { final Predicate<String> baseFilter; if (filterRollups) { baseFilter = IS_ROLLUP.negate(); } else { baseFilter = s -> true; } final Predicate<String> containsFilter; if (containing.isPresent() && !containing.get().isEmpty()) { final String lowerContaining = containing.get().toLowerCase(Locale.getDefault()); containsFilter = s -> s.toLowerCase(Locale.getDefault()).contains(lowerContaining); } else { containsFilter = s -> true; } return metricNames.stream() .filter(baseFilter) .filter(IS_PT1M.negate()) .filter(containsFilter) .collect(ImmutableList.toImmutableList()); }
Source:
private boolean isAnApiRequest(HttpServletRequest httpRequest) { return httpRequest.getRequestURI().contains("/api/"); }

Target:
private boolean isAnApiRequest(HttpServletRequest httpRequest) { return httpRequest.getRequestURI().startsWith("/go/api/"); }
Source:
public void completeCompile(StatementNode qt) throws StandardException { paramTypeDescriptors = qt.getParameterTypes(); if (targetTable != null) { targetTable = null; updateMode = 0; updateColumns = null; targetColumns = null; } resultDesc = qt.makeResultDescription(); if (resultDesc != null) { CursorInfo cursorInfo = (CursorInfo) qt.getCursorInfo(); if (cursorInfo != null) { targetTable = cursorInfo.targetTable; targetColumns = cursorInfo.targetColumns; updateColumns = cursorInfo.updateColumns; updateMode = cursorInfo.updateMode; } } synchronized (this) { isValid = true; } }

Target:
public void completeCompile(StatementNode qt) throws StandardException { paramTypeDescriptors = qt.getParameterTypes(); if (targetTable != null) { targetTable = null; updateMode = 0; updateColumns = null; targetColumns = null; } resultDesc = qt.makeResultDescription(); if (resultDesc != null) { CursorInfo cursorInfo = (CursorInfo) qt.getCursorInfo(); if (cursorInfo != null) { targetTable = cursorInfo.targetTable; targetColumns = cursorInfo.targetColumns; updateColumns = cursorInfo.updateColumns; updateMode = cursorInfo.updateMode; } } setValid(); }
Source:
public Object getObject(String category, String url, String username, String password) throws RestClientException { prepareRestTemplate(username, password); try { return restTemplate.getForObject(url, resolveCategory(category)); } catch(RestClientException e) { log.error(String.format("Exception occurred when getting object. Category: %s, url: %s", category, url), e); throw e; } }

Target:
public Object getObject(String category, String url, String username, String password) throws RestClientException { prepareRestTemplate(username, password); return restTemplate.getForObject(url, resolveCategory(category)); }
Source:
public boolean canHideLabel() { boolean canHideLabel = false; if (!isLabelEmpty()) { if (element instanceof DEdge) { canHideLabel = true; } else if (element instanceof DNode) { if (LabelPosition.BORDER_LITERAL.equals(((DNode) element).getOwnedStyle().getLabelPosition())) { canHideLabel = true; } } else if (element instanceof DNodeContainer) { canHideLabel = true; } else if (element instanceof DNodeList) { canHideLabel = true; } } return canHideLabel; }

Target:
public boolean canHideLabel() { boolean canHideLabel = false; if (!isLabelEmpty()) { if (element instanceof DEdge) { canHideLabel = true; } else if (element instanceof DNode) { if (LabelPosition.BORDER_LITERAL.equals(((DNode) element).getOwnedStyle().getLabelPosition())) { canHideLabel = true; } } else if (element instanceof DDiagramElementContainer) { canHideLabel = true; } } return canHideLabel; }
Source:
public void testBuilder() { Element doc = XmlUtils.getElementInFile(fTestXmlFile.getPath(), TmfXmlStrings.PATTERN, ANALYSIS_ID); NodeList patternSegments = doc.getElementsByTagName(TmfXmlStrings.SEGMENT); assertEquals("Number of pattern segments", 2, patternSegments.getLength()); final Node item2 = patternSegments.item(1); assertNotNull("pattern segment 2", item2); TmfXmlPatternSegmentBuilder builder = new TmfXmlPatternSegmentBuilder(fModelFactory, (Element) item2, fContainer); assertNotNull("builder", builder); final ITmfEvent startEvent = new TmfEvent(null, ITmfContext.UNKNOWN_RANK, new TmfTimestamp(1, ITmfTimestamp.NANOSECOND_SCALE), null, null); final ITmfEvent endEvent = new TmfEvent(null, ITmfContext.UNKNOWN_RANK, new TmfTimestamp(10, ITmfTimestamp.NANOSECOND_SCALE), null, null); TmfXmlPatternSegment segment = builder.generatePatternSegment(endEvent, startEvent.getTimestamp(), endEvent.getTimestamp()); testPatternSegmentData(segment); }

Target:
public void testBuilder() { Element doc = XmlUtils.getElementInFile(fTestXmlFile.getPath(), TmfXmlStrings.PATTERN, ANALYSIS_ID); NodeList patternSegments = doc.getElementsByTagName(TmfXmlStrings.SEGMENT); assertEquals("Number of pattern segments", 2, patternSegments.getLength()); final Node item2 = patternSegments.item(1); assertNotNull("pattern segment 2", item2); TmfXmlPatternSegmentBuilder builder = new TmfXmlPatternSegmentBuilder(fModelFactory, (Element) item2, fContainer); assertNotNull("builder", builder); TmfXmlPatternSegment segment = builder.generatePatternSegment(PatternSegmentFactoryStub.TEST_2_END_EVENT, PatternSegmentFactoryStub.TEST_2_START_EVENT.getTimestamp(), PatternSegmentFactoryStub.TEST_2_END_EVENT.getTimestamp()); XmlUtilsTest.testPatternSegmentData(PatternSegmentFactoryStub.TEST_2, segment); }
Source:
protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { synchronized (this) { if (calledOnce) { return; } calledOnce = true; } IndexTool.IndexVerifyType verifyType = getIndexVerifyType(context.getConfiguration()); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } }

Target:
protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { if (!calledOnce.compareAndSet(false, true)) { return; } IndexTool.IndexVerifyType verifyType = getIndexVerifyType(context.getConfiguration()); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } }
Source:
public void testEncodeUrlInApiCall() throws Exception { try { Map result = api.subFolders("sub^folder test", null); assertEquals("sub%5Efolder%20test", ((Map) ((org.cloudinary.json.JSONArray) result.get("folders")).get(0)).get("path")); } catch (Exception ignored) { } }

Target:
public void testEncodeUrlInApiCall() throws Exception { String apiTestEncodeUrlInApiCall = "sub^folder test"; createdFolders.add(apiTestEncodeUrlInApiCall); Map result = api.createFolder(apiTestEncodeUrlInApiCall, null); assertEquals("sub^folder test", result.get("path")); }
Source:
private List<AuditEvent> resolveEvent(PerunSessionImpl sess, User user) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { List<AuditEvent> resolvingMessages = new ArrayList<>(); Attribute attribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, A_U_V_LOA); if (attribute.getValue() == null) { resolvingMessages.add(new AttributeRemovedForUser(new AttributeDefinition(attribute),user)); } else { resolvingMessages.add(new AttributeSetForUser(attribute,user)); } return resolvingMessages; }

Target:
private AuditEvent resolveEvent(PerunSessionImpl sess, User user) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { Attribute attribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, A_U_V_LOA); if (attribute.getValue() == null) { return new AttributeRemovedForUser(new AttributeDefinition(attribute),user); } else { return new AttributeSetForUser(attribute,user); } }
Source:
public void testDeprecatedAttributeXPathQuery() throws JaxenException { final StringWriter writer = new StringWriter(); class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) { super(id); } } Logger.getLogger(Attribute.class.getName()).setLevel(Level.WARNING); Logger.getLogger(Attribute.class.getName()).addHandler(new Handler() { @Override public void publish(LogRecord record) { writer.write(record.getMessage()); writer.write('\n'); } @Override public void flush() { writer.flush(); } @Override public void close() throws SecurityException { } }); addChild(new MyRootNode(nextId()), new DummyNodeWithDeprecatedAttribute(2)).findChildNodesWithXPath(" writer.flush(); assertTrue(writer.toString().contains("deprecated")); assertTrue(writer.toString().contains("attribute")); assertTrue(writer.toString().contains("dummyNode/@Size")); }

Target:
public void testDeprecatedAttributeXPathQuery() throws JaxenException { class MyRootNode extends DummyNode implements RootNode { private MyRootNode(int id) { super(id); } } addChild(new MyRootNode(nextId()), new DummyNodeWithDeprecatedAttribute(2)).findChildNodesWithXPath(" String log = loggingRule.getLog(); assertTrue(log.contains("deprecated")); assertTrue(log.contains("attribute")); assertTrue(log.contains("dummyNode/@Size")); }
Source:
public void setUp() throws Exception { amazonEC2Client = EasyMock.createMock(AmazonEC2Client.class); mockAmazonEC2Client = new EC2MockClient(); describeInstancesResult = EasyMock.createMock(DescribeInstancesResult.class); reservation = EasyMock.createMock(Reservation.class); instance = new Instance() .withInstanceId(INSTANCE_ID) .withLaunchTime(new Date()) .withImageId(AMI_ID) .withPrivateIpAddress(IP); managementConfig = new SimpleResourceManagementConfig().setWorkerPort(8080).setWorkerVersion(""); }

Target:
public void setUp() throws Exception { amazonEC2Client = EasyMock.createMock(AmazonEC2Client.class); describeInstancesResult = EasyMock.createMock(DescribeInstancesResult.class); reservation = EasyMock.createMock(Reservation.class); instance = new Instance() .withInstanceId(INSTANCE_ID) .withLaunchTime(new Date()) .withImageId(AMI_ID) .withPrivateIpAddress(IP); managementConfig = new SimpleResourceManagementConfig().setWorkerPort(8080).setWorkerVersion(""); }
Source:
public void testCloneRepositoryWhenDestinationDirectoryExistsAndIsNotEmpty() { try { String dirName = "testCloneTargetDirectoryNotEmpty"; File directory = createTempDirectory(dirName); CloneCommand command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); Git git2 = command.call(); assertNotNull(git2); command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); try { git2 = command.call(); fail("destination directory already exists and is not an empty folder, cloning should fail"); } catch (JGitInternalException e) { assertTrue(e.getMessage().contains("not an empty directory")); assertTrue(e.getMessage().contains(dirName)); } } catch (Exception e) { fail(e.getMessage()); } }

Target:
public void testCloneRepositoryWhenDestinationDirectoryExistsAndIsNotEmpty() throws IOException { String dirName = "testCloneTargetDirectoryNotEmpty"; File directory = createTempDirectory(dirName); CloneCommand command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); Git git2 = command.call(); assertNotNull(git2); command = Git.cloneRepository(); command.setDirectory(directory); command.setURI("file://" + git.getRepository().getWorkTree().getPath()); try { git2 = command.call(); fail("destination directory already exists and is not an empty folder, cloning should fail"); } catch (JGitInternalException e) { assertTrue(e.getMessage().contains("not an empty directory")); assertTrue(e.getMessage().contains(dirName)); } }
Source:
void accept(ExpressionWriter writer, int lprec, int rprec) { if (writer.requireParentheses(this, lprec, rprec)) { return; } if (nodeType == ExpressionType.Equal || nodeType == ExpressionType.NotEqual) { Primitive boxPrimitive0 = Primitive.ofBox(expression0.getType()); Primitive boxPrimitive1 = Primitive.ofBox(expression1.getType()); if (boxPrimitive0 != null && boxPrimitive1 != null && !isConstantNullExpression(expression0) && !isConstantNullExpression(expression1)) { if (nodeType == ExpressionType.NotEqual) { writer.append("!"); } writer.append("java.util.Objects.equals("); expression0.accept(writer, lprec, nodeType.lprec); writer.append(", "); expression1.accept(writer, nodeType.rprec, rprec); writer.append(")"); return; } } expression0.accept(writer, lprec, nodeType.lprec); writer.append(nodeType.op); expression1.accept(writer, nodeType.rprec, rprec); }

Target:
void accept(ExpressionWriter writer, int lprec, int rprec) { if (writer.requireParentheses(this, lprec, rprec)) { return; } expression0.accept(writer, lprec, nodeType.lprec); writer.append(nodeType.op); expression1.accept(writer, nodeType.rprec, rprec); }
Source:
public Observable<Product> getProduct(final Long productId) { if (productId == null) { throw new NullPointerException("productId cannot be null"); } final Observable<Product> apiRequest = retrofitService .getProducts(appId, String.valueOf(productId)) .retryWhen(networkRetryPolicyProvider.provide()) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<ProductListings, List<Product>>()) .compose(new FirstListItemOrDefaultTransformer<Product>()) .onErrorResumeNext(new BuyClientExceptionHandler<Product>()); return ApiRequestInterceptWrapper.wrap( apiRequest, new ApiRequestInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>(requestInterceptor) { @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } }, new ApiRequestInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>(responseInterceptor) { @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } } ).observeOn(callbackScheduler); }

Target:
public Observable<Product> getProduct(final Long productId) { if (productId == null) { throw new NullPointerException("productId cannot be null"); } final Observable<Product> apiRequest = retrofitService .getProducts(appId, String.valueOf(productId)) .retryWhen(networkRetryPolicyProvider.provide()) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<ProductListings, List<Product>>()) .compose(new FirstListItemOrDefaultTransformer<Product>()) .onErrorResumeNext(new BuyClientExceptionHandler<Product>()); return ApiInterceptWrapper.wrap( apiRequest, requestInterceptor, responseInterceptor, new ApiInterceptWrapper.InterceptorCall<ProductApiInterceptor, Product>() { @Override public Observable<Product> call(ProductApiInterceptor interceptor, Observable<Product> originalObservable) { return interceptor.getProduct(productId, originalObservable); } } ).observeOn(callbackScheduler); }
Source:
public static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }

Target:
private static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }
Source:
public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = getStyles(); if (styles == null || styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { @NonNull Map<@NonNull String, @NonNull Object> elementStyle = styleEntry.getValue().getStyleValues(); Object color = elementStyle.get(OutputElementStyleProperties.BACKGROUND_COLOR); RGB rgb = new RGB(0, 0, 0); if (color instanceof String) { RGB rgbColor = RGBAUtil.fromHexColor((String) color); rgb = rgbColor != null ? rgbColor : new RGB(0, 0, 0); } fLabelToIndex.put(styleEntry.getKey(), tableIndex); tableIndex++; Map<String, Object> styleMap = new HashMap<>(); styleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); styleMap.put(ITimeEventStyleStrings.fillColor(), new RGBAColor(rgb.red, rgb.green, rgb.blue).toInt()); styleMap.put(ITimeEventStyleStrings.label(), styleEntry.getKey()); styleMap.put(ITimeEventStyleStrings.group(), elementStyle.get(OutputElementStyleProperties.STYLE_GROUP)); stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }

Target:
public StateItem[] getStateTable() { if (fStateTable == null) { Map<@NonNull String, @NonNull OutputElementStyle> styles = getStyles(); if (styles == null || styles.isEmpty()) { return new StateItem[0]; } List<StateItem> stateItemList = new ArrayList<>(); int tableIndex = 0; for (Entry<@NonNull String, @NonNull OutputElementStyle> styleEntry : fStylesMap.entrySet()) { @NonNull Map<@NonNull String, @NonNull Object> elementStyle = styleEntry.getValue().getStyleValues(); Object color = elementStyle.get(OutputElementStyleProperties.BACKGROUND_COLOR); RGB rgb = new RGB(0, 0, 0); if (color instanceof String) { RGB rgbColor = ColorUtils.fromHexColor((String) color); rgb = rgbColor != null ? rgbColor : new RGB(0, 0, 0); } fLabelToIndex.put(styleEntry.getKey(), tableIndex); tableIndex++; Map<String, Object> styleMap = new HashMap<>(); styleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); styleMap.put(ITimeEventStyleStrings.fillColor(), new RGBAColor(rgb.red, rgb.green, rgb.blue).toInt()); styleMap.put(ITimeEventStyleStrings.label(), styleEntry.getKey()); Object styleGroup = elementStyle.get(OutputElementStyleProperties.STYLE_GROUP); if (styleGroup != null) { styleMap.put(ITimeEventStyleStrings.group(), styleGroup); } stateItemList.add(new StateItem(styleMap)); } fStateTable = stateItemList.toArray(new StateItem[stateItemList.size()]); return fStateTable; } return fStateTable; }
Source:
public LogEntry getByUniqueId(String uniqueId) { return null; }

Target:
public LogEntry getByUniqueId(String uniqueId) { List<LogEntry> logentries = Context.getService(IdentifierSourceService.class).getLogEntries(null, null, null, uniqueId, null, null); if (logentries.size() != 0) { return logentries.get(0); } else { return null; } }
Source:
private void drawTextEntrySeparator(UiDrawer uiDrawer) { uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(20.333f), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); }

Target:
private void drawTextEntrySeparator(UiDrawer uiDrawer) { uiDrawer.drawLine(TOP_LEFT.x + 2 * FRAME_WIDTH, getLineY(INPUT_LINE_SEPARATOR_Y), 0, (BOTTOM_RIGHT.x - TOP_LEFT.x) - 4 * FRAME_WIDTH, Color.WHITE); }
Source:
public final T load(GeoServer gs, Resource directory) throws Exception { Resource file; if ( Resources.exists(file = directory.get(getFilename()))) { BufferedInputStream in = new BufferedInputStream( file.in() ); try { XStreamPersister xp = xpf.createXMLPersister(); initXStreamPersister(xp, gs); return initialize( xp.load( in, getServiceClass() ) ); } finally { in.close(); } } else { ServiceInfo service = createServiceFromScratch( gs ); return initialize( (T) service ); } }

Target:
public final T load(GeoServer gs, Resource directory) throws Exception { Resource file; if ( Resources.exists(file = directory.get(getFilename()))) { try (BufferedInputStream in = new BufferedInputStream(file.in())) { XStreamPersister xp = xpf.createXMLPersister(); initXStreamPersister(xp, gs); return initialize( xp.load( in, getServiceClass() ) ); } } else { ServiceInfo service = createServiceFromScratch( gs ); return initialize( (T) service ); } }
Source:
public void store_command_with_error_and_generate_ID_if_needed() { final Command command = Commands.create(org.spine3.server.storage.Given.CommandMessage.createProject(), CommandContext.getDefaultInstance()); final Error error = newError(); storage.store(command, error); final List<CommandStorageRecord> records = Lists.newArrayList(storage.read(ERROR)); assertEquals(1, records.size()); assertFalse(records.get(0) .getCommandId() .trim() .isEmpty()); }

Target:
public void store_command_with_error_and_generate_ID_if_needed() { final Command command = Commands.create(Given.CommandMessage.createProject(), CommandContext.getDefaultInstance()); final Error error = newError(); storage.store(command, error); final List<CommandStorageRecord> records = Lists.newArrayList(storage.read(ERROR)); assertEquals(1, records.size()); assertFalse(records.get(0) .getCommandId() .trim() .isEmpty()); }
Source:
public Page getNextPage() { try { Page page = recordReader.getNextPage(); if (page == null) { close(); } return page; } catch (PrestoException | InvalidFunctionArgumentException e) { closeWithSuppression(e); throw e; } catch (OrcCorruptionException e) { closeWithSuppression(e); throw new PrestoException(HIVE_BAD_DATA, e); } catch (IOException | RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, format("Failed to read ORC file: %s", orcDataSource.getId()), e); } }

Target:
public Page getNextPage() { try { Page page = recordReader.getNextPage(); if (page == null) { close(); } return page; } catch (InvalidFunctionArgumentException e) { closeWithSuppression(e); throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e.getMessage(), e); } catch (PrestoException e) { closeWithSuppression(e); throw e; } catch (OrcCorruptionException e) { closeWithSuppression(e); throw new PrestoException(HIVE_BAD_DATA, e); } catch (IOException | RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, format("Failed to read ORC file: %s", orcDataSource.getId()), e); } }