auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Long getPosition(StreamPartition<Integer> partition) { try { return consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); } catch (TimeoutException e) { throw new PossiblyTransientStreamException(e); } catch (WakeupException | InterruptException e) { throw new TransientStreamException(e); } catch (KafkaException e) { throw new NonTransientStreamException(e); } }

Target:
public Long getPosition(StreamPartition<Integer> partition) { return wrapExceptions(() -> consumer.position(new TopicPartition( partition.getStream(), partition.getPartitionId() ))); }
Source:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); FutureResult futureResult; try { futureResult = (FutureResult) router.getBlobInfo(blobId); while (!futureResult.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } futureResult.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } try { futureResult = (FutureResult) router.getBlob(blobId); while (!futureResult.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } futureResult.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } router.close(); }

Target:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); Future future; try { future = router.getBlobInfo(blobId); while (!future.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } future.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } try { future = router.getBlob(blobId); while (!future.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } future.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } router.close(); }
Source:
public void testResetToNonexistingHEAD() throws JGitInternalException, AmbiguousObjectException, IOException { git = new Git(db); writeTrashFile("f", "content"); try { git.reset().setRef(Constants.HEAD).call(); fail("Excpected JGitInternalException didn't occured"); } catch (JGitInternalException e) { } }

Target:
public void testResetToNonexistingHEAD() throws JGitInternalException, AmbiguousObjectException, IOException { git = new Git(db); writeTrashFile("f", "content"); try { git.reset().setRef(Constants.HEAD).call(); fail("Expected JGitInternalException didn't occur"); } catch (JGitInternalException e) { } }
Source:
protected String getLocalAddressString(SSLSocket socket) { InetAddress addr = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }

