auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ChangelogCommand changelog() { return new ChangelogCommand() { public static final String RAW = "commit %H%ntree %T%nparent %P%nauthor %aN <%aE> %ai%ncommitter %cN <%cE> %ci%n%n%w(0,4,4)%B%n%n"; private final List<String> revs = new ArrayList<>(); private Integer n = null; private Writer out = null; @Override public ChangelogCommand excludes(String rev) { revs.add(sanitize('^'+rev)); return this; } @Override public ChangelogCommand excludes(ObjectId rev) { return excludes(rev.name()); } @Override public ChangelogCommand includes(String rev) { revs.add(rev); return this; } @Override public ChangelogCommand includes(ObjectId rev) { return includes(rev.name()); } @Override public ChangelogCommand to(Writer w) { this.out = w; return this; } @Override public ChangelogCommand max(int n) { this.n = n; return this; } @Override public void abort() { } @Override public void execute() throws GitException, InterruptedException { ArgumentListBuilder args = new ArgumentListBuilder(gitExe, "whatchanged", "--no-abbrev", "-M"); args.add("--format="+RAW); if (n!=null) args.add("-n").add(n); for (String rev : this.revs) args.add(rev); if (out==null) throw new IllegalStateException(); try (WriterOutputStream w = new WriterOutputStream(out, Charset.forName("UTF-8"))) { if (launcher.launch().cmds(args).envs(environment).stdout(w).stderr(listener.getLogger()).pwd(workspace).join() != 0) throw new GitException("Error: " + args + " in " + workspace); } catch (IOException e) { throw new GitException("Error: " + args + " in " + workspace, e); } } }; }

Target:
public ChangelogCommand changelog() { return new ChangelogCommand() { public static final String RAW = "commit %H%ntree %T%nparent %P%nauthor %aN <%aE> %ai%ncommitter %cN <%cE> %ci%n%n%w(0,4,4)%B"; private final List<String> revs = new ArrayList<>(); private Integer n = null; private Writer out = null; @Override public ChangelogCommand excludes(String rev) { revs.add(sanitize('^'+rev)); return this; } @Override public ChangelogCommand excludes(ObjectId rev) { return excludes(rev.name()); } @Override public ChangelogCommand includes(String rev) { revs.add(rev); return this; } @Override public ChangelogCommand includes(ObjectId rev) { return includes(rev.name()); } @Override public ChangelogCommand to(Writer w) { this.out = w; return this; } @Override public ChangelogCommand max(int n) { this.n = n; return this; } @Override public void abort() { } @Override public void execute() throws GitException, InterruptedException { ArgumentListBuilder args = new ArgumentListBuilder(gitExe, "whatchanged", "--no-abbrev", "-M"); args.add("--format="+RAW); if (n!=null) args.add("-n").add(n); for (String rev : this.revs) args.add(rev); if (out==null) throw new IllegalStateException(); try (WriterOutputStream w = new WriterOutputStream(out, Charset.forName("UTF-8"))) { if (launcher.launch().cmds(args).envs(environment).stdout(w).stderr(listener.getLogger()).pwd(workspace).join() != 0) throw new GitException("Error: " + args + " in " + workspace); } catch (IOException e) { throw new GitException("Error: " + args + " in " + workspace, e); } } }; }
Source:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } callback.onCompletion(null, exception); frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); }

Target:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }
Source:
void maybeReadPayload(ChannelHandlerContext ctx) { if (pending.readableBytes() < nextFrameSize) { return; } ByteBuf payload = ctx.alloc().buffer(nextFrameSize); pending.readBytes(payload, nextFrameSize); state = ReadState.HEADER; HttpRequest request = HttpRequest.of( THRIFT_HEADERS.toMutable(), new ByteBufHttpData(payload, true)); ServiceRequestContext requestContext = ServiceRequestContextBuilder.of(request) .service(scribeService) .build(); final HttpResponse response; try { response = scribeService.serve(requestContext, request); } catch (Exception e) { logger.warn("Unexpected exception servicing thrift request. " + "This usually indicates a bug in armeria's thrift implementation.", e); exceptionCaught(ctx, e); return; } response.aggregateWithPooledObjects(ctx.executor(), ctx.alloc()).handle((msg, t) -> { if (t != null) { logger.warn("Unexpected exception reading thrift response. " + "This usually indicates a bug in armeria's thrift implementation.", t); exceptionCaught(ctx, t); return null; } HttpData content = msg.content(); final ByteBuf returned = ctx.alloc().buffer(msg.content().length() + 4); returned.writeInt(msg.content().length()); if (content instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) content).content(); try { returned.writeBytes(((ByteBufHolder) content).content()); } finally { buf.release(); } } else { returned.writeBytes(content.array(), content.offset(), content.length()); } ctx.writeAndFlush(returned); return null; }); }

