auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void onPositionObserverUpdate() { if (controller == null || txtvPosition == null || txtvLength == null) { return; } TimeSpeedConverter timeSpeedConverter = new TimeSpeedConverter( UserPreferences.isTimeRespectSpeed(), Float.parseFloat(UserPreferences.getPlaybackSpeed())); int currentPosition = timeSpeedConverter.convert(controller.getPosition()); int duration = timeSpeedConverter.convert(controller.getDuration()); int remainingTime = timeSpeedConverter.convert(controller.getDuration()); Log.d(TAG, "currentPosition " + Converter.getDurationStringLong(currentPosition)); if (currentPosition == PlaybackService.INVALID_TIME || duration == PlaybackService.INVALID_TIME) { Log.w(TAG, "Could not react to position observer update because of invalid time"); return; } txtvPosition.setText(Converter.getDurationStringLong(currentPosition)); if (showTimeLeft) { txtvLength.setText("-" + Converter.getDurationStringLong(remainingTime)); } else { txtvLength.setText(Converter.getDurationStringLong(duration)); } updateProgressbarPosition(currentPosition, duration); }

Target:
void onPositionObserverUpdate() { if (controller == null || txtvPosition == null || txtvLength == null) { return; } int currentPosition = TimeSpeedConverter.convert(controller.getPosition()); int duration = TimeSpeedConverter.convert(controller.getDuration()); int remainingTime = TimeSpeedConverter.convert( controller.getDuration() - controller.getPosition()); Log.d(TAG, "currentPosition " + Converter.getDurationStringLong(currentPosition)); if (currentPosition == PlaybackService.INVALID_TIME || duration == PlaybackService.INVALID_TIME) { Log.w(TAG, "Could not react to position observer update because of invalid time"); return; } txtvPosition.setText(Converter.getDurationStringLong(currentPosition)); if (showTimeLeft) { txtvLength.setText("-" + Converter.getDurationStringLong(remainingTime)); } else { txtvLength.setText(Converter.getDurationStringLong(duration)); } updateProgressbarPosition(currentPosition, duration); }
Source:
public void configure_withComponentsDefinedInTheBuilderContext_shouldBeAccessibleThroughDomainContext() { final SpringDomainBundle springDomainBundle = new SpringDomainBundle( new MyCustomDomainBox.MyCustomDomain(), Lists.<Class>newArrayList() ); ExecutorService workers = Executors.newFixedThreadPool(2); Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey("workers", ExecutorService.class), workers); KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); springDomainBundle.configure(builderContext); assertEquals(workers, springDomainBundle.get(ExecutorService.class).get()); assertEquals(platformConfiguration.eventBus(), springDomainBundle.get(KasperEventBus.class).get()); assertEquals(platformConfiguration.commandGateway(), springDomainBundle.get(KasperCommandGateway.class).get()); assertEquals(platformConfiguration.queryGateway(), springDomainBundle.get(KasperQueryGateway.class).get()); assertEquals(platformConfiguration.configuration(), springDomainBundle.get(Config.class).get()); assertEquals(platformConfiguration.metricRegistry(), springDomainBundle.get(MetricRegistry.class).get()); }

Target:
public void configure_withComponentsDefinedInTheBuilderContext_shouldBeAccessibleThroughDomainContext() { final SpringDomainBundle springDomainBundle = new SpringDomainBundle( new MyCustomDomainBox.MyCustomDomain(), Lists.<Class>newArrayList() ); final ExecutorService workers = Executors.newFixedThreadPool(2); final Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey("workers", ExecutorService.class), workers); final KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration, extraComponents ); springDomainBundle.configure(builderContext); assertEquals(workers, springDomainBundle.get(ExecutorService.class).get()); assertEquals(platformConfiguration.eventBus(), springDomainBundle.get(KasperEventBus.class).get()); assertEquals(platformConfiguration.commandGateway(), springDomainBundle.get(KasperCommandGateway.class).get()); assertEquals(platformConfiguration.queryGateway(), springDomainBundle.get(KasperQueryGateway.class).get()); assertEquals(platformConfiguration.configuration(), springDomainBundle.get(Config.class).get()); assertEquals(platformConfiguration.metricRegistry(), springDomainBundle.get(MetricRegistry.class).get()); }
Source:
protected void itemAdded(AddRemoveProperty prop, ValueWithId item) { if (prop == NChild.PENALTY) { Penalty p = (Penalty)item; if (FO_EXP_ID.equals(p.getProviderId())) { updateEligibility(); } else if (!p.isServed() && getRole() == Role.JAMMER && getCurrentFielding() != null && !getCurrentFielding().getTeamJam().getOtherTeam().isLead()) { getTeam().set(Team.Value.LOST, true); } else if (!p.isServed() && !getScoreBoard().isInJam()) { getTeam().field(this, getRole(getTeam().getRunningOrEndedTeamJam()), getTeam().getRunningOrUpcomingTeamJam()); } } else if (prop == Child.FIELDING) { Fielding f = (Fielding)item; if (f.isCurrent()) { set(Value.CURRENT_FIELDING, item, Flag.INTERNAL); } else if (team.hasFieldingAdvancePending() && f.getTeamJam().isRunningOrEnded()) { setRole(f.getCurrentRole()); } } }

Target:
protected void itemAdded(AddRemoveProperty prop, ValueWithId item) { if (prop == NChild.PENALTY) { Penalty p = (Penalty)item; if (FO_EXP_ID.equals(p.getProviderId())) { updateEligibility(); } if (!p.isServed() && getRole() == Role.JAMMER && getCurrentFielding() != null && !getCurrentFielding().getTeamJam().getOtherTeam().isLead() && scoreBoard.isInJam()) { getTeam().set(Team.Value.LOST, true); } if (!p.isServed() && !getScoreBoard().isInJam()) { getTeam().field(this, getRole(getTeam().getRunningOrEndedTeamJam()), getTeam().getRunningOrUpcomingTeamJam()); } } else if (prop == Child.FIELDING) { Fielding f = (Fielding)item; if (f.isCurrent()) { set(Value.CURRENT_FIELDING, item, Flag.INTERNAL); } } }
Source:
public void start() { logger.debug("start()"); for (final Class<?> stepDefinitionType : cachedStepsInstances.keySet()) { cachedStepsInstances.put(stepDefinitionType, createStepsInstance(stepDefinitionType)); } }