Target:
protected String getLocalAddressString(SSLSocket socket) { final InetAddress addr = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }
Source:
public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity(new Gson().toJson(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", String.valueOf(request.getEntity().getContentLength())); HttpEntity response = executeRequest(request); consumeEntity(response); }

Target:
public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity(new Gson().toJson(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", String.valueOf(entity.getContentLength())); HttpEntity response = executeRequest(request); consumeResponse(response); }
Source:
public ValidationReport validate(String uri, InputStream inputstream, NestedValidatorContext context) { String fileName = uri.substring(uri.lastIndexOf("/")+1); String viewName = getViewName(fileName); IRepositoryViewObject viewObj = RepositoryResourceUtil.findViewObjectByName(IServerObjectRepositoryType.TYPE_VIEW, viewName); if (viewObj != null) { ViewValidationReport viewValidationReport = null; WSViewItem item = (WSViewItem) viewObj.getProperty().getItem(); WSViewE view = (WSViewE)item.getMDMServerObject(); EList<WSWhereConditionE> whereConditions = view.getWhereConditions(); if(whereConditions != null && whereConditions.size() >0) { viewValidationReport = new ViewValidationReport(uri); for (WSWhereConditionE conditionE : whereConditions) { String userVarValue = conditionE.getRightValueOrPath(); boolean isValid = UserVarValueValidator.validate(userVarValue); if(!isValid) { String validateMsg = Messages.ViewValidator_0 + userVarValue + Messages.ViewValidator_1 + viewName +Messages.ViewValidator_2; viewValidationReport.addValidationMessage(new ValidationMessage(validateMsg, -1, -1)); } } } return viewValidationReport; } return null; }

Target:
public ValidationReport validate(String uri, InputStream inputstream, NestedValidatorContext context) { ViewValidationReport viewValidationReport = new ViewValidationReport(uri); String fileName = uri.substring(uri.lastIndexOf("/")+1); String viewName = getViewName(fileName); viewName = viewName.replace("$", "#"); IRepositoryViewObject viewObj = RepositoryResourceUtil.findViewObjectByName(IServerObjectRepositoryType.TYPE_VIEW, viewName); if (viewObj != null) { WSViewItem item = (WSViewItem) viewObj.getProperty().getItem(); WSViewE view = (WSViewE)item.getMDMServerObject(); EList<WSWhereConditionE> whereConditions = view.getWhereConditions(); if(whereConditions != null && whereConditions.size() >0) { for (WSWhereConditionE conditionE : whereConditions) { String userVarValue = conditionE.getRightValueOrPath(); boolean isValid = UserVarValueValidator.validate(userVarValue); if(!isValid) { String validateMsg = Messages.bind(Messages.ViewValidator_error, userVarValue,viewName); viewValidationReport.addValidationMessage(new ValidationMessage(validateMsg, -1, -1)); } } } } return viewValidationReport; }
Source:
public CommCareApp getCurrentApp() { if (currentApp != null) { System.out.println("current app has display name: " + this.currentApp.getAppRecord().getDisplayName()); } return this.currentApp; }

Target:
public CommCareApp getCurrentApp() { return this.currentApp; }
Source:
public String[] toClassMethodNameWithoutPlan( TestIdentifier testIdentifier ) { Optional<TestSource> testSource = testIdentifier.getSource(); String display = testIdentifier.getDisplayName(); if ( testSource.filter( MethodSource.class::isInstance ).isPresent() ) { MethodSource methodSource = testSource.map( MethodSource.class::cast ).get(); String realClassName = methodSource.getClassName(); String[] source = new String[] {realClassName, realClassName}; String methodName = methodSource.getMethodName(); boolean useMethod = display.equals( methodName ) || display.equals( methodName + "()" ); String resolvedMethodName = useMethod ? methodName : display; return new String[] {source[0], source[1], methodName, resolvedMethodName}; } else if ( testSource.filter( ClassSource.class::isInstance ).isPresent() ) { ClassSource classSource = testSource.map( ClassSource.class::cast ).get(); String className = classSource.getClassName(); String simpleClassName = className.substring( 1 + className.lastIndexOf( '.' ) ); String source = display.equals( simpleClassName ) ? className : display; return new String[] {className, source, null, null}; } else { String source = testPlan == null ? display : testPlan.getParent( testIdentifier ).map( TestIdentifier::getDisplayName ).orElse( display ); return new String[] {source, source, display, display}; } }

Target:
public String[] toClassMethodNameWithoutPlan( TestIdentifier testIdentifier ) { return toClassMethodName( testIdentifier, false ); }
Source:
public void getBulkWithBadArgs() throws Exception { final Arguments args = new Arguments(new String[]{"ds3_java_cli", "-e", "localhost:8080", "-k", "key!", "-a", "access", "-c", "get_bulk", "-b", "bucketName", "-d", "targetdir", "--discard"}); final String expected = "Error (BadArgumentException): Cannot set both directory and --discard"; final Ds3ClientHelpers helpers = mock(Ds3ClientHelpers.class); final Ds3ClientHelpers.Job mockedGetJob = mock(Ds3ClientHelpers.Job.class); final FileUtils mockedFileUtils = mock(FileUtils.class); when(helpers.startReadAllJob(eq("bucketName"), any(ReadJobOptions.class))).thenReturn(mockedGetJob); final Ds3Cli cli = new Ds3Cli(new Ds3ProviderImpl(null, helpers), args, mockedFileUtils); try { final CommandResponse result = cli.call(); } catch (Exception e) { final Ds3ExceptionHandlerMapper exception = Ds3ExceptionHandlerMapper.getInstance(); final DefaultExceptionHandler handler = new DefaultExceptionHandler(); final String formattedException = handler.format(e); assertThat(formattedException, is(expected)); } }

Target:
public void getBulkWithBadArgs() throws Exception { final Arguments args = new Arguments(new String[]{"ds3_java_cli", "-e", "localhost:8080", "-k", "key!", "-a", "access", "-c", "get_bulk", "-b", "bucketName", "-d", "targetdir", "--discard"}); final String expected = "Error (BadArgumentException): Cannot set both directory and --discard"; final Ds3ClientHelpers helpers = mock(Ds3ClientHelpers.class); final Ds3ClientHelpers.Job mockedGetJob = mock(Ds3ClientHelpers.Job.class); final FileUtils mockedFileUtils = mock(FileUtils.class); when(helpers.startReadAllJob(eq("bucketName"), any(ReadJobOptions.class))).thenReturn(mockedGetJob); final Ds3Cli cli = new Ds3Cli(new Ds3ProviderImpl(null, helpers), args, mockedFileUtils); try { final CommandResponse result = cli.call(); } catch (final Exception e) { final Ds3ExceptionHandlerMapper exception = Ds3ExceptionHandlerMapper.getInstance(); final DefaultExceptionHandler handler = new DefaultExceptionHandler(); final String formattedException = handler.format(e); assertThat(formattedException, is(expected)); } }
Source:
public int run() throws IOException { try { byte[] buf = new byte[8192]; int length = in.read(buf); if (length != -1) { aOut.write(buf, 0, length); size += length; return length; } else { aOut.close(); AnyLongObjectId loid = aOut.getId(); aOut = null; Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } else { FileUtils.delete(tmpFile.toFile()); } } else { Path parent = mediaFile.getParent(); if (parent != null) { FileUtils.mkdirs(parent.toFile(), true); } FileUtils.rename(tmpFile.toFile(), mediaFile.toFile(), StandardCopyOption.ATOMIC_MOVE); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); in.close(); out.close(); return -1; } } catch (IOException e) { if (aOut != null) { aOut.abort(); } in.close(); out.close(); throw e; } }

Target:
public int run() throws IOException { try { byte[] buf = new byte[8192]; int length = in.read(buf); if (length != -1) { aOut.write(buf, 0, length); size += length; return length; } else { aOut.close(); AnyLongObjectId loid = aOut.getId(); aOut = null; Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } else { FileUtils.delete(tmpFile.toFile()); } } else { Path parent = mediaFile.getParent(); if (parent != null) { FileUtils.mkdirs(parent.toFile(), true); } FileUtils.rename(tmpFile.toFile(), mediaFile.toFile(), StandardCopyOption.ATOMIC_MOVE); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } } catch (IOException e) { if (aOut != null) { aOut.abort(); } out.close(); throw e; } }
Source:
public void testSqlLedgerStorage() { try { try { PrototypeFactory mPrototypeFactory = new PrototypeFactory(); mPrototypeFactory.addClass(Ledger.class); String storageKey = "Ledger"; String username = "wspride"; SqlTestUtils.deleteDatabase(username); ledgerStorage = new SqlIndexedStorageUtility<Ledger>(Ledger.class, username, storageKey); ledgerStorage.write(l); ledgerStorage.write(l2); ledgerStorage.write(l3); Vector<Object> ids = ledgerStorage.getIDsForValue("entity_id", "ledger_entity_id"); assertEquals(2, ids.size()); assertTrue(ids.contains(1)); assertTrue(ids.contains(2)); Ledger readLedger2 = ledgerStorage.getRecordForValue("entity_id", "ledger_entity_id_3"); int count = ledgerStorage.getNumRecords(); assertEquals(count, 3); assertTrue(ledgerStorage.exists(1)); assertFalse(ledgerStorage.exists(-123)); SqlStorageIterator<Ledger> mIterator = ledgerStorage.iterate(); assertEquals(3, mIterator.numRecords()); assertEquals(1, mIterator.nextID()); assertEquals(2, mIterator.nextID()); assertEquals(3, mIterator.nextID()); assertEquals(-1, mIterator.nextID()); } catch ( Exception e ) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); System.exit(0); } } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); } }

