auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void deleteTiffHeaderFile(List<Process> processes) { for (Process process : processes) { try { File tiffHeaderFile = new File( serviceManager.getFileService().getImagesDirectory(process) + "tiffwriter.conf"); if (tiffHeaderFile.exists()) { tiffHeaderFile.delete(); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "TiffHeaderFile deleted: ", process.getTitle()); } catch (Exception e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while deleting TiffHeader", e); } } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "deleteTiffHeaderFile finished"); }

Target:
public void deleteTiffHeaderFile(List<Process> processes) { for (Process process : processes) { try { File tiffHeaderFile = new File( serviceManager.getFileService().getImagesDirectory(process) + "tiffwriter.conf"); if (tiffHeaderFile.exists()) { tiffHeaderFile.delete(); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "TiffHeaderFile deleted: ", process.getTitle()); } catch (RuntimeException e) { Helper.setErrorMessage(KITODO_SCRIPT_FIELD, "Error while deleting TiffHeader", logger, e); } } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "deleteTiffHeaderFile finished"); }
Source:
public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); String atCommand = ioLine.getPWMATCommand(); ATCommandResponse response = sendATCommand(new ATCommand(atCommand, ByteUtils.intToByteArray(finaldutyCycle))); if (response == null || response.getResponseStatus() != ATCommandStatus.OK) throw new XBeeException(XBeeException.INVALID_OPERATION); }

Target:
public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); String atCommand = ioLine.getPWMDutyCycleATCommand(); ATCommandResponse response = sendATCommand(new ATCommand(atCommand, ByteUtils.intToByteArray(finaldutyCycle))); if (response == null || response.getResponseStatus() != ATCommandStatus.OK) throw new XBeeException(XBeeException.INVALID_OPERATION); }
Source:
public static Set<Path> getIncludedFieldsOfRootEntityForSort(CompositeMetadata root, Sort rootSort) { Set<Path> ret=new HashSet<Path>(); if(rootSort!=null) { SortFieldInfo[] sfi=SortFieldInfo.buildSortFields(rootSort,root.getFieldTreeRoot()); for(SortFieldInfo fi:sfi) ret.add(fi.getName()); } return ret; }

Target:
public static Set<Path> getIncludedFieldsOfRootEntityForSort(CompositeMetadata root, Sort rootSort) { Set<Path> ret=new HashSet<>(); if(rootSort!=null) { SortFieldInfo[] sfi=SortFieldInfo.buildSortFields(rootSort,root.getFieldTreeRoot()); for(SortFieldInfo fi:sfi) ret.add(fi.getName()); } return ret; }
Source:
private void logReceivedMessages(final List<BasicMessage> receivedMessages) { if (isLogReceivedMessages()) { for (final BasicMessage message : receivedMessages) { try { LOGGER.debug("MSG-RECV [{}]", message.getClass().getSimpleName(), message.getBody()); } catch (final MessageParseException e) { LOGGER.debug("MSG-RECV [{}]", e.getMessage()); } } } }

Target:
private void logReceivedMessages(final List<BasicMessage> receivedMessages) { if (isLogReceivedMessages()) { for (final BasicMessage message : receivedMessages) { try { LOGGER.debug("MSG-RECV [{}]", "", message.getBody()); } catch (final MessageParseException e) { LOGGER.debug("MSG-RECV [{}]", e.getMessage()); } } } }
Source:
public long getLockTimeout() { Setting setting = findSetting( SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT)); return setting == null ? Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue(); }

Target:
public int getLockTimeout() { Setting setting = findSetting( SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT)); return setting == null ? Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue(); }
Source:
protected boolean uploadVendorsToPaymentWorks(Collection<PaymentWorksVendor> vendors, PaymentWorksUploadSuppliersBatchReportData reportData) { InputStream vendorCsvDataStream = null; try { checkForPotentialVendorDeletionAttempts(vendors); byte[] vendorCsvData = generateVendorCsvDataForUpload(vendors); vendorCsvDataStream = new ByteArrayInputStream(vendorCsvData); int receivedVendorCount = paymentWorksWebServiceCallsService.uploadVendorsToPaymentWorks(vendorCsvDataStream); reportData.getRecordsProcessedByPaymentWorksSummary().setRecordCount(receivedVendorCount); if (receivedVendorCount != vendors.size()) { LOG.warn("uploadVendorsToPaymentWorks, " + vendors.size() + " vendors were sent to PaymentWorks, but PaymentWorks reported that it received " + receivedVendorCount + " vendors instead"); reportData.getGlobalMessages().add(paymentWorksBatchUtilityService.retrievePaymentWorksParameterValue( PaymentWorksParameterConstants.PAYMENTWORKS_UPLOAD_SUPPLIERS_REPORT_VENDOR_COUNT_MISMATCH_MESSAGE)); } return true; } catch (RuntimeException e) { LOG.error("uploadVendorsToPaymentWorks, error encountered when uploading vendors to PaymentWorks", e); reportData.getGlobalMessages().add(paymentWorksBatchUtilityService.retrievePaymentWorksParameterValue( PaymentWorksParameterConstants.PAYMENTWORKS_UPLOAD_SUPPLIERS_REPORT_VENDOR_UPLOAD_FAILURE_MESSAGE)); return false; } finally { IOUtils.closeQuietly(vendorCsvDataStream); } }