Target:
public void start() { logger.trace("start()"); for (final Class<?> stepDefinitionType : cachedStepsInstances.keySet()) { cachedStepsInstances.put(stepDefinitionType, createStepsInstance(stepDefinitionType)); } }
Source:
public String getScript(String inMoovServiceName) { return String.format((Locale)null,"%s.moveArm(\"%s\",%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, bicep.getPos(), rotate.getPos(), shoulder.getPos(), omoplate.getPos()); }

Target:
public String getScript(String inMoovServiceName) { return String.format(Locale.ENGLISH,"%s.moveArm(\"%s\",%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, bicep.getPos(), rotate.getPos(), shoulder.getPos(), omoplate.getPos()); }
Source:
public void testNullValues() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ChatGrant grant = new ChatGrant() .setDeploymentRoleSid("RL123") .setPushCredentialSid("CR123") .setServiceSid("IS123"); String payload = mapper.writeValueAsString(grant); Assert.assertFalse(payload.contains("endpoint_id")); Assert.assertTrue(payload.contains("deployment_role_sid")); Assert.assertTrue(payload.contains("push_credential_sid")); Assert.assertTrue(payload.contains("service_sid")); }

Target:
public void testNullValues() { ChatGrant cg = new ChatGrant().setDeploymentRoleSid("RL123"); Jwt token = new AccessToken.Builder(ACCOUNT_SID, SIGNING_KEY_SID, SECRET) .grant(cg) .build(); Claims claims = getClaimFromJwtToken(token); validateToken(claims); Map<String, Object> decodedGrants = (Map<String, Object>) claims.get("grants"); Map<String, Object> grant = (Map<String, Object>) decodedGrants.get("chat"); Assert.assertEquals("RL123", grant.get("deployment_role_sid")); Assert.assertFalse(grant.containsKey("endpoint_id")); }
Source:
public XBeePacket parsePacket() throws PacketParsingException { try { readBytes = 0; lengthRead = false; errorMessage = ""; checksum = new XBeeChecksum(); int hSize = readByte(); int lSize = readByte(); length = hSize << 8 | lSize; lengthRead = true; int apiID = readByte(); XBeeAPIType apiType = XBeeAPIType.get(apiID); XBeePacket packet = null; if (apiType == null) { byte[] payload = readBytes(length - 1); packet = new UnknownXBeePacket(apiID, payload); } else { switch (apiType) { case AT_COMMAND: packet = parseATCommandPacket(); break; case AT_COMMAND_RESPONSE: packet = parseATCommandResponsePacket(); break; case RX_64: packet = parseRX64Packet(); break; case RX_16: packet = parseRX16Packet(); break; case RECEIVE_PACKET: packet = parseZigBeeReceivePacket(); break; case GENERIC: default: packet = parseGenericPacket(); } } readByte(); return packet; } catch (IOException e) { throw new PacketParsingException("Error parsing packet: " + e.getMessage()); } }

Target:
public XBeePacket parsePacket() throws PacketParsingException { try { readBytes = 0; lengthRead = false; checksum = new XBeeChecksum(); int hSize = readByte(); int lSize = readByte(); length = hSize << 8 | lSize; lengthRead = true; int apiID = readByte(); APIFrameType apiType = APIFrameType.get(apiID); XBeePacket packet = null; if (apiType == null) { byte[] payload = readBytes(length - 1); packet = new UnknownXBeePacket(apiID, payload); } else { switch (apiType) { case AT_COMMAND: packet = parseATCommandPacket(); break; case AT_COMMAND_RESPONSE: packet = parseATCommandResponsePacket(); break; case RX_64: packet = parseRX64Packet(); break; case RX_16: packet = parseRX16Packet(); break; case RECEIVE_PACKET: packet = parseZigBeeReceivePacket(); break; case GENERIC: default: packet = parseGenericPacket(); } } readByte(); return packet; } catch (IOException e) { throw new PacketParsingException("Error parsing packet: " + e.getMessage()); } }
Source:
public Described copy() { Segment copy = new Segment(); this.copyTo(this, copy); copy.setDuration(this.duration); copy.setDescription(this.description); copy.setSegmentType(this.segmentType); copy.setTitle(this.title); return copy; }

Target:
public Segment copy() { Segment copy = new Segment(); this.copyTo(copy); copy.setDescription(this.getDescription()); copy.setDuration(this.getDuration()); copy.setTitle(this.title); copy.setSegmentType(this.segmentType); return copy; }
Source:
public Map<String, LocalResource> getResourceMap() { return localResourceMap; }

Target:
public Map<String, LocalResource> getResourceMap() { return ImmutableMap.copyOf(localResourceMap); }
Source:
private ConvolutionalLayer(@Parameter(LayerIndex.class) final int index, @Parameter(LayerInputShape.class) final String inputShape, @Parameter(PaddingHeight.class) final int paddingHeight, @Parameter(PaddingWidth.class) final int paddingWidth, @Parameter(StrideHeight.class) final int strideHeight, @Parameter(StrideWidth.class) final int strideWidth, @Parameter(KernelHeight.class) final int kernelHeight, @Parameter(KernelWidth.class) final int kernelWidth, final LayerParameterInitializer layerParameterInitializer, final MatrixFactory matrixFactory) { super(index, inputShape); this.paddingHeight = paddingHeight; this.paddingWidth = paddingWidth; this.strideHeight = strideHeight; this.strideWidth = strideWidth; this.kernelHeight = kernelHeight; this.kernelWidth = kernelWidth; this.outputShape = layerParameterInitializer.getOutputShape(); this.matrixFactory = matrixFactory; this.output = null; this.layerError = null; if (getInputShape().length == 2) { this.inputChannel = 1; this.inputHeight = getInputShape()[0]; this.inputWidth = getInputShape()[1]; } else { this.inputChannel = getInputShape()[0]; this.inputHeight = getInputShape()[1]; this.inputWidth = getInputShape()[2]; } this.weightGradient = matrixFactory.create(kernelHeight * kernelWidth * inputChannel, outputShape[0]); }

Target:
private ConvolutionalLayer(@Parameter(LayerIndex.class) final int index, @Parameter(LayerInputShape.class) final String inputShape, @Parameter(PaddingHeight.class) final int paddingHeight, @Parameter(PaddingWidth.class) final int paddingWidth, @Parameter(StrideHeight.class) final int strideHeight, @Parameter(StrideWidth.class) final int strideWidth, @Parameter(KernelHeight.class) final int kernelHeight, @Parameter(KernelWidth.class) final int kernelWidth, final LayerParameterInitializer layerParameterInitializer, final MatrixFactory matrixFactory) { super(index, inputShape); this.paddingHeight = paddingHeight; this.paddingWidth = paddingWidth; this.strideHeight = strideHeight; this.strideWidth = strideWidth; this.kernelHeight = kernelHeight; this.kernelWidth = kernelWidth; this.outputShape = layerParameterInitializer.getOutputShape(); this.matrixFactory = matrixFactory; if (getInputShape().length == 2) { this.inputChannel = 1; this.inputHeight = getInputShape()[0]; this.inputWidth = getInputShape()[1]; } else { this.inputChannel = getInputShape()[0]; this.inputHeight = getInputShape()[1]; this.inputWidth = getInputShape()[2]; } }
Source:
protected INDArray preOutput(boolean training, boolean forBackprop, LayerWorkspaceMgr workspaceMgr) { assertInputSet(false); applyDropOutIfNecessary(training, workspaceMgr); if (input.rank() != 2) { throw new DL4JInvalidInputException("Got rank " + input.rank() + " array as input to RepeatVector with shape " + Arrays.toString(input.shape()) + ". Expected rank 2 array with shape [minibatchSize, size]. " + layerId()); } if (preOutput != null && forBackprop) { return preOutput; } long miniBatch = input.shape()[0]; long size = input.shape()[1]; INDArray output = input.reshape(miniBatch, size, 1); output = output.repeat(2, (long)getN()); output = output.detach(); return output; }

Target:
protected INDArray preOutput(boolean training, boolean forBackprop, LayerWorkspaceMgr workspaceMgr) { assertInputSet(false); applyDropOutIfNecessary(training, workspaceMgr); if (input.rank() != 2) { throw new DL4JInvalidInputException("Got rank " + input.rank() + " array as input to RepeatVector with shape " + Arrays.toString(input.shape()) + ". Expected rank 2 array with shape [minibatchSize, size]. " + layerId()); } if (preOutput != null && forBackprop) { return preOutput; } long miniBatch = input.shape()[0]; long size = input.shape()[1]; INDArray output = input.reshape(miniBatch, size, 1); try(MemoryWorkspace ws = workspaceMgr.notifyScopeBorrowed(ArrayType.ACTIVATIONS)) { return output.repeat(2, (long) getN()); } }
Source:
private RpslObject convertToRpslObject(final WhoisResources whoisResources, final ObjectType objectType) { for (WhoisObject whoisObject : whoisResources.getWhoisObjects()) { if (objectType == ObjectType.getByName(whoisObject.getType())) { return whoisObjectMapper.map(whoisObject, FormattedServerAttributeMapper.class); } } setErrorMessage(whoisResources, "Unable to find " + objectType + " in WhoisResources"); throw new ReferenceUpdateFailedException(Response.Status.BAD_REQUEST, whoisResources); }

Target:
private RpslObject convertToRpslObject(final WhoisResources whoisResources, final ObjectType objectType) { for (final WhoisObject whoisObject : whoisResources.getWhoisObjects()) { if (objectType == ObjectType.getByName(whoisObject.getType())) { return whoisObjectMapper.map(whoisObject, FormattedServerAttributeMapper.class); } } setErrorMessage(whoisResources, "Unable to find " + objectType + " in WhoisResources"); throw new ReferenceUpdateFailedException(Response.Status.BAD_REQUEST, whoisResources); }
Source:
public Message<?> receive() { return messages.poll(); }

Target:
public Message<?> receive() { return this.receive(0); }
Source:
protected void executeCommand() { setReturnValue(new VdcReturnValueBase()); VDSStatus lastStatus = getVds().getStatus(); try { if (!(getParameters().getAction() == FenceActionType.Start && lastStatus == VDSStatus.Maintenance)) { setStatus(); } setSucceeded(fence(getParameters().getAction())); } finally { if (!getSucceeded()) { setStatus(lastStatus); if (!skippedDueToFencingPolicy) { AlertIfPowerManagementOperationFailed(); } } else if ((getParameters().getAction() == FenceActionType.Restart || getParameters().getAction() == FenceActionType.Stop) && getParameters().getKeepPolicyPMEnabled() == false) { getVds().setPowerManagementControlledByPolicy(false); getDbFacade().getVdsDynamicDao().updateVdsDynamicPowerManagementPolicyFlag( getVdsId(), getVds().getDynamicData().isPowerManagementControlledByPolicy()); } } }

Target:
protected void executeCommand() { auditFenceOperation(); log.info("Power-Management: " + getActionString() + " host " + getVdsName()); setReturnValue(new VdcReturnValueBase()); VDSStatus lastStatus = getVds().getStatus(); try { if (!(getParameters().getAction() == FenceActionType.Start && lastStatus == VDSStatus.Maintenance)) { setStatus(); } setSucceeded(fence(getParameters().getAction())); if (getSucceeded()) { log.info("Power-Management: " + getActionString() + " host " + getVdsName() + " succeeded."); } else { log.info("Power-Management: " + getActionString() + " host " + getVdsName() + " failed."); } } finally { if (!getSucceeded()) { setStatus(lastStatus); if (!skippedDueToFencingPolicy) { AlertIfPowerManagementOperationFailed(); } } else if ((getParameters().getAction() == FenceActionType.Restart || getParameters().getAction() == FenceActionType.Stop) && getParameters().getKeepPolicyPMEnabled() == false) { getVds().setPowerManagementControlledByPolicy(false); getDbFacade().getVdsDynamicDao().updateVdsDynamicPowerManagementPolicyFlag( getVdsId(), getVds().getDynamicData().isPowerManagementControlledByPolicy()); } } }
Source:
private void connectToResourceManager() { assert(resourceManagerAddress != null); assert(establishedResourceManagerConnection == null); assert(resourceManagerConnection == null); log.info("Connecting to ResourceManager {}.", resourceManagerAddress); final TaskExecutorRegistration taskExecutorRegistration = new TaskExecutorRegistration( getAddress(), getResourceID(), unresolvedTaskManagerLocation.getDataPort(), JMXService.getPort().orElse(0), hardwareDescription, memoryConfiguration, taskManagerConfiguration.getDefaultSlotResourceProfile(), taskManagerConfiguration.getTotalResourceProfile() ); resourceManagerConnection = new TaskExecutorToResourceManagerConnection( log, getRpcService(), taskManagerConfiguration.getRetryingRegistrationConfiguration(), resourceManagerAddress.getAddress(), resourceManagerAddress.getResourceManagerId(), getMainThreadExecutor(), new ResourceManagerRegistrationListener(), taskExecutorRegistration); resourceManagerConnection.start(); }

Target:
private void connectToResourceManager() { assert(resourceManagerAddress != null); assert(establishedResourceManagerConnection == null); assert(resourceManagerConnection == null); log.info("Connecting to ResourceManager {}.", resourceManagerAddress); final TaskExecutorRegistration taskExecutorRegistration = new TaskExecutorRegistration( getAddress(), getResourceID(), unresolvedTaskManagerLocation.getDataPort(), JMXService.getPort().orElse(-1), hardwareDescription, memoryConfiguration, taskManagerConfiguration.getDefaultSlotResourceProfile(), taskManagerConfiguration.getTotalResourceProfile() ); resourceManagerConnection = new TaskExecutorToResourceManagerConnection( log, getRpcService(), taskManagerConfiguration.getRetryingRegistrationConfiguration(), resourceManagerAddress.getAddress(), resourceManagerAddress.getResourceManagerId(), getMainThreadExecutor(), new ResourceManagerRegistrationListener(), taskExecutorRegistration); resourceManagerConnection.start(); }
Source:
public static VSpherePlannedNode createInstance(final CloudProvisioningState templateState, final String nodeName, final CloudProvisioningRecord whatWeShouldSpinUp) { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final int numberOfExecutors = template.getNumberOfExecutors(); final Callable<Node> provisionNodeCallable = new Callable<Node>() { @Override public Node call() throws Exception { try { final Node newNode = provisionNewNode(whatWeShouldSpinUp, nodeName); VSLOG.log(Level.INFO, "Provisioned new slave " + nodeName); synchronized (templateState) { templateState.provisionedSlaveNowActive(whatWeShouldSpinUp, nodeName); } return newNode; } catch (Exception ex) { VSLOG.log(Level.WARNING, "Failed to provision new slave " + nodeName, ex); synchronized (templateState) { templateState.provisioningEndedInError(whatWeShouldSpinUp, nodeName); } throw ex; } } }; templateState.provisioningStarted(whatWeShouldSpinUp, nodeName); final Future<Node> provisionNodeTask = Computer.threadPoolForRemoting.submit(provisionNodeCallable); return new VSpherePlannedNode(nodeName, provisionNodeTask, numberOfExecutors); }

Target:
public static VSpherePlannedNode createInstance(final CloudProvisioningState templateState, final String nodeName, final CloudProvisioningRecord whatWeShouldSpinUp) { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final int numberOfExecutors = template.getNumberOfExecutors(); final Callable<Node> provisionNodeCallable = new Callable<Node>() { @Override public Node call() throws Exception { try { final Node newNode = provisionNewNode(whatWeShouldSpinUp, nodeName); VSLOG.log(Level.INFO, "Provisioned new slave " + nodeName); synchronized (templateState) { templateState.provisionedSlaveNowActive(whatWeShouldSpinUp, nodeName); } return newNode; } catch (Exception ex) { VSLOG.log(Level.WARNING, "Failed to provision new slave " + nodeName, ex); synchronized (templateState) { templateState.provisioningEndedInError(whatWeShouldSpinUp, nodeName); } throw ex; } } }; templateState.provisioningStarted(whatWeShouldSpinUp, nodeName); final Future<Node> provisionNodeTask = Computer.threadPoolForRemoting.submit(provisionNodeCallable); final VSpherePlannedNode result = new VSpherePlannedNode(nodeName, provisionNodeTask, numberOfExecutors); return result; }
Source:
public void init(ServerConfiguration conf) { throw new IllegalStateException("Deprecated method, no longer should be used."); }

Target:
public void init(ServerConfiguration conf) { this.config = conf; maxMemory = conf.getSystemConfiguration().getAsBytes(Property.TSERV_MAXMEM); maxConcurrentMincs = conf.getSystemConfiguration().getCount(Property.TSERV_MINC_MAXCONCURRENT); numWaitingMultiplier = TSERV_MINC_MAXCONCURRENT_NUMWAITING_MULTIPLIER; }
Source:
public URI createDirectory(URI parentFolderUri, String directoryName) throws IOException { File directory = new File(parentFolderUri.getPath() + File.separator + directoryName); if (!directory.mkdir()) { throw new IOException(); } return directory.toURI(); }

Target:
public URI createDirectory(URI parentFolderUri, String directoryName) throws IOException { File directory = new File(parentFolderUri.getPath() + File.separator + directoryName); if (!directory.mkdir()) { throw new IOException("Could not create directory."); } return directory.toURI(); }
Source:
public boolean setNavDrawerLogo(String uri, @Nullable String packageName, @Nullable String intent) { String connectedAppDirPath = IndexConstants.PLUGINS_DIR + packageName; File connectedAppDir = app.getAppPath(connectedAppDirPath); if (TextUtils.isEmpty(uri)) { app.getSettings().NAV_DRAWER_LOGO.resetToDefault(); Algorithms.removeAllFiles(connectedAppDir); } else { try { Uri fileUri = Uri.parse(uri); InputStream is = app.getContentResolver().openInputStream(fileUri); if (is != null) { String iconName = ImportHelper.getNameFromContentUri(app, fileUri); if (!connectedAppDir.exists()) { connectedAppDir.mkdirs(); } OutputStream fout = new FileOutputStream(new File(connectedAppDir, iconName)); try { Algorithms.streamCopy(is, fout); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } JSONObject json = new JSONObject(); json.put("", connectedAppDirPath + "/" + iconName); app.getSettings().NAV_DRAWER_LOGO.set(json.toString()); } } catch (FileNotFoundException e) { return false; } catch (JSONException e) { } catch (IOException e) { } if (packageName != null && intent != null) { navDrawerParams = new ArrayList<>(); navDrawerParams.add(packageName); navDrawerParams.add(intent); } } return true; }

Target:
public boolean setNavDrawerLogo(String uri, @Nullable String packageName, @Nullable String intent) { String connectedAppDirPath = IndexConstants.PLUGINS_DIR + packageName; File connectedAppDir = app.getAppPath(connectedAppDirPath); if (TextUtils.isEmpty(uri)) { app.getSettings().NAV_DRAWER_LOGO.resetToDefault(); Algorithms.removeAllFiles(connectedAppDir); } else { try { Uri fileUri = Uri.parse(uri); InputStream is = app.getContentResolver().openInputStream(fileUri); if (is != null) { String iconName = ImportHelper.getNameFromContentUri(app, fileUri); if (!connectedAppDir.exists()) { connectedAppDir.mkdirs(); } OutputStream fout = new FileOutputStream(new File(connectedAppDir, iconName)); try { Algorithms.streamCopy(is, fout); } finally { try { is.close(); } catch (IOException e) { LOG.error(e); } try { fout.close(); } catch (IOException e) { LOG.error(e); } } JSONObject json = new JSONObject(); json.put("", connectedAppDirPath + "/" + iconName); app.getSettings().NAV_DRAWER_LOGO.set(json.toString()); } } catch (FileNotFoundException e) { LOG.error(e); return false; } catch (JSONException e) { LOG.error("Failed to read json", e); } catch (IOException e) { LOG.error("Failed to write file", e); } if (packageName != null && intent != null) { navDrawerParams = new ArrayList<>(); navDrawerParams.add(packageName); navDrawerParams.add(intent); } } return true; }
Source:
public void setReferenceName(final String referenceName) { if (null == referenceName) { throw new IllegalArgumentException( "Reference name must not be null. Use SAMRecord.NO_ALIGNMENT_REFERENCE_NAME to reset the reference name."); } if (null != mHeader) { mReferenceIndex = resolveIndexFromName(referenceName, mHeader, false); mReferenceName = null == mReferenceIndex ? referenceName.intern() : resolveNameFromIndex(mReferenceIndex, mHeader); } else { mReferenceName = referenceName.intern(); mReferenceIndex = null; } }

Target:
public void setReferenceName(final String referenceName) { if (null == referenceName) { throw new IllegalArgumentException( "Reference name must not be null. Use SAMRecord.NO_ALIGNMENT_REFERENCE_NAME to reset the reference name."); } if (null != mHeader) { mReferenceIndex = resolveIndexFromName(referenceName, mHeader, false); mReferenceName = null == mReferenceIndex ? referenceName.intern() : resolveNameFromIndex(mReferenceIndex, mHeader); } else if (NO_ALIGNMENT_REFERENCE_NAME.equals(referenceName)) { mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else { mReferenceName = referenceName.intern(); mReferenceIndex = null; } }
Source:
public List<Column> getColumns() { return Collections.unmodifiableList(new ArrayList<>(columns)); }

Target:
public Set<Column> getColumns() { return Collections.unmodifiableSet(columns); }
Source:
private static void setMetadataRelatedIdentifiers(DepositMetadata depositMetadata, String dockstoreUrl, Workflow workflow) { List<RelatedIdentifier> aliasList = workflow.getAliases().keySet().stream() .map(alias -> { RelatedIdentifier relatedIdentifier = new RelatedIdentifier(); String aliasUrl = dockstoreUrl + "/aliases/workflows/" + alias; relatedIdentifier.setIdentifier(aliasUrl.toString()); relatedIdentifier.setRelation(RelatedIdentifier.RelationEnum.ISIDENTICALTO); return relatedIdentifier; }).collect(Collectors.toList()); depositMetadata.setRelatedIdentifiers(aliasList); }

Target:
private static void setMetadataRelatedIdentifiers(DepositMetadata depositMetadata, String dockstoreUrl, Workflow workflow) { List<RelatedIdentifier> aliasList = workflow.getAliases().keySet().stream() .map(alias -> { RelatedIdentifier relatedIdentifier = new RelatedIdentifier(); String aliasUrl = dockstoreUrl + "/aliases/workflows/" + alias; relatedIdentifier.setIdentifier(aliasUrl); relatedIdentifier.setRelation(RelatedIdentifier.RelationEnum.ISIDENTICALTO); return relatedIdentifier; }).collect(Collectors.toList()); depositMetadata.setRelatedIdentifiers(aliasList); }
Source:
public List<QuizSubmissionQuestion> answerQuestions(AnswerQuizQuestionOptions options, String answerArrayJson) throws IOException { LOG.debug("answering questions for quiz submission: " + options.getQuizSubmissionid()); String url = buildCanvasUrl("quiz_submissions/" + options.getQuizSubmissionid() + "/questions", options.getOptionsMap()); JsonObject requestBody = new JsonObject(); JsonParser parser = new JsonParser(); JsonArray answerJson = (JsonArray) parser.parse(answerArrayJson); requestBody.add("quiz_questions", answerJson); Response response = canvasMessenger.sendJsonPostToCanvas(oauthToken, url, requestBody); if(response.getErrorHappened() || response.getResponseCode() != 200) { LOG.error("Error answering questions. Returning null"); LOG.debug(response.getContent()); return null; } Type responseType = new TypeToken<QuizSubmissionWrapper>() { }.getType(); Gson responseGson = new GsonBuilder().registerTypeAdapter(responseType, new QuizSubmissionQuestionTypeAdapter()).create(); QuizSubmissionQuestionWrapper wrapper = responseGson.fromJson(response.getContent(), responseType); return wrapper.getQuizSubmissionQuestions(); }

Target:
public List<QuizSubmissionQuestion> answerQuestions(AnswerQuizQuestionOptions options, String answerArrayJson) throws IOException { if(options == null || answerArrayJson == null) { throw new IllegalArgumentException("options and answers must not be null"); } LOG.debug("answering questions for quiz submission: " + options.getQuizSubmissionid()); String url = buildCanvasUrl("quiz_submissions/" + options.getQuizSubmissionid() + "/questions", options.getOptionsMap()); JsonObject requestBody = new JsonObject(); JsonParser parser = new JsonParser(); JsonArray answerJson = (JsonArray) parser.parse(answerArrayJson); requestBody.add("quiz_questions", answerJson); Response response = canvasMessenger.sendJsonPostToCanvas(oauthToken, url, requestBody); if(response.getErrorHappened() || response.getResponseCode() != 200) { LOG.error("Error answering questions. Returning null"); LOG.debug(response.getContent()); return null; } Type responseType = new TypeToken<QuizSubmissionWrapper>() { }.getType(); Gson responseGson = new GsonBuilder().registerTypeAdapter(responseType, new QuizSubmissionQuestionTypeAdapter()).create(); QuizSubmissionQuestionWrapper wrapper = responseGson.fromJson(response.getContent(), responseType); return wrapper.getQuizSubmissionQuestions(); }
Source:
public void testParcelNetworkCapabilities() { final Set<UidRange> uids = new ArraySet<>(); uids.add(new UidRange(50, 100)); uids.add(new UidRange(3000, 4000)); final NetworkCapabilities netCap = new NetworkCapabilities() .addCapability(NET_CAPABILITY_INTERNET) .setUids(uids) .addCapability(NET_CAPABILITY_EIMS) .addCapability(NET_CAPABILITY_NOT_METERED); assertParcelingIsLossless(netCap); netCap.setSSID(TEST_SSID); assertParcelingIsLossless(netCap); }

Target:
public void testParcelNetworkCapabilities() { final Set<UidRange> uids = new ArraySet<>(); uids.add(new UidRange(50, 100)); uids.add(new UidRange(3000, 4000)); final NetworkCapabilities netCap = new NetworkCapabilities() .addCapability(NET_CAPABILITY_INTERNET) .setUids(uids) .addCapability(NET_CAPABILITY_EIMS) .addCapability(NET_CAPABILITY_NOT_METERED); assertParcelingIsLossless(netCap); netCap.setSSID(TEST_SSID); assertParcelSane(netCap, 11); }
Source:
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); final String authentication = restTemplate.execute(base.toString() + "/authentication", HttpMethod.GET, clientHttpRequest -> { }, clientHttpResponse -> IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset())); final String principal = restTemplate.execute(base.toString() + "/principal", HttpMethod.GET, clientHttpRequest -> { }, clientHttpResponse -> IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset())); assertNotNull(accessToken); assertEquals(authentication, "baeldung"); assertEquals(principal, "baeldung"); }