Target:
public void testSqlLedgerStorage() { try { PrototypeFactory mPrototypeFactory = new PrototypeFactory(); mPrototypeFactory.addClass(Ledger.class); String storageKey = "Ledger"; String username = "wspride"; ledgerStorage = new SqliteIndexedStorageUtility<Ledger>(Ledger.class, username, storageKey); ledgerStorage.write(l); ledgerStorage.write(l2); ledgerStorage.write(l3); Vector ids = ledgerStorage.getIDsForValue("entity_id", "ledger_entity_id"); assertEquals(2, ids.size()); assertTrue(ids.contains(1)); assertTrue(ids.contains(2)); Ledger readLedger2 = ledgerStorage.getRecordForValue("entity_id", "ledger_entity_id_3"); assertEquals(readLedger2.getID(), 3); int count = ledgerStorage.getNumRecords(); assertEquals(count, 3); assertTrue(ledgerStorage.exists(1)); assertFalse(ledgerStorage.exists(-123)); JdbcSqlStorageIterator<Ledger> mIterator = ledgerStorage.iterate(); assertEquals(3, mIterator.numRecords()); assertEquals(1, mIterator.nextID()); assertEquals(2, mIterator.nextID()); assertEquals(3, mIterator.nextID()); assertEquals(-1, mIterator.nextID()); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); } }
Source:
public ConvertOperationBuilder<T> excludeAttribute(String attributePath) { if ( (key.getSourceType() != null) && !key.getSourceType().getRecursiveAttributes().containsKey(attributePath) && !key.getSourceType().getRecursiveSubviewAttributes().containsKey(attributePath) ) { throw new IllegalArgumentException("Attribute '" + attributePath + "' could not be found on type: " + key.getSourceType().getJavaType().getName()); } subMappers.put(attributePath, ViewMapper.Key.EXCLUDE_MARKER); return this; }

Target:
public ConvertOperationBuilder<T> excludeAttribute(String attributePath) { if (!key.getTargetType().getRecursiveAttributes().containsKey(attributePath) && !key.getTargetType().getRecursiveSubviewAttributes().containsKey(attributePath)) { throw new IllegalArgumentException("Attribute '" + attributePath + "' could not be found on type: " + key.getTargetType().getJavaType().getName()); } subMappers.put(attributePath, ViewMapper.Key.EXCLUDE_MARKER); return this; }
Source:
public Duration nextWait() { if (nextBackoffTime == 0) { nextBackoffTime = System.currentTimeMillis() + backoffDuration.toMillis(); } long sleepTime = (long) Math.pow(base, retryCounter.incrementAndGet()); sleepTime += extraWait; float randomPart = new Random().nextFloat() * randomPortion; sleepTime -= sleepTime * randomPart; if (maxRetryThreshold.toMillis() > 0) { sleepTime = Math.min(sleepTime, maxRetryThreshold.toMillis()); } if (System.currentTimeMillis() + sleepTime > nextBackoffTime) { nextBackoffTime = 0; retryCounter.set(1); sleepTime = base + extraWait; sleepTime -= sleepTime * randomPart; } return Duration.ofMillis(sleepTime); }

Target:
public Duration nextWait() { if (nextBackoffTime == 0) { nextBackoffTime = System.currentTimeMillis() + backoffDuration.toMillis(); } long sleepTime = (long) Math.pow(base, retryCounter.incrementAndGet()); sleepTime += extraWait; float randomPart = new Random().nextFloat() * randomPortion; sleepTime -= sleepTime * randomPart; if (maxRetryThreshold.toMillis() > 0) { sleepTime = Math.min(sleepTime, maxRetryThreshold.toMillis()); } if (System.currentTimeMillis() + sleepTime > nextBackoffTime) { nextBackoffTime = 0; retryCounter.set(this.startPower); sleepTime = base + extraWait; sleepTime -= sleepTime * randomPart; } return Duration.ofMillis(sleepTime); }
Source:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { synchronized (startsWithObject) { startsWithObject.setPattern(session, rightValue); return startsWithObject.compare(session, leftValue); } } return startsWithObject.compare(session, leftValue); }

Target:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { startsWithObject.setPattern(session, rightValue); } return startsWithObject.compare(session, leftValue); }
Source:
public UmaMetadata getUmaDiscovery(String opConfigurationEndpoint, String opHost, String opDiscoveryPath) { return Strings.isNullOrEmpty(opConfigurationEndpoint) ? getUmaDiscovery(opHost, opDiscoveryPath) : getUmaDiscovery(opConfigurationEndpoint); }

Target:
public UmaMetadata getUmaDiscovery(String opConfigurationEndpoint, String opHost, String opDiscoveryPath) { return Strings.isNullOrEmpty(opConfigurationEndpoint) ? getUmaDiscovery(getConnectDiscoveryUrl(opHost, opDiscoveryPath)) : getUmaDiscovery(opConfigurationEndpoint); }
Source:
public <R> Collection<Future<R>> executeOn(ServiceEndPointPredicate predicate, final RetryPolicy retry, final ServiceCallback<S, R> callback) { Collection<Future<R>> futures = Lists.newArrayList(); for (final ServiceEndPoint endPoint : _pool.getAllEndPoints()) { if (!predicate.apply(endPoint)) { continue; } Future<R> future = _executor.submit(new Callable<R>() { @Override public R call() throws Exception { TimerContext timer = _executionTime.time(); Stopwatch sw = new Stopwatch(_ticker).start(); int numAttempts = 0; try { Exception lastException; do { try { R result = _pool.executeOnEndPoint(endPoint, callback); _numExecuteSuccesses.mark(); return result; } catch (Exception e) { _numExecuteFailures.mark(); if (!_pool.isRetriableException(e)) { throw e; } lastException = e; } } while (retry.allowRetry(++numAttempts, sw.elapsedMillis())); throw new MaxRetriesException( "Exception from the last retry attempt", lastException ); } finally { timer.stop(); } } }); futures.add(future); } _executeBatchSize.update(futures.size()); return futures; }