Target:
void maybeReadPayload(ChannelHandlerContext ctx) { if (pending.readableBytes() < nextFrameSize) { return; } ByteBuf payload = ctx.alloc().buffer(nextFrameSize); pending.readBytes(payload, nextFrameSize); pending.discardSomeReadBytes(); state = ReadState.HEADER; HttpRequest request = HttpRequest.of( THRIFT_HEADERS.toMutable(), new ByteBufHttpData(payload, true)); ServiceRequestContextBuilder requestContextBuilder = ServiceRequestContextBuilder.of(request) .service(scribeService) .alloc(ctx.alloc()); if (ctx.executor() instanceof EventLoop) { requestContextBuilder.eventLoop((EventLoop) ctx.executor()); } ServiceRequestContext requestContext = requestContextBuilder.build(); final HttpResponse response; try (SafeCloseable unused = requestContext.push()){ response = scribeService.serve(requestContext, request); } catch (Exception e) { exceptionCaught(ctx, e); return; } int responseIndex = nextResponseIndex++; response.aggregateWithPooledObjects(ctx.executor(), ctx.alloc()).handle((msg, t) -> { if (t != null) { exceptionCaught(ctx, t); return null; } HttpData content = msg.content(); ByteBuf returned = ctx.alloc().buffer(content.length() + 4); returned.writeInt(content.length()); if (content instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) content).content(); try { returned.writeBytes(((ByteBufHolder) content).content()); } finally { buf.release(); } } else { returned.writeBytes(content.array(), content.offset(), content.length()); } if (responseIndex == previouslySentResponseIndex + 1) { ctx.writeAndFlush(returned); previouslySentResponseIndex++; flushResponses(ctx); } else { pendingResponses.put(responseIndex, returned); } return null; }); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(false); if ((req.getHeader("Authorization") != null)) { if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if ((req.getHeader("Authorization") != null)) { HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }
Source:
public final void registerHandlerFor(String subject) { LOGGER.debug("Registering handler for {}", subject); String serviceName = "taskTriggerHandler"; Method method = ReflectionUtils.findMethod(this.getClass(), "handle", MotechEvent.class); Object obj = CollectionUtils.find( registryService.getListeners(subject), withServiceName(serviceName) ); try { if (method != null && obj == null) { EventListener proxy = new MotechListenerEventProxy(serviceName, this, method); registryService.registerListener(proxy, subject); LOGGER.info(String.format("%s listens on subject %s", serviceName, subject)); } } catch (Exception exp) { LOGGER.error( String.format("%s can not listen on subject %s due to:", serviceName, subject), exp ); } }

Target:
public final void registerHandlerFor(String subject) { LOGGER.info("Registering handler for {}", subject); String serviceName = "taskTriggerHandler"; Method method = ReflectionUtils.findMethod(this.getClass(), "handle", MotechEvent.class); Object obj = CollectionUtils.find( registryService.getListeners(subject), withServiceName(serviceName) ); try { if (method != null && obj == null) { EventListener proxy = new MotechListenerEventProxy(serviceName, this, method); registryService.registerListener(proxy, subject); LOGGER.info(String.format("%s listens on subject %s", serviceName, subject)); } } catch (Exception exp) { LOGGER.error( String.format("%s can not listen on subject %s due to:", serviceName, subject), exp ); } }
Source:
public StudentProfile(String fullName, StudentProfileAttributes student, String pictureUrl) { this.pictureUrl = pictureUrl; this.name = fullName; this.shortName = student.shortName; this.gender = Gender.valueOf(student.gender.name()); this.email = student.email; this.institute = student.institute; this.nationality = student.nationality; this.moreInfo = student.moreInfo; }

Target:
public StudentProfile(String fullName, StudentProfileAttributes student, String pictureUrl) { this.pictureUrl = pictureUrl; this.name = fullName; this.shortName = student.shortName; this.gender = student.gender; this.email = student.email; this.institute = student.institute; this.nationality = student.nationality; this.moreInfo = student.moreInfo; }
Source:
public void handleNewSession(final String sessionId) throws Exception { }

Target:
public void handleNewSession(final String sessionId) throws Exception { handleNewSession(); }
Source:
private Entry lookupUser(String username) throws LdapException { for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { EntryCursor responseCursor = connection.search(userDn, "(&(objectclass=user)(" + attrName + "=" + username + "))", SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { return responseCursor.get(); } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } } } return null; }

Target:
private Entry lookupUser(String username) throws LdapException { StringBuilder userQuery = new StringBuilder(); userQuery.append("(&(objectclass=user)(|"); boolean hasCondition = false; for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { userQuery.append('(').append(attrName).append('=').append(username).append(')'); hasCondition = true; } } userQuery.append("))"); if (!hasCondition) { return null; } logger.debug("LDAP user query " + userQuery.toString()); EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { Entry match = responseCursor.get(); logger.debug("LDAP user query result: " + match.getDn()); return match; } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } return null; }
Source:
public Multimap<String, String> getQueryParams() { return queryParams; }

Target:
public Map<String, Collection<String>> getQueryParams() { return queryParams; }
Source:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { final Jenkins j = Jenkins.get(); final JCloudsSlaveDescriptor jcsd = (JCloudsSlaveDescriptor) j.getDescriptor(JCloudsSlave.class); return jcsd.nodePropertyDescriptors(null); }

Target:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { final Jenkins j = Jenkins.get(); final JCloudsSlaveDescriptor jcsd = (JCloudsSlaveDescriptor) j.getDescriptorOrDie(JCloudsSlave.class); return jcsd.nodePropertyDescriptors(null); }
Source:
public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, name, element)); }

Target:
public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, element)); }
Source:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { if (monitor.isCanceled()) { return false; } @Nullable SegmentStoreStatistics totalStats = getTotalStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (totalStats == null) { return false; } @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = getPerTypeStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (perTypeStats == null || perTypeStats.isEmpty()) { return false; } fTotalStats = totalStats; fPerSegmentTypeStats = perTypeStats; return true; }

Target:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { if (monitor.isCanceled()) { return false; } @Nullable SegmentStoreStatistics totalStats = getTotalStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (totalStats == null) { return false; } @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = getPerTypeStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (perTypeStats == null) { return false; } fTotalStats = totalStats; fPerSegmentTypeStats = perTypeStats; return true; }
Source:
public OptionalDouble getValue() { ModelNode result = readAttributeValue(address, attributeName); if (result.isDefined()) { try { return OptionalDouble.of(result.asDouble()); } catch (Exception e) { throw MetricsLogger.LOGGER.unableToConvertAttribute(attributeName, address, e); } } return OptionalDouble.empty(); }

