auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static byte[] convertRecordToAvro(Schema schema, Map<String, Object> values) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GenericData.Record record = new GenericData.Record(schema); values.forEach(record::put); try { DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(new GenericDatumWriter<>(schema)); dataFileWriter.create(schema, outputStream); dataFileWriter.append(record); dataFileWriter.close(); } catch (IOException e) { throw new RuntimeException("Failed to convert to AVRO.", e); } return outputStream.toByteArray(); }

Target:
private static byte[] convertRecordToAvro(Schema schema, Map<String, Object> values) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GenericData.Record record = new GenericData.Record(schema); values.forEach(record::put); try (DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(new GenericDatumWriter<>(schema))) { dataFileWriter.create(schema, outputStream); dataFileWriter.append(record); dataFileWriter.close(); } catch (IOException e) { throw new UncheckedIOException("Failed to convert to AVRO.", e); } return outputStream.toByteArray(); }
Source:
public void tearDown() { System.gc(); for (int k = 0; k < testEnv.downloadFileList.size(); k++) { LOGGER.log(Level.INFO, testEnv.downloadFileList.get(k).getParent() + " will now be deleted"); try { FileUtils.deleteDirectory(testEnv.downloadFileList.get(k).getParentFile()); } catch (IOException ex) { Logger.getLogger(WAStorageClientDownloadIT.class.getName()).log(Level.SEVERE, null, ex); } break; } testEnv.downloadFileList.clear(); }

Target:
public void tearDown() throws StorageException { System.gc(); Iterator it = testEnv.downloadFileList.entrySet().iterator(); if (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); File x = (File) pair.getValue(); LOGGER.log(Level.INFO, x.getParent() + " will now be deleted"); try { FileUtils.deleteDirectory(x.getParentFile()); } catch (IOException ex) { Logger.getLogger(WAStorageClientUploadIT.class.getName()).log(Level.SEVERE, null, ex); } } testEnv.downloadFileList.clear(); }
Source:
@VisibleForTesting Call<RbPageSummary> request(@NonNull Service service, @NonNull final WikiSite wiki, @NonNull final Callback cb) { Call<RbPageSummary> call = service.get(); call.enqueue(new retrofit2.Callback<RbPageSummary>() { @Override public void onResponse(@NonNull Call<RbPageSummary> call, @NonNull Response<RbPageSummary> response) { if (response.isSuccessful()) { if (response.body() == null) { cb.onSuccess(call, null); return; } WikipediaApp.getInstance().getWikipediaZeroHandler().onHeaderCheck(response); RbPageSummary item = response.body(); PageTitle title = new PageTitle(null, item.getTitle(), wiki); cb.onSuccess(call, title); } else { L.v(response.message()); cb.onError(call, new IOException(response.message())); } } @Override public void onFailure(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(call, t); } }); return call; }

Target:
@VisibleForTesting Call<RbPageSummary> request(@NonNull Service service, @NonNull final WikiSite wiki, @NonNull final Callback cb) { Call<RbPageSummary> call = service.get(); call.enqueue(new retrofit2.Callback<RbPageSummary>() { @Override public void onResponse(@NonNull Call<RbPageSummary> call, @NonNull Response<RbPageSummary> response) { if (response.isSuccessful()) { if (response.body() == null) { cb.onError(call, new JsonParseException("Response missing required fields")); return; } WikipediaApp.getInstance().getWikipediaZeroHandler().onHeaderCheck(response); RbPageSummary item = response.body(); PageTitle title = new PageTitle(null, item.getTitle(), wiki); cb.onSuccess(call, title); } else { L.v(response.message()); cb.onError(call, new IOException(response.message())); } } @Override public void onFailure(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(call, t); } }); return call; }
Source:
public static Domain domain(byte[] data) { try (JarInputStream jin = new JarInputStream(new ByteArrayInputStream(data))) { return Domain.domain(jin); } catch (Exception e) { throw Exceptions.duck(e); } }

Target:
public static Domain domain(byte[] data) { try (JarInputStream jin = new JarInputStream(new ByteBufferInputStream(data))) { return Domain.domain(jin); } catch (Exception e) { throw Exceptions.duck(e); } }
Source:
public void start() { if (client.getState() != CuratorFrameworkState.STARTED) { client.start(); } if (clusterId != null) { client.getConnectionStateListenable().addListener(connectionStateListener); checkClusterIdExists(clusterId, "start"); } }

Target:
public void start() { if (client.getState() != CuratorFrameworkState.STARTED) { client.start(); if (clusterId != null) { client.getConnectionStateListenable().addListener(connectionStateListener); checkClusterIdExists(clusterId, "start"); } } }
Source:
public void selectInactiveContainersAndMarkInZK(StatsSnapshot statsSnapshot) { primaryAccountService.selectInactiveContainersAndMarkInZK(statsSnapshot); try { secondaryAccountService.selectInactiveContainersAndMarkInZK(statsSnapshot); } catch (Exception e) { logger.warn("Marking containers as inactive failed for secondary", e); accountServiceMetrics.updateContainerInconsistencyCount.inc(); } }

Target:
public void selectInactiveContainersAndMarkInZK(StatsSnapshot statsSnapshot) { primaryAccountService.selectInactiveContainersAndMarkInZK(statsSnapshot); secondaryAccountService.selectInactiveContainersAndMarkInZK(statsSnapshot); }
Source:
public JSONObject toJson() throws JSONException { JSONObject metadata; switch (version) { case ACCOUNT_METADATA_VERSION_1: metadata = new JSONObject(); metadata.put(ACCOUNT_METADATA_VERSION_KEY, version); metadata.put(ACCOUNT_ID_KEY, id); metadata.put(ACCOUNT_NAME_KEY, name); metadata.put(ACCOUNT_STATUS_KEY, status); JSONArray containerArray = new JSONArray(); for (Container container : containerIdToContainerMap.values()) { containerArray.put(container.toJson()); } metadata.put(CONTAINERS_KEY, containerArray); break; default: throw new IllegalArgumentException("Unsupported account metadata version=" + version); } return metadata; }