Target:
public <R> Collection<Future<R>> executeOn(ServiceEndPointPredicate predicate, final RetryPolicy retry, final ServiceCallback<S, R> callback) { Collection<Future<R>> futures = Lists.newArrayList(); for (final ServiceEndPoint endPoint : _pool.getAllEndPoints()) { if (!predicate.apply(endPoint)) { continue; } Future<R> future = _executor.submit(new Callable<R>() { @Override public R call() throws Exception { TimerContext timer = _executionTime.time(); Stopwatch sw = new Stopwatch(_ticker).start(); int numAttempts = 0; try { Exception lastException; do { try { R result = _pool.executeOnEndPoint(endPoint, callback); _numExecuteSuccesses.mark(); return result; } catch (Exception e) { _numExecuteFailures.mark(); if (!_pool.isRetriableException(e)) { throw e; } lastException = e; LOG.info("Retriable exception from end point id: " + endPoint.getId(), e); } } while (retry.allowRetry(++numAttempts, sw.elapsedMillis())); throw new MaxRetriesException(lastException); } finally { timer.stop(); } } }); futures.add(future); } _executeBatchSize.update(futures.size()); return futures; }
Source:
private static Object findFragmentForViewInActivity(Activity activity, View view) { FragmentCompat supportLib = FragmentCompat.getSupportLibInstance(); if (supportLib != null && supportLib.getFragmentActivityClass() == activity.getClass()) { Object fragment = findFragmentForViewInActivity(supportLib, activity, view); if (fragment != null) { return fragment; } } FragmentCompat framework = FragmentCompat.getFrameworkInstance(); if (framework != null) { Object fragment = findFragmentForViewInActivity(framework, activity, view); if (fragment != null) { return fragment; } } return null; }

Target:
private static Object findFragmentForViewInActivity(Activity activity, View view) { FragmentCompat supportLib = FragmentCompat.getSupportLibInstance(); if (supportLib != null && supportLib.getFragmentActivityClass().isInstance(activity)) { Object fragment = findFragmentForViewInActivity(supportLib, activity, view); if (fragment != null) { return fragment; } } FragmentCompat framework = FragmentCompat.getFrameworkInstance(); if (framework != null) { Object fragment = findFragmentForViewInActivity(framework, activity, view); if (fragment != null) { return fragment; } } return null; }
Source:
public ConnectionFactory jmsConnectionFactory(AzureServiceBusJMSProperties serviceBusJMSProperties) { final String connectionString = serviceBusJMSProperties.getConnectionString(); final long idleTimeout = serviceBusJMSProperties.getIdleTimeout(); final ServiceBusJmsConnectionFactorySettings settings = new ServiceBusJmsConnectionFactorySettings(idleTimeout, false); final ServiceBusJmsConnectionFactory serviceBusJmsConnectionFactory = new ServiceBusJmsConnectionFactory(connectionString, settings); return new CachingConnectionFactory(serviceBusJmsConnectionFactory); }

Target:
public ConnectionFactory jmsConnectionFactory(AzureServiceBusJMSProperties serviceBusJMSProperties) { final String connectionString = serviceBusJMSProperties.getConnectionString(); final String clientId = serviceBusJMSProperties.getTopicClientId(); final long idleTimeout = serviceBusJMSProperties.getIdleTimeout(); final ServiceBusJmsConnectionFactorySettings settings = new ServiceBusJmsConnectionFactorySettings(idleTimeout, false); final SpringServiceBusJmsConnectionFactory springServiceBusJmsConnectionFactory = new SpringServiceBusJmsConnectionFactory(connectionString, settings); springServiceBusJmsConnectionFactory.setClientId(clientId); springServiceBusJmsConnectionFactory.setCustomUserAgent(AZURE_SPRING_SERVICE_BUS); return new CachingConnectionFactory(springServiceBusJmsConnectionFactory); }
Source:
public void respectIndexOrder() throws Exception { IndexEntryUpdate<IndexDescriptor>[] someUpdates = layoutUtil.someUpdates(); processAll( someUpdates ); Value[] expectedValues = layoutUtil.extractValuesFromUpdates( someUpdates ); IndexReader reader = accessor.newReader(); IndexQuery.NumberRangePredicate supportedQuery = IndexQuery.range( 0, Double.NEGATIVE_INFINITY, true, Double.POSITIVE_INFINITY, true ); for ( IndexOrder supportedOrder : NumberSchemaIndexProvider.CAPABILITY.orderCapability( ValueGroup.NUMBER ) ) { if ( supportedOrder == IndexOrder.ASCENDING ) { Arrays.sort( expectedValues, Values.COMPARATOR ); } if ( supportedOrder == IndexOrder.DESCENDING ) { Arrays.sort( expectedValues, Values.COMPARATOR.reversed() ); } SimpleNodeValueClient client = new SimpleNodeValueClient(); reader.query( client, supportedOrder, supportedQuery ); int i = 0; while ( client.next() ) { assertEquals( "values in order", expectedValues[i++], client.values[0] ); } assertTrue( "found all values", i == expectedValues.length ); } }

Target:
public void respectIndexOrder() throws Exception { IndexEntryUpdate<IndexDescriptor>[] someUpdates = layoutUtil.someUpdates(); processAll( someUpdates ); Value[] expectedValues = layoutUtil.extractValuesFromUpdates( someUpdates ); IndexReader reader = accessor.newReader(); IndexQuery.NumberRangePredicate supportedQuery = IndexQuery.range( 0, Double.NEGATIVE_INFINITY, true, Double.POSITIVE_INFINITY, true ); for ( IndexOrder supportedOrder : NumberSchemaIndexProvider.CAPABILITY.orderCapability( ValueGroup.NUMBER ) ) { if ( supportedOrder == IndexOrder.ASCENDING ) { Arrays.sort( expectedValues, Values.COMPARATOR ); } if ( supportedOrder == IndexOrder.DESCENDING ) { Arrays.sort( expectedValues, Values.COMPARATOR.reversed() ); } SimpleNodeValueClient client = new SimpleNodeValueClient(); reader.query( client, supportedOrder, supportedQuery ); int i = 0; while ( client.next() ) { assertEquals( "values in order", expectedValues[i++], client.values[0] ); } assertEquals( "found all values", i, expectedValues.length ); } }
Source:
public void testReaderIsNotBrokenWhileWritingFeatureDirectly() throws IOException { int expectedFeatureCount = roadFeatures.length; int currentFeatureCount = 0; FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = memoryDataStore .getFeatureReader( new Query(roadType.getTypeName(), Filter.INCLUDE), transaction); if (featureReader.hasNext()) { featureReader.next(); currentFeatureCount++; } SimpleFeature newFeature = SimpleFeatureBuilder.template(roadType, null); memoryDataStore.addFeature(newFeature); while (featureReader.hasNext()) { featureReader.next(); currentFeatureCount++; } assertEquals("a write in MemoryDataStore should not 'destroy' readers", expectedFeatureCount, currentFeatureCount); }

