auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static @Nullable String getDimensionName(Unit<?> unit) { for (Class<? extends SystemOfUnits> system : ALL_SYSTEM_OF_UNITS) { for (Field field : system.getDeclaredFields()) { if (field.getType().isAssignableFrom(Unit.class) && Modifier.isStatic(field.getModifiers())) { try { String dimension = ((Class<?>) ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]).getSimpleName(); Unit<?> systemUnit = (Unit<?>) field.get(null); if (systemUnit.isCompatible(unit)) { return dimension; } } catch (Exception e) { LOGGER.error("Failed to get Dimension string for unit: {}", field, e); } } } } return null; }

Target:
public static @Nullable String getDimensionName(Unit<?> unit) { for (Class<? extends SystemOfUnits> system : ALL_SYSTEM_OF_UNITS) { for (Field field : system.getDeclaredFields()) { if (field.getType().isAssignableFrom(Unit.class) && Modifier.isStatic(field.getModifiers())) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { String dimension = ((Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0]) .getSimpleName(); Unit<?> systemUnit; try { systemUnit = (Unit<?>) field.get(null); if (systemUnit == null) { LOGGER.warn("Unit field points to a null value: {}", field); } else if (systemUnit.isCompatible(unit)) { return dimension; } } catch (IllegalArgumentException | IllegalAccessException e) { LOGGER.error("The unit field '{}' seems to be not accessible", field, e); } } else { LOGGER.warn("There is a unit field defined which has no generic type parametrization: {}", field); } } } } return null; }
Source:
private Module kerberosInternalCommunicationModule() { return binder -> { KerberosInternalCommunicationConfig internalKerberosConfig = buildConfigObject(KerberosInternalCommunicationConfig.class); com.facebook.presto.server.security.KerberosConfig serverKerberosConfig = buildConfigObject(com.facebook.presto.server.security.KerberosConfig.class); checkState(serverKerberosConfig.getKeytab() != null && serverKerberosConfig.getKeytab().getAbsolutePath().equals(internalKerberosConfig.getKerberosKeytab().getAbsolutePath()), "kerberos keytab values must match"); checkState(serverKerberosConfig.getServiceName() != null && serverKerberosConfig.getServiceName().equals(internalKerberosConfig.getKerberosServiceName()), "kerberos servicename values must match"); checkState(serverKerberosConfig.getKerberosConfig() != null && serverKerberosConfig.getKerberosConfig().getAbsolutePath().equals(internalKerberosConfig.getKerberosConfig().getAbsolutePath()), "kerberos keytab values must match"); configBinder(binder).bindConfigGlobalDefaults(KerberosConfig.class, kerberosConfig -> { kerberosConfig.setConfig(internalKerberosConfig.getKerberosConfig()); kerberosConfig.setKeytab(internalKerberosConfig.getKerberosKeytab()); kerberosConfig.setUseCanonicalHostname(internalKerberosConfig.isKerberosUseCanonicalHostname()); kerberosConfig.setCredentialCache(internalKerberosConfig.getKerberosCredentialCache()); }); configBinder(binder).bindConfigGlobalDefaults(HttpClientConfig.class, httpClientConfig -> { httpClientConfig.setAuthenticationEnabled(true); httpClientConfig.setKerberosPrincipal(internalKerberosConfig.getKerberosPrincipal()); httpClientConfig.setKerberosRemoteServiceName(internalKerberosConfig.getKerberosServiceName()); }); }; }

Target:
private Module kerberosInternalCommunicationModule() { return binder -> { InternalCommunicationConfig clientKerberosConfig = buildConfigObject(InternalCommunicationConfig.class); com.facebook.presto.server.security.KerberosConfig serverKerberosConfig = buildConfigObject(com.facebook.presto.server.security.KerberosConfig.class); verify(serverKerberosConfig.getKeytab() != null, "%s must be set when %s is true", HTTP_SERVER_AUTHENTICATION_KRB5_KEYTAB, INTERNAL_COMMUNICATION_KERBEROS_ENABLED); configBinder(binder).bindConfigGlobalDefaults(KerberosConfig.class, kerberosConfig -> { kerberosConfig.setConfig(serverKerberosConfig.getKerberosConfig()); kerberosConfig.setKeytab(serverKerberosConfig.getKeytab()); kerberosConfig.setUseCanonicalHostname(clientKerberosConfig.isKerberosUseCanonicalHostname()); }); String kerberosPrincipal = serverKerberosConfig.getServiceName() + "/" + getLocalCanonicalHostName(); configBinder(binder).bindConfigGlobalDefaults(HttpClientConfig.class, httpClientConfig -> { httpClientConfig.setAuthenticationEnabled(true); httpClientConfig.setKerberosPrincipal(kerberosPrincipal); httpClientConfig.setKerberosRemoteServiceName(serverKerberosConfig.getServiceName()); }); }; }
Source:
private boolean validateDestStorage(StorageDomain destDomain) { StorageDomainValidator validator = new StorageDomainValidator(destDomain); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); }

