auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void handleBackupWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { handleBackupWallet(); } } }); return; } if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) showBackupWalletDialog = true; else ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_BACKUP_WALLET); }

Target:
public void handleBackupWallet() { final WalletLock walletLock = WalletLock.getInstance(); if (WalletLock.getInstance().isWalletLocked(wallet)) { UnlockWalletDialogFragment.show(getSupportFragmentManager(), new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!walletLock.isWalletLocked(wallet)) { handleBackupWallet(); } } }); return; } if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) BackupWalletDialogFragment.show(getSupportFragmentManager()); else ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_BACKUP_WALLET); }
Source:
public static BinaryData fromObject(Object data) { Objects.requireNonNull(data, "'data' cannot be null."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonSerializerProviders.createInstance().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }

Target:
public static BinaryData fromObject(Object data) { if (Objects.isNull(data)) { return EMPTY_DATA; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getDefaultSerializer().serialize(outputStream, data); return new BinaryData(outputStream.toByteArray()); }
Source:
private void addRecentPage(int page, boolean shouldDelete) { ContentValues contentValues = new ContentValues(); contentValues.put(LastPagesTable.PAGE, page); contentValues.put(LastPagesTable.ADDED_DATE, System.currentTimeMillis() / 1000); if (db.replace(LastPagesTable.TABLE_NAME, null, contentValues) != -1 && shouldDelete) { db.execSQL("DELETE FROM " + LastPagesTable.TABLE_NAME + " WHERE " + LastPagesTable.ID + " NOT IN( SELECT " + LastPagesTable.ID + " FROM " + LastPagesTable.TABLE_NAME + " ORDER BY " + LastPagesTable.ADDED_DATE + " DESC LIMIT ? )", new Object[] { Constants.MAX_RECENT_PAGES }); } }

Target:
private void addRecentPage(int page, boolean shouldDelete) { ContentValues contentValues = new ContentValues(); contentValues.put(LastPagesTable.PAGE, page); if (db.replace(LastPagesTable.TABLE_NAME, null, contentValues) != -1 && shouldDelete) { db.execSQL("DELETE FROM " + LastPagesTable.TABLE_NAME + " WHERE " + LastPagesTable.ID + " NOT IN( SELECT " + LastPagesTable.ID + " FROM " + LastPagesTable.TABLE_NAME + " ORDER BY " + LastPagesTable.ADDED_DATE + " DESC LIMIT ? )", new Object[] { Constants.MAX_RECENT_PAGES }); } }
Source:
public void start() { queueModeHelper.initialize(); queueModeHelper.createServer((int) queueModeHelper.awaketime * 1000); queueModeHelper.server.start(); queueModeHelper.createClient(); }

Target:
public void start() { queueModeHelper.initialize(); queueModeHelper.createServer((int) awaketime * 1000); queueModeHelper.server.start(); queueModeHelper.createClient(); }
Source:
public void testGetDocContent_excludedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar", "filenet.excludedMetadata", "bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), mockProperty("bar", "barValue")), new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata(ImmutableMap.of("foo", "fooValue").entrySet()), response.getMetadata()); }

Target:
public void testGetDocContent_excludedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar", "filenet.excludedMetadata", "bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), mockProperty("bar", "barValue"), mockProperty("baz", "bazValue")), new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata(ImmutableMap.of("foo", "fooValue").entrySet()), response.getMetadata()); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || !(o instanceof RyaType)) { return false; } final RyaType ryaType = (RyaType) o; if (data != null ? !data.equals(ryaType.data) : ryaType.data != null) { return false; } return dataType != null ? dataType.equals(ryaType.dataType) : ryaType.dataType == null; }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || !(o instanceof RyaType)) { return false; } final RyaType other = (RyaType) o; final EqualsBuilder builder = new EqualsBuilder() .append(getData(), other.getData()) .append(getDataType(), other.getDataType()); return builder.isEquals(); }
Source:
private boolean sortToRelationshipGroups(SnomedConcepts referencedComponents, String relationshipTypeId) { Map<Integer, Integer> groupsAndCounts = Maps.newHashMap(); AtomicBoolean occoursAsUngrouped = new AtomicBoolean(false); AtomicBoolean noOccurance = new AtomicBoolean(false); referencedComponents.getItems().stream() .forEach(concept -> { AtomicInteger i = new AtomicInteger(); concept.getRelationships().getItems().stream() .filter(relationship -> relationship.getType().getId().equals(relationshipTypeId)) .forEach(relationship -> { if (relationship.getGroup() == 0) { occoursAsUngrouped.set(true); } else { groupsAndCounts.merge(relationship.getGroup(), 1, (key, oldValue) -> oldValue + 1 ); } i.incrementAndGet(); }); if (i.get() == 1) { noOccurance.set(true); } groupsAndCounts.entrySet().stream().forEach(entry -> { groupedRelationships.compute(entry.getKey(), (key, oldValue) -> { LinkedHashMap<String, Integer> relationshipTypeOccurence = ofNullable(oldValue).orElseGet(LinkedHashMap::new); relationshipTypeOccurence.merge(relationshipTypeId, entry.getValue(), (innerKey, innerOldValue) -> Math.max(innerOldValue, entry.getValue())); return relationshipTypeOccurence; }); }); } ); return occoursAsUngrouped.get() || noOccurance.get(); }