Target:
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); assertNotNull(accessToken); }
Source:
void validateText() { if (!funnel.shouldSeeChecks()) { return; } isTextValid = true; String text = pageDescriptionText.getText().toString().toLowerCase(); if (text.length() == 0) { isTextValid = false; setError(null); } else if (text.length() < 2) { isTextValid = false; setError(getContext().getString(R.string.description_too_short)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && StringUtils.endsWithAny(text, ".", ",", "!", "?")) { isTextValid = false; setError(getContext().getString(R.string.description_ends_with_punctuation)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && StringUtils.startsWithAny(text, "a ", "an ", "the ")) { setWarning(getContext().getString(R.string.description_starts_with_article)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && Character.isUpperCase(pageDescriptionText.getText().toString().charAt(0))) { setWarning(getContext().getString(R.string.description_starts_with_uppercase)); } else { setError(null); } updateSaveButtonEnabled(); }

Target:
void validateText() { if (!funnel.shouldSeeChecks()) { return; } isTextValid = true; String text = pageDescriptionText.getText().toString().toLowerCase().trim(); if (text.length() == 0) { isTextValid = false; setError(null); } else if (text.length() < 2) { isTextValid = false; setError(getContext().getString(R.string.description_too_short)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && StringUtils.endsWithAny(text, ".", ",", "!", "?")) { isTextValid = false; setError(getContext().getString(R.string.description_ends_with_punctuation)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && StringUtils.startsWithAny(text, "a ", "an ", "the ")) { setWarning(getContext().getString(R.string.description_starts_with_article)); } else if (pageTitle.getWikiSite().languageCode().equals("en") && Character.isUpperCase(pageDescriptionText.getText().toString().charAt(0))) { setWarning(getContext().getString(R.string.description_starts_with_uppercase)); } else { setError(null); } updateSaveButtonEnabled(); }
Source:
public void checkContainers() throws InterruptedException { long minIntervalMs = getMinIntervalMs(); getCandidates().stream() .forEach(containerPath -> { long startMs = Time.currentElapsedTime(); ByteBuffer path = ByteBuffer.wrap(containerPath.getBytes()); Request request = new Request(null, 0, 0, ZooDefs.OpCode.deleteContainer, path, null); try { LOG.info("Attempting to delete candidate container: {}", containerPath); postDeleteRequest(request); } catch (Exception e) { LOG.error("Could not delete container: {}", containerPath, e); } long elapsedMs = Time.currentElapsedTime() - startMs; long waitMs = minIntervalMs - elapsedMs; if (waitMs > 0) { try { Thread.sleep(waitMs); } catch (InterruptedException e) { e.printStackTrace(); } } }); }

Target:
public void checkContainers() throws InterruptedException { long minIntervalMs = getMinIntervalMs(); for (String containerPath : getCandidates()) { long startMs = Time.currentElapsedTime(); ByteBuffer path = ByteBuffer.wrap(containerPath.getBytes()); Request request = new Request(null, 0, 0, ZooDefs.OpCode.deleteContainer, path, null); try { LOG.info("Attempting to delete candidate container: {}", containerPath); postDeleteRequest(request); } catch (Exception e) { LOG.error("Could not delete container: {}", containerPath, e); } long elapsedMs = Time.currentElapsedTime() - startMs; long waitMs = minIntervalMs - elapsedMs; if (waitMs > 0) { Thread.sleep(waitMs); } } }
Source:
protected void deactivateTaskInternal(ITask task) { if (task == null) { return; } if (task.isActive() && task == activeTask) { initTaskListeners(); for (ITaskActivationListener listener : new ArrayList<ITaskActivationListener>(activationListeners)) { try { listener.preTaskDeactivated(task); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Notification failed for: " + listener, t)); } } ((AbstractTask) activeTask).setActive(false); activeTask = null; for (ITaskActivationListener listener : new ArrayList<ITaskActivationListener>(activationListeners)) { try { listener.taskDeactivated(task); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Notification failed for: " + listener, t)); } } } else { ((AbstractTask) task).setActive(false); } }

Target:
protected void deactivateTaskInternal(ITask task) { if (task.isActive() && task == activeTask) { initTaskListeners(); for (ITaskActivationListener listener : new ArrayList<ITaskActivationListener>(activationListeners)) { try { listener.preTaskDeactivated(task); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Notification failed for: " + listener, t)); } } ((AbstractTask) activeTask).setActive(false); activeTask = null; for (ITaskActivationListener listener : new ArrayList<ITaskActivationListener>(activationListeners)) { try { listener.taskDeactivated(task); } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Notification failed for: " + listener, t)); } } } else { ((AbstractTask) task).setActive(false); } }
Source:
public String[] getFinalizedUptoPartitions(List<Message> lastMessages, List<Message> committedMessages) throws Exception { return null; }

Target:
public String[] getFinalizedUptoPartitions(List<Message> lastMessages, List<Message> committedMessages) throws Exception { throw new UnsupportedOperationException("Partition finalization is not supported"); }
Source:
OffHeapResource(long size) { if (size < 0) { throw new IllegalArgumentException("Resource size cannot be negative"); } else { this.remaining = new AtomicLong(size); } }

Target:
OffHeapResource(long size) throws IllegalArgumentException { if (size < 0) { throw new IllegalArgumentException("Resource size cannot be negative"); } else { this.remaining = new AtomicLong(size); } }
Source:
private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { checkNotNull(endPoint); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized ( this ) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if ( existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld() ) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; if (existingServiceHandle != null) { toDelete = existingServiceHandle; } toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } return toReturn; }