Target:
public JSONObject toJson() throws JSONException { JSONObject metadata = new JSONObject(); metadata.put(JSON_VERSION_KEY, CURRENT_JSON_VERSION); metadata.put(ACCOUNT_ID_KEY, id); metadata.put(ACCOUNT_NAME_KEY, name); metadata.put(STATUS_KEY, status); JSONArray containerArray = new JSONArray(); for (Container container : containerIdToContainerMap.values()) { containerArray.put(container.toJson()); } metadata.put(CONTAINERS_KEY, containerArray); return metadata; }
Source:
public static KubernetesAuth fromCredentialsId(String credentialsId, String serviceAddress, String caCertData, Boolean skipTlsVerify) throws Exception { StandardCredentials c = getAuthenticationTokenCredentials(credentialsId); if (c != null) { return AuthenticationTokens.convert(KubernetesAuth.class, c); } c = getCredentials(credentialsId); if (c instanceof StringCredentials) { return new KubernetesAuthToken(((StringCredentials) c).getSecret().getPlainText()); } else if (c instanceof TokenProducer) { return new KubernetesAuthToken(((TokenProducer) c).getToken(serviceAddress, caCertData, skipTlsVerify)); } else if (c instanceof UsernamePasswordCredentials) { UsernamePasswordCredentials usernamePassword = (UsernamePasswordCredentials) c; return new KubernetesAuthUsernamePassword( usernamePassword.getUsername(), usernamePassword.getPassword().getPlainText() ); } else if (c instanceof StandardCertificateCredentials) { StandardCertificateCredentials certificateCredentials = (StandardCertificateCredentials) c; KeyStore keyStore = certificateCredentials.getKeyStore(); String password = certificateCredentials.getPassword().getPlainText(); String alias = keyStore.aliases().nextElement(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); return new KubernetesAuthCertificate( Utils.wrapWithMarker( Utils.BEGIN_CERTIFICATE, Utils.END_CERTIFICATE, Base64.encodeBase64String( certificate.getEncoded() ) ), Utils.wrapWithMarker( Utils.BEGIN_PRIVATE_KEY, Utils.END_PRIVATE_KEY, Base64.encodeBase64String( keyStore.getKey(alias, password.toCharArray()).getEncoded() ) ), password ); } else if (c instanceof DockerServerCredentials) { DockerServerCredentials certificateCredentials = (DockerServerCredentials) c; return new KubernetesAuthCertificate(certificateCredentials.getClientCertificate(), certificateCredentials.getClientKey()); } else if (c instanceof FileCredentials) { try (InputStream is = ((FileCredentials) c).getContent()) { return new KubernetesAuthKubeconfig(IOUtils.toString(is, StandardCharsets.UTF_8)); } } else { throw new Exception("Unable to use " + credentialsId + " for authentication"); } }

Target:
public static KubernetesAuth fromCredentialsId(String credentialsId, String serviceAddress, String caCertData, Boolean skipTlsVerify) throws KubernetesAuthException { StandardCredentials c = getAuthenticationTokenCredentials(credentialsId); if (c != null) { return AuthenticationTokens.convert(KubernetesAuth.class, c); } else { throw new KubernetesAuthException("Unable to use " + credentialsId + " for authentication"); } }
Source:
public void testSingleMatch() { writeBulkSets(); Set<Integer> sizeMatch = new HashSet<>(); sizeMatch.add(tenSizesOfMensNikes[2].getID()); sizeMatch.add(eightSizesOfWomensNikes[2].getID()); sizeMatch.add(fiveSizesOfMensVans[2].getID()); List<Integer> matches = storage.getIDsForValue(Shoe.META_SIZE, "3"); Assert.assertEquals("Failed single index match [size][3]", sizeMatch, new HashSet<Integer>(matches)); List<Integer> matchesOnVector = storage.getIDsForValues(new String[]{Shoe.META_SIZE}, new String[] {"3"}); Assert.assertEquals("Failed single vector index match [size][3]", sizeMatch, new HashSet<Integer>(matchesOnVector)); }

Target:
public void testSingleMatch() { writeBulkSets(); Set<Integer> sizeMatch = new HashSet<>(); sizeMatch.add(tenSizesOfMensNikes[2].getID()); sizeMatch.add(eightSizesOfWomensNikes[2].getID()); sizeMatch.add(fiveSizesOfMensVans[2].getID()); List<Integer> matches = storage.getIDsForValue(Shoe.META_SIZE, "3"); Assert.assertEquals("Failed single index match [size][3]", sizeMatch, new HashSet<>(matches)); List<Integer> matchesOnVector = storage.getIDsForValues(new String[]{Shoe.META_SIZE}, new String[] {"3"}); Assert.assertEquals("Failed single vector index match [size][3]", sizeMatch, new HashSet<>(matchesOnVector)); }
Source:
public ReferenceCounter referenceCounter() { return new ReferenceCounter() { @Override public boolean increment() { return ReferenceCountingSegment.this.increment(); } @Override public Closeable decrementOnceCloseable() { return ReferenceCountingSegment.this.decrementOnceCloseable(); } @Override public void decrement() { ReferenceCountingSegment.this.decrement(); } }; }