Target:
private boolean sortToRelationshipGroups(SnomedConcepts referencedComponents, String relationshipTypeId) { Map<Integer, Integer> groupsAndCounts = Maps.newHashMap(); AtomicBoolean occursAsUngrouped = new AtomicBoolean(false); AtomicBoolean noOccurance = new AtomicBoolean(false); referencedComponents.getItems().stream() .forEach(concept -> { AtomicInteger i = new AtomicInteger(); concept.getRelationships().getItems().stream() .filter(relationship -> relationship.getType().getId().equals(relationshipTypeId)) .forEach(relationship -> { if (relationship.getGroup() == 0) { occursAsUngrouped.set(true); } else { groupsAndCounts.merge(relationship.getGroup(), 1, (key, oldValue) -> oldValue + 1 ); } i.incrementAndGet(); }); if (i.get() == 1) { noOccurance.set(true); } groupsAndCounts.entrySet().stream().forEach(entry -> { groupedRelationships.compute(entry.getKey(), (key, oldValue) -> { LinkedHashMap<String, Integer> relationshipTypeOccurence = ofNullable(oldValue).orElseGet(LinkedHashMap::new); relationshipTypeOccurence.merge(relationshipTypeId, entry.getValue(), (innerKey, innerOldValue) -> Math.max(innerOldValue, entry.getValue())); return relationshipTypeOccurence; }); }); } ); return occursAsUngrouped.get() || noOccurance.get(); }
Source:
public static Principal[] getGrantedRoles(SecurityIdentity securityIdentity) { Set<String> roles = new HashSet<>(); for (String s : securityIdentity.getRoles("ejb")) { roles.add(s); } List<Principal> list = new ArrayList<>(); Function<String, Principal> mapper = roleName -> (Principal) () -> roleName; for (String role : roles) { Principal principal = mapper.apply(role); list.add(principal); } return list.toArray(new Principal[0]); }

Target:
public static Principal[] getGrantedRoles(SecurityIdentity securityIdentity) { Set<String> roles = new HashSet<>(); for (String s : securityIdentity.getRoles("ejb")) { roles.add(s); } List<Principal> list = new ArrayList<>(); Function<String, Principal> mapper = roleName -> (Principal) () -> roleName; for (String role : roles) { Principal principal = mapper.apply(role); list.add(principal); } return list.toArray(NO_PRINCIPALS); }
Source:
public final void testSessionVariables() throws IOException, TajoException, InterruptedException { String prefixName = "key_"; String prefixValue = "val_"; List<String> unsetList = client.getAllSessionVariables().entrySet().stream() .map(Map.Entry<String, String>::getKey).collect(Collectors.toList()); client.unsetSessionVariables(unsetList); for (int i = 0; i < 10; i++) { String key = prefixName + i; String val = prefixValue + i; assertEquals(i + 4, client.getAllSessionVariables().size()); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); Map<String, String> map = Maps.newHashMap(); map.put(key, val); client.updateSessionVariables(map); assertEquals(i + 5, client.getAllSessionVariables().size()); assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); } int totalSessionVarNum = client.getAllSessionVariables().size(); for (int i = 0; i < 10; i++) { String key = prefixName + i; assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); client.unsetSessionVariables(Lists.newArrayList(key)); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); } assertEquals(totalSessionVarNum - 10, client.getAllSessionVariables().size()); }

Target:
public final void testSessionVariables() throws IOException, TajoException, InterruptedException { String prefixName = "key_"; String prefixValue = "val_"; List<String> unsetList = new ArrayList<>(client.getAllSessionVariables().keySet()); client.unsetSessionVariables(unsetList); for (int i = 0; i < 10; i++) { String key = prefixName + i; String val = prefixValue + i; assertEquals(i + 4, client.getAllSessionVariables().size()); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); Map<String, String> map = Maps.newHashMap(); map.put(key, val); client.updateSessionVariables(map); assertEquals(i + 5, client.getAllSessionVariables().size()); assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); } int totalSessionVarNum = client.getAllSessionVariables().size(); for (int i = 0; i < 10; i++) { String key = prefixName + i; assertTrue(client.getAllSessionVariables().containsKey(key)); assertTrue(client.existSessionVariable(key)); client.unsetSessionVariables(Lists.newArrayList(key)); assertFalse(client.getAllSessionVariables().containsKey(key)); assertFalse(client.existSessionVariable(key)); } assertEquals(totalSessionVarNum - 10, client.getAllSessionVariables().size()); }
Source:
public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { if (certificateVerifier == null) { AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Certificate chain could not be validated", alert); } certificateVerifier.verifyCertificate(message, session); } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }

Target:
public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { certificateVerifier.verifyCertificate(message, session); } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }
Source:
public List<Concept> get(String targetTable, String targetField) { if (!this.containsKey(targetTable, targetField)) { return null; } return this.conceptMap.get(targetTable).get(targetField); }

Target:
public List<Concept> get(String targetTable, String targetField) { return conceptMap.getOrDefault(targetTable, Collections.emptyMap()).get(targetField); }
Source:
ClusteredStateRepository(ClusteringService.ClusteredCacheIdentifier clusterCacheIdentifier, String id, EhcacheClientEntity clientEntity) { this.clusterCacheIdentifier = clusterCacheIdentifier; this.clientEntity = clientEntity; }

Target:
ClusteredStateRepository(ClusteringService.ClusteredCacheIdentifier clusterCacheIdentifier, String id, EhcacheClientEntity clientEntity) { this.clusterCacheIdentifier = clusterCacheIdentifier; this.composedId = clusterCacheIdentifier.getId() + "-" + id; this.clientEntity = clientEntity; }
Source:
public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return Objects.equal(input.getId(), val); } }; }