Target:
public void testReaderIsNotBrokenWhileWritingFeatureDirectly() throws IOException { int expectedFeatureCount = roadFeatures.length; int currentFeatureCount = 0; FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = memoryDataStore .getFeatureReader( new Query(roadType.getTypeName(), Filter.INCLUDE), transaction); if (featureReader.hasNext()) { featureReader.next(); currentFeatureCount++; } SimpleFeature newFeature = SimpleFeatureBuilder.template(roadType, null); memoryDataStore.addFeature(newFeature); assertReaderHasFeatureCount(expectedFeatureCount, currentFeatureCount, featureReader); }
Source:
private static String getProcname(ITmfEvent event) { ITmfEventField field = event.getContent().getField(UstMemoryStrings.CONTEXT_PROCNAME); if (field == null) { return new String(); } return (String) field.getValue(); }

Target:
private static String getProcname(ITmfEvent event) { ITmfEventField field = event.getContent().getField(UstMemoryStrings.CONTEXT_PROCNAME); if (field == null) { return EMPTY_STRING; } return (String) field.getValue(); }
Source:
public void testNullDatasource() throws IOException { Map<DataSegment, SegmentMetadataHolder> segmentsMetadata = schema.getSegmentMetadata(); Set<DataSegment> segments = segmentsMetadata.keySet(); Assert.assertEquals(segments.size(), 3); final DataSegment segmentToRemove = segments.stream().findFirst().orElse(null); Assert.assertFalse(segmentToRemove == null); schema.removeSegment(segmentToRemove); schema.refreshSegments(segments); segmentsMetadata = schema.getSegmentMetadata(); segments = segmentsMetadata.keySet(); Assert.assertEquals(segments.size(), 2); }

Target:
public void testNullDatasource() throws IOException { Map<DataSegment, SegmentMetadataHolder> segmentMetadatas = schema.getSegmentMetadata(); Set<DataSegment> segments = segmentMetadatas.keySet(); Assert.assertEquals(segments.size(), 3); final DataSegment segmentToRemove = segments.stream().filter(segment -> segment.getDataSource().equals("foo2")).findFirst().orElse(null); Assert.assertFalse(segmentToRemove == null); schema.removeSegment(segmentToRemove); schema.refreshSegments(segments); segmentMetadatas = schema.getSegmentMetadata(); segments = segmentMetadatas.keySet(); Assert.assertEquals(segments.size(), 2); }
Source:
private static boolean isUnsuitableOperand(Expression expr) { InferredType tpe = expr.type(); if (isUnsuitableType(tpe)) { if (expr.is(Tree.Kind.NAME)) { Symbol symb = ((Name) expr).symbol(); return symb != null && !isVariableThatCanEscape(symb); } else { return true; } } if (expr.is(Tree.Kind.STRING_LITERAL)) { return true; } else if (expr.is(Tree.Kind.CALL_EXPR)) { Symbol calleeSymbol = ((CallExpression) expr).calleeSymbol(); if (calleeSymbol != null) { String calleeFqn = calleeSymbol.fullyQualifiedName(); return VULNERABLE_CONSTRUCTOR_FQNS.contains(calleeFqn); } else { return false; } } else { return false; } }

Target:
private static boolean isUnsuitableOperand(Expression expr) { InferredType tpe = expr.type(); if (isUnsuitableType(tpe)) { if (expr.is(Tree.Kind.NAME)) { Symbol symb = ((Name) expr).symbol(); return symb != null && !isVariableThatCanEscape(symb); } else { return true; } } if (expr.is(Tree.Kind.STRING_LITERAL)) { return true; } else if (expr.is(Tree.Kind.CALL_EXPR)) { Symbol calleeSymbol = ((CallExpression) expr).calleeSymbol(); if (calleeSymbol != null) { String calleeFqn = calleeSymbol.fullyQualifiedName(); return FQNS_CONSTRUCTORS_RETURNING_UNIQUE_REF.contains(calleeFqn); } } return false; }
Source:
public void testSaveNullData() throws Exception { Document expectedDocument = new Document(); expectedDocument.setId(UUID.randomUUID().toString()); expectedDocument.setTimestamp(System.currentTimeMillis()); expectedDocument.setData(null); queryStore.save(TestUtils.TEST_TABLE_NAME, expectedDocument); }