Target:
public ReferenceCounter referenceCounter() { return this; }
Source:
public int hashCode() { if (hashCode == Utils.NO_HASHCODE) { int accum = 1; accum = accum * Utils.HASH_PRIME + label.hashCode(); accum = accum * Utils.HASH_PRIME + leftHandSide.hashCode(); accum = accum * Utils.HASH_PRIME + rightHandSide.hashCode(); accum = accum * Utils.HASH_PRIME + requires.hashCode(); accum = accum * Utils.HASH_PRIME + ensures.hashCode(); accum = accum * Utils.HASH_PRIME + lookups.hashCode(); accum = accum * Utils.HASH_PRIME + freshConstants.hashCode(); hashCode = accum; } return hashCode; }

Target:
public int hashCode() { int h = hashCode; if (h == Utils.NO_HASHCODE) { h = 1; h = h * Utils.HASH_PRIME + label.hashCode(); h = h * Utils.HASH_PRIME + leftHandSide.hashCode(); h = h * Utils.HASH_PRIME + rightHandSide.hashCode(); h = h * Utils.HASH_PRIME + requires.hashCode(); h = h * Utils.HASH_PRIME + ensures.hashCode(); h = h * Utils.HASH_PRIME + lookups.hashCode(); h = h * Utils.HASH_PRIME + freshConstants.hashCode(); hashCode = h == 0 ? 1 : h; } return h; }
Source:
private String getVmIsBeingRemovedFromExportDomainMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_REMOVED_FROM_EXPORT_DOMAIN.name()); builder.append(String.format("$VmName %1$s", getVmName())); return builder.toString(); }

Target:
private String getVmIsBeingRemovedFromExportDomainMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_REMOVED_FROM_EXPORT_DOMAIN.name()); if (getVmName() != null) { builder.append(String.format("$VmName %1$s", getVmName())); } return builder.toString(); }
Source:
public ValidationResult validateDeletion(Sample object) { ValidationResult result = new ValidationResult(); if (isDetailedSample(object)) { long childCount = sampleStore.getChildSampleCount(object); if (childCount > 0L) { result.addError(new ValidationError(object.getName() + " has " + childCount + " child sample" + (childCount > 1 ? "s" : ""))); } } try { final List<Library> libraries = libraryService.listBySampleId(object.getId()); if (libraries.isEmpty()) { result.addError(new ValidationError(object.getName() + " has " + libraries.size() + " librar" + (libraries.size() > 1 ? "ies" : "y"))); } } catch (IOException e) { log.error("Failed to fetch libraries for " + object.getName(), e); result.addError(new ValidationError("Failed to check for libraries.")); } return result; }

Target:
public ValidationResult validateDeletion(Sample object) throws IOException { ValidationResult result = new ValidationResult(); if (isDetailedSample(object)) { long childCount = sampleStore.getChildSampleCount(object); if (childCount > 0L) { result.addError(new ValidationError(object.getName() + " has " + childCount + " child sample" + (childCount > 1 ? "s" : ""))); } } final int libraries = libraryService.listBySampleId(object.getId()).size(); if (libraries > 0) { result.addError(ValidationError.forDeletionUsage(object, libraries, Pluralizer.libraries(libraries))); } return result; }
Source:
public void defaultPopulatesReactorContext() { this.spring.register(Config.class).autowire(); Authentication currentPrincipal = new TestingAuthenticationToken("user", "password", "ROLE_USER"); WebSessionServerSecurityContextRepository contextRepository = new WebSessionServerSecurityContextRepository(); SecurityContext context = new SecurityContextImpl(currentPrincipal); WebTestClient client = WebTestClientBuilder.bindToWebFilters( (exchange, chain) -> contextRepository.save(exchange, context) .switchIfEmpty(chain.filter(exchange)) .flatMap(e -> chain.filter(exchange)), this.springSecurityFilterChain, (exchange, chain) -> ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .flatMap( principal -> exchange.getResponse() .writeWith(Mono.just(toDataBuffer(principal.getName())))) ).build(); client .get() .uri("/") .headers(headers -> headers.setBasicAuth("user", "password")) .exchange() .expectStatus().isOk() .expectBody(String.class).consumeWith( result -> assertThat(result.getResponseBody()).isEqualTo(currentPrincipal.getName())); }

Target:
public void defaultPopulatesReactorContext() { this.spring.register(Config.class).autowire(); Authentication currentPrincipal = new TestingAuthenticationToken("user", "password", "ROLE_USER"); WebSessionServerSecurityContextRepository contextRepository = new WebSessionServerSecurityContextRepository(); SecurityContext context = new SecurityContextImpl(currentPrincipal); WebTestClient client = WebTestClientBuilder.bindToWebFilters( (exchange, chain) -> contextRepository.save(exchange, context) .switchIfEmpty(chain.filter(exchange)) .flatMap(e -> chain.filter(exchange)), this.springSecurityFilterChain, (exchange, chain) -> ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .flatMap( principal -> exchange.getResponse() .writeWith(Mono.just(toDataBuffer(principal.getName())))) ).build(); client .get() .uri("/") .exchange() .expectStatus().isOk() .expectBody(String.class).consumeWith( result -> assertThat(result.getResponseBody()).isEqualTo(currentPrincipal.getName())); }
Source:
public void callsExecuteOnAccept() { final ExecutorService executor = Mockito.mock(ExecutorService.class); final BkParallel parallel = new BkParallel( Mockito.mock(Back.class), executor ); parallel.accept(Mockito.mock(Socket.class)); Mockito.verify(executor, Mockito.times(1)).execute( Mockito.<Runnable>any() ); }

Target:
public void callsExecuteOnAccept() { final ExecutorService executor = Mockito.mock(ExecutorService.class); final BkParallel parallel = new BkParallel( Mockito.mock(Back.class), executor ); parallel.accept(Mockito.mock(Socket.class)); Mockito.verify(executor).execute( Mockito.<Runnable>any() ); }
Source:
public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item.getItemId() == R.id.action_logout) { doLogout(); } return super.onMenuItemSelected(featureId, item); }