Target:
private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { checkNotNull(endPoint); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized (this) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if (existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld()) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; toDelete = existingServiceHandle; toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } return toReturn; }
Source:
public OmemoBundleElement(int signedPreKeyId, String signedPreKeyB64, String signedPreKeySigB64, String identityKeyB64, HashMap<Integer, String> preKeysB64) { if (signedPreKeyId <= 0) { throw new IllegalArgumentException("signedPreKeyId MUST be greater than 0."); } this.signedPreKeyId = signedPreKeyId; if (StringUtils.isNullOrEmpty(signedPreKeyB64)) { throw new IllegalArgumentException("signedPreKeyB64 MUST NOT be null nor empty."); } this.signedPreKeyB64 = signedPreKeyB64; if (StringUtils.isNullOrEmpty(signedPreKeySigB64)) { throw new IllegalArgumentException("signedPreKeySigB64 MUST NOT be null nor empty."); } this.signedPreKeySignatureB64 = signedPreKeySigB64; if (StringUtils.isNullOrEmpty(identityKeyB64)) { throw new IllegalArgumentException("identityKeyB64 MUST NOT be null nor empty."); } this.identityKeyB64 = identityKeyB64; if (preKeysB64 == null || preKeysB64.isEmpty()) { throw new IllegalArgumentException("PreKeys MUST NOT be null nor empty."); } this.preKeysB64 = preKeysB64; }