Target:
protected boolean uploadVendorsToPaymentWorks(Collection<PaymentWorksVendor> vendors, PaymentWorksUploadSuppliersBatchReportData reportData) { InputStream vendorCsvDataStream = null; try { checkForPotentialVendorDeletionAttempts(vendors); byte[] vendorCsvData = generateVendorCsvDataForUpload(vendors); vendorCsvDataStream = new ByteArrayInputStream(vendorCsvData); int receivedVendorCount = paymentWorksWebServiceCallsService.uploadVendorsToPaymentWorks(vendorCsvDataStream); reportData.getRecordsProcessedByPaymentWorksSummary().setRecordCount(receivedVendorCount); if (receivedVendorCount != vendors.size()) { LOG.warn("uploadVendorsToPaymentWorks, " + vendors.size() + " vendors were sent to PaymentWorks, but PaymentWorks reported that it received " + receivedVendorCount + " vendors instead"); String warningPrefix = paymentWorksBatchUtilityService.retrievePaymentWorksParameterValue( PaymentWorksParameterConstants.PAYMENTWORKS_UPLOAD_SUPPLIERS_REPORT_VENDOR_COUNT_MISMATCH_MESSAGE_PREFIX); reportData.getGlobalMessages().add(warningPrefix + buildVendorNumberList(vendors)); } return true; } catch (RuntimeException e) { LOG.error("uploadVendorsToPaymentWorks, error encountered when uploading vendors to PaymentWorks", e); String errorPrefix = paymentWorksBatchUtilityService.retrievePaymentWorksParameterValue( PaymentWorksParameterConstants.PAYMENTWORKS_UPLOAD_SUPPLIERS_REPORT_VENDOR_UPLOAD_FAILURE_MESSAGE_PREFIX); reportData.getGlobalMessages().add( formatGlobalErrorMessage(errorPrefix, buildVendorNumberList(vendors), e.getMessage())); return false; } finally { IOUtils.closeQuietly(vendorCsvDataStream); } }
Source:
private void useAppFor2minThenBackground() throws Exception { advanceSystemAndElapsedTimeBy(time,0); OneSignalInit(); threadAndTaskWait(); advanceSystemAndElapsedTimeBy(time, 2 * 60); blankActivityController.pause(); OneSignalPackagePrivateHelper.runFocusRunnables(); threadAndTaskWait(); }