Target:
private boolean validateDestStorage(StorageDomain destDomain) { StorageDomainValidator validator = new StorageDomainValidator(destDomain); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()) && validate(validator.isNotBackupDomain()); }
Source:
public String getPresignedObjectUrl(GetPresignedObjectUrlArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidExpiresRangeException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { if (args == null) { throw new IllegalArgumentException("null arguments"); } if (args.expires() < 1 || args.expires() > DEFAULT_EXPIRY_TIME) { throw new InvalidExpiresRangeException( args.expires(), "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME); } byte[] body = null; if (args.method() == Method.PUT || args.method() == Method.POST) { body = new byte[0]; } Multimap<String, String> queryParamMap = null; if (args.params() != null) { queryParamMap = HashMultimap.create(); for (Map.Entry<String, String> m : args.params().entrySet()) { queryParamMap.put(m.getKey(), m.getValue()); } } String region = getRegion(args.bucket()); HttpUrl url = buildUrl(args.method(), args.bucket(), args.object(), region, queryParamMap); Request request = createRequest(url, args.method(), null, body, 0); url = Signer.presignV4(request, region, accessKey, secretKey, args.expires()); return url.toString(); }

Target:
public String getPresignedObjectUrl(GetPresignedObjectUrlArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidExpiresRangeException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException, ServerException { checkArgs(args); byte[] body = null; if (args.method() == Method.PUT || args.method() == Method.POST) { body = EMPTY_BODY; } String region = getRegion(args.bucket()); HttpUrl url = buildUrl(args.method(), args.bucket(), args.object(), region, args.extraQueryParams()); Request request = createRequest(url, args.method(), null, body, 0); url = Signer.presignV4(request, region, accessKey, secretKey, args.expiry()); return url.toString(); }
Source:
public ClouderaManagerParcelDeletedListenerTask(ClouderaManagerApiPojoFactory clouderaManagerApiPojoFactory, CloudbreakEventService cloudbreakEventService, Map<String, String> parcelVersions) { super(clouderaManagerApiPojoFactory, cloudbreakEventService); this.parcelVersion = parcelVersions; }

Target:
public ClouderaManagerParcelDeletedListenerTask(ClouderaManagerApiPojoFactory clouderaManagerApiPojoFactory, CloudbreakEventService cloudbreakEventService, Map<String, String> parcelVersions) { super(clouderaManagerApiPojoFactory, cloudbreakEventService); this.parcelVersions = parcelVersions; }
Source:
public void close() throws IOException { synchronized (outstandingRequests) { try { while (!outstandingRequests.isEmpty()) { outstandingRequests.wait(); } } catch (InterruptedException e) { Thread.interrupted(); } delegate.close(); } }

Target:
public void close() throws IOException { closed = true; synchronized (outstandingRequests) { try { while (!canClose()) { outstandingRequests.wait(); } } catch (InterruptedException e) { Thread.interrupted(); } delegateChannel.close(); } }
Source:
private < A extends ArrayDataAccess< A > > CellImg< T, A > create( final long[] dimensions, final T type, final NativeTypeFactory< T, A > typeFactory ) { Dimensions.InvalidDimensions.checkAllPositiveOrElseThrow( dimensions ); verifyDimensions( dimensions ); final int n = dimensions.length; final Fraction entitiesPerPixel = type.getEntitiesPerPixel(); final int[] cellDimensions = getCellDimensions( defaultCellDimensions, n, entitiesPerPixel ); final CellGrid grid = new CellGrid( dimensions, cellDimensions ); final long[] gridDimensions = new long[ grid.numDimensions() ]; grid.gridDimensions( gridDimensions ); final Cell< A > cellType = new Cell<>( new int[] { 1 }, new long[] { 1 }, null ); final ListImg< Cell< A > > cells = new ListImg<>( gridDimensions, cellType ); final long[] cellGridPosition = new long[ n ]; final long[] cellMin = new long[ n ]; final int[] cellDims = new int[ n ]; final ListLocalizingCursor< Cell< A > > cellCursor = cells.localizingCursor(); while ( cellCursor.hasNext() ) { cellCursor.fwd(); cellCursor.localize( cellGridPosition ); grid.getCellDimensions( cellGridPosition, cellMin, cellDims ); final A data = ArrayDataAccessFactory.get( typeFactory ).createArray( ( int ) entitiesPerPixel.mulCeil( Intervals.numElements( cellDims ) ) ); cellCursor.set( new Cell<>( cellDims, cellMin, data ) ); } final CellImg< T, A > img = new CellImg<>( this, grid, cells, entitiesPerPixel ); img.setLinkedType( typeFactory.createLinkedType( img ) ); return img; }

Target:
private < A extends ArrayDataAccess< A > > CellImg< T, A > create( final long[] dimensions, final T type, final NativeTypeFactory< T, A > typeFactory ) { Dimensions.verify( dimensions ); final int n = dimensions.length; final Fraction entitiesPerPixel = type.getEntitiesPerPixel(); final int[] cellDimensions = getCellDimensions( defaultCellDimensions, n, entitiesPerPixel ); final CellGrid grid = new CellGrid( dimensions, cellDimensions ); final long[] gridDimensions = new long[ grid.numDimensions() ]; grid.gridDimensions( gridDimensions ); final Cell< A > cellType = new Cell<>( new int[] { 1 }, new long[] { 1 }, null ); final ListImg< Cell< A > > cells = new ListImg<>( gridDimensions, cellType ); final long[] cellGridPosition = new long[ n ]; final long[] cellMin = new long[ n ]; final int[] cellDims = new int[ n ]; final ListLocalizingCursor< Cell< A > > cellCursor = cells.localizingCursor(); while ( cellCursor.hasNext() ) { cellCursor.fwd(); cellCursor.localize( cellGridPosition ); grid.getCellDimensions( cellGridPosition, cellMin, cellDims ); final A data = ArrayDataAccessFactory.get( typeFactory ).createArray( ( int ) entitiesPerPixel.mulCeil( Intervals.numElements( cellDims ) ) ); cellCursor.set( new Cell<>( cellDims, cellMin, data ) ); } final CellImg< T, A > img = new CellImg<>( this, grid, cells, entitiesPerPixel ); img.setLinkedType( typeFactory.createLinkedType( img ) ); return img; }
Source:
public Object apply(ChangeResource rsrc, Input input) throws NoSuchChangeException, OrmException, IOException { ChangeUtil.deleteDraftChange(rsrc.getChange().getId(), gitManager, gitRefUpdated, dbProvider.get()); return Response.none(); }

Target:
public Object apply(ChangeResource rsrc, Input input) throws ResourceConflictException, AuthException, ResourceNotFoundException, OrmException, IOException { if (rsrc.getChange().getStatus() != Status.DRAFT) { throw new ResourceConflictException("Change is not a draft"); } if (!rsrc.getControl().canDeleteDraft(dbProvider.get())) { throw new AuthException("Not permitted to delete this draft change"); } try { ChangeUtil.deleteDraftChange(rsrc.getChange().getId(), gitManager, gitRefUpdated, dbProvider.get()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(e.getMessage()); } return Response.none(); }
Source:
protected void setLaunchAttributes() { super.setLaunchAttributes(); setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, TEST_PROGRAM_NAME); setLaunchAttribute(IGDBJtagConstants.ATTR_USE_REMOTE_TARGET, remote); setLaunchAttribute(IGDBJtagConstants.ATTR_JTAG_DEVICE_ID, TEST_JTAG_DEVICE_ID); setLaunchAttribute(IGDBJtagConstants.ATTR_LOAD_IMAGE, false); setLaunchAttribute(IGDBJtagConstants.ATTR_LOAD_SYMBOLS, remote); setLaunchAttribute(IGDBJtagConstants.ATTR_SET_STOP_AT, true); setLaunchAttribute(IGDBJtagConstants.ATTR_STOP_AT, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT); setLaunchAttribute(IGDBJtagConstants.ATTR_SET_RESUME, remote); if (remote) { setLaunchAttribute(IGDBJtagConstants.ATTR_USE_PROJ_BINARY_FOR_SYMBOLS, true); if (0 > LaunchUtils.compareVersions(getGdbVersion(), GdbDebugServicesFactory.GDB_7_10_VERSION)) { setLaunchAttribute(IGDBLaunchConfigurationConstants.ATTR_GDB_INIT, X86_64_INIT); } } else { setLaunchAttribute(IGDBJtagConstants.ATTR_INIT_COMMANDS, "# Commented line\nfile " + TEST_PROGRAM_NAME); setLaunchAttribute(IGDBJtagConstants.ATTR_RUN_COMMANDS, "# Commented line\nrun"); } }

Target:
protected void setLaunchAttributes() { super.setLaunchAttributes(); setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, TEST_PROGRAM_NAME); setLaunchAttribute(IGDBJtagConstants.ATTR_USE_REMOTE_TARGET, remote); setLaunchAttribute(IGDBJtagConstants.ATTR_JTAG_DEVICE_ID, TEST_JTAG_DEVICE_ID); setLaunchAttribute(IGDBJtagConstants.ATTR_LOAD_IMAGE, false); setLaunchAttribute(IGDBJtagConstants.ATTR_LOAD_SYMBOLS, remote); setLaunchAttribute(IGDBJtagConstants.ATTR_SET_STOP_AT, true); setLaunchAttribute(IGDBJtagConstants.ATTR_STOP_AT, ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT); setLaunchAttribute(IGDBJtagConstants.ATTR_SET_RESUME, remote); if (remote) { setLaunchAttribute(IGDBJtagConstants.ATTR_USE_PROJ_BINARY_FOR_SYMBOLS, true); if (0 > LaunchUtils.compareVersions(getGdbVersion(), GdbDebugServicesFactory.GDB_7_10_VERSION)) { setLaunchAttribute(IGDBLaunchConfigurationConstants.ATTR_GDB_INIT, X86_64_INIT); } } else { String comments = "# Commented line\n\n \n # Commented indented line\n"; setLaunchAttribute(IGDBJtagConstants.ATTR_INIT_COMMANDS, comments + "file " + TEST_PROGRAM_NAME); setLaunchAttribute(IGDBJtagConstants.ATTR_RUN_COMMANDS, comments + "run"); } }
Source:
@Override protected void readChunk(ReadableByteChannel ch) throws IOException { assert fileIo != null; long batchSize = Math.min(chunkSize, meta.count() - transferred); long readed = fileIo.transferFrom(ch, meta.offset() + transferred, batchSize); if (readed == 0) throw new IOException("Channel is reached the end of stream. Probably, channel is closed on the remote node"); if (readed > 0) transferred += readed; }

Target:
@Override protected void readChunk(ReadableByteChannel ch) throws IOException { assert fileIo != null; long batchSize = Math.min(chunkSize, meta.count() - transferred); long read = fileIo.transferFrom(ch, meta.offset() + transferred, batchSize); if (read == 0) throw new IOException("Channel is reached the end of stream. Probably, channel is closed on the remote node"); if (read > 0) transferred += read; }
Source:
public int hashCode() { return Arrays.hashCode(copy().getBuf()); }

Target:
public int hashCode() { if (buf == null) return 0; int result = 1; for (int i = 0; i < length; i++) { result = 31 * result + buf[offset + i]; } return result; }
Source:
public void _run() throws IOException, InstallationStatus { if (wasInstalled()) { LOGGER.info("Skipping duplicate install of: " + plugin.getDisplayName() + "@" + plugin.version); throw new Skipped(); } try { super._run(); PluginWrapper pw = plugin.getInstalled(); if (pw!=null && pw.isBundled()) { SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM); try { pw.doPin(); } finally { SecurityContextHolder.setContext(oldContext); } } if (dynamicLoad) { try { pm.dynamicLoad(getDestination()); } catch (RestartRequiredException e) { throw new SuccessButRequiresRestart(e.message); } catch (Exception e) { throw new IOException("Failed to dynamically deploy this plugin",e); } } else { throw new SuccessButRequiresRestart(Messages._UpdateCenter_DownloadButNotActivated()); } } finally { synchronized(this) { LOGGER.fine("Install complete for: " + plugin.getDisplayName() + "@" + plugin.version); status = new Skipped(); notifyAll(); } } }

Target:
public void _run() throws IOException, InstallationStatus { if (wasInstalled()) { LOGGER.info("Skipping duplicate install of: " + plugin.getDisplayName() + "@" + plugin.version); return; } try { super._run(); PluginWrapper pw = plugin.getInstalled(); if (pw!=null && pw.isBundled()) { SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM); try { pw.doPin(); } finally { SecurityContextHolder.setContext(oldContext); } } if (dynamicLoad) { try { pm.dynamicLoad(getDestination()); } catch (RestartRequiredException e) { throw new SuccessButRequiresRestart(e.message); } catch (Exception e) { throw new IOException("Failed to dynamically deploy this plugin",e); } } else { throw new SuccessButRequiresRestart(Messages._UpdateCenter_DownloadButNotActivated()); } } finally { synchronized(this) { LOGGER.fine("Install complete for: " + plugin.getDisplayName() + "@" + plugin.version); status = new Skipped(); notifyAll(); } } }
Source:
private void mayBeAddAdminUsers() { LOG.info("Checking user entries for admin users"); adminUsers.stream() .filter(name -> { User user = catalogService.getUser(name); if (user != null) { LOG.info("User entry for '{}' already exists", name); return false; } else { return true; } }) .forEach(name -> { User user = new User(); user.setName(name); user.setEmail(name + "@auto-generated"); User addedUser = catalogService.addUser(user); LOG.info("Added admin user entry: {}", addedUser); }); }

Target:
private void mayBeAddAdminUsers() { LOG.info("Checking user entries for admin users"); adminUsers.stream() .filter(name -> { User user = catalogService.getUser(name); if (user != null) { LOG.info("Entry for user '{}' already exists", name); return false; } else { return true; } }) .forEach(name -> { User user = new User(); user.setName(name); user.setEmail(name + "@auto-generated"); User addedUser = catalogService.addUser(user); LOG.info("Added admin user entry: {}", addedUser); }); }
Source:
private boolean isTattleTaleReportGenerationEnabled(GraphRewrite event) { Boolean enableReport = (Boolean) event.getGraphContext().getOptionMap().get(EnableTattletaleReportOption.NAME); Boolean disableReport = (Boolean) event.getGraphContext().getOptionMap().get(DisableTattletaleReportOption.NAME); Collection<String> targets = (Collection<String>) event.getGraphContext().getOptionMap().get(TargetOption.NAME); boolean eapTarget = targets != null && targets.stream().anyMatch(target -> target.startsWith("eap")); if (eapTarget && BooleanUtils.isTrue(disableReport) && BooleanUtils.isNotTrue(enableReport)) return false; else if (!eapTarget && BooleanUtils.isNotTrue(enableReport)) return false; return true; }

Target:
private boolean isTattleTaleReportGenerationEnabled(GraphRewrite event) { Boolean enableReport = (Boolean) event.getGraphContext().getOptionMap().getOrDefault(EnableTattletaleReportOption.NAME, Boolean.FALSE); Boolean disableReport = (Boolean) event.getGraphContext().getOptionMap().getOrDefault(DisableTattletaleReportOption.NAME, Boolean.FALSE); Collection<String> targets = (Collection<String>) event.getGraphContext().getOptionMap().getOrDefault(TargetOption.NAME, Collections.EMPTY_SET); boolean eapTarget = targets.stream().anyMatch(target -> target.startsWith("eap")); if (eapTarget && disableReport && !enableReport) return false; else if (!eapTarget && !enableReport) return false; return true; }
Source:
protected void convertTable(Table table) { String tableKindId = table.getTableKindId(); if (tableKindId != null) { ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance(); RepresentationKind kind = (PapyrusDiagram) manager.getRepresentationKindById(tableKindId); if (UMLArchitectureContextIds.UML.equals(kind.getLanguage().getId())) return; } table.setTableKindId(UMLTableKinds.GENERIC_TABLE); }

Target:
protected void convertTable(Table table) { String tableKindId = table.getTableKindId(); if (tableKindId != null) { ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance(); RepresentationKind kind = manager.getRepresentationKindById(tableKindId); if (kind != null && UMLArchitectureContextIds.UML.equals(kind.getLanguage().getId())) return; } table.setTableKindId(UMLTableKinds.GENERIC_TABLE); }
Source:
public XDocResourceKey(Project.NameKey project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }

Target:
XDocResourceKey(Project.NameKey project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }
Source:
private Object extractValue(Object object, Schema schema) { Schema.Type fieldType = schema.getType(); switch (fieldType) { case ARRAY: return convertArray(object, schema.getComponentSchema()); case BYTES: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: return object; case NULL: return null; default: throw new UnexpectedFormatException("field type " + fieldType + " is not supported."); } }

Target:
private Object extractValue(Object object, Schema schema) { if (schema.isNullable()) { if (object == null) { return null; } schema = schema.getNonNullable(); } Schema.Type fieldType = schema.getType(); switch (fieldType) { case ARRAY: return convertArray(object, schema.getComponentSchema()); case BYTES: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: return object; case NULL: return null; default: throw new UnexpectedFormatException("field type " + fieldType + " is not supported."); } }
Source:
public Iterator<Entry<KeyType>> iterator(final boolean sorted) { final List<Iterator<Entry<KeyType>>> iterators = new ArrayList<>(groupers.size()); for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { iterators.add(grouper.iterator(sorted)); } } return Groupers.mergeIterators(iterators, sorted); }

Target:
public Iterator<Entry<KeyType>> iterator(final boolean sorted) { if (closed) { throw new ISE("Grouper is closed"); } final List<Iterator<Entry<KeyType>>> iterators = new ArrayList<>(groupers.size()); for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { iterators.add(grouper.iterator(sorted)); } } return Groupers.mergeIterators(iterators, sorted); }
Source:
public final void run() { while(running){ while (isDataAvaid()) { final int[] data = nrfGetOneDataPacket(); executorService.execute(new Runnable() { public void run() { listener.dataRecived(data); } }); } try { DataPackage pkg = fifo.poll(25, TimeUnit.MILLISECONDS); if(pkg==null) continue; int retry = nrfSendData(pkg.chanel, pkg.power, pkg.maxRetry, pkg.addrWidth, pkg.txAddr, pkg.dataWidth, pkg.txData); pkg.sentTimestamp=System.currentTimeMillis(); pkg.retry = retry; setRxMode(this.localRFChanel, 5, this.localRFAddress); } catch (InterruptedException e) { e.printStackTrace(); } } }