Target:
public OmemoBundleElement(int signedPreKeyId, String signedPreKeyB64, String signedPreKeySigB64, String identityKeyB64, HashMap<Integer, String> preKeysB64) { if (signedPreKeyId <= 0) { throw new IllegalArgumentException("signedPreKeyId MUST be greater than 0."); } this.signedPreKeyId = signedPreKeyId; this.signedPreKeyB64 = StringUtils.requireNotNullNorEmpty(signedPreKeyB64, "signedPreKeyB64 MUST NOT be null nor empty."); this.signedPreKeySignatureB64 = StringUtils.requireNotNullNorEmpty(signedPreKeySigB64, "signedPreKeySigB64 MUST NOT be null nor empty."); this.identityKeyB64 = StringUtils.requireNotNullNorEmpty(identityKeyB64, "identityKeyB64 MUST NOT be null nor empty."); if (preKeysB64 == null || preKeysB64.isEmpty()) { throw new IllegalArgumentException("PreKeys MUST NOT be null nor empty."); } this.preKeysB64 = preKeysB64; }
Source:
public static NewDeviceRequestDTO createInstance(NewDeviceRequest newDeviceRequestEntity) { if (newDeviceRequestEntity == null) { return new NewDeviceRequestDTO(null, null); } return new NewDeviceRequestDTO(newDeviceRequestEntity.getExpirationTime(), null); }