Target:
public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getId(), val); } }; }
Source:
public Object processInvocation(final InterceptorContext context) throws Exception { latch.countDown(); return context.proceed(); }

Target:
public Object processInvocation(final InterceptorContext context) throws Exception { countdown.markAsPrivileged(); try { return context.proceed(); } finally { countdown.unmarkAsPrivileged(); countdown.countDown(); } }
Source:
public Boolean verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> client.verify(algorithm, digest, signature, context)).block(); }

Target:
public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); }
Source:
public void addAssetSource(AssetSource newSource) { String idKey = newSource.getSourceId().toLowerCase(Locale.ENGLISH); AssetSource originalSource = assetSources.get(idKey); if (null == originalSource) { assetSources.put(idKey, newSource); for (AssetUri asset : newSource.list()) { uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } } else { AssetSourceCollection combinedSource = new AssetSourceCollection(idKey, originalSource, newSource); assetSources.put(idKey, combinedSource); for (AssetUri asset : newSource.list()) { uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } } }

Target:
public void addAssetSource(AssetSource newSource) { String idKey = newSource.getSourceId().toLowerCase(Locale.ENGLISH); AssetSource originalSource = assetSources.get(idKey); if (null == originalSource) { assetSources.put(idKey, newSource); } else { AssetSourceCollection combinedSource = new AssetSourceCollection(idKey, originalSource, newSource); assetSources.put(idKey, combinedSource); } for (AssetUri asset : newSource.list()) { uriLookup.get(asset.getAssetType()).put(asset.getNormalisedAssetName(), asset.getNormalisedModuleName(), asset); } }
Source:
public void addFieldsFromClient(SolrClient client) { if (client == null) { LOGGER.debug("Solr client is null, could not add fields to cache."); return; } SolrQuery query = new SolrQuery(); query.add("numterms", "0"); query.setRequestHandler("/admin/luke"); try { QueryResponse response = client.query(query); NamedList<?> fields = (SimpleOrderedMap<?>) (response.getResponse().get(FIELDS_KEY)); if (fields != null) { for (Entry<String, ?> e : fields) { if (e != null) { fieldsCache.add(e.getKey()); if (e.getKey().endsWith(SchemaFields.TEXT_SUFFIX)) { anyTextFieldsCache.add(e.getKey()); } } } } } catch (SolrServerException | SolrException | IOException e) { LOGGER.info("Could not update cache for field names.", e); } }

Target:
public void addFieldsFromClient(SolrClient client) { if (client == null) { LOGGER.debug("Solr client is null, could not add fields to cache."); return; } SolrQuery query = new SolrQuery(); query.add("numterms", "0"); query.setRequestHandler("/admin/luke"); QueryResponse response; try { response = client.query(query); } catch (SolrServerException | SolrException | IOException e) { LOGGER.info("Could not update cache for field names.", e); return; } NamedList<?> fields = (SimpleOrderedMap<?>) (response.getResponse().get(FIELDS_KEY)); if (fields == null) { return; } for (Entry<String, ?> e : fields) { String key = e.getKey(); fieldsCache.add(key); if (key.endsWith(SchemaFields.TEXT_SUFFIX)) { anyTextFieldsCache.add(key); } } }
Source:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(1), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("max(1, ?) > 1", BigDecimal.valueOf(2), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("? = 2", BigDecimal.valueOf(2), BigDecimal.class)); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); }