Target:
public void testSaveNullData() throws Exception { Document expectedDocument = new Document(); expectedDocument.setId(UUID.randomUUID().toString()); expectedDocument.setTimestamp(System.currentTimeMillis()); expectedDocument.setData(null); try { queryStore.save(TestUtils.TEST_TABLE_NAME, expectedDocument); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, e.getErrorCode()); throw e; } }
Source:
public String getInlineComments(int lines) { StringBuilder cmts = new StringBuilder(); final Repository repo = getRepository(); try { final PatchList patchList = repo != null ? getPatchList() : null; Patch.Key currentFileKey = null; PatchFile currentFileData = null; for (final PatchLineComment c : inlineComments) { final Patch.Key pk = c.getKey().getParentKey(); final int lineNbr = c.getLine(); final short side = c.getSide(); if (!pk.equals(currentFileKey)) { cmts.append("....................................................\n"); if (Patch.COMMIT_MSG.equals(pk.get())) { cmts.append("Commit Message\n"); } else { cmts.append("File "); cmts.append(pk.get()); cmts.append("\n"); } currentFileKey = pk; if (patchList != null) { try { currentFileData = new PatchFile(repo, patchList, pk.getFileName()); } catch (IOException e) { } } else { currentFileData = null; } } for (int line = lineNbr - lines + 1; line <= lineNbr; ++line) { appendFileLine(cmts, currentFileData, side, line); } cmts.append(c.getMessage().trim()); cmts.append("\n"); for (int line = lineNbr + 1; line < lineNbr + lines ; ++line) { appendFileLine(cmts, currentFileData, side, line); } cmts.append("\n\n"); } } finally { if (repo != null) { repo.close(); } } return cmts.toString(); }

Target:
public String getInlineComments(int lines) { StringBuilder cmts = new StringBuilder(); final Repository repo = getRepository(); try { final PatchList patchList = repo != null ? getPatchList() : null; Patch.Key currentFileKey = null; PatchFile currentFileData = null; for (final PatchLineComment c : inlineComments) { final Patch.Key pk = c.getKey().getParentKey(); final int lineNbr = c.getLine(); final short side = c.getSide(); if (!pk.equals(currentFileKey)) { cmts.append("....................................................\n"); if (Patch.COMMIT_MSG.equals(pk.get())) { cmts.append("Commit Message\n"); } else { cmts.append("File "); cmts.append(pk.get()); cmts.append("\n"); } currentFileKey = pk; if (patchList != null) { try { currentFileData = new PatchFile(repo, patchList, pk.getFileName()); } catch (IOException e) { } } else { currentFileData = null; } } if (currentFileData != null) { int maxLines; try { maxLines = currentFileData.getLineCount(side); } catch (Throwable e) { maxLines = Integer.MAX_VALUE; } final int startLine = Math.max(1, lineNbr - lines + 1); final int stopLine = Math.min(maxLines, lineNbr + lines); for (int line = startLine; line <= lineNbr; ++line) { appendFileLine(cmts, currentFileData, side, line); } cmts.append(c.getMessage().trim()); cmts.append("\n"); for (int line = lineNbr + 1; line < stopLine; ++line) { appendFileLine(cmts, currentFileData, side, line); } } cmts.append("\n\n"); } } finally { if (repo != null) { repo.close(); } } return cmts.toString(); }
Source:
public void testHetVsArbitrary(final File metricsFile, final double tolerance, final int sampleSize) throws Exception { final MetricsFile Metrics = new MetricsFile(); Metrics.read(new FileReader(metricsFile)); final List<Histogram> histograms = Metrics.getAllHistograms(); final Histogram depthHistogram = histograms.get(0); final Histogram qualityHistogram = histograms.get(1); final double[] qualityDistribution = TheoreticalSensitivity.normalizeHistogram(qualityHistogram); final double[] depthDistribution = TheoreticalSensitivity.normalizeHistogram(depthHistogram); final double resultFromTS = TheoreticalSensitivity.theoreticalSensitivity(depthDistribution, qualityDistribution, sampleSize, 3, 0.5); final double resultFromTHS = TheoreticalSensitivity.hetSNPSensitivity(depthDistribution, qualityDistribution, sampleSize, 3); Assert.assertEquals(resultFromTHS, resultFromTS, tolerance); }

Target:
public void testHetVsArbitrary(final File metricsFile, final double tolerance, final int sampleSize) throws Exception { final MetricsFile Metrics = new MetricsFile(); Metrics.read(new FileReader(metricsFile)); final List<Histogram> histograms = Metrics.getAllHistograms(); final Histogram depthHistogram = histograms.get(0); final Histogram qualityHistogram = histograms.get(1); final double[] qualityDistribution = TheoreticalSensitivity.normalizeHistogram(qualityHistogram); final double[] depthDistribution = TheoreticalSensitivity.normalizeHistogram(depthHistogram); final double resultFromTS = TheoreticalSensitivity.theoreticalSensitivity(depthDistribution, qualityDistribution, sampleSize, 3, 0.5); final double resultFromTHS = TheoreticalSensitivity.hetSNPSensitivity(depthDistribution, qualityDistribution, sampleSize, 3); Assert.assertEquals(resultFromTS, resultFromTHS, tolerance); }
Source:
public IsWidget getFormWidget() { inlineFrame.setWidth("100%"); inlineFrame.setHeight("100%"); inlineFrame.getElement().setPropertyBoolean("webkitallowfullscreen", true); inlineFrame.getElement().setPropertyBoolean("mozallowfullscreen", true); inlineFrame.getElement().setPropertyBoolean("allowfullscreen", true); inlineFrame.getElement().getStyle().setBorderWidth(0, Style.Unit.PX); inlineFrame.getElement().getStyle().setPosition(Position.ABSOLUTE); inlineFrame.getElement().getStyle().setTop(0, Unit.PX); inlineFrame.getElement().getStyle().setLeft(0, Unit.PX); inlineFrame.setUrl(renderingSettings.getUrl()); FlowPanel div = new FlowPanel(); div.getElement().getStyle().setPosition(Position.RELATIVE); div.getElement().getStyle().setOverflow(Overflow.HIDDEN); div.getElement().getStyle().setPaddingTop(40, Unit.PCT); div.add(inlineFrame); return div; }