Target:
public static NewDeviceRequestDTO createInstance(NewDeviceRequest newDeviceRequestEntity) { return new NewDeviceRequestDTO(null, false); }
Source:
private boolean testStorageConnection() { AddManagedBlockStorageDomainParameters parameters = (AddManagedBlockStorageDomainParameters) getParameters(); Map<String, Object> driverOptions = new HashMap<>(parameters.getDriverOptions()); if (parameters.getDriverSensitiveOptions() != null) { driverOptions.putAll(parameters.getDriverSensitiveOptions()); } CinderlibReturnValue returnValue = null; Map<String, Object> storageStats; try { CinderlibCommandParameters params = new CinderlibCommandParameters(JsonHelper.mapToJson(driverOptions, false), Collections.singletonList(Boolean.TRUE.toString())); returnValue = cinderlibExecutor.runCommand(CinderlibExecutor.CinderlibCommand.STORAGE_STAT, params); storageStats = JsonHelper.jsonToMap(returnValue.getOutput()); } catch (Exception e) { failValidation(EngineMessage.FAILED_TO_CONNECT_MANAGED_BLOCK_DOMAIN, String.format("$output %1$s", returnValue != null ? returnValue.getOutput() : "")); return false; } if (storageStats != null) { log.debug(storageStats.toString()); } return (returnValue.getSucceed() && storageStats != null) || failValidation(EngineMessage.FAILED_TO_CONNECT_MANAGED_BLOCK_DOMAIN, String.format("$output %1$s", returnValue.getOutput())); }