Target:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(1), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("abs(-1)", BigDecimal.valueOf(-1), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("max(1, ?) > 1", BigDecimal.valueOf(2), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("max(1, ?) < 1", BigDecimal.valueOf(2), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("? = 2", BigDecimal.valueOf(2), BigDecimal.class)); assertFalse(expressionEvaluator.evaluateUnaryExpression("? > 2", BigDecimal.valueOf(2), BigDecimal.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression("? + 1 > ?", BigDecimal.valueOf(2), BigDecimal.class)); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("? > 2", null, BigDecimal.class)) .isInstanceOf(NullPointerException.class); }
Source:
public FailoverFeignTarget(Collection<String> servers, Class<T> type, BackoffStrategy backoffStrategy) { this.servers = ImmutableList.copyOf(servers); this.type = type; this.backoffStrategy = backoffStrategy; }

Target:
public FailoverFeignTarget(Collection<String> servers, Class<T> type, BackoffStrategy backoffStrategy) { List<String> shuffledServers = new ArrayList<>(servers); Collections.shuffle(shuffledServers); this.servers = ImmutableList.copyOf(shuffledServers); this.type = type; this.backoffStrategy = backoffStrategy; }
Source:
public void stop() throws Exception { }

Target:
public void stop() throws Exception { stop(false); }
Source:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { ThriftIndexHandle thriftIndexHandle = (ThriftIndexHandle) indexHandle; return new ThriftConnectorIndex(clientProvider, thriftIndexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }

Target:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { return new ThriftConnectorIndex(clientProvider, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }
Source:
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) { Map<String, BinderType> binderTypes = new HashMap<>(); ClassLoader classLoader = configurableApplicationContext.getClassLoader(); if (classLoader == null) { classLoader = BinderFactoryConfiguration.class.getClassLoader(); } try { Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders"); if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) { throw new BeanCreationException("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath"); } while (resources.hasMoreElements()) { URL url = resources.nextElement(); UrlResource resource = new UrlResource(url); for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) { if (!binderType.getDefaultName().equalsIgnoreCase("test")) { binderTypes.put(binderType.getDefaultName(), binderType); } } } } catch (IOException | ClassNotFoundException e) { throw new BeanCreationException("Cannot create binder factory:", e); } return new DefaultBinderTypeRegistry(binderTypes); }

Target:
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) { Map<String, BinderType> binderTypes = new HashMap<>(); ClassLoader classLoader = configurableApplicationContext.getClassLoader(); if (classLoader == null) { classLoader = BinderFactoryConfiguration.class.getClassLoader(); } try { Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders"); if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) { throw new BeanCreationException("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath"); } while (resources.hasMoreElements()) { URL url = resources.nextElement(); UrlResource resource = new UrlResource(url); for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) { binderTypes.put(binderType.getDefaultName(), binderType); } } } catch (IOException | ClassNotFoundException e) { throw new BeanCreationException("Cannot create binder factory:", e); } return new DefaultBinderTypeRegistry(binderTypes); }
Source:
public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } if (labelHandle > 0 && OS.GTK_IS_LABEL (labelHandle)) { OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }

Target:
public void setText (String string) { checkWidget(); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); if ((style & SWT.SEPARATOR) != 0) return; if (text.equals (string)) return; super.setText (string); String accelString = ""; int index = string.indexOf ('\t'); if (index != -1) { boolean isRTL = (parent.style & SWT.RIGHT_TO_LEFT) != 0; accelString = (isRTL? "" : " ") + string.substring (index+1, string.length()) + (isRTL? " " : ""); string = string.substring (0, index); } char chars = fixMnemonic (string); byte buffer = Converter.wcsToMbcs (null, chars, true); if (boxHandle == 0 && !OS.GTK3) { labelHandle = OS.gtk_bin_get_child (handle); } if (labelHandle != 0 && OS.GTK_IS_LABEL (labelHandle)) { OS.gtk_label_set_text_with_mnemonic (labelHandle, buffer); if (OS.GTK_IS_ACCEL_LABEL (labelHandle)) { if (OS.GTK3) { if (OS.GTK_VERSION >= OS.VERSION(3, 6, 0)) { MaskKeysym maskKeysym = getMaskKeysym(); if (maskKeysym != null) { OS.gtk_accel_label_set_accel_widget (labelHandle, handle); OS.gtk_accel_label_set_accel (labelHandle, maskKeysym.keysym, maskKeysym.mask); } } else { setAccelLabel (labelHandle, accelString); } } else { setAccelLabel (labelHandle, accelString); } OS.g_signal_emit_by_name(handle, OS.accel_closures_changed); } } }
Source:
List<ServiceIntegrationView> getAvailableDescriptorViews(final User user) throws DotSecurityException, DotDataException { final ImmutableList.Builder<ServiceIntegrationView> viewsBuilder = new ImmutableList.Builder<>(); final List<ServiceDescriptor> serviceDescriptors = serviceIntegrationAPI .getAvailableServiceDescriptors(user); final List<Host> hosts = hostAPI.findAll(user, false); for (final ServiceDescriptor serviceDescriptor : serviceDescriptors) { final String serviceKey = serviceDescriptor.getServiceKey(); final long configurationsCount = computeHostsWithConfigurations(serviceKey, hosts, user).size(); viewsBuilder.add(new ServiceIntegrationView(serviceDescriptor, configurationsCount)); } return viewsBuilder.build(); }

Target:
List<ServiceIntegrationView> getAvailableDescriptorViews(final User user) throws DotSecurityException, DotDataException { final List<ServiceIntegrationView> views = new ArrayList<>(); final List<ServiceDescriptor> serviceDescriptors = serviceIntegrationAPI.getServiceDescriptors(user); final List<Host> hosts = getHosts(user); for (final ServiceDescriptor serviceDescriptor : serviceDescriptors) { final String serviceKey = serviceDescriptor.getKey(); final long configurationsCount = computeSitesWithConfigurations(serviceKey, hosts, user).size(); views.add(new ServiceIntegrationView(serviceDescriptor, configurationsCount)); } return views.stream().sorted(compareByCountAndName).collect(CollectionsUtils.toImmutableList()); }
Source:
private List<ElementTag> getCourseIdOptions(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession) { ArrayList<ElementTag> result = new ArrayList<ElementTag>(); for (CourseAttributes course : courses) { boolean isFilledFormForSessionInThisCourse = newFeedbackSession != null && course.id.equals(newFeedbackSession.courseId); boolean isEmptyFormForSessionInThisCourse = courseIdForNewSession != null && course.id.equals(courseIdForNewSession); if (instructors.get(course.id).isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION)) { ElementTag option = createOption(course.id, course.id, (isFilledFormForSessionInThisCourse || isEmptyFormForSessionInThisCourse)); result.add(option); } } ElementTag defaultOption; if (result.isEmpty() && !courses.isEmpty()) { defaultOption = createOption("No permission to modify courses!", "", true); result.add(defaultOption); } if (result.isEmpty()) { defaultOption = createOption("No active courses!", "", true); result.add(defaultOption); } return result; }

Target:
private List<ElementTag> getCourseIdOptions(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession) { ArrayList<ElementTag> result = new ArrayList<ElementTag>(); for (CourseAttributes course : courses) { boolean isFilledFormForSessionInThisCourse = newFeedbackSession != null && course.id.equals(newFeedbackSession.courseId); boolean isEmptyFormForSessionInThisCourse = courseIdForNewSession != null && course.id.equals(courseIdForNewSession); if (instructors.get(course.id).isAllowedForPrivilege( Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION)) { ElementTag option = createOption(course.id, course.id, (isFilledFormForSessionInThisCourse || isEmptyFormForSessionInThisCourse)); result.add(option); } } return result; }
Source:
public StatementMetadata(byte[] value) throws RdfDAOException { super(); try { if (value == null) { metadataMap = new HashMap<>(); } else { String metadataString = new String(value, "UTF8"); metadataMap = gson.fromJson(metadataString, type); if (metadataMap == null) { metadataMap = new HashMap<>(); } } } catch (UnsupportedEncodingException e) { throw new RdfDAOException(e); } }

Target:
public StatementMetadata(byte[] value) throws RdfDAOException { try { if (value == null) { metadataMap = new HashMap<>(); } else { String metadataString = new String(value, "UTF8"); metadataMap = gson.fromJson(metadataString, type); if (metadataMap == null) { metadataMap = new HashMap<>(); } } } catch (UnsupportedEncodingException e) { throw new RdfDAOException(e); } }
Source:
private boolean renameInConditionalBuildStep(Project<?,?> p, String oldName, String newName) { boolean changed = false; List<ConditionalBuilder> cbuilders = p.getBuildersList().getAll(ConditionalBuilder.class); for (ConditionalBuilder conditionalBuilder : cbuilders) { final List<BuildStep> cbs = conditionalBuilder.getConditionalbuilders(); for (BuildStep buildStep : cbs) { if(buildStep instanceof TriggerBuilder) { TriggerBuilder ctb = (TriggerBuilder)buildStep; if (ctb != null) { for (BuildTriggerConfig co : ctb.getConfigs()){ changed |= co.onJobRenamed(oldName, newName); } } } } } List<SingleConditionalBuilder> scb = p.getBuildersList().getAll(SingleConditionalBuilder.class); for (SingleConditionalBuilder singleConditionalBuilder : scb) { final BuildStep buildStep = singleConditionalBuilder.getBuildStep(); if(buildStep instanceof TriggerBuilder) { TriggerBuilder ctb = (TriggerBuilder)buildStep; if (ctb != null) { for (BuildTriggerConfig co : ctb.getConfigs()){ changed |= co.onJobRenamed(oldName, newName); } } } } return changed; }

Target:
private boolean renameInConditionalBuildStep(Project<?,?> p, String oldName, String newName) { boolean changed = false; final List<TriggerBuilder> containedBuilders = ConditionalBuildStepHelper.getContainedBuilders(p, TriggerBuilder.class); for (TriggerBuilder triggerBuilder : containedBuilders) { for (BuildTriggerConfig co : triggerBuilder.getConfigs()){ changed |= co.onJobRenamed(oldName, newName); } } return changed; }
Source:
public String getObjectDescription(Object o) { Class<? extends LocationPoint> fcl = getFavoriteClass(); if(o!= null && fcl.isInstance(o)) { String desciption = ((FavouritePoint)o).getDescription() != null ? ((FavouritePoint)o).getDescription() : ""; return getObjName() + " : " + ((LocationPoint)o).getName(view.getContext()) + desciption; } return null; }

Target:
public String getObjectDescription(Object o) { Class<? extends LocationPoint> fcl = getFavoriteClass(); if(o!= null && fcl.isInstance(o)) { String desciption = ((FavouritePoint)o).getDescription() != null ? " " + ((FavouritePoint)o).getDescription() : ""; return getObjName() + ": " + ((LocationPoint)o).getName(view.getContext()) + desciption; } return null; }
Source:
public float getHeightFactor(ITimeEvent event) { int stateTableIndex = getStateTableIndex(event); LinuxStateItem linuxStyle = null; if (stateTableIndex >= 0 && stateTableIndex < STATES.length) { linuxStyle = STATES[stateTableIndex]; } return linuxStyle != null ? linuxStyle.getHeightFactor() : super.getHeightFactor(event); }

Target:
public float getHeightFactor(ITimeEvent event) { int stateTableIndex = getStateTableIndex(event); LinuxStyle linuxStyle = null; if (stateTableIndex >= 0 && stateTableIndex < STATES.length) { linuxStyle = STYLE_LIST[stateTableIndex]; } return linuxStyle != null ? linuxStyle.getHeightFactor() : super.getHeightFactor(event); }
Source:
public void init(Config config, TaskContext taskContext) { int numberOfTasks = taskContext.getSamzaContainerContext().taskNames.size(); this.rateLimiter = com.google.common.util.concurrent.RateLimiter.create( targetRate / numberOfTasks); }

Target:
public void init(Config config, TaskContext taskContext) { int effectiveRate = targetRate; if (taskContext != null) { effectiveRate /= taskContext.getSamzaContainerContext().taskNames.size(); LOGGER.info(String.format("Effective rate limit for task %s is %d", taskContext.getTaskName(), effectiveRate)); } this.rateLimiter = com.google.common.util.concurrent.RateLimiter.create(effectiveRate); }
Source:
public Optional<ValueAndBound<T>> getValueForTimestamp(long timestamp) { SequenceAndValueAndBound<T> cachedReference = cache.get(); if (cachedReference == null || cachedReference.bound() < timestamp) { return store.getCoordinationValue() .filter(sequenceAndBound -> sequenceAndBound.bound() >= timestamp) .map(this::getCorrespondingValueFromStore); } return Optional.of(ImmutableValueAndBound.of(cachedReference.value(), cachedReference.bound())); }

Target:
public Optional<ValueAndBound<T>> getValueForTimestamp(long timestamp) { ValueAndBound<T> cachedReference = cache.get(); if (cachedReference.bound() < timestamp) { return readLatestValueFromStore() .filter(valueAndBound -> valueAndBound.bound() >= timestamp); } return Optional.of(cachedReference); }
Source:
public void shouldDeliverBatchInGivenTimePeriod() throws IOException { Topic topic = operations.buildTopic("deliverBatchInGivenTimePeriod", "topic"); operations.createBatchSubscription(topic, HTTP_ENDPOINT_URL, LARGE_MESSAGE_TTL, LARGE_BATCH_SIZE, SMALL_BATCH_TIME, LARGE_BATCH_VOLUME); remoteService.expectMessages(SINGLE_MESSAGE); publish(topic, SINGLE_MESSAGE); expectSingleBatch(SINGLE_MESSAGE); }

Target:
public void shouldDeliverBatchInGivenTimePeriod() throws IOException { Topic topic = operations.buildTopic("deliverBatchInGivenTimePeriod", "topic"); operations.createBatchSubscription(topic, HTTP_ENDPOINT_URL, buildBatchPolicy() .withBatchSize(100) .withBatchTime(1) .withBatchVolume(1024) .build()); remoteService.expectMessages(SINGLE_MESSAGE); publish(topic, SINGLE_MESSAGE); expectSingleBatch(SINGLE_MESSAGE); }
Source:
private Dictionary<String, Object> populatePropertiesWithRequiredAttributes( final Dictionary<String, Object> properties, ConnectorId id) { Dictionary<String, Object> result = DictionaryUtils.copy(properties); for (Entry<String, Object> entry : DictionaryAsMap.wrap(properties).entrySet()) { result.put(entry.getKey(), entry.getValue()); } result.put(Constants.ID_KEY, id.getDomainType()); result.put(Constants.CONNECTOR_KEY, id.getConnectorType()); result.put(Constants.ID_KEY, id.toFullID()); return result; }

Target:
private Dictionary<String, Object> populatePropertiesWithRequiredAttributes( final Dictionary<String, Object> properties, ConnectorId id) { Dictionary<String, Object> result = DictionaryUtils.copy(properties); for (Entry<String, Object> entry : DictionaryAsMap.wrap(properties).entrySet()) { result.put(entry.getKey(), entry.getValue()); } result.put(Constants.DOMAIN_KEY, id.getDomainType()); result.put(Constants.CONNECTOR_KEY, id.getConnectorType()); result.put(Constants.ID_KEY, id.toFullID()); return result; }
Source:
private List<UserSession> searchSessions() { return genericSearch(getDbFacade().getEngineSessionDao(), false).stream().map(this::injectSessionInfo) .map(UserSession::new) .collect(Collectors.toList()); }

Target:
private List<UserSession> searchSessions() { return genericSearch(getDbFacade().getEngineSessionDao(), false).stream().peek(this::injectSessionInfo) .map(UserSession::new) .collect(Collectors.toList()); }
Source:
private static void removeInMemoryData(Cache cache) { EmbeddedCacheManager mgr = cache.getCacheManager(); Address a = mgr.getAddress(); String str; if (a == null) str = "a non-clustered cache manager"; else str = "a cache manager at address " + a; log.debugf("Cleaning data for cache '%s' on %s", cache.getName(), str); DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); if (log.isDebugEnabled()) log.debugf("removeInMemoryData(): dataContainerBefore == %d", dataContainer.size()); dataContainer.clear(); if (log.isDebugEnabled()) log.debugf("removeInMemoryData(): dataContainerAfter == %d", dataContainer.size()); }

Target:
private static void removeInMemoryData(Cache cache) { EmbeddedCacheManager mgr = cache.getCacheManager(); Address a = mgr.getAddress(); String str; if (a == null) str = "a non-clustered cache manager"; else str = "a cache manager at address " + a; log.debugf("Cleaning data for cache '%s' on %s", cache.getName(), str); DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); if (log.isDebugEnabled()) log.debugf("Data container size before clear: %d", dataContainer.size()); dataContainer.clear(); }
Source:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { HandlerDecorator decorator; try { decorator = decoratorClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } return decorator; }