Target:
public IsWidget getFormWidget() { inlineFrame.setWidth("100%"); inlineFrame.setHeight("100%"); inlineFrame.getElement().setPropertyBoolean("webkitallowfullscreen", true); inlineFrame.getElement().setPropertyBoolean("mozallowfullscreen", true); inlineFrame.getElement().setPropertyBoolean("allowfullscreen", true); inlineFrame.getElement().getStyle().setBorderWidth(0, Style.Unit.PX); inlineFrame.getElement().getStyle().setPosition(Position.ABSOLUTE); inlineFrame.getElement().getStyle().setTop(0, Unit.PX); inlineFrame.getElement().getStyle().setLeft(0, Unit.PX); inlineFrame.setUrl(renderingSettings.getUrl()); FlowPanel div = GWT.create(FlowPanel.class); div.getElement().getStyle().setPosition(Position.RELATIVE); div.getElement().getStyle().setOverflow(Overflow.HIDDEN); div.getElement().getStyle().setPaddingTop(40, Unit.PCT); div.add(inlineFrame); return div; }
Source:
public static StudentCurricularPlan getStudentCurricularPlan(Registration registration, CycleType cycleType) { Optional<StudentCurricularPlan> studentCurricularPlan = registration.getStudentCurricularPlansSet().stream() .filter(scp -> scp.getRoot().getCycleCurriculumGroup(cycleType) != null) .max(StudentCurricularPlan.STUDENT_CURRICULAR_PLAN_COMPARATOR_BY_START_DATE); if (!studentCurricularPlan.isPresent()) { return registration.getLastStudentCurricularPlan(); } else { return studentCurricularPlan.get(); } }

Target:
public static StudentCurricularPlan getStudentCurricularPlan(Registration registration, CycleType cycleType) { Optional<StudentCurricularPlan> studentCurricularPlan = registration.getStudentCurricularPlansSet().stream() .filter(scp -> scp.getRoot().getCycleCurriculumGroup(cycleType) != null) .max(StudentCurricularPlan.STUDENT_CURRICULAR_PLAN_COMPARATOR_BY_START_DATE); return studentCurricularPlan.orElse(registration.getLastStudentCurricularPlan()); }
Source:
void mavenResourcesCanBeLoaded() { MavenBuild build = new MavenBuild(); List<String> includes = Arrays.asList("** *.properties"); build.resource("src/main/resources", (resource) -> { resource.include(includes); resource.targetPath("targetPath"); resource.filtering(false); resource.excludes(excludes); }); Resource resource = build.getResources().get(0); assertThat(resource.getIncludes().get(0)).isEqualTo("** *.properties"); assertThat(resource.isFiltering()).isFalse(); assertThat(resource.getTargetPath()).isEqualTo("targetPath"); assertThat(resource.getDirectory()).isEqualTo("src/main/resources"); }

Target:
void mavenResourcesCanBeLoaded() { MavenBuild build = new MavenBuild(); build.resource("src/main/resources", (resource) -> { resource.include("** *.properties"); }); Resource resource = build.getResources().get(0); assertThat(resource.getIncludes().get(0)).isEqualTo("** *.properties"); assertThat(resource.isFiltering()).isTrue(); assertThat(resource.getTargetPath()).isEqualTo("targetPath"); assertThat(resource.getDirectory()).isEqualTo("src/main/resources"); }
Source:
public Map<TargetEnvironment, P2ResolutionResult> resolveTargetDependencies(TargetPlatform targetPlatform, ReactorProject project) { setContext(targetPlatform, project); if (project != null && PackagingType.TYPE_ECLIPSE_TEST_PLUGIN.equals(project.getPackaging())) { addDependenciesForTests(); } Map<TargetEnvironment, P2ResolutionResult> results = new LinkedHashMap<>(); usedTargetPlatformUnits = new LinkedHashSet<>(); Set<?> metadata = project != null ? project.getDependencyMetadata(true) : Collections.emptySet(); targetLoop: for (TargetEnvironment environment : environments) { for (Object meta : metadata) { if (meta instanceof IInstallableUnit) { IMatchExpression<IInstallableUnit> filter = ((IInstallableUnit) meta).getFilter(); if (filter != null && !filter.isMatch(InstallableUnit.contextIU(environment.toFilterProperties()))) { logger.debug(MessageFormat.format("{0}: {1}", filter, Arrays.toString(filter.getParameters()))); logger.info(MessageFormat.format( "Project {0}:{1}:{2} does not match environment {3} skipp dependecy resolution", project.getGroupId(), project.getArtifactId(), project.getVersion(), environment.toFilterExpression())); continue targetLoop; } } } results.put(environment, resolveDependencies(project, new ProjectorResolutionStrategy(logger), environment)); } context.reportUsedLocalIUs(usedTargetPlatformUnits); usedTargetPlatformUnits = null; return results; }

Target:
public Map<TargetEnvironment, P2ResolutionResult> resolveTargetDependencies(TargetPlatform targetPlatform, ReactorProject project) { setContext(targetPlatform, project); if (project != null && PackagingType.TYPE_ECLIPSE_TEST_PLUGIN.equals(project.getPackaging())) { addDependenciesForTests(); } Map<TargetEnvironment, P2ResolutionResult> results = new LinkedHashMap<>(); usedTargetPlatformUnits = new LinkedHashSet<>(); Set<?> metadata = project != null ? project.getDependencyMetadata(true) : Collections.emptySet(); for (TargetEnvironment environment : environments) { if (isMatchingEnv(metadata, environment)) { results.put(environment, resolveDependencies(project, new ProjectorResolutionStrategy(logger), environment)); } else { logger.info(MessageFormat.format( "Project {0}:{1}:{2} does not match environment {3} skipp dependecy resolution", project.getGroupId(), project.getArtifactId(), project.getVersion(), environment.toFilterExpression())); } } context.reportUsedLocalIUs(usedTargetPlatformUnits); usedTargetPlatformUnits = null; return results; }
Source:
private static String getUrl(final String urlBase, final String filter, final int page, final int perPage, final String orderBy, final OrderDirection direction, final Map<String, Object> extraParams){ final Map<String, String> params = new HashMap<>(); if (UtilMethods.isSet(filter)){ params.put(FILTER, String.valueOf(filter)); } params.put(PER_PAGE, String.valueOf(perPage)); if (page != -1){ params.put(PAGE, String.valueOf(page)); }else{ params.put(PAGE, "pageValue"); } if (UtilMethods.isSet(direction)) { params.put(DIRECTION, direction.toString()); } if (UtilMethods.isSet(orderBy)) { params.put(ORDER_BY, orderBy); } if (extraParams != null) { for (final Map.Entry<String, Object> extraParamsEntry : extraParams.entrySet()) { final Object value = extraParamsEntry.getValue(); if (value != null) { params.put(extraParamsEntry.getKey(), value.toString()); } } } final StringBuilder buffer = new StringBuilder(urlBase); boolean firstParam = true; for (final Map.Entry<String, String> paramsEntry : params.entrySet()) { if (firstParam){ buffer.append('?'); firstParam = false; }else{ buffer.append('&'); } try { final String encode = URLEncoder.encode(paramsEntry.getValue(), "UTF-8"); buffer.append(paramsEntry.getKey()) .append('=') .append(encode); } catch (UnsupportedEncodingException e) { continue; } } return buffer.toString(); }