Target:
private boolean testStorageConnection() { ActionReturnValue actionReturnValue = runInternalAction(ActionType.GetManagedBlockStorageStat, getParameters()); return (actionReturnValue.getSucceeded() && actionReturnValue.getActionReturnValue() != null) || failValidation(EngineMessage.FAILED_TO_CONNECT_MANAGED_BLOCK_DOMAIN); }
Source:
public void operateOn(StructuredRecord record) { T field = record.get(fieldName); if (Objects.nonNull(field)) { collectSet.add(field); } }

Target:
public void operateOn(StructuredRecord record) { T field = record.get(fieldName); collectSet.add(field); }
Source:
protected String getFixedPart() { if (getDefinition().getWhereClause() != null) { String fixedPart = getDefinition().getWhereClause().getFixedPart(); if (fixedPart != null && !fixedPart.isEmpty()) { return fixedPart; } } if (getParameters().length == 3) { return complexQuery; } else { return singleQuery; } }

Target:
protected String getFixedPart() { if (getDefinition().getWhereClause() != null) { String fixedPart = getDefinition().getWhereClause().getFixedPart(); if (StringUtils.isNotEmpty(fixedPart)) { return fixedPart; } } if (getParameters().length == 3) { return complexQuery; } else { return singleQuery; } }
Source:
public File getRepositoryArchive(Integer projectId, String sha, File directory, String format) throws GitLabApiException { Form formData = new GitLabApiForm().withParam("sha", sha); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", projectId, "repository", "archive".concat(checkFormat(format))); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = FileUtils.getFilenameFromContentDisposition(response); File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }

Target:
public File getRepositoryArchive(Integer projectId, String sha, File directory, String format) throws GitLabApiException { format = checkFormat(format); Form formData = new GitLabApiForm().withParam("sha", sha); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", projectId, "repository", "archive", ".", format); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = FileUtils.getFilenameFromContentDisposition(response); File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }
Source:
public void doesNotFallbackOnPingWhenPingV2Responds() { availableServer.stubFor(PING_V2_MAPPING.willReturn(WireMock.aResponse().withStatus(200) .withBody("{\"isLeader\":false}"))); pingerWithVersion(OrderableSlsVersion.valueOf("1.1.1")).pingLeaderWithUuid(REMOTE_UUID); List<LoggedRequest> requests = WireMock.findAll(WireMock.getRequestedFor(WireMock.urlMatching(PING_V2))); assertThat(requests.size()).isEqualTo(1); requests = WireMock.findAll(WireMock.getRequestedFor(WireMock.urlMatching(PING))); assertThat(requests.size()).isEqualTo(0); }

Target:
public void doesNotFallbackOnPingWhenPingV2Responds() { availableServer.stubFor(PING_V2_MAPPING.willReturn(WireMock.aResponse().withStatus(200) .withBody("{\"isLeader\":false}"))); getDefaultLeaderPinger().pingLeaderWithUuid(REMOTE_UUID); assertPingV2RequestsMadeAreExactly(1); assertLegacyPingRequestsMade(0); }