Target:
public final void run() { while(running){ while (isDataAvaid()) { final int[] data = nrfGetOneDataPacket(); executorService.execute(new Runnable() { public void run() { listener.dataReceived(data); } }); } try { DataPackage pkg = fifo.poll(25, TimeUnit.MILLISECONDS); if(pkg==null) continue; int retry = nrfSendData(pkg.chanel, pkg.power, pkg.maxRetry, pkg.addrWidth, pkg.txAddr, pkg.dataWidth, pkg.txData); pkg.sentTimestamp=System.currentTimeMillis(); pkg.retry = retry; } catch (InterruptedException e) { e.printStackTrace(); } finally{ setRxMode(this.localRFChanel, 5, this.localRFAddress); } } }
Source:
default TimestampedLockResponse acquireLocksForWrites(LockRequest lockRequest) { return TimestampedLockResponse.of(getFreshTimestamp(), lock(lockRequest)); }

Target:
default TimestampedLockResponse acquireLocksForWrites(LockRequest lockRequest) { return TimestampedLockResponse.of(null, lock(lockRequest)); }
Source:
public CompletableFuture<Void> addEvent(final Event event) { return CompletableFuture.runAsync(new Runnable() { @Override public void run() { try { LOG.debug("run: calling onEvent on for event {}", m_listener.getName(), event.toStringSimple()); Map<String,String> mdc = Logging.getCopyOfContextMap(); try { m_listener.onEvent(event); } finally { Logging.setContextMap(mdc); } } catch (Throwable t) { LOG.warn("run: an unexpected error occured during ListenerThread {}", m_listener.getName(), t); } } }, m_delegateThread); }