Target:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { HandlerDecorator decorator; try { decorator = decoratorClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } return decorator; }
Source:
public Path run() { GoGoDuckModule module = GoGoDuckModule.newInstance(profile, indexReader, subset, userLog); Path tmpDir = null; try { tmpDir = Files.createTempDirectory(baseTmpDir, "gogoduck"); URIList URIList = module.getUriList(); enforceFileLimit(URIList, limit); downloadFiles(URIList, tmpDir); throwIfCancelled(); applySubsetMultiThread(tmpDir, module, threadCount); throwIfCancelled(); postProcess(tmpDir, module); throwIfCancelled(); aggregate(tmpDir, outputFile); throwIfCancelled(); updateMetadata(module, outputFile); throwIfCancelled(); if (converter != null) { Path outputPath = converter.convert(outputFile); outputFile = outputPath; mimeType = converter.getMimeType(); extension = converter.getExtension(); throwIfCancelled(); } userLog.log("Your aggregation was successful!"); } catch (Exception e) { userLog.log("Your aggregation failed!"); userLog.log(String.format("Reason for failure is: '%s'", e.getMessage())); logger.error(e.toString()); throw new GoGoDuckException(e.getMessage()); } finally { cleanTmpDir(tmpDir); userLog.close(); return outputFile; } }