Target:
private void useAppFor2minThenBackground() throws Exception { time.advanceSystemAndElapsedTimeBy(0); OneSignalInit(); threadAndTaskWait(); time.advanceSystemAndElapsedTimeBy(2 * 60); blankActivityController.pause(); OneSignalPackagePrivateHelper.runFocusRunnables(); threadAndTaskWait(); }
Source:
public int getInt(int length, boolean signed) { int val = 0; if (!canRead(length)) { throw new BufferOverflowException(); } if (length > BIT_INT) { throw new IllegalArgumentException("Maximum size of value is 32 requested size" + length); } if (length < 0) { throw new IllegalArgumentException("Cannot handle negative reads"); } if (length == 0) { return 0; } boolean gotIt = false; if (this.pos % BitBuffer.BIT_CHAR == 0) { switch (length) { case BitBuffer.BIT_CHAR: if (signed) { val = this.buf.get((int) (this.pos / 8)); } else { val = (this.buf.get((int) (this.pos / 8))) & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: if (signed) { val = this.buf.getShort((int) (this.pos / 8)); } else { short a = this.buf.getShort((int) (this.pos / 8)); val = a & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }

Target:
public int getInt(int length, boolean signed) { if (length == 0) { return 0; } if (!canRead(length)) { throw new BufferOverflowException(); } if (length > BIT_INT) { throw new IllegalArgumentException("Maximum size of value is 32 requested size" + length); } if (length < 0) { throw new IllegalArgumentException("Cannot handle negative reads"); } int val = 0; if (!canRead(length)) { throw new BufferOverflowException(); } boolean gotIt = false; if (this.pos % BitBuffer.BIT_CHAR == 0) { switch (length) { case BitBuffer.BIT_CHAR: val = this.buf.get((int) (this.pos / 8)); if (!signed) { val = val & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: val = this.buf.getShort((int) (this.pos / 8)); if (!signed) { val = val & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }
Source:
public ParallelExecutor(ConfigurationParameters parameters) { ConfigurationParameters prefixedParameters = new PrefixedConfigurationParameters(parameters, PARALLEL_CONFIG); String strategyName = prefixedParameters.get("strategy").orElse("dynamic"); ParallelExecutionConfigurationStrategy executionStrategy = DefaultParallelExecutionConfigurationStrategy.valueOf( strategyName.toUpperCase()); ParallelExecutionConfiguration executionConfiguration = executionStrategy.createConfiguration( prefixedParameters); executorService = new ForkJoinPoolFactory().apply(executionConfiguration); }

Target:
public ParallelExecutor(ConfigurationParameters parameters) { ConfigurationParameters prefixedParameters = new PrefixedConfigurationParameters(parameters, PARALLEL_CONFIG); String strategyName = prefixedParameters.get("strategy").orElse("dynamic"); ParallelExecutionConfigurationStrategy executionStrategy = DefaultParallelExecutionConfigurationStrategy.valueOf( strategyName.toUpperCase()); ParallelExecutionConfiguration executionConfiguration = executionStrategy.createConfiguration( prefixedParameters); executorService = ForkJoinPoolFactory.create(executionConfiguration); }
Source:
public HideAttributesWizardPage(AbstractTaskEditorPage page, String listVar) { super("HideAttributes"); setTitle("Hide Attributes"); setDescription( "The attributes in the left list will be displayed and the attributes in the right list will be hidden."); TaskData data = page.getModel().getTaskData(); this.attributes = data.getRoot().getAttributes(); this.currentList = listVar; optionAttributes = new ArrayList<>(); chosenAttributes = new ArrayList<>(); }

Target:
public HideAttributesWizardPage(AbstractTaskEditorPage page, String listVar) { super("HideAttributes"); setTitle(Messages.HideAttributesWizardPage_ConfigureAttributeVisibility); setDescription(Messages.HideAttributesWizardPage_Description); TaskData data = page.getModel().getTaskData(); this.attributes = data.getRoot().getAttributes(); this.currentList = listVar; optionAttributes = new ArrayList<>(); chosenAttributes = new ArrayList<>(); }
Source:
public LiveData<List<Object>> getBookmarkedSessions() { if (filterableRealmLiveData == null) filterableRealmLiveData = RealmDataRepository.asFilterableLiveData(realmRepo.getSessions()); Predicate<Session> predicate = Session::getIsBookmarked; filterableRealmLiveData.filter(predicate); return Transformations.map(filterableRealmLiveData, this::getSessionsList); }

Target:
public LiveData<List<Object>> getBookmarkedSessions() { if (filterableRealmLiveData == null) filterableRealmLiveData = RealmDataRepository.asFilterableLiveData(realmRepo.getBookMarkedSessions()); Predicate<Session> predicate = Session::getIsBookmarked; filterableRealmLiveData.filter(predicate); return Transformations.map(filterableRealmLiveData, this::getSessionsList); }
Source:
public List<ServerTemplate> load() { synchronized (store) { return store.values().stream().map(e -> cloneServerTemplate(e)).collect(Collectors.toList()); } }

Target:
public List<ServerTemplate> load() { synchronized (store) { return store.values().stream().map(this::cloneServerTemplate).collect(Collectors.toList()); } }
Source:
public static void initializeDefaultPreferences(IEclipsePreferences defaultPreferences) { Preferences prefs= defaultPreferences.node(INDEXER_NODE); prefs.put(KEY_INDEXER_ID, IPDOMManager.ID_FAST_INDEXER); prefs.putBoolean(KEY_INDEX_ALL_FILES, true); prefs.putBoolean(KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG, true); prefs.putBoolean(KEY_INDEX_UNUSED_HEADERS_WITH_ALTERNATE_LANG, true); prefs.putBoolean(KEY_INDEX_ON_OPEN, false); prefs.putBoolean(KEY_INCLUDE_HEURISTICS, true); prefs.putInt(KEY_SKIP_FILES_LARGER_THAN_MB, DEFAULT_FILE_SIZE_LIMIT); prefs.putBoolean(KEY_SKIP_ALL_REFERENCES, false); prefs.putBoolean(KEY_SKIP_IMPLICIT_REFERENCES, false); prefs.putBoolean(KEY_SKIP_TYPE_REFERENCES, false); prefs.putBoolean(KEY_SKIP_MACRO_REFERENCES, false); prefs.put(KEY_INDEX_IMPORT_LOCATION, DEFAULT_INDEX_IMPORT_LOCATION); }

Target:
public static void initializeDefaultPreferences(IEclipsePreferences defaultPreferences) { Preferences prefs= defaultPreferences.node(INDEXER_NODE); prefs.put(KEY_INDEXER_ID, IPDOMManager.ID_FAST_INDEXER); prefs.putBoolean(KEY_INDEX_ALL_FILES, true); prefs.putBoolean(KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG, true); prefs.putBoolean(KEY_INDEX_UNUSED_HEADERS_WITH_ALTERNATE_LANG, false); prefs.putBoolean(KEY_INDEX_ON_OPEN, false); prefs.putBoolean(KEY_INCLUDE_HEURISTICS, true); prefs.putInt(KEY_SKIP_FILES_LARGER_THAN_MB, DEFAULT_FILE_SIZE_LIMIT); prefs.putBoolean(KEY_SKIP_ALL_REFERENCES, false); prefs.putBoolean(KEY_SKIP_IMPLICIT_REFERENCES, false); prefs.putBoolean(KEY_SKIP_TYPE_REFERENCES, false); prefs.putBoolean(KEY_SKIP_MACRO_REFERENCES, false); prefs.put(KEY_INDEX_IMPORT_LOCATION, DEFAULT_INDEX_IMPORT_LOCATION); }
Source:
public DefaultEquivalenceResultBuilder( ScoreCombiner<T> combiner, EquivalenceFilter<T> filter, List<EquivalenceExtractor<T>> extractors ) { this.combiner = combiner; this.filter = filter; this.extractors = extractors; this.multipleCandidateExtractor = MultipleCandidateExtractor.create(); }

Target:
public DefaultEquivalenceResultBuilder( ScoreCombiner<T> combiner, EquivalenceFilter<T> filter, List<EquivalenceExtractor<T>> extractors ) { this.combiner = combiner; this.filter = filter; this.extractors = extractors; }
Source:
public void shouldConvertToAvroWhenReceivedJSONOnAvroTopic() throws IOException { AvroMessage message = new AvroMessage("1", avroMessage.asJson().getBytes(), 1234, schema); Message enforcedMessage = enforcer.enforceAvro("application/json", message); assertThat(enforcedMessage.getData()).isEqualTo(avroMessage.asBytes()); }

Target:
public void shouldConvertToAvroWhenReceivedJSONOnAvroTopic() throws IOException { byte[] enforcedMessage = enforcer.enforceAvro("application/json", avroMessage.asJson().getBytes(), schema.getSchema()); assertThat(enforcedMessage).isEqualTo(avroMessage.asBytes()); }
Source:
public boolean containsValue(final TransactionLocal transactionLocal, final Transaction transaction) { com.arjuna.ats.jta.transaction.Transaction transactionImple = (com.arjuna.ats.jta.transaction.Transaction) transaction; if(transactionImple.isAlive()) { return (transactionImple.getTxLocalResource(transactionLocal) != null); } else { return false; } }

Target:
public boolean containsValue(final TransactionLocal transactionLocal, final Transaction transaction) { com.arjuna.ats.jta.transaction.Transaction transactionImple = (com.arjuna.ats.jta.transaction.Transaction) transaction; if(transactionImple.isAlive()) { return (transactionImple.getTxLocalResource(transactionLocal) != null ? true : false); } else { return false; } }
Source:
private void setNetInterfaceAddressConfigs(String interfaceName, boolean dhcp, List<NetConfig> netConfigs, NetInterfaceAddressConfig netInterfaceAddressConfig) { if (netInterfaceAddressConfig instanceof NetInterfaceAddressConfigImpl) { ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig).setNetConfigs(netConfigs); if (dhcp) { List<? extends IPAddress> dhcpRouters = getDhcpRouters(interfaceName, netInterfaceAddressConfig.getAddress()); if (!dhcpRouters.isEmpty()) { ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig).setGateway(dhcpRouters.get(0)); } List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers(interfaceName, netInterfaceAddressConfig.getAddress()); if (!dhcpDnsServers.isEmpty()) { ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig).setDnsServers(dhcpDnsServers); } } } else if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfigImpl) { ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig).setNetConfigs(netConfigs); if (dhcp) { List<? extends IPAddress> dhcpRouters = getDhcpRouters(interfaceName, netInterfaceAddressConfig.getAddress()); if (!dhcpRouters.isEmpty()) { ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig).setGateway(dhcpRouters.get(0)); } List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers(interfaceName, netInterfaceAddressConfig.getAddress()); if (!dhcpDnsServers.isEmpty()) { ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig).setDnsServers(dhcpDnsServers); } } } }

Target:
private void setNetInterfaceAddressConfigs(String interfaceName, boolean dhcp, List<NetConfig> netConfigs, NetInterfaceAddressConfig netInterfaceAddressConfig) { if (netInterfaceAddressConfig instanceof NetInterfaceAddressConfigImpl) { setNetInterfaceAddressConfigs(interfaceName, netConfigs, netInterfaceAddressConfig, dhcp); } else if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfigImpl) { setWifiNetInterfaceAddressConfigs(interfaceName, netConfigs, netInterfaceAddressConfig, dhcp); } }
Source:
public void setTerminator(String terminator) { if (terminator.length() != 1 || !StatementFinder.isValidTerminator(terminator.charAt(0))) { out.println(langUtil.getTextMessage("IJ_TerminatorInvalid", terminator)); } this.terminator = terminator.charAt(0); commandGrabber[currCE].setTerminator(this.terminator); }