Target:
public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item.getItemId() == R.id.action_logout) { doLogout(); return true; } return super.onMenuItemSelected(featureId, item); }
Source:
public void endToEndSSLTestWithPrefetch() throws InterruptedException, IOException, InstantiationException, URISyntaxException, GeneralSecurityException { DataNodeId dataNodeId = sslCluster.getClusterMap().getDataNodeIds().get(8); ServerTestUtil.endToEndTest(new Port(dataNodeId.getSSLPort(), PortType.SSL), "DC1", "DC2,DC3", sslCluster, clientSSLConfig1, clientSSLSocketFactory1, routerProps, testEncryption); }

Target:
public void endToEndSSLTestWithPrefetch() throws InterruptedException, IOException, InstantiationException, URISyntaxException, GeneralSecurityException { DataNodeId dataNodeId = sslCluster.getPrefetchDataNode(); ServerTestUtil.endToEndTest(new Port(dataNodeId.getSSLPort(), PortType.SSL), "DC1", "DC2,DC3", sslCluster, clientSSLConfig1, clientSSLSocketFactory1, routerProps, testEncryption); }
Source:
public static SpatialRDD<Geometry> createSpatialRDD(JavaRDD rawTextRDD, FormatMapper<Geometry> formatMapper) { SpatialRDD spatialRDD = new SpatialRDD<Geometry>(); spatialRDD.rawSpatialRDD = rawTextRDD.mapPartitions(formatMapper); spatialRDD.fieldNames = formatMapper.readColumnNames(rawTextRDD.take(1).get(0).toString()); return spatialRDD; }

Target:
public static SpatialRDD<Geometry> createSpatialRDD(JavaRDD rawTextRDD, FormatMapper<Geometry> formatMapper) { SpatialRDD spatialRDD = new SpatialRDD<Geometry>(); spatialRDD.rawSpatialRDD = rawTextRDD.mapPartitions(formatMapper); spatialRDD.fieldNames = formatMapper.readPropertyNames(rawTextRDD.take(1).get(0).toString()); return spatialRDD; }
Source:
public void setUp() throws Exception { when(message.getReplyTo()).thenReturn(new Address[]{}); when(message.getListPost()).thenReturn(new Address[]{}); when(message.getFrom()).thenReturn(new Address[]{}); }

Target:
public void setUp() throws Exception { when(message.getReplyTo()).thenReturn(new Address[]{}); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(new String[]{}); when(message.getFrom()).thenReturn(new Address[]{}); }
Source:
protected Span getTracingSpan(String spanName) { if (traceContext == null) { return BlankSpan.INSTANCE; } Tracer tracer = Tracing.getTracer(); BinaryFormat binaryFormat = Tracing.getPropagationComponent().getBinaryFormat(); try { SpanContext spanContext = binaryFormat.fromByteArray(traceContext); Span span = tracer.spanBuilderWithRemoteParent(spanName, spanContext).startSpan(); span.addLink(Link.fromSpanContext(spanContext, Link.Type.PARENT_LINKED_SPAN)); HashMap<String, AttributeValue> map = new HashMap<>(); map.put("tx.thread", AttributeValue.stringAttributeValue(Thread.currentThread().getName())); map.put("bundle.event_count", AttributeValue.longAttributeValue(bundle.size())); map.put("bundle.caller_thread", AttributeValue.stringAttributeValue(callerThread)); span.putAttributes(map); return span; } catch (SpanContextParseException e) { log.warn("Invalid trace context: " + traceContext.length); } return BlankSpan.INSTANCE; }

Target:
protected Span getTracingSpan(String spanName) { if (traceContext == null) { return BlankSpan.INSTANCE; } Tracer tracer = Tracing.getTracer(); BinaryFormat binaryFormat = Tracing.getPropagationComponent().getBinaryFormat(); try { SpanContext spanContext = binaryFormat.fromByteArray(traceContext); Span span = tracer.spanBuilderWithRemoteParent(spanName, spanContext).startSpan(); span.addLink(Link.fromSpanContext(spanContext, Link.Type.PARENT_LINKED_SPAN)); Map<String, AttributeValue> map = new HashMap<>(); map.put("tx.thread", AttributeValue.stringAttributeValue(Thread.currentThread().getName())); map.put("bundle.event_count", AttributeValue.longAttributeValue(bundle.size())); map.put("bundle.caller_thread", AttributeValue.stringAttributeValue(callerThread)); span.putAttributes(map); return span; } catch (SpanContextParseException e) { log.warn("Invalid trace context: " + traceContext.length, e); return BlankSpan.INSTANCE; } }
Source:
public Void doInLock(RedisConnection connection) throws DataAccessException { byte[] wildCard = "*".getBytes(); byte[] prefixToUse = Arrays.copyOf(metadata.getKeyPrefix(), metadata.getKeyPrefix().length + wildCard.length); System.arraycopy(wildCard, 0, prefixToUse, metadata.getKeyPrefix().length, wildCard.length); connection.eval(REMOVE_KEYS_BY_PATTERN_LUA.getBytes(), ReturnType.INTEGER, 0, prefixToUse); return null; }

Target:
public Void doInLock(RedisConnection connection) throws DataAccessException { byte[] prefixToUse = Arrays.copyOf(metadata.getKeyPrefix(), metadata.getKeyPrefix().length + WILD_CARD.length); System.arraycopy(WILD_CARD, 0, prefixToUse, metadata.getKeyPrefix().length, WILD_CARD.length); connection.eval(REMOVE_KEYS_BY_PATTERN_LUA, ReturnType.INTEGER, 0, prefixToUse); return null; }
Source:
public void init() { factory = new DepositStatusFactory(); factory.setJedisPool(jedisPool); jedisPool.getResource().flushAll(); }