Target:
public CompletableFuture<Void> addEvent(final Event event) { return CompletableFuture.runAsync(new Runnable() { @Override public void run() { try { if (LOG.isDebugEnabled()) LOG.debug("run: calling onEvent on for event {}", m_listener.getName(), event.toStringSimple()); Map<String,String> mdc = Logging.getCopyOfContextMap(); try { m_listener.onEvent(event); } finally { Logging.setContextMap(mdc); } } catch (Throwable t) { LOG.warn("run: an unexpected error occured during ListenerThread {}", m_listener.getName(), t); } } }, m_delegateThread); }
Source:
public static Optional<Unit> getUnit(String cssSize) { if (cssSize == null) { throw new IllegalArgumentException("The parameter can't be null"); } Stream<Unit> units = getUnits().filter(unit -> cssSize.endsWith(unit.toString())); return units.findFirst(); }

Target:
public static Optional<Unit> getUnit(String cssSize) { if (cssSize == null) { throw new IllegalArgumentException("The parameter can't be null"); } return getUnits().filter(unit -> cssSize.endsWith(unit.toString())).findFirst(); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } VDSGroup cluster = getVdsGroup(); if (cluster == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (!cluster.supportsGlusterService()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_DOES_NOT_SUPPORT_GLUSTER); return false; } if (!GlusterFeatureSupported.glusterSnapshot(cluster.getcompatibility_version())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); return false; } GlusterVolumeEntity volume = getGlusterVolume(); if (volume == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID); } else if (volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } if (getDbFacade().getGlusterVolumeSnapshotDao().getByName(getGlusterVolumeId(), snapshot.getSnapshotName()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_SNAPSHOT_ALREADY_EXISTS); } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } VDSGroup cluster = getVdsGroup(); if (!GlusterFeatureSupported.glusterSnapshot(cluster.getcompatibility_version())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); return false; } GlusterVolumeEntity volume = getGlusterVolume(); if (volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } if (getDbFacade().getGlusterVolumeSnapshotDao().getByName(getGlusterVolumeId(), snapshot.getSnapshotName()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_SNAPSHOT_ALREADY_EXISTS); } return true; }
Source:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderAsObservable() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final TestSubscriber<DeleteResults<TestItem>> testSubscriber = new TestSubscriber<DeleteResults<TestItem>>(); storIOContentResolver .delete() .objects(items) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); testSubscriber.assertError(StorIOException.class); verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderAsObservable() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final TestSubscriber<DeleteResults<TestItem>> testSubscriber = new TestSubscriber<DeleteResults<TestItem>>(); storIOContentResolver .delete() .objects(items) .prepare() .createObservable() .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertNoValues(); TestUtils.checkException(testSubscriber, StorIOException.class, IllegalStateException.class); verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }
Source:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond ); }