Target:
public void setTerminator(String terminator) { if (terminator.length() != 1 || !StatementFinder.isValidTerminator(terminator.charAt(0))) { out.println(langUtil.getTextMessage("IJ_TerminatorInvalid", terminator)); return; } this.terminator = terminator.charAt(0); commandGrabber[currCE].setTerminator(this.terminator); }
Source:
public Date getCreationDate() { return creationDate; }

Target:
public Date getCreationDate() { return (Date) creationDate.clone(); }
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { BulkChange b = new BulkChange(this); SMTPAuthentication current = this.authentication; try { this.authentication = null; req.bindJSON(this, json); b.commit(); } catch (IOException e) { this.authentication = current; b.abort(); throw new FormException("Failed to apply configuration", e, null); } return true; }

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { BulkChange b = new BulkChange(this); SMTPAuthentication current = this.authentication; try { this.authentication = null; req.bindJSON(this, json); b.commit(); } catch (IOException e) { b.abort(); throw new FormException("Failed to apply configuration", e, null); } finally { this.authentication = current; } return true; }
Source:
private ReconnectionManager(AbstractXMPPConnection connection) { weakRefConnection = new WeakReference<AbstractXMPPConnection>(connection); reconnectionRunnable = new Thread() { private int attempts = 0; private int timeDelay() { attempts++; int delay = -1; switch(reconnectionPolicy) { case FIXED_DELAY: delay = fixedDelay; break; case RANDOM_INCREASING_DELAY: if (attempts > 13) { delay = randomBase * 6 * 5; } if (attempts > 7) { delay = randomBase * 6; } delay = randomBase; break; } return delay; } public void run() { final AbstractXMPPConnection connection = weakRefConnection.get(); if (connection == null) { return; } while (isReconnectionPossible(connection)) { int remainingSeconds = timeDelay(); while (isReconnectionPossible(connection) && remainingSeconds > 0) { try { Thread.sleep(1000); remainingSeconds--; for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectingIn(remainingSeconds); } } catch (InterruptedException e) { LOGGER.log(Level.FINE, "waiting for reconnection interrupted", e); break; } } for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectingIn(0); } try { if (isReconnectionPossible(connection)) { connection.connect(); } } catch (Exception e) { for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectionFailed(e); } } } } }; if (getEnabledByDefault()) { enableAutomaticReconnection(); } }

Target:
private ReconnectionManager(AbstractXMPPConnection connection) { weakRefConnection = new WeakReference<AbstractXMPPConnection>(connection); reconnectionRunnable = new Thread() { private int attempts = 0; private int timeDelay() { attempts++; int delay; switch(reconnectionPolicy) { case FIXED_DELAY: delay = fixedDelay; break; case RANDOM_INCREASING_DELAY: if (attempts > 13) { delay = randomBase * 6 * 5; } if (attempts > 7) { delay = randomBase * 6; } delay = randomBase; break; default: throw new AssertionError("Unknown reconnection policy " + reconnectionPolicy); } return delay; } public void run() { final AbstractXMPPConnection connection = weakRefConnection.get(); if (connection == null) { return; } while (isReconnectionPossible(connection)) { int remainingSeconds = timeDelay(); while (isReconnectionPossible(connection) && remainingSeconds > 0) { try { Thread.sleep(1000); remainingSeconds--; for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectingIn(remainingSeconds); } } catch (InterruptedException e) { LOGGER.log(Level.FINE, "waiting for reconnection interrupted", e); break; } } for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectingIn(0); } try { if (isReconnectionPossible(connection)) { connection.connect(); } } catch (Exception e) { for (ConnectionListener listener : connection.connectionListeners) { listener.reconnectionFailed(e); } } } } }; if (getEnabledPerDefault()) { enableAutomaticReconnection(); } }
Source:
public BehaviorState modify(Actor oreon, BehaviorState result) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); EntityRef building = entityManager.getEntity(oreonTaskComponent.task.requiredBuildingEntityID); ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); int minX = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int minZ = Integer.MAX_VALUE; int maxZ = Integer.MIN_VALUE; int y = oreonTaskComponent.taskRegion.minY(); for (BlockRegion region : buildingComponent.boundingRegions) { minX = Math.min(minX, region.minX()); maxX = Math.max(maxX, region.maxX()); minZ = Math.min(minZ, region.minZ()); maxZ = Math.max(maxZ, region.maxZ()); } Vector3i min = new Vector3i(minX - 1, y, minZ - 1); Vector3i max = new Vector3i(maxX + 1, y, maxZ + 1); oreonTaskComponent.taskRegion = new BlockRegion(min, max); oreon.save(oreonTaskComponent); if (oreonTaskComponent.taskCompletionTime < time.getGameTime()) { return BehaviorState.SUCCESS; } setTargetToNearbyBoundaryBlock(oreon, oreonTaskComponent); return BehaviorState.RUNNING; }