Target:
public void init() { factory = new DepositStatusFactory(); factory.setJedisPool(jedisPool); jedisResource = jedisPool.getResource(); jedisResource.flushAll(); }
Source:
private void updateDependency(@NotNull ModifiableRootModel moduleModel, @NotNull JavaModuleDependency dependency) { DependencySetupErrors setupErrors = getSetupErrors(moduleModel.getProject()); String moduleName = dependency.getModuleName(); ModuleManager moduleManager = ModuleManager.getInstance(moduleModel.getProject()); Module found = null; for (Module module : moduleManager.getModules()) { if (moduleName.equals(module.getName())) { found = module; } } if (found != null) { AndroidFacet androidFacet = AndroidFacet.getInstance(found); if (androidFacet == null) { ModuleOrderEntry orderEntry = moduleModel.addModuleOrderEntry(found); orderEntry.setExported(true); } else { IdeaAndroidProject androidProject = androidFacet.getIdeaAndroidProject(); String detail = ""; if (androidProject != null) { String archiveType = "APK"; if (androidProject.isLibrary()) { archiveType = "AAR"; } detail = "resolves to an " + archiveType + " archive which is not supported as compilation dependency."; } setupErrors.addInvalidModuleDependency(moduleModel.getModule(), found.getName(), detail); } return; } setupErrors.addMissingModule(moduleName, moduleModel.getModule().getName(), null); }

Target:
private void updateDependency(@NotNull ModifiableRootModel moduleModel, @NotNull JavaModuleDependency dependency) { DependencySetupErrors setupErrors = getSetupErrors(moduleModel.getProject()); String moduleName = dependency.getModuleName(); ModuleManager moduleManager = ModuleManager.getInstance(moduleModel.getProject()); Module found = null; for (Module module : moduleManager.getModules()) { if (moduleName.equals(module.getName())) { found = module; } } if (found != null) { AndroidFacet androidFacet = AndroidFacet.getInstance(found); if (androidFacet == null) { ModuleOrderEntry orderEntry = moduleModel.addModuleOrderEntry(found); orderEntry.setExported(true); } else { setupErrors.addInvalidModuleDependency(moduleModel.getModule(), found.getName(), "Java modules cannot depend on Android modules"); } return; } setupErrors.addMissingModule(moduleName, moduleModel.getModule().getName(), null); }
Source:
R repositoryFor(String uriString) { return repositoryFor(URI.create(uriString)); }

Target:
public static <R extends DatasetRepository> R repositoryFor(String uriString) { return repositoryFor(URI.create(uriString)); }
Source:
public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); LocalDate expiry = LocalDate.now().plusMonths(2); UserContext context = UserContext.signIn(username, password, network, crypto).get(); boolean isExpired = context.usernameIsExpired().get(); if (isExpired) LOG.info(context.renewUsernameClaim(expiry).get() ? "Renewed username" : "Failed to renew username"); }

Target:
public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); LocalDate expiry = LocalDate.now().plusMonths(2); UserContext context = UserContext.signIn(username, password, network, crypto).get(); boolean isExpired = context.usernameIsExpired().get(); if (isExpired) System.out.println(context.renewUsernameClaim(expiry).get() ? "Renewed username" : "Failed to renew username"); }
Source:
public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { if (fEditGroups == null || fEditGroups.length == 0) return null; CompilationUnitChange result= new CompilationUnitChange(getDisplayString(), fCompilationUnit); for (TextEditGroup fEditGroup : fEditGroups) { String groupName= fEditGroup.getName(); for (TextEdit edit : fEditGroup.getTextEdits()) { TextChangeCompatibility.addTextEdit(result, groupName, edit); } } return result; }

Target:
public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException { if (fEditGroups == null || fEditGroups.length == 0) return null; CompilationUnitChange result= new CompilationUnitChange(getDisplayString(), fCompilationUnit); for (TextEditGroup editGroup : fEditGroups) { String groupName= editGroup.getName(); for (TextEdit edit : editGroup.getTextEdits()) { TextChangeCompatibility.addTextEdit(result, groupName, edit); } } return result; }
Source:
public void testEndToEndFunctionTranslation() { String untranslated = "LN(bitwise_and(1, col1))"; TypeProvider typeProvider = TypeProvider.copyOf(ImmutableMap.of("col1", BIGINT)); CallExpression callExpression = (CallExpression) sqlToRowExpressionTranslator.translate(expression(untranslated), typeProvider); TranslatedExpression translatedExpression = translateWith( callExpression, determinismEvaluator, functionResolution, functionManager, new TestFunctionTranslator(functionManager, buildFunctionTranslator(ImmutableSet.of(TestFunctions.class))), emptyMap()); assertTrue(translatedExpression.getTranslated().isPresent()); assertEquals(translatedExpression.getTranslated().get(), "LNof(1 BITWISE_AND col1)"); }

Target:
public void testEndToEndFunctionTranslation() { String untranslated = "LN(bitwise_and(1, col1))"; TypeProvider typeProvider = TypeProvider.copyOf(ImmutableMap.of("col1", BIGINT)); CallExpression callExpression = (CallExpression) sqlToRowExpressionTranslator.translate(expression(untranslated), typeProvider); TranslatedExpression translatedExpression = translateWith( callExpression, new TestFunctionTranslator(functionManager, buildFunctionTranslator(ImmutableSet.of(TestFunctions.class))), emptyMap()); assertTrue(translatedExpression.getTranslated().isPresent()); assertEquals(translatedExpression.getTranslated().get(), "LNof(1 BITWISE_AND col1)"); }
Source:
public ValueMatcher makeMatcher( BitmapIndexSelector selector, ValueMatcherFactory valueMatcherFactory, RowOffsetMatcherFactory rowOffsetMatcherFactory ) { final List<ValueMatcher> offsetMatchers = new ArrayList<>(); final List<ValueMatcher> valueMatchers = new ArrayList<>(); for (Filter filter : filters) { ValueMatcher matcher = filter.makeMatcher(selector, valueMatcherFactory, rowOffsetMatcherFactory); if (filter.supportsBitmapIndex(selector)) { offsetMatchers.add(matcher); } else { valueMatchers.add(matcher); } } return new ValueMatcher() { @Override public boolean matches() { for (ValueMatcher offsetMatcher : offsetMatchers) { if (!offsetMatcher.matches()) { return false; } } for (ValueMatcher valueMatcher : valueMatchers) { if (!valueMatcher.matches()) { return false; } } return true; } }; }