Target:
public OptionalDouble getValue() { ModelNode result = readAttributeValue(address, attributeName); if (result.isDefined()) { try { return OptionalDouble.of(result.asDouble()); } catch (Exception e) { LOGGER.unableToConvertAttribute(attributeName, address, e); } } return OptionalDouble.empty(); }
Source:
public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; final String requestId = "testCreatePurchaseWithTimeout"; Request.setPerThreadRequestData(new RequestData(requestId)); final String pluginName = mockPaymentProviderPlugin.PLUGIN_NAME; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds(10000); SpyLogger spyLogger = withSpyLogger(OperationCallbackBase.class, new Callable<Void>() { @Override public Void call() throws Exception { PaymentApiException thrownException = null; try { final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { thrownException = e; } assertNotNull(thrownException); Throwable operationException = thrownException.getCause(); assertNotNull(operationException); assertTrue(operationException instanceof OperationException); Throwable timeoutException = operationException.getCause(); assertNotNull(timeoutException); assertTrue(timeoutException instanceof TimeoutException); return null; } }); assertTrue(spyLogger.contains("Calling plugin.*" + pluginName + ".*" + requestId, Optional.of(SpyLogger.LOG_LEVEL_INFO))); assertTrue(spyLogger.contains("TimeoutException.*" + pluginName + ".*" + requestId, Optional.of(SpyLogger.LOG_LEVEL_ERROR))); }

Target:
public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; final String pluginName = mockPaymentProviderPlugin.PLUGIN_NAME; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds(1100); SpyLogger spyLogger = withSpyLogger(OperationCallbackBase.class, new Callable<Void>() { @Override public Void call() throws Exception { PaymentApiException thrownException = null; try { final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { thrownException = e; } assertNotNull(thrownException); Throwable operationException = thrownException.getCause(); assertNotNull(operationException); assertTrue(operationException instanceof OperationException); Throwable timeoutException = operationException.getCause(); assertNotNull(timeoutException); assertTrue(timeoutException instanceof TimeoutException); return null; } }); assertTrue(spyLogger.contains("Calling plugin.*" + pluginName, Optional.of(SpyLogger.LOG_LEVEL_DEBUG))); assertTrue(spyLogger.contains("TimeoutException.*" + pluginName, Optional.of(SpyLogger.LOG_LEVEL_WARN))); }
Source:
public void onMessage(Message<Long> message) { long payload = message.getMessageObject(); sleepRandom(random, maxProcessingDelayNanos); if (isStopped(payload)) { totalFoundCounter.addAndGet(count); count = 0; if (!completed) { completed = true; listenersCompleteLatch.countDown(); } topic.removeMessageListener(registrationId); } else { count += message.getMessageObject(); } }

Target:
public void onMessage(Message<Long> message) { sleepRandomNanos(random, maxProcessingDelayNanos); count += message.getMessageObject(); }
Source:
void open(Open token) { Publisher<? extends Close> p; C buf; try { buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); SubscriptionHelper.cancel(upstream); if (errors.addThrowable(ex)) { subscribers.dispose(); synchronized (this) { buffers = null; } done = true; drain(); } else { RxJavaPlugins.onError(ex); } return; } long idx = index; index = idx + 1; synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } bufs.put(idx, buf); } BufferCloseSubscriber<T, C> bc = new BufferCloseSubscriber<T, C>(this, idx); subscribers.add(bc); p.subscribe(bc); }

Target:
void open(Open token) { Publisher<? extends Close> p; C buf; try { buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); SubscriptionHelper.cancel(upstream); onError(ex); return; } long idx = index; index = idx + 1; synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } bufs.put(idx, buf); } BufferCloseSubscriber<T, C> bc = new BufferCloseSubscriber<T, C>(this, idx); subscribers.add(bc); p.subscribe(bc); }
Source:
public double impliedVolatilityFromPresentValue( SwaptionProduct swaption, RatesProvider ratesProvider, DayCount dayCount, double presentValue) { ExpandedSwaption expanded = swaption.expand(); double sign = expanded.getLongShort().sign(); ArgChecker.isTrue(presentValue * sign > 0, "Present value sign must be in ligne with the option Long/Short flag "); validateSwaption(ratesProvider, expanded); LocalDate valuationDate = ratesProvider.getValuationDate(); LocalDate expiryDate = expanded.getExpiryDate(); ArgChecker.isTrue(expiryDate.isAfter(valuationDate), "Expiry must be after valuation date to compute an implied volatility"); double expiry = dayCount.yearFraction(valuationDate, expiryDate); ExpandedSwap underlying = expanded.getUnderlying(); ExpandedSwapLeg fixedLeg = fixedLeg(underlying); double forward = swapPricer.parRate(underlying, ratesProvider); double pvbp = swapPricer.getLegPricer().pvbp(fixedLeg, ratesProvider); double strike = swapPricer.getLegPricer().couponEquivalent(fixedLeg, ratesProvider, pvbp); NormalFunctionData normalData = NormalFunctionData.of(forward, Math.abs(pvbp), 0.01); boolean isCall = fixedLeg.getPayReceive().isPay(); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, expiry, isCall ? PutCall.CALL : PutCall.PUT); return FORMULA_IMPLIED.impliedVolatility(normalData, option, Math.abs(presentValue)); }