Target:
public BehaviorState modify(Actor oreon, BehaviorState result) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); EntityRef building = entityManager.getEntity(oreonTaskComponent.task.requiredBuildingEntityID); ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); int y = oreonTaskComponent.taskRegion.minY(); final BlockRegion taskRegion = buildingComponent.boundingRegions.stream() .reduce(new BlockRegion(BlockRegion.INVALID), BlockRegion::union, BlockRegion::union) .minY(y).maxY(y) .addToMin(-1, 0, -1) .addToMax(1, 0, 1); oreonTaskComponent.taskRegion = taskRegion; oreon.save(oreonTaskComponent); if (oreonTaskComponent.taskCompletionTime < time.getGameTime()) { return BehaviorState.SUCCESS; } setTargetToNearbyBoundaryBlock(oreon, oreonTaskComponent); return BehaviorState.RUNNING; }
Source:
private void logTransactionDetails(CorporateBilledCorporatePaidTransactionDetail transactionDetail) { if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder("logTransactionDetails, "); if (ObjectUtils.isNotNull(transactionDetail)) { sb.append("ProcurementCardTransactionDetail: "); sb.append("document number = ").append(transactionDetail.getDocumentNumber()); sb.append(" transaction reference number - ").append(transactionDetail.getTransactionReferenceNumber()); sb.append(" financial line number - ").append(transactionDetail.getFinancialDocumentTransactionLineNumber()); sb.append(" Source Lines - "); logAccountingLineBaseList(transactionDetail.getSourceAccountingLines(), sb); sb.append(" Target lines - "); logAccountingLineBaseList(transactionDetail.getTargetAccountingLines(), sb); } else { sb.append("transaction detail is NULL"); } LOG.debug(sb.toString()); } }