Target:
public ValueMatcher makeMatcher( BitmapIndexSelector selector, ValueMatcherFactory valueMatcherFactory, RowOffsetMatcherFactory rowOffsetMatcherFactory ) { final List<ValueMatcher> matchers = new ArrayList<>(); final List<ImmutableBitmap> bitmaps = new ArrayList<>(); for (Filter filter : filters) { if (filter.supportsBitmapIndex(selector)) { bitmaps.add(filter.getBitmapIndex(selector)); } else { ValueMatcher matcher = filter.makeMatcher(valueMatcherFactory); matchers.add(matcher); } } if (bitmaps.size() > 0) { ImmutableBitmap combinedBitmap = selector.getBitmapFactory().intersection(bitmaps); ValueMatcher offsetMatcher = rowOffsetMatcherFactory.makeRowOffsetMatcher(combinedBitmap); matchers.add(0, offsetMatcher); } return new ValueMatcher() { @Override public boolean matches() { for (ValueMatcher valueMatcher : matchers) { if (!valueMatcher.matches()) { return false; } } return true; } }; }
Source:
private void addStyling(@NonNull List<Point> pointList) { if (mapboxMap.getStyle() != null) { Style loadedStyle = mapboxMap.getStyle(); List<LineString> innerList = new ArrayList<>(); innerList.add(LineString.fromLngLats(pointList)); List<List<Point>> megaInnerList = new ArrayList<>(); megaInnerList.add(pointList); loadedStyle.addSource(new GeoJsonSource(FILL_SOURCE_ID, Polygon.fromOuterInner(LineString.fromLngLats(OUTER_POLYGON_COORDINATES), innerList))); loadedStyle.addSource(new GeoJsonSource(LINE_SOURCE_ID, Polygon.fromLngLats(megaInnerList))); loadedStyle.addLayerBelow(new FillLayer(FILL_LAYER_ID, FILL_SOURCE_ID).withProperties( fillColor(GREY_COLOR), fillOpacity(FILL_OPACITY)), "road-street"); loadedStyle.addLayer(new LineLayer(LINE_LAYER_ID, LINE_SOURCE_ID).withProperties( lineColor(RED_COLOR), lineWidth(LINE_WIDTH), lineCap(Property.LINE_CAP_ROUND), lineJoin(Property.LINE_JOIN_ROUND) )); mapboxMap.animateCamera( CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder() .zoom(11) .build()), 3000); } }

Target:
private void addStyling(@NonNull List<Point> pointList) { mapboxMap.getStyle(new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style loadedStyle) { List<LineString> innerList = new ArrayList<>(); LineString innerLineString = LineString.fromLngLats(pointList); innerList.add(innerLineString); loadedStyle.addSource(new GeoJsonSource(FILL_SOURCE_ID, Polygon.fromOuterInner(LineString.fromLngLats(OUTER_POLYGON_COORDINATES), innerList))); loadedStyle.addSource(new GeoJsonSource(LINE_SOURCE_ID, innerLineString)); loadedStyle.addLayerBelow(new FillLayer(FILL_LAYER_ID, FILL_SOURCE_ID).withProperties( fillColor(GREY_COLOR), fillOpacity(FILL_OPACITY)), "road-street"); loadedStyle.addLayer(new LineLayer(LINE_LAYER_ID, LINE_SOURCE_ID).withProperties( lineColor(RED_COLOR), lineWidth(LINE_WIDTH), lineCap(Property.LINE_CAP_ROUND), lineJoin(Property.LINE_JOIN_ROUND) )); } }); }
Source:
public void nullWriteTest() throws Exception { String fname="~benchmark::all_types::200kb"; HPCCFile file = new HPCCFile(fname, connString, hpccUser, hpccPass); file.setProjectList(""); List<HPCCRecord> records = readFile(file); assertEquals( "Record count mismatch for dataset:" + fname + ". got: " + records.size() + " expected:" + 5600,5600,records.size()); HPCCRecord first = records.get(0); for (int f = 0; f < first.getNumFields(); f++) { first.setField(f, null); } String copyFileName = fname + "_copy"; writeFile(records, copyFileName, file.getProjectedRecordDefinition()); file = new HPCCFile(copyFileName, connString, hpccUser, hpccPass); records = readFile(file); assertEquals( "Record count mismatch for dataset:" + copyFileName + ". got: " + records.size() + " expected:" + 5600,5600,records.size()); HPCCRecord rec0 = records.get(0); for (int i = 0; i < rec0.getNumFields(); i++) { Object field = rec0.getField(0); if (field instanceof Long) { assertEquals((Long) field, new Long(0)); } else if (field instanceof Double) { assertEquals((Double) field, new Double(0.0)); } else if (field instanceof Boolean) { assertEquals((Boolean) field, new Boolean(false)); } else if (field instanceof String) { assertEquals((String) field, ""); } else if (field instanceof BigDecimal) { assertEquals(((BigDecimal) field).intValue(),0); } else if (field instanceof List) { assertEquals(((List) field).size(),0); } } }