Target:
public double impliedVolatilityFromPresentValue( SwaptionProduct swaption, RatesProvider ratesProvider, DayCount dayCount, double presentValue) { ExpandedSwaption expanded = swaption.expand(); double sign = expanded.getLongShort().sign(); ArgChecker.isTrue(presentValue * sign > 0, "Present value sign must be in line with the option Long/Short flag "); validateSwaption(ratesProvider, expanded); LocalDate valuationDate = ratesProvider.getValuationDate(); LocalDate expiryDate = expanded.getExpiryDate(); ArgChecker.isTrue(expiryDate.isAfter(valuationDate), "Expiry must be after valuation date to compute an implied volatility"); double expiry = dayCount.yearFraction(valuationDate, expiryDate); ExpandedSwap underlying = expanded.getUnderlying(); ExpandedSwapLeg fixedLeg = fixedLeg(underlying); double forward = swapPricer.parRate(underlying, ratesProvider); double pvbp = swapPricer.getLegPricer().pvbp(fixedLeg, ratesProvider); double strike = swapPricer.getLegPricer().couponEquivalent(fixedLeg, ratesProvider, pvbp); NormalFunctionData normalData = NormalFunctionData.of(forward, Math.abs(pvbp), 0.01); boolean isCall = fixedLeg.getPayReceive().isPay(); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, expiry, isCall ? PutCall.CALL : PutCall.PUT); return FORMULA_IMPLIED.impliedVolatility(normalData, option, Math.abs(presentValue)); }
Source:
public P decorate(P project) { if (!isProject(project)) { return project; } Branch branch = getBranch(project); BulkChange bc = new BulkChange(project); try { List<BranchProperty> properties = new ArrayList<BranchProperty>(branch.getProperties()); Collections.sort(properties, DescriptorOrder.reverse(BranchProperty.class)); for (BranchProperty property : properties) { ProjectDecorator<P, R> decorator = property.decorator(project); if (decorator != null) { if (project instanceof Project) { DescribableList<Publisher, Descriptor<Publisher>> publishersList = ((Project) project).getPublishersList(); DescribableList buildWrappersList = ((Project) project).getBuildWrappersList(); List<Publisher> publishers = decorator.publishers(publishersList.toList()); List<BuildWrapper> buildWrappers = decorator.buildWrappers(buildWrappersList.toList()); publishersList.replaceBy(publishers); buildWrappersList.replaceBy(buildWrappers); } List<JobProperty<? super P>> jobProperties = decorator.jobProperties(project.getAllProperties()); for (JobProperty<? super P> p : project.getAllProperties()) { project.removeProperty(p); } for (JobProperty<? super P> p : jobProperties) { project.addProperty(p); } decorator.project(project); } } } catch (IOException e) { } finally { bc.abort(); } return project; }

Target:
public P decorate(P project) { if (!isProject(project)) { return project; } Branch branch = getBranch(project); BulkChange bc = new BulkChange(project); try { List<BranchProperty> properties = new ArrayList<BranchProperty>(branch.getProperties()); Collections.sort(properties, DescriptorOrder.reverse(BranchProperty.class)); for (BranchProperty property : properties) { JobDecorator<P, R> decorator = property.jobDecorator(project.getClass()); if (decorator != null) { if (project instanceof Project && decorator instanceof ProjectDecorator) { DescribableList<Publisher, Descriptor<Publisher>> publishersList = ((Project) project).getPublishersList(); DescribableList<BuildWrapper, Descriptor<BuildWrapper>> buildWrappersList = ((Project) project).getBuildWrappersList(); List<Publisher> publishers = ((ProjectDecorator) decorator).publishers(publishersList.toList()); List<BuildWrapper> buildWrappers = ((ProjectDecorator) decorator).buildWrappers(buildWrappersList.toList()); publishersList.replaceBy(publishers); buildWrappersList.replaceBy(buildWrappers); } List<JobProperty<? super P>> jobProperties = decorator.jobProperties(project.getAllProperties()); for (JobProperty<? super P> p : project.getAllProperties()) { project.removeProperty(p); } for (JobProperty<? super P> p : jobProperties) { project.addProperty(p); } decorator.project(project); } } } catch (IOException e) { } finally { bc.abort(); } return project; }
Source:
private void trackAssignmentFailures() { if (!blacklistSendAssignentFailures) { return; } Map<String, Integer> assignmentFailureWindow = new HashMap<>(); assignmentFailureWindow.putAll(this.assignmentFailures); synchronized (assignmentFailures) { this.assignmentFailures.clear(); } this.sendAssignmentFailureCount.add(assignmentFailureWindow); }

Target:
private void trackAssignmentFailures() { if (!blacklistSendAssignentFailures) { return; } Map<String, Integer> assignmentFailureWindow = new HashMap<>(); synchronized (assignmentFailures) { assignmentFailureWindow.putAll(this.assignmentFailures); this.assignmentFailures.clear(); } this.sendAssignmentFailureCount.add(assignmentFailureWindow); }
Source:
public static void initConnectionSettings(Configuration conf, ClientConfiguration awsConf) throws IOException { awsConf.setMaxConnections(intOption(conf, MAXIMUM_CONNECTIONS, DEFAULT_MAXIMUM_CONNECTIONS, 1)); initProtocolSettings(conf, awsConf); awsConf.setMaxErrorRetry(intOption(conf, MAX_ERROR_RETRIES, DEFAULT_MAX_ERROR_RETRIES, 0)); awsConf.setConnectionTimeout(intOption(conf, ESTABLISH_TIMEOUT, DEFAULT_ESTABLISH_TIMEOUT, 0)); awsConf.setSocketTimeout(intOption(conf, SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, 0)); int sockSendBuffer = intOption(conf, SOCKET_SEND_BUFFER, DEFAULT_SOCKET_SEND_BUFFER, 2048); int sockRecvBuffer = intOption(conf, SOCKET_RECV_BUFFER, DEFAULT_SOCKET_RECV_BUFFER, 2048); int requestTimeoutMillis = intOption(conf, REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, 0); awsConf.setSocketBufferSizeHints(sockSendBuffer, sockRecvBuffer); awsConf.setRequestTimeout(requestTimeoutMillis); String signerOverride = conf.getTrimmed(SIGNING_ALGORITHM, ""); if (!signerOverride.isEmpty()) { LOG.debug("Signer override = {}", signerOverride); awsConf.setSignerOverride(signerOverride); } }