Target:
private void logTransactionDetails(CorporateBilledCorporatePaidTransactionDetail transactionDetail) { if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder("logTransactionDetails, "); if (ObjectUtils.isNotNull(transactionDetail)) { sb.append("ProcurementCardTransactionDetail: "); sb.append("document number - ").append(transactionDetail.getDocumentNumber()); sb.append(" transaction reference number - ").append(transactionDetail.getTransactionReferenceNumber()); sb.append(" financial line number - ").append(transactionDetail.getFinancialDocumentTransactionLineNumber()); sb.append(" Source Lines - "); logAccountingLineBaseList(transactionDetail.getSourceAccountingLines(), sb); sb.append(" Target lines - "); logAccountingLineBaseList(transactionDetail.getTargetAccountingLines(), sb); } else { sb.append("transaction detail is NULL"); } LOG.debug(sb.toString()); } }
Source:
public void testViolationsByGoogleAndXpathSuppressions(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws Exception { System.setProperty("org.checkstyle.google.suppressionxpathfilter.config", "src/test/resources/com/puppycrawl/tools/checkstyle/main/" + "InputMainViolationsForGoogleXpathSuppressions.xml"); Main.main("-c", "/google_checks.xml", getPath("InputMainViolationsForGoogle.java")); assertThat("Unexpected output log", systemOut.getCapturedData(), is(noViolationsOutput)); assertThat("Unexpected system error log", systemErr.getCapturedData(), is("")); }

Target:
public void testViolationsByGoogleAndXpathSuppressions(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws Exception { System.setProperty("org.checkstyle.google.suppressionxpathfilter.config", getPath("InputMainViolationsForGoogleXpathSuppressions.xml")); Main.main("-c", "/google_checks.xml", getPath("InputMainViolationsForGoogle.java")); assertThat("Unexpected output log", systemOut.getCapturedData(), is(noViolationsOutput)); assertThat("Unexpected system error log", systemErr.getCapturedData(), is("")); }
Source:
private void checkPendingAndContinue() { initializeIfRequired(); if (queueFile.size() > 0) { try { peekedBatch = (queueFile.size() == cachedQueue.size()) ? cachedQueue.peek() : queueFile.peek(); if (peekedBatch != null) { callPersistSuccess(peekedBatch); } } catch (IOException e) { e.printStackTrace(); } } else { callQueueEnd(); } }

Target:
private void checkPendingAndContinue() { initializeIfRequired(); if (queueFile.size() > 0) { try { peekedBatch = (queueFile.size() == cachedQueue.size()) ? cachedQueue.peek() : queueFile.peek(); if (peekedBatch != null) { callPersistSuccess(peekedBatch); } } catch (IOException e) { if (log.isErrorEnabled()) { log.error(e.getLocalizedMessage()); } } } else { callQueueEnd(); } }
Source:
public CreateServerOptions networks(String... networks) { return networks(ImmutableSet.copyOf(checkNotNull(networks, "network should not be empty"))); }

Target:
public CreateServerOptions networks(String... networks) { return networks(ImmutableSet.copyOf(networks)); }
Source:
public Element createRootElement(Document doc, Jsr107CacheConfiguration cacheConfiguration) { Element rootElement = doc.createElementNS(NAMESPACE.toString(), JSR_NAMESPACE_PREFIX + COLON + MBEANS_ELEMENT_NAME); rootElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + JSR_NAMESPACE_PREFIX, NAMESPACE.toString()); ConfigurationElementState managementState = cacheConfiguration.isManagementEnabled(); ConfigurationElementState statisticsState = cacheConfiguration.isStatisticsEnabled(); if (ConfigurationElementState.ENABLED == managementState || ConfigurationElementState.DISABLED == managementState) { rootElement.setAttribute(MANAGEMENT_ENABLED_ATTRIBUTE, String.valueOf(cacheConfiguration.isManagementEnabled() .asBoolean())); } if (ConfigurationElementState.ENABLED == statisticsState || ConfigurationElementState.DISABLED == statisticsState) { rootElement.setAttribute(STATISTICS_ENABLED_ATTRIBUTE, String.valueOf(cacheConfiguration.isStatisticsEnabled() .asBoolean())); } return rootElement; }

Target:
protected Element createRootElement(Document doc, Jsr107CacheConfiguration cacheConfiguration) { Element rootElement = doc.createElementNS(NAMESPACE.toString(), JSR_NAMESPACE_PREFIX + COLON + MBEANS_ELEMENT_NAME); ConfigurationElementState managementState = cacheConfiguration.isManagementEnabled(); ConfigurationElementState statisticsState = cacheConfiguration.isStatisticsEnabled(); if (ConfigurationElementState.ENABLED == managementState || ConfigurationElementState.DISABLED == managementState) { rootElement.setAttribute(MANAGEMENT_ENABLED_ATTRIBUTE, String.valueOf(cacheConfiguration.isManagementEnabled() .asBoolean())); } if (ConfigurationElementState.ENABLED == statisticsState || ConfigurationElementState.DISABLED == statisticsState) { rootElement.setAttribute(STATISTICS_ENABLED_ATTRIBUTE, String.valueOf(cacheConfiguration.isStatisticsEnabled() .asBoolean())); } return rootElement; }
Source:
public void afterPropertiesSet() throws Exception { Mongo mongo; ServerAddress defaultOptions = new ServerAddress(); if (mongoOptions == null) { mongoOptions = new MongoOptions(); } if (replicaPair != null && !replicaPair.isEmpty()) { if (replicaPair.size() < 2) { throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries"); } mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); } else if (replicaSetSeeds != null && !replicaSetSeeds.isEmpty()) { mongo = new Mongo(replicaSetSeeds, mongoOptions); } else { String mongoHost = StringUtils.hasText(host) ? host : defaultOptions.getHost(); mongo = port != null ? new Mongo(new ServerAddress(mongoHost, port), mongoOptions) : new Mongo(mongoHost, mongoOptions); } if (writeConcern != null) { mongo.setWriteConcern(writeConcern); } this.mongo = mongo; }

Target:
public void afterPropertiesSet() throws Exception { Mongo mongo; ServerAddress defaultOptions = new ServerAddress(); if (mongoOptions == null) { mongoOptions = new MongoOptions(); } if (!isNullOrEmpty(replicaPair)) { if (replicaPair.size() < 2) { throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries"); } mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); } else if (!isNullOrEmpty(replicaSetSeeds)) { mongo = new Mongo(replicaSetSeeds, mongoOptions); } else { String mongoHost = StringUtils.hasText(host) ? host : defaultOptions.getHost(); mongo = port != null ? new Mongo(new ServerAddress(mongoHost, port), mongoOptions) : new Mongo(mongoHost, mongoOptions); } if (writeConcern != null) { mongo.setWriteConcern(writeConcern); } this.mongo = mongo; }
Source:
public ImmutableMap<String, LookupExtractor> getAll() throws ISE { synchronized (lock) { assertStarted(); return ImmutableMap.copyOf(lookupMap); } }

Target:
public Map<String, LookupExtractorFactory> getAll() { assertStarted(); return Maps.newHashMap(lookupMap); }
Source:
public void startVDOService(VDS vds) { boolean succeeded = runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("vdo"), "restart")).getSucceeded(); if (!succeeded) { log.error("Failed to stop VDO service while moving the host '{}' to maintenance", vds.getHostName()); } }

Target:
public void startVDOService(VDS vds) { boolean succeeded = runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("vdo"), "restart")).getSucceeded(); if (!succeeded) { log.error("Failed to start VDO service while moving the host '{}' to maintenance", vds.getHostName()); } }
Source:
public void testResultMessagesNullValue() throws Exception { try { new BusinessException(null, null); } catch (Exception e) { assertThat(e.getMessage(), is("messages must not be null")); throw e; } }

Target:
public void testResultMessagesNullValue() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("messages must not be null"); throw new BusinessException(null, null); }
Source:
public void visit( OutputPortInfo p ) { if( p.protocol() != null ) { p.protocol().accept( this ); p.setProtocol( currNode ); } if( p.location() != null ) { p.location().accept( this ); p.setLocation( currNode ); } programChildren.add( p ); }

Target:
public void visit( OutputPortInfo p ) { if( p.protocol() != null ) { p.setProtocol( optimizeNode( p.protocol() ) ); } if( p.location() != null ) { p.setLocation( optimizeNode( p.location() ) ); } programChildren.add( p ); }
Source:
public void scheduleService() throws Exception { if (SnapshotBackup.getTimer(config) != null && (CollectionUtils.isEmpty(config.getBackupRacs()) || config.getBackupRacs() .contains(instanceIdentity.getInstanceInfo().getRac()))) { scheduleTask(scheduler, SnapshotBackup.class, SnapshotBackup.getTimer(config)); scheduleTask( scheduler, CommitLogBackupTask.class, CommitLogBackupTask.getTimer(config)); } scheduleTask( scheduler, IncrementalBackup.class, IncrementalBackup.getTimer(config, backupRestoreConfig)); scheduleTask(scheduler, UpdateCleanupPolicy.class, UpdateCleanupPolicy.getTimer()); }

Target:
public void scheduleService() throws Exception { TaskTimer snapshotTimer = SnapshotBackup.getTimer(config); scheduleTask(scheduler, SnapshotBackup.class, snapshotTimer); if (snapshotTimer != null) { scheduleTask( scheduler, CommitLogBackupTask.class, CommitLogBackupTask.getTimer(config)); } scheduleTask( scheduler, IncrementalBackup.class, IncrementalBackup.getTimer(config, backupRestoreConfig)); scheduleTask(scheduler, UpdateCleanupPolicy.class, UpdateCleanupPolicy.getTimer()); }
Source:
private static boolean startupChecksPass() { CassandraKeyValueServiceConfigManager manager = CassandraKeyValueServiceConfigManager.createSimpleManager( ThreeNodeCassandraCluster.KVS_CONFIG); try { new CassandraClientPool(manager.getConfig()); } catch (Exception e) { return false; } return true; }

Target:
private static boolean startupChecksPass() { CassandraKeyValueServiceConfigManager manager = CassandraKeyValueServiceConfigManager.createSimpleManager( ThreeNodeCassandraCluster.KVS_CONFIG); try { new CassandraClientPool(manager.getConfig()); return true; } catch (Exception e) { return false; } }
Source:
public List<String> getAliasesForCluster(final String clusterName) throws AliasServiceException { final List<String> localAliases = localAliasService == null ? Collections.emptyList() : localAliasService.getAliasesForCluster(clusterName); if (localAliases == null || localAliases.isEmpty()) { if (remoteClient != null) { final List<String> remoteAliases = remoteClient.listChildEntries(buildClusterEntryName(clusterName)); return remoteAliases == null ? new ArrayList<>() : remoteAliases; } else { return new ArrayList<>(); } } else { return localAliases; } }

Target:
public List<String> getAliasesForCluster(final String clusterName) throws AliasServiceException { final List<String> localAliases = localAliasService.getAliasesForCluster(clusterName); if (localAliases == null || localAliases.isEmpty()) { if (remoteClient != null) { final List<String> remoteAliases = remoteClient.listChildEntries(buildClusterEntryName(clusterName)); return remoteAliases == null ? new ArrayList<>() : remoteAliases; } else { return new ArrayList<>(); } } else { return localAliases; } }
Source:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: case Screen.COURSE_VIDEOS: { if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); } break; } case Screen.PROGRAM: { if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { router.showMainDashboard(activity, screenName); } break; } case Screen.COURSE_DISCOVERY: { String courseId = null; if (paramsJson.has(KEY_COURSE_ID)) { courseId = paramsJson.getString(KEY_COURSE_ID); } if (!isLoggedIn) { activity.startActivity(DiscoveryActivity.newIntent(activity, screenName, courseId)); } else { router.showMainDashboard(activity, screenName, courseId); } break; } } }