Target:
public Path run() { GoGoDuckModule module = GoGoDuckModule.newInstance(profile, indexReader, subset, userLog); Path tmpDir = null; try { tmpDir = Files.createTempDirectory(baseTmpDir, "gogoduck"); URIList URIList = module.getUriList(); enforceFileLimit(URIList, limit); downloadFiles(URIList, tmpDir); throwIfCancelled(); applySubsetMultiThread(tmpDir, module, threadCount); throwIfCancelled(); postProcess(tmpDir, module); throwIfCancelled(); aggregate(tmpDir, outputFile); throwIfCancelled(); updateMetadata(module, outputFile); throwIfCancelled(); for (Converter converter : converters) { outputFile = converter.convert(outputFile); mimeType = converter.getMimeType(); extension = converter.getExtension(); throwIfCancelled(); } userLog.log("Your aggregation was successful!"); } catch (Exception e) { userLog.log("Your aggregation failed!"); userLog.log(String.format("Reason for failure is: '%s'", e.getMessage())); logger.error(e.toString()); throw new GoGoDuckException(e.getMessage()); } finally { cleanTmpDir(tmpDir); userLog.close(); return outputFile; } }
Source:
private static Object measureServiceMethod( ServiceProcessorAdapter srvcProc, Service srvc, String srvcName, Method mtd, Object[] args ) throws InvocationTargetException, IllegalAccessException { long startTime = System.nanoTime(); try { return mtd.invoke(srvc, args); } finally { if (srvcProc instanceof IgniteServiceProcessor) { long duration = System.nanoTime() - startTime; HistogramMetricImpl histogram = ((IgniteServiceProcessor)srvcProc).histogram(srvcName, mtd); assert histogram != null; if (histogram != null) histogram.value(duration); } } }