Target:
public static void initConnectionSettings(Configuration conf, ClientConfiguration awsConf) throws IOException { awsConf.setMaxConnections(intOption(conf, MAXIMUM_CONNECTIONS, DEFAULT_MAXIMUM_CONNECTIONS, 1)); initProtocolSettings(conf, awsConf); awsConf.setMaxErrorRetry(intOption(conf, MAX_ERROR_RETRIES, DEFAULT_MAX_ERROR_RETRIES, 0)); awsConf.setConnectionTimeout(intOption(conf, ESTABLISH_TIMEOUT, DEFAULT_ESTABLISH_TIMEOUT, 0)); awsConf.setSocketTimeout(intOption(conf, SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, 0)); int sockSendBuffer = intOption(conf, SOCKET_SEND_BUFFER, DEFAULT_SOCKET_SEND_BUFFER, 2048); int sockRecvBuffer = intOption(conf, SOCKET_RECV_BUFFER, DEFAULT_SOCKET_RECV_BUFFER, 2048); long requestTimeoutMillis = conf.getTimeDuration(REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); if (requestTimeoutMillis > Integer.MAX_VALUE) { LOG.debug("Request timeout is too high({} ms). Setting to ms instead", requestTimeoutMillis, Integer.MAX_VALUE); requestTimeoutMillis = Integer.MAX_VALUE; } awsConf.setRequestTimeout((int) requestTimeoutMillis); awsConf.setSocketBufferSizeHints(sockSendBuffer, sockRecvBuffer); String signerOverride = conf.getTrimmed(SIGNING_ALGORITHM, ""); if (!signerOverride.isEmpty()) { LOG.debug("Signer override = {}", signerOverride); awsConf.setSignerOverride(signerOverride); } }
Source:
public ZombieData getZombieData() { System.out.println("Forge zombie"); VillagerRegistry.VillagerProfession forgeProf = getVillagerTypeForge(); if (forgeProf == null) { ZombieType type = EntityUtil.typeFromNative(getZombieType()); return new SpongeZombieData(type, Optional.empty()); } return new SpongeZombieData(ZombieTypes.VILLAGER, SpongeForgeVillagerRegistry.getProfession(getVillagerTypeForge())); }

Target:
public ZombieData getZombieData() { VillagerRegistry.VillagerProfession forgeProf = getVillagerTypeForge(); if (forgeProf == null) { ZombieType type = EntityUtil.typeFromNative(getZombieType()); return new SpongeZombieData(type, Optional.empty()); } return new SpongeZombieData(ZombieTypes.VILLAGER, SpongeForgeVillagerRegistry.getProfession(getVillagerTypeForge())); }
Source:
public boolean track(byte[] key, short status, ClassWhiteList whitelist) { if (!trackSegments) { return keyOnlyTracker.track(key, status, whitelist); } int segment = HotRodConstants.isObjectStorage(status) ? segmentConsistentHash.getSegment(dataFormat.keyToObj(key, whitelist)) : segmentConsistentHash.getSegment(key); Set<WrappedByteArray> keys = keysPerSegment.get(segment); if (keys == null) { trackSegments = false; keyOnlyTracker = new ReplKeyTracker(drainKeys()); return keyOnlyTracker.track(key, status, whitelist); } boolean result = keys.add(new WrappedByteArray(key)); if (trace) log.trackingSegmentKey(Util.printArray(key), segment, !result); return result; }

Target:
public boolean track(byte[] key, short status, ClassWhiteList whitelist) { if (!trackSegments) return keyOnlyTracker.add(new WrappedByteArray(key)); int segment = HotRodConstants.isObjectStorage(status) ? segmentConsistentHash.getSegment(dataFormat.keyToObj(key, whitelist)) : segmentConsistentHash.getSegment(key); Set<WrappedByteArray> keys = keysPerSegment.get(segment); if (keys == null) { trackSegments = false; this.drainKeys(); return keyOnlyTracker.add(new WrappedByteArray(key)); } boolean result = keys.add(new WrappedByteArray(key)); if (trace) log.trackingSegmentKey(Util.printArray(key), segment, !result); return result; }
Source:
private void dropConglomerate(long CID, Activation activation) { TransactionController tc = activation.getTransactionController(); LOG.trace(format("Dropping temporary conglomerate splice:%d", CID)); try { tc.dropConglomerate(CID); } catch (StandardException e) { } try { dropTable(CID); } catch (StandardException e) { } }