Target:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond ); }
Source:
public void testNewSecurityPolicy() throws Exception { DocumentRef folderRef; try (CoreSession session = coreFeature.openCoreSession(ADMINISTRATOR)) { setTestPermissions(ANONYMOUS, READ); DocumentModel root = session.getRootDocument(); DocumentModel folder = new DocumentModelImpl(root.getPathAsString(), "folder#1", "Folder"); folder.setProperty("secupolicy", "securityLevel", Long.valueOf(4)); folder = session.createDocument(folder); folderRef = folder.getRef(); session.save(); Principal fooUser = new UserPrincipal("foo", new ArrayList<String>(), false, false); assertFalse(session.hasPermission(fooUser, folderRef, READ)); assertArrayEquals(session.filterGrantedPermissions(fooUser, folderRef, Arrays.asList(READ)).toArray(), new String[0]); setTestPermissions(fooUser.getName(), READ); assertTrue(session.hasPermission(fooUser, folderRef, READ)); assertArrayEquals(session.filterGrantedPermissions(fooUser, folderRef, Arrays.asList(READ)).toArray(), new String[] { READ }); } try (CoreSession session = coreFeature.openCoreSession(ANONYMOUS)) { DocumentModelImpl documentModelImpl = new DocumentModelImpl("User"); Map<String, Object> data = new HashMap<String, Object>(); data.put("accessLevel", Long.valueOf(3)); documentModelImpl.addDataModel(new DataModelImpl("user", data)); ((NuxeoPrincipal) session.getPrincipal()).setModel(documentModelImpl); assertFalse(session.hasPermission(folderRef, READ)); ((NuxeoPrincipal) session.getPrincipal()).getModel().setProperty("user", "accessLevel", Long.valueOf(5)); assertTrue(session.hasPermission(folderRef, READ)); session.save(); } }