Target:
private static Object measureServiceMethod( ServiceProcessorAdapter srvcProc, Service srvc, String srvcName, Method mtd, Object[] args ) throws InvocationTargetException, IllegalAccessException { long startTime = System.nanoTime(); try { return mtd.invoke(srvc, args); } finally { if (srvcProc instanceof IgniteServiceProcessor) { long duration = System.nanoTime() - startTime; HistogramMetricImpl histogram = ((IgniteServiceProcessor)srvcProc).histogram(srvcName, mtd); if (histogram != null) histogram.value(duration); } } }
Source:
protected RedirectResult createSpecificRedirectResult() { if (regkey == null && !isError) { return createRedirectResult(Const.ActionURIs.STUDENT_HOME_PAGE); } else { RedirectResult redirect = createRedirectResult(Const.ActionURIs.STUDENT_FEEDBACK_SUBMISSION_EDIT_PAGE); if(student != null){ redirect.responseParams.put(Const.ParamsNames.STUDENT_EMAIL, student.email); redirect.responseParams.put(Const.ParamsNames.COURSE_ID, student.course); } redirect.responseParams.put(Const.ParamsNames.FEEDBACK_SESSION_NAME, getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME)); return redirect; } }

Target:
protected RedirectResult createSpecificRedirectResult() { if(!isRegisteredStudent()){ return createRedirectResult(Const.ActionURIs.STUDENT_FEEDBACK_SUBMISSION_EDIT_PAGE); }else if(isError){ RedirectResult result = createRedirectResult(Const.ActionURIs.STUDENT_FEEDBACK_SUBMISSION_EDIT_PAGE); result.responseParams.put(Const.ParamsNames.COURSE_ID, student.course); result.responseParams.put(Const.ParamsNames.FEEDBACK_SESSION_NAME, getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME)); return result; }else { return createRedirectResult(Const.ActionURIs.STUDENT_HOME_PAGE); } }
Source:
public void testThatSymbolicLinksAreResolved() { Assume.assumeTrue(Platform.isMac()); final String message = "Hello World"; final String file = "file.txt"; try { final Path tempDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "ds3"); final Path realDirectory = Files.createDirectory(Paths.get(tempDirectory.toString(), "dir")); final Path symbolicDirectory = Paths.get(tempDirectory.toString(), "symbolic"); Files.createSymbolicLink(symbolicDirectory, realDirectory); Files.createFile(Paths.get(realDirectory.toString(), file)); final ByteBuffer bb = ByteBuffer.wrap(message.getBytes()); final SeekableByteChannel getterChannel = new FileObjectGetter(symbolicDirectory).buildChannel(file); getterChannel.write(bb); getterChannel.close(); final String content = new String(Files.readAllBytes(Paths.get(realDirectory.toString(), file))); assertTrue(message.equals(content)); } catch (final IOException e) { fail("Symbolic links are not handled correctly"); } }