Target:
private void dropConglomerate(long CID, Activation activation) { TransactionController tc = activation.getTransactionController(); LOG.trace(format("Dropping temporary conglomerate splice:%d", CID)); try { tc.dropConglomerate(CID); } catch (StandardException e) { LOG.warn(format("Unable to drop temporary trigger conglomerate %d. Cleanup may have been called twice.", CID), e); } try { dropTable(CID); } catch (StandardException e) { LOG.warn(format("Unable to drop HBase table for temporary trigger conglomerate %d. Cleanup may have been called twice.", CID), e); } }
Source:
public boolean isEnvironmentVariable(ICdtVariable variable, ICConfigurationDescription cfg) { if(variable instanceof EnvironmentVariableSupplier.EnvVarMacro) return true; if (variable == null) return false; IVariableContextInfo info = getVariableContextInfo(cfg); ICdtVariable var = fEnvironmentMacroSupplier.getVariable(variable.getName(), info); if(var != null && variablesEqual(var, variable)) return true; return false; }

Target:
public boolean isEnvironmentVariable(ICdtVariable variable, ICConfigurationDescription cfg) { if(variable instanceof EnvironmentVariableSupplier.EnvVarMacro) return true; IVariableContextInfo info = getVariableContextInfo(cfg); ICdtVariable var = fEnvironmentMacroSupplier.getVariable(variable.getName(), info); if(var != null && variablesEqual(var, variable)) return true; return false; }
Source:
public void exitLongArray(ExprParser.LongArrayContext ctx) { Long[] values = ctx.longArrayBody() == null ? new Long[0] : new Long[ctx.longArrayBody().longElement().size()]; for (int i = 0; i < values.length; i++) { if (ctx.longArrayBody().longElement(i).getText().equalsIgnoreCase(Expr.NULL_LITERAL)) { values[i] = null; } else { values[i] = Long.parseLong(ctx.longArrayBody().longElement(i).getText()); } } nodes.put(ctx, new LongArrayExpr(values)); }

Target:
public void exitLongArray(ExprParser.LongArrayContext ctx) { Long[] values = new Long[ctx.longElement().size()]; for (int i = 0; i < values.length; i++) { if (ctx.longElement(i).NULL() != null) { values[i] = null; } else if (ctx.longElement(i).LONG() != null) { values[i] = Long.parseLong(ctx.longElement(i).LONG().getText()); } else { throw new RE("Failed to parse array element %s as a long", ctx.longElement(i).getText()); } } nodes.put(ctx, new LongArrayExpr(values)); }
Source:
public DBObject getMappedExample(Example<?> example, MongoPersistentEntity<?> entity) { DBObject reference = (DBObject) converter.convertToMongoType(example.getProbe()); if (entity.hasIdProperty() && entity.getIdentifierAccessor(example.getProbe()).getIdentifier() == null) { reference.removeField(entity.getIdProperty().getFieldName()); } ExampleSpecAccessor exampleSpecAccessor = new ExampleSpecAccessor(example.getExampleSpec()); applyPropertySpecs("", reference, example.getProbeType(), exampleSpecAccessor); if (exampleSpecAccessor.isTyped()) { Set<Class<?>> restrictedTypes = new HashSet<Class<?>>(); restrictedTypes.add(example.getResultType()); this.converter.getTypeMapper().writeTypeRestrictions(reference, restrictedTypes); } return ObjectUtils.nullSafeEquals(NullHandler.INCLUDE, exampleSpecAccessor.getNullHandler()) ? reference : new BasicDBObject(SerializationUtils.flatMap(reference)); }

Target:
public DBObject getMappedExample(Example<?> example, MongoPersistentEntity<?> entity) { DBObject reference = (DBObject) converter.convertToMongoType(example.getProbe()); if (entity.hasIdProperty() && entity.getIdentifierAccessor(example.getProbe()).getIdentifier() == null) { reference.removeField(entity.getIdProperty().getFieldName()); } ExampleSpecAccessor exampleSpecAccessor = new ExampleSpecAccessor(example.getExampleSpec()); applyPropertySpecs("", reference, example.getProbeType(), exampleSpecAccessor); if (exampleSpecAccessor.isTyped()) { this.converter.getTypeMapper().writeTypeRestrictions(reference, (Set) Collections.singleton(example.getResultType())); } return ObjectUtils.nullSafeEquals(NullHandler.INCLUDE, exampleSpecAccessor.getNullHandler()) ? reference : new BasicDBObject(SerializationUtils.flattenMap(reference)); }
Source:
public static void parseOptionsAndPayload(DatagramReader reader, Message message) { int currentOptionNumber = 0; byte nextByte = 0; while (reader.bytesAvailable()) { nextByte = reader.readNextByte(); if (nextByte != PAYLOAD_MARKER) { int optionDeltaNibble = (0xF0 & nextByte) >> 4; currentOptionNumber = calculateNextOptionNumber(reader, currentOptionNumber, optionDeltaNibble, message); int optionLengthNibble = 0x0F & nextByte; int optionLength = determineValueFromNibble(reader, optionLengthNibble, message); if (reader.bytesAvailable(optionLength)) { Option option = new Option(currentOptionNumber); option.setValue(reader.readBytes(optionLength)); message.getOptions().addOption(option); } else { String msg = String.format( "Message contains option of length %d with only fewer bytes left in the message", optionLength); throw new CoAPMessageFormatException(msg, message.getMID(), message.getRawCode(), message.isConfirmable()); } } else break; } if (nextByte == PAYLOAD_MARKER) { if (!reader.bytesAvailable()) { throw new CoAPMessageFormatException( "Found payload marker (0xFF) but message contains no payload", message.getMID(), message.getRawCode(), message.isConfirmable()); } else { message.setPayload(reader.readBytesLeft()); } } else { message.setPayload((String) null); } }