Target:
public void nullWriteTest() throws Exception { String fname = datasets[1]; HPCCFile file = new HPCCFile(fname, connString, hpccUser, hpccPass); file.setProjectList(""); List<HPCCRecord> records = readFile(file); assertEquals( "Record count mismatch for dataset:" + fname + ". got: " + records.size() + " expected:" + expectedCounts[1],expectedCounts[1],records.size()); HPCCRecord first = records.get(0); for (int f = 0; f < first.getNumFields(); f++) { first.setField(f, null); } String copyFileName = fname + "_copy"; writeFile(records, copyFileName, file.getProjectedRecordDefinition()); file = new HPCCFile(copyFileName, connString, hpccUser, hpccPass); records = readFile(file); assertEquals( "Record count mismatch for dataset:" + copyFileName + ". got: " + records.size() + " expected:" + 5600,5600,records.size()); HPCCRecord rec0 = records.get(0); for (int i = 0; i < rec0.getNumFields(); i++) { Object field = rec0.getField(0); if (field instanceof Long) { assertEquals((Long) field, new Long(0)); } else if (field instanceof Double) { assertEquals((Double) field, new Double(0.0)); } else if (field instanceof Boolean) { assertEquals((Boolean) field, new Boolean(false)); } else if (field instanceof String) { assertEquals((String) field, ""); } else if (field instanceof BigDecimal) { assertEquals(((BigDecimal) field).intValue(),0); } else if (field instanceof List) { assertEquals(((List) field).size(),0); } } }
Source:
public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { rmId = (rmId == null) ? "" : ("." + rmId); InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } LOG.info("rm webapp address setting {}", address); LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); address = NetUtils.getConnectAddress(address); InetAddress resolved = address.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { address = new InetSocketAddress(InetAddress.getLocalHost(), address.getPort()); } catch (UnknownHostException e) { } } return address; }

Target:
public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { rmId = (rmId == null) ? "" : ("." + rmId); InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } LOG.info("rm webapp address setting {}", address); LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address); InetAddress resolved = resolvedSocketAddress.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { resolvedSocketAddress = InetSocketAddress.createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort()); } catch (UnknownHostException e) { } } return resolvedSocketAddress; }
Source:
public Config getConfig() { try { InputStream in = new FileInputStream(path); Properties props = new Properties(); props.load(in); in.close(); LOG.debug("got config from config {}", props, path); return new MapConfig(props); } catch (IOException e) { throw new SamzaException("Failed to read from"); } }

Target:
public Config getConfig() { try { InputStream in = new FileInputStream(path); Properties props = new Properties(); props.load(in); in.close(); LOG.debug("got config from path {}", props, path); Map<String, String> config = new HashMap<>(props.size()); props.forEach((key, value) -> config.put(key.toString(), value.toString())); return new MapConfig(config); } catch (IOException e) { throw new SamzaException("Failed to read from " + path); } }
Source:
protected AxonServerConnectionManager(Builder builder) { builder.validate(); this.axonServerConfiguration = builder.axonServerConfiguration; this.tagsConfiguration = builder.tagsConfiguration; this.scheduler = builder.scheduler; onOutboundInstruction(NODE_NOTIFICATION, instruction -> logger.debug("Received: {}", instruction.getNodeNotification())); handlers.register(RESULT, (instruction, stream) -> logger .trace("Received instruction result {}.", instruction.getResult())); }

Target:
protected AxonServerConnectionManager(Builder builder) { builder.validate(); this.axonServerConfiguration = builder.axonServerConfiguration; this.tagsConfiguration = builder.tagsConfiguration; this.scheduler = builder.scheduler; this.requestStreamFactory = builder.requestStreamFactory; this.instructionAckSource = builder.instructionAckSource; onOutboundInstruction(NODE_NOTIFICATION, (instruction, stream) -> logger.debug("Received: {}", instruction.getNodeNotification())); handlers.register(ACK, (instruction, stream) -> { if (isUnsupportedInstructionErrorAck(instruction.getAck())) { logger.warn("Unsupported instruction sent to the server. {}", instruction.getAck()); } else { logger.trace("Received instruction ack {}.", instruction.getAck()); } }); }
Source:
public void write(Enriched<EntityType> enrichable, JsonGenerator jg) { try (TokenBuffer tb = new TokenBuffer(MAPPER, false)) { tb.writeStartObject(); write(tb, enrichable.getEntity()); tb.writeEndObject(); tb.flush(); try (JsonParser parser = tb.asParser()) { parser.nextToken(); while (parser.nextToken() == FIELD_NAME) { jg.copyCurrentStructure(parser); } if (parser.currentToken() != END_OBJECT) { log.error("Enricher: failed on current token: {}, output to write: {}", name, parser.currentToken(), MAPPER.readTree(tb.asParser())); } } } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } else { log.info("Enricher failed", name, e); } } }

Target:
public void write(Enriched<EntityType> enrichable, JsonGenerator jg) { try (TokenBuffer tb = new TokenBuffer(MAPPER, false)) { tb.writeStartObject(); write(tb, enrichable.getEntity()); tb.writeEndObject(); tb.flush(); try (JsonParser parser = tb.asParser()) { parser.nextToken(); while (parser.nextToken() == FIELD_NAME) { jg.copyCurrentStructure(parser); } if (parser.currentToken() != END_OBJECT) { log.error("Enricher: failed on current token: {}, output to write: {}", name::toString, parser::currentToken, () -> safeReadBuffer(tb)); } } } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } else { log.info("Enricher: failed", name, e); } } }
Source:
public void initializeHardDeleteMetric(final HardDeleter hardDeleter, final Log log) { currentHardDeleteProgress = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.getProgress(); } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "CurrentHardDeleteProgress"), currentHardDeleteProgress); percentageHardDeleteCompleted = new Gauge<Double>() { @Override public Double getValue() { return ((double) hardDeleter.getProgress() / log.getLogEndOffset()) * 100; } }; registry.register(MetricRegistry.name(Log.class, name + "PercentageHardDeleteCompleted"), percentageHardDeleteCompleted); hardDeleteThreadRunning = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.hardDeleteThreadRunning() ? 1L : 0L; } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "HardDeleteThreadRunning"), hardDeleteThreadRunning); hardDeleteCaughtUp = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.isCaughtUp() ? 1L : 0L; } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "HardDeleteCaughtUp"), hardDeleteCaughtUp); }