Target:
private static String getUrl(final String urlBase, final String filter, final int page, final int perPage, final String orderBy, final OrderDirection direction, final Map<String, Object> extraParams){ final Map<String, String> params = new HashMap<>(); if (UtilMethods.isSet(filter)){ params.put(FILTER, String.valueOf(filter)); } params.put(PER_PAGE, String.valueOf(perPage)); params.put (PAGE, (-1 != page) ? String.valueOf(page) : PAGE_VALUE_TEMPLATE); if (UtilMethods.isSet(direction)) { params.put(DIRECTION, direction.toString()); } if (UtilMethods.isSet(orderBy)) { params.put(ORDER_BY, orderBy); } if (extraParams != null) { for (final Map.Entry<String, Object> extraParamsEntry : extraParams.entrySet()) { final Object value = extraParamsEntry.getValue(); if (value != null) { params.put(extraParamsEntry.getKey(), value.toString()); } } } final StringBuilder buffer = new StringBuilder(urlBase); boolean firstParam = true; for (final Map.Entry<String, String> paramsEntry : params.entrySet()) { if (firstParam){ buffer.append('?'); firstParam = false; }else{ buffer.append('&'); } try { final String encode = URLEncoder.encode(paramsEntry.getValue(), "UTF-8"); buffer.append(paramsEntry.getKey()) .append('=') .append(encode); } catch (UnsupportedEncodingException e) { continue; } } return buffer.toString(); }
Source:
public static Collection<Object[]> data() throws Exception { final Collection<DatabaseConfiguration> configurations = DatabaseTestUtil.loadConfigurations(); final Collection<String> schemaPolicies = Arrays.asList( "drop-create", "create-drop", "create", "none" ); final ArrayList<Object[]> data = new ArrayList<>(); for (DatabaseConfiguration configuration : configurations) { for (String schemaPolicy : schemaPolicies) { data.add(new Object[]{configuration, schemaPolicy}); } } return data; }

Target:
public static Collection<Object[]> data() throws Exception { final Collection<DatabaseConfiguration> configurations = DatabaseTestUtil.loadConfigurations(); final Collection<String> schemaPolicies = Arrays.asList( "drop-create", "create-drop", "create", "none" ); final ArrayList<Object[]> data = new ArrayList<>(); for (final DatabaseConfiguration configuration : configurations) { for (final String schemaPolicy : schemaPolicies) { data.add(new Object[]{configuration, schemaPolicy}); } } return data; }
Source:
private Path useBundledMaven() { Path mavenHome = getConfigDirectory(); if (Files.exists(mavenHome)) { log.info("Maven already extracted"); return mavenHome.resolve("apache-maven-3.3.9"); } log.info("Maven bundle not previously extracted, extracting..."); try { InputStream data = getClass().getResourceAsStream("apache-maven-3.3.9.zip"); Preconditions.checkNotNull(data, "Couldn't load bundled maven from tmc-langs-java.jar."); Path tmpFile = File.createTempFile("tmc-maven", "zip").toPath(); Files.copy(data, tmpFile, StandardCopyOption.REPLACE_EXISTING); Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP); archiver.extract(tmpFile.toFile(), mavenHome.toFile()); return mavenHome.resolve("apache-maven-3.3.9"); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private Path useBundledMaven() { Path mavenHome = getConfigDirectory(); if (Files.exists(mavenHome)) { log.info("Maven already extracted"); return mavenHome.resolve("apache-maven-3.3.9"); } log.info("Maven bundle not previously extracted, extracting..."); try { InputStream data = getClass().getResourceAsStream("apache-maven-3.3.9.zip"); Preconditions.checkNotNull( data, "Couldn't load bundled maven from tmc-langs-java.jar."); Path tmpFile = Files.createTempFile("tmc-maven", "zip"); Files.copy(data, tmpFile, StandardCopyOption.REPLACE_EXISTING); Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP); archiver.extract(tmpFile.toFile(), mavenHome.toFile()); try { Files.deleteIfExists(tmpFile); } catch (IOException e) { log.warn("Deleting tmp apache-maven.zip failed", e); } return mavenHome.resolve("apache-maven-3.3.9"); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void download(@Observes MethodExecuted event) { if (isDownloadType(event.getControllerMethod().getMethod().getReturnType())) { logger.debug("Sending a file to the client"); Object result = event.getMethodInfo().getResult(); if (result == null && this.result.used()) return; checkNotNull(result, "You've just returned a Null Download. Consider redirecting to another page/logic"); try (OutputStream output = response.getOutputStream()) { Download download = resolveDownload(result); download.write(response); output.flush(); } catch (IOException e) { throw new RuntimeException(e); } } }

Target:
public void download(@Observes MethodExecuted event) throws IOException { Object methodResult = event.getMethodInfo().getResult(); Download download = resolveDownload(methodResult); if (download != null) { logger.debug("Sending a file to the client"); if (this.result.used()) return; this.result.use(DownloadView.class).of(download); } }