Target:
public static void parseOptionsAndPayload(DatagramReader reader, Message message) { if (reader == null) { throw new NullPointerException("reader must not be null!"); } if (message == null) { throw new NullPointerException("message must not be null!"); } int currentOptionNumber = 0; byte nextByte = 0; while (reader.bytesAvailable()) { nextByte = reader.readNextByte(); if (nextByte != PAYLOAD_MARKER) { int optionDeltaNibble = (0xF0 & nextByte) >> 4; currentOptionNumber = calculateNextOptionNumber(reader, currentOptionNumber, optionDeltaNibble, message); int optionLengthNibble = 0x0F & nextByte; int optionLength = determineValueFromNibble(reader, optionLengthNibble, message); if (reader.bytesAvailable(optionLength)) { Option option = new Option(currentOptionNumber); option.setValue(reader.readBytes(optionLength)); message.getOptions().addOption(option); } else { String msg = String.format( "Message contains option of length %d with only fewer bytes left in the message", optionLength); throw new CoAPMessageFormatException(msg, message.getMID(), message.getRawCode(), message.isConfirmable()); } } else break; } if (nextByte == PAYLOAD_MARKER) { if (!reader.bytesAvailable()) { throw new CoAPMessageFormatException( "Found payload marker (0xFF) but message contains no payload", message.getMID(), message.getRawCode(), message.isConfirmable()); } else { message.setPayload(reader.readBytesLeft()); } } else { message.setPayload((String) null); } }
Source:
void typeSelectorKeyDownEventListener(final Object event) { if (event instanceof KeyboardEvent) { final KeyboardEvent keyEvent = (KeyboardEvent) event; if (isEnterKeyPressed(keyEvent)) { hide(true); keyEvent.preventDefault(); onClosedByKeyboard(); } else if (isEscapeKeyPressed(keyEvent)) { reset(); hide(false); onClosedByKeyboard(); } else if (isTabKeyPressed(keyEvent)) { if (keyEvent.shiftKey) { final Button managerButton = getManagerButton(); managerButton.focus(); } else { nameEditor.focus(); } keyEvent.preventDefault(); } } }

Target:
void typeSelectorKeyDownEventListener(final Object event) { if (event instanceof KeyboardEvent) { final KeyboardEvent keyEvent = (KeyboardEvent) event; if (isEnterKeyPressed(keyEvent)) { hide(true); keyEvent.preventDefault(); onClosedByKeyboard(); } else if (isEscapeKeyPressed(keyEvent)) { reset(); hide(false); onClosedByKeyboard(); } else if (isTabKeyPressed(keyEvent)) { if (keyEvent.shiftKey) { final Button manageButton = getManageButton(); manageButton.focus(); } else { nameEditor.focus(); } keyEvent.preventDefault(); } } }
Source:
private void fireDamageEventExplosion(final DamageSource source, final float amount, final CallbackInfoReturnable<Boolean> cir) { this.fireDestroyDamageEvent(source, cir); }

Target:
private void impl$fireDamageEventExplosion(final DamageSource source, final float amount, final CallbackInfoReturnable<Boolean> cir) { this.fireDestroyDamageEvent(source, cir); }
Source:
public static TmfStateValue newValueInt(int intValue) { if (intValue == -1) { return nullValue(); } int offset = intValue & (INT_CACHE_SIZE-1); IntegerStateValue cached = intCache[offset]; if (cached != null && cached.unboxInt() == intValue) { return cached; } IntegerStateValue new_value = new IntegerStateValue(intValue); intCache[offset] = new_value; return new_value; }

Target:
public static TmfStateValue newValueInt(int intValue) { int offset = intValue & (INT_CACHE_SIZE -1 ); IntegerStateValue cached = intCache[offset]; if (cached != null && cached.unboxInt() == intValue) { return cached; } IntegerStateValue newValue = new IntegerStateValue(intValue); intCache[offset] = newValue; return newValue; }
Source:
public void shouldDecreaseIdleWhenClosedOutsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); channel.close(); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }

Target:
public void shouldDecreaseIdleWhenClosedOutsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); channel.close().sync(); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }
Source:
private static String getMatchingLocation(String discoveredLocation, String pattern) { String regex = pattern.replace("*", "[^" + OsgiServiceUtils.LOCATION_END + "]+"); Pattern compliedPattern = Pattern.compile(regex); Matcher matcher = compliedPattern.matcher(discoveredLocation); if (!matcher.find()) { throw new IllegalArgumentException(String.format( "could not find location matching pattern \"%s\" in provided list \"%s\"", pattern, discoveredLocation)); } return matcher.group(); }

Target:
private static String getMatchingLocation(String discoveredLocation, String pattern) { Pattern compliedPattern = getCompiledPattern(pattern); Matcher matcher = compliedPattern.matcher(discoveredLocation); if (!matcher.find()) { throw new IllegalArgumentException(String.format( "could not find location matching pattern \"%s\" in provided list \"%s\"", pattern, discoveredLocation)); } return matcher.group(); }
Source:
public byte[] serialize(LedgerMetadata metadata) throws IOException { int formatVersion = Math.min(maxLedgerMetadataFormatVersion, metadata.getMetadataFormatVersion()); final byte[] serialized; switch (formatVersion) { case 3: serialized = serializeVersion3(metadata); break; case 2: serialized = serializeVersion2(metadata); break; case 1: serialized = serializeVersion1(metadata); break; default: throw new IllegalArgumentException("Invalid format version " + formatVersion); } if (log.isDebugEnabled()) { log.debug("Serialized with format {}: {}", formatVersion, Base64.getEncoder().encodeToString(serialized)); } return serialized; }