Target:
public void testThatSymbolicLinksAreResolved() { Assume.assumeFalse(Platform.isWindows()); final String message = "Hello World"; final String file = "file.txt"; try { final Path tempDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "ds3"); final Path realDirectory = Files.createDirectory(Paths.get(tempDirectory.toString(), "dir")); final Path symbolicDirectory = Paths.get(tempDirectory.toString(), "symbolic"); Files.createSymbolicLink(symbolicDirectory, realDirectory); Files.createFile(Paths.get(realDirectory.toString(), file)); final ByteBuffer bb = ByteBuffer.wrap(message.getBytes()); final SeekableByteChannel getterChannel = new FileObjectGetter(symbolicDirectory).buildChannel(file); getterChannel.write(bb); getterChannel.close(); final String content = new String(Files.readAllBytes(Paths.get(realDirectory.toString(), file))); assertTrue(message.equals(content)); } catch (final IOException e) { fail("Symbolic links are not handled correctly"); } }
Source:
private static String getDependencyVersion(MavenProject mavenProject, String dependency) throws MojoExecutionException { if (mavenProject == null) { throw new MojoExecutionException("Unable to read maven project for finding dependencies."); } else { String dependencyVersion = null; for (Artifact artifact : mavenProject.getDependencyArtifacts()) { if (artifact.getArtifactId() != null && artifact.getArtifactId().contains(dependency)) { dependencyVersion = artifact.getBaseVersion(); break; } } return dependencyVersion; } }

Target:
private static String getDependencyVersion(MavenProject mavenProject, String dependency) throws MojoExecutionException { if (mavenProject == null) { throw new MojoExecutionException("Unable to read maven project for finding dependencies."); } else if (dependency == null || dependency.isEmpty()) { throw new MojoExecutionException("Unable to find version for invalid dependency value."); } else { Artifact artifact = mavenProject.getDependencyArtifacts().stream(). filter(a -> a.getArtifactId().contains(dependency)).findFirst().orElse(null); if (artifact == null) { throw new MojoExecutionException("Unable to find version as there seems to be " + "no pom based configuration for the provided dependency."); } String dependencyVersion = artifact.getBaseVersion(); if (dependencyVersion == null || dependencyVersion.isEmpty()) { throw new MojoExecutionException("Unable to find version for the provided dependency."); } return dependencyVersion; } }