Target:
public void testNewSecurityPolicy() throws Exception { DocumentRef folderRef; try (CoreSession session = coreFeature.openCoreSession(ADMINISTRATOR)) { setTestPermissions(ANONYMOUS, READ); DocumentModel root = session.getRootDocument(); DocumentModel folder = new DocumentModelImpl(root.getPathAsString(), "folder#1", "Folder"); folder.setProperty("secupolicy", "securityLevel", Long.valueOf(4)); folder = session.createDocument(folder); folderRef = folder.getRef(); session.save(); Principal fooUser = new UserPrincipal("foo", new ArrayList<String>(), false, false); assertFalse(session.hasPermission(fooUser, folderRef, READ)); assertTrue(session.filterGrantedPermissions(fooUser, folderRef, Arrays.asList(READ)).isEmpty()); setTestPermissions(fooUser.getName(), READ); assertTrue(session.hasPermission(fooUser, folderRef, READ)); assertEquals(session.filterGrantedPermissions(fooUser, folderRef, Arrays.asList(READ)), Arrays.asList(READ)); } try (CoreSession session = coreFeature.openCoreSession(ANONYMOUS)) { DocumentModelImpl documentModelImpl = new DocumentModelImpl("User"); Map<String, Object> data = new HashMap<String, Object>(); data.put("accessLevel", Long.valueOf(3)); documentModelImpl.addDataModel(new DataModelImpl("user", data)); ((NuxeoPrincipal) session.getPrincipal()).setModel(documentModelImpl); assertFalse(session.hasPermission(folderRef, READ)); ((NuxeoPrincipal) session.getPrincipal()).getModel().setProperty("user", "accessLevel", Long.valueOf(5)); assertTrue(session.hasPermission(folderRef, READ)); session.save(); } }
Source:
@Override public <T> IgniteInternalFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync( Map<? extends K, ? extends EntryProcessor<K, V, T>> map, Object... args) { A.notNull(map, "map"); if (keyCheck) validateCacheKeys(map.keySet()); checkKeysOrdered(map, "Invoke All"); final boolean statsEnabled = ctx.statisticsEnabled(); final long start = statsEnabled ? System.nanoTime() : 0L; IgniteInternalFuture fut = updateAllAsync0(null, map, args, true, false, null); if (statsEnabled) fut.listen(new InvokeAllTimeStatClosure(metrics0(), start)); return fut; }

Target:
@Override public <T> IgniteInternalFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync( Map<? extends K, ? extends EntryProcessor<K, V, T>> map, Object... args) { A.notNull(map, "map"); if (keyCheck) validateCacheKeys(map.keySet()); warnIfUnordered(map, BulkOperation.INVOKE); final boolean statsEnabled = ctx.statisticsEnabled(); final long start = statsEnabled ? System.nanoTime() : 0L; IgniteInternalFuture fut = updateAllAsync0(null, map, args, true, false, null); if (statsEnabled) fut.listen(new InvokeAllTimeStatClosure(metrics0(), start)); return fut; }
Source:
public boolean isApplicable(@NotNull PsiElement[] elements) { if (!super.isApplicable(elements) || elements.length == 0) return false; GoType type = ((GoExpression)elements[0]).getGoType(null); return type != null && type.textMatches("bool"); }

Target:
public boolean isApplicable(@NotNull PsiElement[] elements) { if (!super.isApplicable(elements)) return false; return GoTypeUtil.isBuiltinType(getExpression(elements).getGoType(null), "bool"); }
Source:
private void saveMaps() throws IOException { for (Map.Entry<String, Tuple> entry : knownHolders.entrySet()) { File outFile = new File(dataDirectory, createFileName(entry)); try (FileOutputStream fos = new FileOutputStream(outFile)) { try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(entry.getKey()); oos.writeObject(entry.getValue()); } } } }

Target:
private void saveMaps() throws IOException { for (Map.Entry<String, Tuple> entry : knownHolders.entrySet()) { File outFile = new File(dataDirectory, createFileName(entry)); try (FileOutputStream fos = new FileOutputStream(outFile); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(entry.getKey()); oos.writeObject(entry.getValue()); } } }
Source:
public void transform(StructuredRecord input, Emitter<KeyValue<byte[], byte[]>> emitter) throws Exception { Object key = input.get(kvTableConfig.keyField); Preconditions.checkArgument(key != null, "Key cannot be null."); byte[] keyBytes = key instanceof String ? Bytes.toBytes((String) key) : (byte[]) key; Object val = input.get(kvTableConfig.valueField); byte[] valBytes = val instanceof String ? Bytes.toBytes((String) val) : (byte[]) val; emitter.emit(new KeyValue<>(keyBytes, valBytes)); }