Target:
public void initializeHardDeleteMetric(final HardDeleter hardDeleter, final Log log) { currentHardDeleteProgress = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.getProgress(); } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "CurrentHardDeleteProgress"), currentHardDeleteProgress); percentageHardDeleteCompleted = new Gauge<Double>() { @Override public Double getValue() { return ((double) hardDeleter.getProgress() / log.getLogEndOffset()) * 100; } }; registry.register(MetricRegistry.name(Log.class, name + "PercentageHardDeleteCompleted"), percentageHardDeleteCompleted); hardDeleteThreadRunning = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.isRunning() ? 1L : 0L; } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "HardDeleteThreadRunning"), hardDeleteThreadRunning); hardDeleteCaughtUp = new Gauge<Long>() { @Override public Long getValue() { return hardDeleter.isCaughtUp() ? 1L : 0L; } }; registry.register(MetricRegistry.name(PersistentIndex.class, name + "HardDeleteCaughtUp"), hardDeleteCaughtUp); }
Source:
public Iterable<EntryKey> list() { ImmutableSet.Builder<EntryKey> result = ImmutableSet.builder(); for (String section : sec.getSections()) { for (String subsection : sec.getSubsections(section)) { for (String name : sec.getNames(section, subsection)) { result.add(new EntryKey(section, subsection, name)); } } for (String name : sec.getNames(section)) { result.add(new EntryKey(section, null, name)); } } return result.build(); }

Target:
public Iterable<EntryKey> list() { List<EntryKey> result = new ArrayList<>(); for (String section : sec.getSections()) { for (String subsection : sec.getSubsections(section)) { for (String name : sec.getNames(section, subsection)) { result.add(new EntryKey(section, subsection, name)); } } for (String name : sec.getNames(section)) { result.add(new EntryKey(section, null, name)); } } return result; }
Source:
private void validateNumSegments(Map<ServerInstance, List<String>> offlineRoutingTable, Map<ServerInstance, List<String>> realtimeRoutingTable, int querySegmentLimit) { int numOffline = offlineRoutingTable == null ? 0 : offlineRoutingTable.values().stream().mapToInt(List::size).sum(); int numRealtime = realtimeRoutingTable == null ? 0 : realtimeRoutingTable.values().stream().mapToInt(List::size).sum(); int numSegments = numOffline + numRealtime; if (numSegments > querySegmentLimit) { throw new IllegalStateException(String.format("Query exceeds segment limit of %d", querySegmentLimit)); } }

Target:
private void validateNumSegments(Map<ServerInstance, List<String>> offlineRoutingTable, Map<ServerInstance, List<String>> realtimeRoutingTable, int querySegmentLimit) { if (_querySegmentLimit > 0) { int numOffline = offlineRoutingTable == null ? 0 : offlineRoutingTable.values().stream().mapToInt(List::size).sum(); int numRealtime = realtimeRoutingTable == null ? 0 : realtimeRoutingTable.values().stream().mapToInt(List::size).sum(); int numSegments = numOffline + numRealtime; if (numSegments > querySegmentLimit) { throw new IllegalStateException(String.format("Query exceeds segment limit of %d", querySegmentLimit)); } } }
Source:
public void accept(String json, Context context) throws RuntimeException { JsonObject body = gsonParser.fromJson(json, JsonObject.class); JsonObject fields = body.getAsJsonObject("value").getAsJsonObject("fields"); if (!fields.has("original")) { return; } String currentValue = fields.getAsJsonObject("original").get("stringValue").getAsString(); String newValue = currentValue.toUpperCase(); Map<String, String> newFields = new HashMap<>(); newFields.put("original", newValue); String affectedDoc = context.resource().split("/documents/")[1].replace("\"", ""); LOGGER.info(String.format("Replacing value: %s --> %s", currentValue, newValue)); try { firestore.document(affectedDoc).set(newFields, SetOptions.merge()).get(); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void accept(String json, Context context) throws RuntimeException { JsonObject body = gsonParser.fromJson(json, JsonObject.class); JsonObject tempJson = body.getAsJsonObject("value"); String currentValue = null; if (tempJson != null) { tempJson = tempJson.getAsJsonObject("fields"); } if (tempJson != null) { tempJson = tempJson.getAsJsonObject("original"); } if (tempJson != null && tempJson.has("stringValue")) { currentValue = tempJson.get("stringValue").getAsString(); } if (currentValue == null) { throw new IllegalArgumentException("Malformed JSON"); } String newValue = currentValue.toUpperCase(); Map<String, String> newFields = new HashMap<>(); newFields.put("original", newValue); String affectedDoc = context.resource().split("/documents/")[1].replace("\"", ""); LOGGER.info(String.format("Replacing value: %s --> %s", currentValue, newValue)); try { firestore.document(affectedDoc).set(newFields, SetOptions.merge()).get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } }
Source:
private void unit1() { when(unit1.getType()).thenReturn(mockUnit1Type); when(mockUnit1Type.getAttachment(anyString())).thenReturn(mockUnit1Attachment); }

Target:
private void unit1() { when(unit1.getType()).thenReturn(unit1Type); when(unit1Type.getAttachment(anyString())).thenReturn(unit1Attachment); }