Target:
public byte[] serialize(LedgerMetadata metadata) throws IOException { int formatVersion = metadata.getMetadataFormatVersion(); final byte[] serialized; switch (formatVersion) { case METADATA_FORMAT_VERSION_3: serialized = serializeVersion3(metadata); break; case METADATA_FORMAT_VERSION_2: serialized = serializeVersion2(metadata); break; case METADATA_FORMAT_VERSION_1: serialized = serializeVersion1(metadata); break; default: throw new IllegalArgumentException("Invalid format version " + formatVersion); } if (log.isDebugEnabled()) { String serializedStr; if (formatVersion > METADATA_FORMAT_VERSION_2) { serializedStr = Base64.getEncoder().encodeToString(serialized); } else { serializedStr = new String(serialized, UTF_8); } log.debug("Serialized with format {}: {}", formatVersion, serializedStr); } return serialized; }
Source:
public StandardBuilder ignoreFailure() { ignoreFailure = true; return this; }

Target:
public StandardBuilder ignoreFailure() { return ignoreFailure(true); }
Source:
public String getName(ITmfEvent event) { if (fNameStateValue != null) { getNameFromXmlStateValue(event, fName, fNameStateValue); } return fName.toString(); }

Target:
public String getName(ITmfEvent event) { StringBuilder name = new StringBuilder(PATTERN_SEGMENT_NAME_PREFIX); if (fNameStateValue != null) { getNameFromXmlStateValue(event, name, fNameStateValue); } else { name.append(fSegmentNameAttribute); } return name.toString(); }
Source:
public static PDPrintStyle getPointStyle (JSONObject oskariStyle, PDDocument doc) throws IOException { PDPrintStyle style = new PDPrintStyle(); JSONObject image = JSONHelper.optJSONObject(oskariStyle, "image", () -> new JSONObject()); int shape = image.optInt("shape", 5); JSONObject imageFill = JSONHelper.optJSONObject(image, "fill", () -> new JSONObject()); String fillColor = JSONHelper.optString(imageFill, "color"); style.setFillColor(ColorUtil.parseColor(fillColor)); int size = image.optInt("size", 3); style.setIcon(getIcon(doc, shape, fillColor, size)); setLabelStyle(style, oskariStyle); return style; }

Target:
public static PDPrintStyle getPointStyle (JSONObject oskariStyle, PDDocument doc) throws IOException { PDPrintStyle style = new PDPrintStyle(); setImageStyle(style, oskariStyle, doc); setLabelStyle(style, oskariStyle); return style; }
Source:
public void versionUpdatesForGetAfterRefreshMillis() throws InterruptedException { assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, 1L)); waitForUpdate(); assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, 2L)); waitForUpdate(); waitForUpdate(); assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, 3L)); }

Target:
public void versionUpdatesForGetAfterRefreshMillis() throws InterruptedException { assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, UNINITIALIZED_VERSION + 1L)); waitForUpdate(); assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, UNINITIALIZED_VERSION + 2L)); waitForUpdate(); assertThat(supplier.get()).isEqualTo(VersionedType.of(0L, UNINITIALIZED_VERSION + 3L)); }
Source:
public void stop() { for(String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).stop(); } catch (Exception ex) { LOG.warn(String.format("Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } _eventProducerPool.shutdown(); while (_eventThread.isAlive()) { try { _eventThread.interrupt(); _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); } catch (InterruptedException e) { LOG.warn("Exception caught while stopping coordinator", e); } } _adapter.disconnect(); }

Target:
public void stop() { for(String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).stop(); } catch (Exception ex) { LOG.warn(String.format("Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } while (_eventThread.isAlive()) { try { _eventThread.interrupt(); _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); } catch (InterruptedException e) { LOG.warn("Exception caught while stopping coordinator", e); } } _eventProducerPool.shutdown(); _adapter.disconnect(); }
Source:
static String trimPathDepth(String path, int maxDepth) { int count = 0; String pathSeparator = "/"; StringBuilder sb = new StringBuilder(); StringTokenizer pathTokenizer = new StringTokenizer(path, pathSeparator); while (pathTokenizer.hasMoreElements() && count++ < maxDepth) { sb.append(pathSeparator); sb.append(pathTokenizer.nextToken()); } path = sb.toString(); return path; }

Target:
static String trimPathDepth(String path, int maxDepth) { int count = 0; StringBuilder sb = new StringBuilder(); StringTokenizer pathTokenizer = new StringTokenizer(path, PATH_SEPERATOR); while (pathTokenizer.hasMoreElements() && count++ < maxDepth) { sb.append(PATH_SEPERATOR); sb.append(pathTokenizer.nextToken()); } path = sb.toString(); return path; }
Source:
public void testTurboJpegStatus() { try{ Runtime.getRuntime().loadLibrary("turbojpeg"); } catch (java.lang.UnsatisfiedLinkError e) { Runtime.getRuntime().loadLibrary("turbojpeg"); } TurboJpegStatus status = new TurboJpegStatus(); assertTrue(status.getModule().length() > 0); assertTrue(status.getName().length() > 0); assertTrue(status.getComponent().get().length() > 0); assertTrue(status.getMessage().get().length() > 0); if (!status.isAvailable()) { return; } assertTrue(status.getMessage().get().contains("Wrapper Version")); }

Target:
public void testTurboJpegStatus() { TurboJpegStatus status = new TurboJpegStatus(); assertTrue(status.getModule().length() > 0); assertTrue(status.getName().length() > 0); assertTrue(status.getComponent().get().length() > 0); assertTrue(status.getMessage().get().length() > 0); if (!status.isAvailable()) { return; } assertTrue(status.getMessage().get().contains("Wrapper Version")); }