Target:
public void transform(StructuredRecord input, Emitter<KeyValue<byte[], byte[]>> emitter) throws Exception { Object key = input.get(kvTableConfig.keyField); Preconditions.checkArgument(key != null, "Key cannot be null."); byte[] keyBytes; Schema keyFieldSchema = input.getSchema().getField(kvTableConfig.keyField).getSchema(); if (keyFieldSchema.getType().equals(Schema.Type.STRING)) { keyBytes = Bytes.toBytes((String) key); } else if (keyFieldSchema.getType().equals(Schema.Type.BYTES)) { keyBytes = key instanceof ByteBuffer ? Bytes.toBytes((ByteBuffer) key) : (byte[]) key; } else if (keyFieldSchema.isNullable()) { throw new Exception( String.format("Key field %s cannot have nullable schema %s", kvTableConfig.keyField, keyFieldSchema)); } else { throw new Exception( String.format("Key field %s cannot have schema %s. It must of either String or Bytes", kvTableConfig.keyField, keyFieldSchema)); } Schema.Field valueFieldSchema = input.getSchema().getField(kvTableConfig.valueField); if (valueFieldSchema == null) { throw new Exception("Value Field " + kvTableConfig.valueField + " is missing in the input record"); } byte[] valBytes = null; Object val = input.get(kvTableConfig.valueField); if (val != null) { Schema.Type valueFieldType = valueFieldSchema.getSchema().isNullable() ? valueFieldSchema.getSchema().getNonNullable().getType() : valueFieldSchema.getSchema().getType(); if (valueFieldType.equals(Schema.Type.STRING)) { valBytes = Bytes.toBytes((String) val); } else if (valueFieldType.equals(Schema.Type.BYTES)) { valBytes = val instanceof ByteBuffer ? Bytes.toBytes((ByteBuffer) val) : (byte[]) val; } else { throw new Exception( String.format("Value field %s cannot have schema %s. It must of either String or Bytes", kvTableConfig.valueField, valueFieldSchema)); } } emitter.emit(new KeyValue<>(keyBytes, valBytes)); }
Source:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { log.unableToLoadDriver("org.apache.cassandra.cql.jdbc.CassandraDriver") ; } }

Target:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { throw log.unableToLoadDriver( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } }
Source:
public void handleDataChange(String dataPath, Object data) throws Exception { Stat stat = new Stat(); ZNRecord readData = _baseDataAccessor.get(dataPath, stat, AccessOption.THROW_EXCEPTION_IFNOTEXIST); LockInfo lockInfo = new LockInfo(readData); if (lockInfo.getOwner().equals(_userId)) { if (lockInfo.getRequestorId() == null || lockInfo.getPriority() > lockInfo .getRequestorPriority()) { LOG.info("We do not need to handle this data change"); } else { _lockListener.onCleanupNotification(); readData = _baseDataAccessor.get(dataPath, stat, AccessOption.THROW_EXCEPTION_IFNOTEXIST); if (lockInfo.getOwner().equals(_userId)) { ZNRecord znRecord = new ZNRecord(readData); znRecord.setSimpleField(LockInfo.LockInfoAttribute.OWNER.name(), ""); znRecord.setSimpleField(LockInfo.LockInfoAttribute.MESSAGE.name(), ""); znRecord.setLongField(LockInfo.LockInfoAttribute.TIMEOUT.name(), -1); znRecord.setIntField(LockInfo.LockInfoAttribute.PRIORITY.name(), -1); znRecord.setLongField(LockInfo.LockInfoAttribute.WAITING_TIMEOUT.name(), -1); znRecord.setLongField(LockInfo.LockInfoAttribute.CLEANUP_TIMEOUT.name(), -1); _baseDataAccessor .update(_lockPath, new ZNRecordUpdater(znRecord), AccessOption.PERSISTENT); } else { LOG.info("We are not current lock owner"); } } } else if (lockInfo.getRequestorId().equals(_userId)) { if (lockInfo.getOwner().isEmpty()) { ZNRecord znRecord = composeNewOwnerRecord(); _baseDataAccessor.update(_lockPath, new ZNRecordUpdater(znRecord), AccessOption.PERSISTENT); onAcquiredLockNotification(); } else { LOG.info("We do not need to handle this data change"); } } else if (lockInfo.getRequestorId() != null && !lockInfo.getRequestorId().equals(_userId) && _isPending) { onDeniedPendingLockNotification(); } }