Target:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(new Config(activity)); final String username = new LoginPrefs(activity).getUsername(); @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); if (username == null) { switch (screenName) { case Screen.COURSE_DISCOVERY: router.showFindCourses(activity, screenName, paramsJson.optString(KEY_PATH_ID)); break; default: activity.startActivity(router.getLogInIntent()); break; } return; } switch (screenName) { case Screen.COURSE_DASHBOARD: case Screen.COURSE_VIDEOS: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); break; } case Screen.PROGRAM: case Screen.COURSE_DISCOVERY: { router.showMainDashboard(activity, screenName, paramsJson.optString(KEY_PATH_ID)); break; } case Screen.PROFILE: { router.showUserProfile(activity, username); break; } } }
Source:
public void testGoToTimeAndCheckStackWithNames() throws IOException { goToTime(TIMESTAMPS[0]); final SWTBotView viewBot = fBot.viewById(CallStackView.ID); viewBot.setFocus(); SWTBotTree tree = viewBot.bot().tree(); Object mapObj = CtfTmfTestTraceUtils.class.getResource("cyg-profile-mapping.txt"); assertTrue(mapObj instanceof URL); URL mapUrl = (URL) mapObj; String absoluteFile = FileLocator.toFileURL(mapUrl).getFile(); TmfFileDialogFactory.setOverrideFiles(absoluteFile); viewBot.toolbarButton("Configure how the addresses are mapped to function names").click(); String shellTitle = "Symbol mapping"; fBot.waitUntil(Conditions.shellIsActive(shellTitle)); SWTBot shellBot = fBot.shell(shellTitle).bot(); SWTBotShell activeShell = shellBot.activeShell(); shellBot.radio(1).click(); shellBot.button("Browse...", 1).click(); shellBot.button("OK").click(); shellBot.waitUntil(Conditions.shellCloses(activeShell)); goToTime(TIMESTAMPS[0]); List<String> functions = new ArrayList<>(); WaitUtils.waitForJobs(); List<String> names = new ArrayList<>(); for (SWTBotTreeItem swtBotTreeItem : tree.getAllItems()) { for (SWTBotTreeItem items : swtBotTreeItem.getItems()) { for (SWTBotTreeItem item : items.getItems()) { names.add(item.cell(0)); } } } functions = getVisibleStackFrames(viewBot); assertEquals(ImmutableList.of("glxgears-16073"), names); assertEquals(ImmutableList.of("main", "event_loop", "handle_event", "", ""), functions); }