Target:
public void handleDataChange(String dataPath, Object data) throws Exception { Stat stat = new Stat(); ZNRecord readData = _baseDataAccessor.get(dataPath, stat, AccessOption.THROW_EXCEPTION_IFNOTEXIST); LockInfo lockInfo = new LockInfo(readData); if (isCurrentOwner(lockInfo)) { if (lockInfo.getRequestorId().equals(LockConstants.DEFAULT_USER_ID) || lockInfo.getPriority() > lockInfo.getRequestorPriority()) { LOG.debug("We do not need to handle this data change"); } else { _lockListener.onCleanupNotification(); CleanupUpdater cleanupUpdater = new CleanupUpdater(); boolean res = _baseDataAccessor.update(_lockPath, cleanupUpdater, AccessOption.PERSISTENT); if (!res) { throw new HelixException( String.format("User %s failed to update lock path %s", _userId, _lockPath)); } } } else if (lockInfo.getRequestorId().equals(_userId)) { if (lockInfo.getOwner().equals(LockConstants.DEFAULT_USER_ID)) { ZNRecord znRecord = composeNewOwnerRecord(); LockUpdater updater = new LockUpdater(new LockInfo(znRecord)); _baseDataAccessor.update(_lockPath, updater, AccessOption.PERSISTENT); onAcquiredLockNotification(); } else { LOG.info("We do not need to handle this data change"); } } else if (!lockInfo.getRequestorId().equals(LockConstants.DEFAULT_USER_ID) && !lockInfo .getRequestorId().equals(_userId) && _lockStatus == LockConstants.LockStatus.PENDING) { onDeniedPendingLockNotification(); } }
Source:
public int run(String[] args) throws Exception { if (args.length != 3) { log.error("Usage: " + this.getClass().getSimpleName() + "<nodeSize> <fluoProps> <input dir>"); System.exit(-1); } int nodeSize = Integer.parseInt(args[0]); FluoConfiguration props = new FluoConfiguration(new File(args[1])); Path input = new Path(args[2]); Job job = Job.getInstance(getConf()); job.setJarByClass(Load.class); job.getConfiguration().setInt(TRIE_NODE_SIZE_PROP, nodeSize); job.setInputFormatClass(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(job, input); job.setMapperClass(LoadMapper.class); job.setNumReduceTasks(0); job.setOutputFormatClass(FluoOutputFormat.class); FluoOutputFormat.configure(job, ConfigurationConverter.getProperties(props)); job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", false); boolean success = job.waitForCompletion(true); return success ? 0 : 1; }

Target:
public int run(String[] args) throws Exception { if (args.length != 3) { log.error("Usage: " + this.getClass().getSimpleName() + "<nodeSize> <fluoProps> <input dir>"); System.exit(-1); } int nodeSize = Integer.parseInt(args[0]); FluoConfiguration props = new FluoConfiguration(new File(args[1])); Path input = new Path(args[2]); Job job = Job.getInstance(getConf()); job.setJarByClass(Load.class); job.getConfiguration().setInt(TRIE_NODE_SIZE_PROP, nodeSize); job.setInputFormatClass(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(job, input); job.setMapperClass(LoadMapper.class); job.setNumReduceTasks(0); job.setOutputFormatClass(FluoOutputFormat.class); FluoOutputFormat.configure(job, ConfigurationConverter.getProperties(props)); job.getConfiguration().setBoolean("mapreduce.map.speculative", false); boolean success = job.waitForCompletion(true); return success ? 0 : 1; }
Source:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { return new ThriftConnectorIndex(client, sessionProperties.createHeaderFromSession(session), stats, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }

Target:
public ConnectorIndex getIndex( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema) { return new ThriftConnectorIndex( client, sessionProperties.toHeader(session), stats, (ThriftIndexHandle) indexHandle, lookupSchema, outputSchema, maxBytesPerResponse, lookupRequestsConcurrency); }
Source:
public void shouldSuccessfullySendACaptureRequest() { PaymentProvider paymentProvider = getSmartpayPaymentProvider(); CardAuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertTrue(response.isSuccessful()); assertThat(response.getBaseResponse().isPresent(), is(true)); SmartpayAuthorisationResponse smartpayAuthorisationResponse = (SmartpayAuthorisationResponse) response.getBaseResponse().get(); String transactionId = smartpayAuthorisationResponse.getPspReference(); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); CaptureResponse captureGatewayResponse = paymentProvider.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertTrue(captureGatewayResponse.isSuccessful()); }

Target:
public void shouldSuccessfullySendACaptureRequest() { PaymentProvider paymentProvider = getSmartpayPaymentProvider(); CardAuthorisationGatewayRequest request = getCardAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertTrue(response.isSuccessful()); assertThat(response.getBaseResponse().isPresent(), is(true)); SmartpayAuthorisationResponse smartpayAuthorisationResponse = (SmartpayAuthorisationResponse) response.getBaseResponse().get(); String transactionId = smartpayAuthorisationResponse.getPspReference(); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); CaptureResponse captureGatewayResponse = paymentProvider.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertTrue(captureGatewayResponse.isSuccessful()); MatcherAssert.assertThat(captureGatewayResponse.state(), Is.is(CaptureResponse.ChargeState.PENDING)); }
Source:
private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> newContainers = new ArrayList<>(); final List<Container> nativeContainers = new ArrayList<>(); try { synchronized (clientLock) { if (client == null) { return newContainers; } nativeContainers.addAll(client.listContainers( DockerClient.ListContainersParam.allContainers())); } for (Container nativeContainer : nativeContainers) { if (nativeContainer.status() .startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(nativeContainer.id())) { loggingThreads.get(nativeContainer.id()).requestStop(); loggingThreads.remove(nativeContainer.id()); } } newContainers.add(new DockerContainer(this, nativeContainer)); } } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind(Messages.List_Docker_Containers_Failure, this.getName()), e); } finally { synchronized (containerLock) { this.containers = newContainers; this.containersLoaded = true; } } notifyContainerListeners(this.containers); return containers; }

Target:
private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> updatedContainers = new ArrayList<>(); final List<Container> rawContainers = new ArrayList<>(); try { synchronized (clientLock) { if (client == null) { return updatedContainers; } rawContainers.addAll(client.listContainers( DockerClient.ListContainersParam.allContainers())); } for (Container nativeContainer : rawContainers) { if (nativeContainer.status() .startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(nativeContainer.id())) { loggingThreads.get(nativeContainer.id()).requestStop(); loggingThreads.remove(nativeContainer.id()); } } if (!nativeContainer.status() .equals(Messages.Removal_In_Progress_specifier)) { updatedContainers .add(new DockerContainer(this, nativeContainer)); } } } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind(Messages.List_Docker_Containers_Failure, this.getName()), e); } finally { synchronized (containerLock) { this.containers = updatedContainers; this.containersLoaded = true; } } notifyContainerListeners(this.containers); return containers; }