Target:
public void testGoToTimeAndCheckStackWithNames() throws IOException { goToTime(TIMESTAMPS[0]); final SWTBotView viewBot = fBot.viewById(CallStackView.ID); viewBot.setFocus(); SWTBotTree tree = viewBot.bot().tree(); Object mapObj = CtfTmfTestTraceUtils.class.getResource("cyg-profile-mapping.txt"); assertTrue(mapObj instanceof URL); URL mapUrl = (URL) mapObj; String absoluteFile = FileLocator.toFileURL(mapUrl).getFile(); TmfFileDialogFactory.setOverrideFiles(absoluteFile); viewBot.toolbarButton("Configure how the addresses are mapped to function names").click(); String shellTitle = "Symbol mapping"; fBot.waitUntil(Conditions.shellIsActive(shellTitle)); SWTBot shellBot = fBot.shell(shellTitle).bot(); SWTBotShell activeShell = shellBot.activeShell(); shellBot.radio(1).click(); shellBot.button("Browse...", 1).click(); shellBot.button("OK").click(); shellBot.waitUntil(Conditions.shellCloses(activeShell)); goToTime(TIMESTAMPS[0]); WaitUtils.waitForJobs(); List<String> names = new ArrayList<>(); for (SWTBotTreeItem swtBotTreeItem : tree.getAllItems()) { for (SWTBotTreeItem items : swtBotTreeItem.getItems()) { for (SWTBotTreeItem item : items.getItems()) { names.add(item.cell(0)); } } } List<String> functions = getVisibleStackFrames(viewBot); assertEquals(ImmutableList.of("glxgears-16073"), names); assertEquals(ImmutableList.of("main", "event_loop", "handle_event", "", ""), functions); }
Source:
public void getInformations(APIRequest apiRequest) { String msg = "<msg><header " + "deviceID=\"" + handler.getMacAddress() + "\"" + " url=\"" + apiRequest + "\" method=\"GET\"><request requestID=\"0\"><info type=\"new\"/></request></header></msg>"; try { handler.getSession().getRemote().sendString(msg); } catch (IOException e) { handler.onWebSocketError(e); } }

Target:
public void getInformations(APIRequest apiRequest) { String msg = "<msg><header " + "deviceID=\"" + handler.getMacAddress() + "\"" + " url=\"" + apiRequest + "\" method=\"GET\"><request requestID=\"0\"><info type=\"new\"/></request></header></msg>"; try { handler.getSession().getRemote().sendString(msg); logger.debug("{}: sending request: {}", handler.getDeviceName(), msg); } catch (IOException e) { handler.onWebSocketError(e); } }
Source:
public void testListTypesIsEmpty() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/resource_type_list_response.json")))); try { HeatApi heatApi = api(server.getUrl("/").toString(), "openstack-heat", overrides); ResourceApi api = heatApi.getResourceApi("RegionOne"); List<String> resourceTypes = api.listTypes(); assertThat(server.getRequestCount()).isEqualTo(2); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", BASE_URI + "/resource_types"); assertThat(resourceTypes).isEmpty(); } finally { server.shutdown(); } }

Target:
public void testListTypesIsEmpty() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404))); try { HeatApi heatApi = api(server.getUrl("/").toString(), "openstack-heat", overrides); ResourceApi api = heatApi.getResourceApi("RegionOne"); List<String> resourceTypes = api.listTypes(); assertThat(server.getRequestCount()).isEqualTo(2); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", BASE_URI + "/resource_types"); assertThat(resourceTypes).isEmpty(); } finally { server.shutdown(); } }
Source:
private void verifyModelParsing(CourseComponent component) { JSONObject jsonObj; try { jsonObj = new JSONObject(MockDataUtil.getMockResponse("get_course_structure")); jsonObj = jsonObj.getJSONObject("blocks"); jsonObj = jsonObj.getJSONObject(component.getId()); assertNotNull(jsonObj); assertEquals(jsonObj.getString("display_name"), component.getInternalName()); assertEquals(jsonObj.getBoolean("graded"), component.isGraded()); assertEquals(jsonObj.getString("student_view_url"), component.getBlockUrl()); assertEquals(jsonObj.getBoolean("student_view_multi_device"), component.isMultiDevice()); assertEquals(jsonObj.getString("lms_web_url"), component.getWebUrl()); Gson gson = new Gson(); switch (component.getType()) { case VIDEO: { String dataRawJson = jsonObj.getJSONObject("student_view_data").toString(); assertTrue(component instanceof VideoBlockModel); VideoBlockModel model = (VideoBlockModel) component; VideoData expected = gson.fromJson(dataRawJson, VideoData.class); assertEquals(expected, model.getData()); break; } case DISCUSSION: { String dataRawJson = jsonObj.getJSONObject("student_view_data").toString(); assertTrue(component instanceof DiscussionBlockModel); DiscussionBlockModel model = (DiscussionBlockModel) component; DiscussionData expected = gson.fromJson(dataRawJson, DiscussionData.class); assertEquals(expected, model.getData()); break; } } } catch (JSONException e) { fail("Error while converting raw json to JSONObject: " + e.getMessage()); } catch (IOException e) { fail("Error reading raw json: " + e.getMessage()); } }

Target:
private void verifyModelParsing(CourseComponent component) throws IOException, JSONException { JSONObject jsonObj; jsonObj = new JSONObject(MockDataUtil.getMockResponse("get_course_structure")); jsonObj = jsonObj.getJSONObject("blocks"); jsonObj = jsonObj.getJSONObject(component.getId()); assertNotNull(jsonObj); assertEquals(jsonObj.getString("display_name"), component.getInternalName()); assertEquals(jsonObj.getBoolean("graded"), component.isGraded()); assertEquals(jsonObj.getString("student_view_url"), component.getBlockUrl()); assertEquals(jsonObj.getBoolean("student_view_multi_device"), component.isMultiDevice()); assertEquals(jsonObj.getString("lms_web_url"), component.getWebUrl()); Gson gson = new Gson(); switch (component.getType()) { case VIDEO: { JSONObject dataObj = jsonObj.getJSONObject("student_view_data"); assertTrue(dataObj.has("encoded_videos") || dataObj.has("transcripts")); String dataRawJson = dataObj.toString(); assertTrue(component instanceof VideoBlockModel); VideoBlockModel model = (VideoBlockModel) component; VideoData expected = gson.fromJson(dataRawJson, VideoData.class); assertEquals(expected, model.getData()); break; } case DISCUSSION: { JSONObject dataObj = jsonObj.getJSONObject("student_view_data"); assertTrue(dataObj.has("topic_id")); String dataRawJson = dataObj.toString(); assertTrue(component instanceof DiscussionBlockModel); DiscussionBlockModel model = (DiscussionBlockModel) component; DiscussionData expected = gson.fromJson(dataRawJson, DiscussionData.class); assertEquals(expected, model.getData()); break; } } }