auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static RNMGLAnnotationOptions markerOptionsFromJS(ReadableMap annotation, Context context) { MarkerOptions marker = new MarkerOptions(); double latitude = annotation.getArray("coordinates").getDouble(0); double longitude = annotation.getArray("coordinates").getDouble(1); LatLng markerCenter = new LatLng(latitude, longitude); marker.position(markerCenter); if (annotation.hasKey("title")) { String title = annotation.getString("title"); marker.title(title); } if (annotation.hasKey("subtitle")) { String subtitle = annotation.getString("subtitle"); marker.snippet(subtitle); } if (annotation.hasKey("annotationImage")) { ReadableMap annotationImage = annotation.getMap("annotationImage"); String annotationURL = annotationImage.getString("url"); try { int width = -1; int height = -1; if (annotationImage.hasKey("height") && annotationImage.hasKey("width")) { float scale = context.getResources().getDisplayMetrics().density; height = Math.round((float)annotationImage.getInt("height") * scale); width = Math.round((float)annotationImage.getInt("width") * scale); } marker.icon(iconFromPathAndSize(context, annotationURL, width, height)); } catch (Exception e) { e.printStackTrace(); } } return new RNMGLMarkerOptions(marker); }

Target:
static RNMGLAnnotationOptions markerOptionsFromJS(ReadableMap annotation, Context context) { MarkerOptions marker = new MarkerOptions(); double latitude = annotation.getArray("coordinates").getDouble(0); double longitude = annotation.getArray("coordinates").getDouble(1); LatLng markerCenter = new LatLng(latitude, longitude); marker.position(markerCenter); if (annotation.hasKey("title")) { String title = annotation.getString("title"); marker.title(title); } if (annotation.hasKey("subtitle")) { String subtitle = annotation.getString("subtitle"); marker.snippet(subtitle); } if (annotation.hasKey("annotationImage")) { ReadableMap annotationImage = annotation.getMap("annotationImage"); ReadableMap annotationSource = annotationImage.getMap("source"); try { int width = -1; int height = -1; if (annotationImage.hasKey("height") && annotationImage.hasKey("width")) { float scale = context.getResources().getDisplayMetrics().density; height = Math.round((float)annotationImage.getInt("height") * scale); width = Math.round((float)annotationImage.getInt("width") * scale); } marker.icon(iconFromSourceAndSize(context, annotationSource, width, height)); } catch (Exception e) { e.printStackTrace(); } } return new RNMGLMarkerOptions(marker); }
Source:
public void doNotSweepAnythingAfterEntryWithCommitTsAfterSweepTs() { immutableTs = 1000L; enqueueWrite(TABLE_CONS, 900); enqueueWrite(TABLE_CONS, 910); enqueueWriteCommitedAt(TABLE_CONS, 950, 1000); enqueueWrite(TABLE_CONS, 970); enqueueWrite(TABLE_CONS, 920); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(920L); ArgumentCaptor<Map> argument = ArgumentCaptor.forClass(Map.class); verify(spiedKvs, times(1)).deleteAllTimestamps(eq(TABLE_CONS), argument.capture(), eq(false)); assertThat(argument.getValue()).containsValue(920L); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(920L); verify(spiedKvs, times(1)).deleteAllTimestamps(any(TableReference.class), anyMap(), eq(false)); immutableTs = 1101L; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(1101L - 1L); verify(spiedKvs, times(2)).deleteAllTimestamps(eq(TABLE_CONS), argument.capture(), eq(false)); assertThat(argument.getValue()).containsValue(970L); }

Target:
public void doNotSweepAnythingAfterEntryWithCommitTsAfterSweepTs() { immutableTs = 1000L; enqueueWriteCommitted(TABLE_CONS, 900); enqueueWriteCommitted(TABLE_CONS, 910); enqueueWriteCommitted(TABLE_CONS, 920); enqueueWriteCommitedAt(TABLE_CONS, 950, immutableTs); enqueueWriteCommitted(TABLE_CONS, 970); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(920L); ArgumentCaptor<Map> argument = ArgumentCaptor.forClass(Map.class); verify(spiedKvs, times(1)).deleteAllTimestamps(eq(TABLE_CONS), argument.capture(), eq(false)); assertThat(argument.getValue()).containsValue(920L); sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(920L); verify(spiedKvs, times(1)).deleteAllTimestamps(any(TableReference.class), anyMap(), eq(false)); immutableTs = 1001L; sweepQueue.sweepNextBatch(ShardAndStrategy.conservative(CONS_SHARD)); assertThat(progress.getLastSweptTimestamp(ShardAndStrategy.conservative(CONS_SHARD))).isEqualTo(1001L - 1L); verify(spiedKvs, times(2)).deleteAllTimestamps(eq(TABLE_CONS), argument.capture(), eq(false)); assertThat(argument.getValue()).containsValue(970L); }
Source:
protected void publishMetrics(Latency latency, String prefix, String partition, String stream, String group) { if (verbose) { log.info(latency.toString()); } long metricTime = latency.upper() / 1000; String host = ""; List<String> mTags = new ArrayList<>(tags.size() + 3); mTags.addAll(tags); mTags.add("stream:" + stream); mTags.add("consumer:" + group); mTags.add("partition:" + partition); try { Transport.Request request = transport.prepare(); request.addGauge(new DatadogGauge(prefix + ".lag", latency.lag().lag(), metricTime, host, mTags)); request.addGauge(new DatadogGauge(prefix + ".end", latency.lag().upper(), metricTime, host, mTags)); request.addGauge(new DatadogGauge(prefix + ".pos", latency.lag().lower(), metricTime, host, mTags)); request.addGauge(new DatadogGauge(prefix + ".latency", latency.latency(), metricTime, host, mTags)); request.send(); } catch (IOException e) { log.error("Fail to prepare metric to datadog " + prefix + " " + latency, e); } catch (Exception e) { log.error("Fail to send metric to datadog " + prefix + " " + latency, e); } }

Target:
protected void publishMetrics(Latency latency, String prefix, String partition, String stream, String group) { if (verbose) { log.info(latency.toString()); } long metricTime = latency.upper() / 1000; List<String> mTags = new ArrayList<>(tags.size() + 3); mTags.addAll(tags); mTags.add("stream:" + stream); mTags.add("consumer:" + group); mTags.add("partition:" + partition); try { Transport.Request request = transport.prepare(); request.addGauge(new DatadogGauge(prefix + ".lag", latency.lag().lag(), metricTime, hostname, mTags)); request.addGauge(new DatadogGauge(prefix + ".end", latency.lag().upper(), metricTime, hostname, mTags)); request.addGauge(new DatadogGauge(prefix + ".pos", latency.lag().lower(), metricTime, hostname, mTags)); request.addGauge(new DatadogGauge(prefix + ".latency", latency.latency(), metricTime, hostname, mTags)); request.send(); } catch (IOException e) { log.error("Fail to prepare metric to datadog " + prefix + " " + latency, e); } catch (Exception e) { log.error("Fail to send metric to datadog " + prefix + " " + latency, e); } }
Source:
public void openCloseUpdate() { OpenCloseValue v = new OpenCloseValue("fancyON", "fancyOff"); assertThat(v.update(OpenClosedType.CLOSED), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(OpenClosedType.OPEN), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); assertThat(v.update(new StringType("CLOSED")), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(new StringType("OPEN")), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); assertThat(v.update(new StringType("CLOSED")), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(new StringType("OPEN")), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); }

Target:
public void openCloseUpdate() { OpenCloseValue v = new OpenCloseValue("fancyON", "fancyOff"); assertThat(v.update(OpenClosedType.CLOSED), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(OpenClosedType.OPEN), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); assertThat(v.update(new StringType("CLOSED")), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(new StringType("OPEN")), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); assertThat(v.update(new StringType("fancyOff")), is("fancyOff")); assertThat(v.getValue(), is(OpenClosedType.CLOSED)); assertThat(v.update(new StringType("fancyON")), is("fancyON")); assertThat(v.getValue(), is(OpenClosedType.OPEN)); }
Source:
public void testUnmarshallTopLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptyEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptyEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); assertDataIOSet(emptyEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptyEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptyEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptyEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public FeatureEditorListPanel(String aId, IModel<AnnotatorState> aModel, AnnotationDetailEditorPanel aOwner) { super(aId, aModel); setOutputMarkupPlaceholderTag(true); owner = aOwner; featureEditorContainer = new WebMarkupContainer("featureEditorContainer"); featureEditorContainer.setOutputMarkupPlaceholderTag(true); featureEditorContainer.add(featureEditorPanelContent = new FeatureEditorPanelContent("featureEditors")); featureEditorContainer.add(createFocusResetHelper()); featureEditorContainer.add(visibleWhen(() -> selectedLayerHasFeatures())); add(featureEditorContainer); noFeaturesWarning = new WebMarkupContainer("noFeaturesWarning"); noFeaturesWarning.setOutputMarkupPlaceholderTag(true); noFeaturesWarning.add(visibleWhen(() -> selectedLayerHasNoFeatures())); add(noFeaturesWarning); }

Target:
public FeatureEditorListPanel(String aId, IModel<AnnotatorState> aModel, AnnotationDetailEditorPanel aOwner) { super(aId, aModel); setOutputMarkupPlaceholderTag(true); owner = aOwner; featureEditorContainer = new WebMarkupContainer("featureEditorContainer"); featureEditorContainer.setOutputMarkupPlaceholderTag(true); featureEditorContainer.add(featureEditorPanelContent = new FeatureEditorPanelContent("featureEditors")); featureEditorContainer.add(createFocusResetHelper()); featureEditorContainer.add(visibleWhen(() -> layerIsSelectedAndHasFeatures())); add(featureEditorContainer); noFeaturesWarning = new WebMarkupContainer("noFeaturesWarning"); noFeaturesWarning.setOutputMarkupPlaceholderTag(true); noFeaturesWarning.add(visibleWhen(() -> layerIsSelectedButHasNoFeatures())); add(noFeaturesWarning); }
Source:
protected void postComment(PullRequest pull, String comment) { System.out.println("Posting '" + comment + "' to pullrequest '" + pull.getNumber() + "'"); if (!DRY_RUN) { helper.githubHelper.postGithubComment(pull, comment); } }

Target:
protected void postComment(PullRequest pull, String comment) { System.out.println("Posting '" + comment + "' to pullrequest '" + pull.getNumber() + "'"); if (!DRY_RUN) { helper.getGHHelper().postGithubComment(pull, comment); } }
Source:
public List<Optional<PartitionStatistics>> loadPartitionStatistics( final Collection<TimelinePartition> partitions) throws ServiceTemporarilyUnavailableException { try { return Retryer.executeWithRetry(() -> { return loadPartitionStatisticsInternal(partitions); }, new RetryForSpecifiedCountStrategy(3) .withWaitBetweenEachTry(5000) .withExceptionsThatForceRetry(org.apache.kafka.common.errors.TimeoutException.class)); } catch (final Exception e) { throw new ServiceTemporarilyUnavailableException("Error occurred when fetching partitions offsets", e); } }

Target:
public List<Optional<PartitionStatistics>> loadPartitionStatistics( final Collection<TimelinePartition> partitions) throws ServiceTemporarilyUnavailableException { try { return Retryer.executeWithRetry(() -> { return loadPartitionStatisticsInternal(partitions); }, new RetryForSpecifiedCountStrategy(3) .withWaitBetweenEachTry(5000) .withExceptionsThatForceRetry(org.apache.kafka.common.errors.TimeoutException.class)); } catch (final RuntimeException e) { throw new ServiceTemporarilyUnavailableException("Error occurred when fetching partitions offsets", e); } }
Source:
public WebSocketResponse processTokenCreate(JsonObject request, WebSocketSession session) { JwtPayload payload = gson.fromJson(request.get(Constants.PAYLOAD), JwtPayload.class); if (payload == null) { String msg = "JwtToken: payload was not found"; logger.warn(msg); throw new HiveException(msg); } UserVO user = userService.findById(payload.getUserId()); if (user == null) { String msg = String.format("JwtToken: User with specified id %s was not found", payload.getUserId()); logger.warn(msg); throw new HiveException(msg); } if (!user.getStatus().equals(UserStatus.ACTIVE)) { String msg = String.format("JwtToken: User with specified id %s is not active", payload.getUserId()); logger.warn(msg); throw new HiveException(msg); } logger.debug("JwtToken: generate access and refresh token"); JwtPayload refreshPayload = JwtPayload.newBuilder().withPayload(payload) .buildPayload(); WebSocketResponse response = new WebSocketResponse(); response.addValue("accessToken", tokenService.generateJwtAccessToken(payload, true)); response.addValue("refreshToken", tokenService.generateJwtRefreshToken(refreshPayload, true)); return response; }

Target:
public WebSocketResponse processTokenCreate(JsonObject request, WebSocketSession session) { JwtPayload payload = gson.fromJson(request.get(Constants.PAYLOAD), JwtPayload.class); if (payload == null) { logger.warn("JwtToken: payload was not found"); throw new HiveException(Messages.PAYLOAD_NOT_FOUND, SC_BAD_REQUEST); } UserVO user = userService.findById(payload.getUserId()); if (user == null) { logger.warn(String.format("JwtToken: User with specified id %s was not found", payload.getUserId())); throw new HiveException(Messages.USER_NOT_FOUND, SC_NOT_FOUND); } if (!user.getStatus().equals(UserStatus.ACTIVE)) { logger.warn(String.format("JwtToken: User with specified id %s is not active", payload.getUserId())); throw new HiveException(Messages.USER_NOT_ACTIVE, SC_NOT_FOUND); } logger.debug("JwtToken: generate access and refresh token"); JwtPayload refreshPayload = JwtPayload.newBuilder().withPayload(payload) .buildPayload(); WebSocketResponse response = new WebSocketResponse(); response.addValue("accessToken", tokenService.generateJwtAccessToken(payload, true)); response.addValue("refreshToken", tokenService.generateJwtRefreshToken(refreshPayload, true)); return response; }
Source:
private List<StoragePool> getCandidateStoragePoolsToMigrateLocalVolume(VirtualMachineProfile profile, Host targetHost, Volume volume) { List<StoragePool> poolList = new ArrayList<>(); DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType()); DataCenterDeployment plan = new DataCenterDeployment(targetHost.getDataCenterId(), targetHost.getPodId(), targetHost.getClusterId(), targetHost.getId(), null, null); ExcludeList avoid = new ExcludeList(); StoragePoolVO volumeStoragePool = _storagePoolDao.findById(volume.getPoolId()); if (volumeStoragePool.isLocal()) { diskProfile.setUseLocalStorage(true); } for (StoragePoolAllocator allocator : _storagePoolAllocators) { List<StoragePool> poolListFromAllocator = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL); if (CollectionUtils.isEmpty(poolListFromAllocator)) { continue; } for (StoragePool pool : poolListFromAllocator) { if (pool.isLocal() || isStorageCrossClusterMigration(targetHost, volumeStoragePool)) { poolList.add(pool); } } } return poolList; }

Target:
protected List<StoragePool> getCandidateStoragePoolsToMigrateLocalVolume(VirtualMachineProfile profile, Host targetHost, Volume volume) { List<StoragePool> poolList = new ArrayList<>(); DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType()); DataCenterDeployment plan = new DataCenterDeployment(targetHost.getDataCenterId(), targetHost.getPodId(), targetHost.getClusterId(), targetHost.getId(), null, null); ExcludeList avoid = new ExcludeList(); StoragePoolVO volumeStoragePool = _storagePoolDao.findById(volume.getPoolId()); if (volumeStoragePool.isLocal()) { diskProfile.setUseLocalStorage(true); } for (StoragePoolAllocator allocator : _storagePoolAllocators) { List<StoragePool> poolListFromAllocator = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL); if (CollectionUtils.isEmpty(poolListFromAllocator)) { continue; } for (StoragePool pool : poolListFromAllocator) { if (pool.isLocal() || isStorageCrossClusterMigration(targetHost, volumeStoragePool)) { poolList.add(pool); } } } return poolList; }
Source:
public void sendCommand(String eiscpCmd) { String data = getEiscpMessage(eiscpCmd).toString(); if (in == null || out == null) { connectSocket(); } try { if (in.markSupported()) { in.reset(); } else { while (in.available() > 0) { int availableBytes = in.available(); if (availableBytes > 0) { byte[] tmpData = new byte[availableBytes]; in.read(tmpData, 0, availableBytes); } } } String response = sendMmsg(data, timeout); if (response!=null) notifier.notifyMessage(new OnkyoStatusUpdateEvent(this), response.getBytes(), 8); } catch (IOException e) { logger.debug("IO error occured...reconnect and resend ones"); closeSocket(); connectSocket(); try { String response = sendMmsg(data, timeout); if (response!=null) notifier.notifyMessage(new OnkyoStatusUpdateEvent(this), response.getBytes(), 8); } catch (IOException e1) { logger.error("Send failed.."+e1); }catch(EiscpException ee){ logger.error("Unable to notify "+ee); } } catch (Exception e) { logger.error("Send failed.."+e); } }

Target:
public void sendCommand(String eiscpCmd) { String data = getEiscpMessage(eiscpCmd).toString(); if (in == null || out == null) { connectSocket(); } try { if (in.markSupported()) { in.reset(); } else { while (in.available() > 0) { int availableBytes = in.available(); if (availableBytes > 0) { byte[] tmpData = new byte[availableBytes]; in.read(tmpData, 0, availableBytes); } } } String response = sendMessage(data, timeout); if (response != null) { notifier.notifyMessage(new OnkyoStatusUpdateEvent(this), response.getBytes(), 8); } } catch (IOException e) { logger.debug("IO error occured...reconnect and resend ones"); closeSocket(); connectSocket(); try { String response = sendMessage(data, timeout); if (response != null) { notifier.notifyMessage(new OnkyoStatusUpdateEvent(this), response.getBytes(), 8); } } catch (IOException e1) { logger.error("Send failed..{}", e1); } catch (EiscpException ee) { logger.error("Unable to notify {}", ee); } } catch (Exception e) { logger.error("Send failed..{}", e); } }
Source:
public void testNoCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.validateCassandraHosts(); } catch (BluefloodServiceStarterException e) { ex = e; } assertNotNull(ex); assertEquals(-1, ex.getStatus()); }

Target:
public void testNoCassandraHostsFailsValidation() { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); BluefloodServiceStarter.validateCassandraHosts(); }
Source:
public String getBranch() throws IOException { String name = getFullBranch(); if (name != null) return shortenRefName(name); return name; }

Target:
public String getBranch() throws IOException { String name = getFullBranch(); if (name != null) return shortenRefName(name); return null; }
Source:
void startEngine(boolean dryRun) throws IOException { @CheckForNull File jarCacheDirectory = null; if (workDir != null) { final WorkDirManager workDirManager = WorkDirManager.getInstance(); if (jarCache != null) { workDirManager.disable(WorkDirManager.DirType.JAR_CACHE_DIR); } if (loggingConfigFilePath != null) { workDirManager.setLoggingConfig(loggingConfigFilePath.toFile()); } final Path path = workDirManager.initializeWorkDir(workDir.toFile(), internalDir, failIfWorkDirIsMissing); jarCacheDirectory = workDirManager.getLocation(WorkDirManager.DirType.JAR_CACHE_DIR); workDirManager.setupLogging(path, agentLog); } else if (jarCache == null) { LOGGER.log(Level.WARNING, "No Working Directory. Using the legacy JAR Cache location: {0}", JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION); jarCacheDirectory = JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION; } if (jarCache == null){ if (jarCacheDirectory == null) { throw new IOException("Cannot find the JAR Cache location"); } LOGGER.log(Level.FINE, "Using standard File System JAR Cache. Root Directory is {0}", jarCacheDirectory); try { jarCache = new FileSystemJarCache(jarCacheDirectory, true); } catch (IllegalArgumentException ex) { throw new IOException("Failed to initialize FileSystem JAR Cache in " + jarCacheDirectory, ex); } } else { LOGGER.log(Level.INFO, "Using custom JAR Cache: {0}", jarCache); } LOGGER.log(Level.INFO, "Using agent version: {0}", Launcher.VERSION); if (!dryRun) { this.start(); } }

Target:
void startEngine(boolean dryRun) throws IOException { LOGGER.log(Level.INFO, "Using Remoting version: {0}", Launcher.VERSION); @CheckForNull File jarCacheDirectory = null; if (workDir != null) { final WorkDirManager workDirManager = WorkDirManager.getInstance(); if (jarCache != null) { workDirManager.disable(WorkDirManager.DirType.JAR_CACHE_DIR); } if (loggingConfigFilePath != null) { workDirManager.setLoggingConfig(loggingConfigFilePath.toFile()); } final Path path = workDirManager.initializeWorkDir(workDir.toFile(), internalDir, failIfWorkDirIsMissing); jarCacheDirectory = workDirManager.getLocation(WorkDirManager.DirType.JAR_CACHE_DIR); workDirManager.setupLogging(path, agentLog); } else if (jarCache == null) { LOGGER.log(Level.WARNING, "No Working Directory. Using the legacy JAR Cache location: {0}", JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION); jarCacheDirectory = JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION; } if (jarCache == null){ if (jarCacheDirectory == null) { throw new IOException("Cannot find the JAR Cache location"); } LOGGER.log(Level.FINE, "Using standard File System JAR Cache. Root Directory is {0}", jarCacheDirectory); try { jarCache = new FileSystemJarCache(jarCacheDirectory, true); } catch (IllegalArgumentException ex) { throw new IOException("Failed to initialize FileSystem JAR Cache in " + jarCacheDirectory, ex); } } else { LOGGER.log(Level.INFO, "Using custom JAR Cache: {0}", jarCache); } if (!dryRun) { this.start(); } }
Source:
private boolean evaluateDeterministicFilterFunctionsWithConstantInputs(List<FilterFunction> filterFunctions) { for (FilterFunction function : filterFunctions) { if (function.isDeterministic() && hasInputs(function) && allConstantInputs(function)) { if (!evaluateDeterministicFilterFunctionWithConstantInputs(function)) { return false; } } } return true; }

Target:
private boolean evaluateDeterministicFilterFunctionsWithConstantInputs(List<FilterFunction> filterFunctions) { for (FilterFunction function : filterFunctions) { if (function.isDeterministic() && hasInputs(function) && allConstantInputs(function) && !evaluateDeterministicFilterFunctionWithConstantInputs(function)) { return false; } } return true; }
Source:
public void onSuccess(final Message<Tuple<K, V>> message) { if (tupleLinkListener != null) { tupleLinkListener.onSuccess(message); } }

Target:
public void onSuccess(final Message<Tuple<K, V>> message) { if (tupleLinkListener == null) { throw new RuntimeException("The tuple link listener should be set first through TupleMessageSetup " + " before sending tuples."); } tupleLinkListener.onSuccess(message); }
Source:
private void storeNetwork() throws UnsupportedEncodingException { StringBuilder output = new StringBuilder(); if (vmInit.getNetworks() != null) { List<VmInitNetwork> networks = vmInit.getNetworks(); for (VmInitNetwork iface: networks) { output.append("iface " + iface.getName() + " inet " + iface.getBootProtocol().getDisplayName() + "\n"); if (!StringUtils.isEmpty(iface.getIp())) { output.append(" address " + iface.getIp() + "\n"); } if (!StringUtils.isEmpty(iface.getNetmask())) { output.append(" netmask " + iface.getNetmask() + "\n"); } if (!StringUtils.isEmpty(iface.getGateway())) { output.append(" gateway " + iface.getGateway() + "\n"); } if (vmInit.getDnsServers() != null) { output.append(" dns-nameservers") .append(" ").append(vmInit.getDnsServers()); output.append("\n"); } if (vmInit.getDnsSearch() != null) { output.append(" dns-search") .append(" ").append(vmInit.getDnsSearch()); output.append("\n"); } } output.append("auto"); for (VmInitNetwork iface : networks) { output.append(" " + iface.getName()); } output.append("\n"); } interfaces = output.toString(); if (!interfaces.isEmpty()) { metaData.put("network-interfaces", interfaces); storeNextFile(CloudInitFileMode.NETWORK, "/etc/network/interfaces", interfaces.getBytes("US-ASCII")); } }

Target:
private void storeNetwork() throws UnsupportedEncodingException { StringBuilder output = new StringBuilder(); if (vmInit.getNetworks() != null) { List<VmInitNetwork> networks = vmInit.getNetworks(); for (VmInitNetwork iface: networks) { output.append("iface " + iface.getName() + " inet " + iface.getBootProtocol().getDisplayName() + "\n"); if (StringUtils.isNotEmpty(iface.getIp())) { output.append(" address " + iface.getIp() + "\n"); } if (StringUtils.isNotEmpty(iface.getNetmask())) { output.append(" netmask " + iface.getNetmask() + "\n"); } if (StringUtils.isNotEmpty(iface.getGateway())) { output.append(" gateway " + iface.getGateway() + "\n"); } if (vmInit.getDnsServers() != null) { output.append(" dns-nameservers") .append(" ").append(vmInit.getDnsServers()); output.append("\n"); } if (vmInit.getDnsSearch() != null) { output.append(" dns-search") .append(" ").append(vmInit.getDnsSearch()); output.append("\n"); } } output.append("auto"); for (VmInitNetwork iface : networks) { output.append(" " + iface.getName()); } output.append("\n"); } interfaces = output.toString(); if (!interfaces.isEmpty()) { metaData.put("network-interfaces", interfaces); storeNextFile(CloudInitFileMode.NETWORK, "/etc/network/interfaces", interfaces.getBytes("US-ASCII")); } }
Source:
public String getUrl() { StringBuilder url = new StringBuilder(100); url.append("jdbc:postgresql://"); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { url.append(","); } url.append(serverNames[i]); if (portNumbers.length >= i && portNumbers[i] != 0) { url.append(":").append(portNumbers[i]); } } url.append("/").append(URLCoder.encode(databaseName)); StringBuilder query = new StringBuilder(100); for (PGProperty property: PGProperty.values()) { if (property.isPresent(properties)) { if (query.length() != 0) { query.append("&"); } query.append(property.getName()); query.append("="); query.append(URLCoder.encode(property.get(properties))); } } if (query.length() > 0) { url.append("?"); url.append(query); } return url.toString(); }

Target:
public String getUrl() { StringBuilder url = new StringBuilder(100); url.append("jdbc:postgresql://"); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { url.append(","); } url.append(serverNames[i]); if (portNumbers != null && portNumbers.length >= i && portNumbers[i] != 0) { url.append(":").append(portNumbers[i]); } } url.append("/").append(URLCoder.encode(databaseName)); StringBuilder query = new StringBuilder(100); for (PGProperty property: PGProperty.values()) { if (property.isPresent(properties)) { if (query.length() != 0) { query.append("&"); } query.append(property.getName()); query.append("="); query.append(URLCoder.encode(property.get(properties))); } } if (query.length() > 0) { url.append("?"); url.append(query); } return url.toString(); }
Source:
public List<CloudVmInstanceStatus> reboot(AuthenticatedContext ac, List<CloudInstance> vms) { AmazonEC2Client amazonEC2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()), ac.getCloudContext().getLocation().getRegion().value()); List<CloudInstance> affectedVms = new ArrayList<>(); List<CloudVmInstanceStatus> rebootedVmsStatus = new ArrayList<>(); try { if (!vms.isEmpty()) { List<CloudVmInstanceStatus> statuses = check(ac, vms); doStop(new ArrayList<>(), ac, getStarted(statuses)); statuses = check(ac, vms); doStart(affectedVms, ac, getStopped(statuses), rebootedVmsStatus); logInvalidStatuses(getNotStoppedOrStarted(statuses)); } } catch (SdkClientException e) { LOGGER.warn("Failed to send reboot request to AWS: ", e); throw e; } return rebootedVmsStatus; }

Target:
public List<CloudVmInstanceStatus> reboot(AuthenticatedContext ac, List<CloudInstance> vms) { List<CloudVmInstanceStatus> rebootedVmsStatus = new ArrayList<>(); try { if (!vms.isEmpty()) { List<CloudVmInstanceStatus> statuses = check(ac, vms); doStop(ac, getStarted(statuses)); statuses = check(ac, vms); logInvalidStatuses(getNotStopped(statuses), InstanceStatus.STOPPED); rebootedVmsStatus = doStart(ac, getStopped(statuses)); logInvalidStatuses(getNotStarted(statuses), InstanceStatus.STARTED); } } catch (SdkClientException e) { LOGGER.warn("Failed to send reboot request to AWS: ", e); throw e; } return rebootedVmsStatus; }
Source:
private Map<String, Long> getNumTasks(List<SingularityRequestWithState> requests) { final CounterMap<String> numTasks = new CounterMap<>(requests.size()); for (SingularityTaskId taskId : taskManager.getActiveTaskIds()) { numTasks.incr(taskId.getRequestId()); } for (SingularityPendingTaskId pendingTaskId : taskManager.getPendingTaskIds()) { numTasks.incr(pendingTaskId.getRequestId()); } for (SingularityTaskId cleaningTaskId : taskManager.getCleanupTaskIds()) { numTasks.decr(cleaningTaskId.getRequestId()); } return numTasks.toCountMap(); }

Target:
private Map<String, Long> getNumTasks(List<SingularityRequestWithState> requests) { final CounterMap<String> numTasks = new CounterMap<>(requests.size()); for (SingularityTaskId taskId : taskManager.getActiveTaskIds()) { numTasks.incr(taskId.getRequestId()); } for (SingularityPendingTaskId pendingTaskId : taskManager.getPendingTaskIds()) { numTasks.incr(pendingTaskId.getRequestId()); } for (SingularityTaskId cleaningTaskId : taskManager.getCleanupTaskIds()) { Optional<SingularityRequestWithState> request = requestManager.getRequest(cleaningTaskId.getRequestId()); if (request.isPresent() && request.get().getRequest().isScheduled()) { continue; } numTasks.decr(cleaningTaskId.getRequestId()); } return numTasks.toCountMap(); }
Source:
public void messageReceived(ChannelHandlerContext ctx, Message message) throws Exception { switch (message.getMessageType()) { case InitRequest: InitRequest initRequestMessage = (InitRequest) message; if (initRequestMessage.getVersion() == InitMessage.DEFAULT_VERSION) { InitResponse initResponse = new InitResponse( initRequestMessage.getId(), InitMessage.DEFAULT_VERSION ); initResponse.setHostPort(this.channelManager.getHostPort()); initResponse.setProcessName("java-process"); ChannelFuture f = ctx.writeAndFlush(initResponse); f.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); ctx.pipeline().remove(this); channelManager.setIdentified(ctx.channel(), initRequestMessage.getHeaders()); } else { throw new FatalProtocolError( String.format("Expected Protocol version: %d", InitMessage.DEFAULT_VERSION), new Trace(0, 0, 0, (byte) 0x00) ); } break; default: throw new FatalProtocolError( "Must not send any data until receiving Init Request", new Trace(0, 0, 0, (byte) 0x00) ); } }

Target:
public void messageReceived(ChannelHandlerContext ctx, Message message) throws Exception { switch (message.getMessageType()) { case InitRequest: InitRequest initRequestMessage = (InitRequest) message; if (initRequestMessage.getVersion() == InitMessage.DEFAULT_VERSION) { InitResponse initResponse = new InitResponse( initRequestMessage.getId(), InitMessage.DEFAULT_VERSION ); initResponse.setHostPort(this.peerManager.getHostPort()); initResponse.setProcessName("java-process"); ChannelFuture f = ctx.writeAndFlush(initResponse); f.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); ctx.pipeline().remove(this); peerManager.setIdentified(ctx.channel(), initRequestMessage.getHeaders()); } else { throw new FatalProtocolError( String.format("Expected Protocol version: %d", InitMessage.DEFAULT_VERSION), new Trace(0, 0, 0, (byte) 0x00) ); } break; default: throw new FatalProtocolError( "Must not send any data until receiving Init Request", new Trace(0, 0, 0, (byte) 0x00) ); } }
Source:
public boolean isDefaultFilterFactorEnabled() { return true; }

Target:
public boolean isDefaultFilterFactorEnabled() { return defaultFilterFactorEnabled; }
Source:
private void applyDevfileEndpoints(InternalMachineConfig machineConfig) { for (org.eclipse.che.api.core.model.workspace.devfile.Endpoint endpoint : component.getEndpoints()) { machineConfig .getServers() .put(endpoint.getName(), ServerConfigImpl.createFromEndpoint(endpoint)); } }

Target:
private void applyDevfileEndpoints(InternalMachineConfig machineConfig) throws InfrastructureException { for (org.eclipse.che.api.core.model.workspace.devfile.Endpoint endpoint : component.getEndpoints()) { if (!machineConfig.getServers().containsKey(endpoint.getName())) { machineConfig .getServers() .put(endpoint.getName(), ServerConfigImpl.createFromEndpoint(endpoint)); } else { throw new InfrastructureException( format( "Devfile overrides the endpoint '%s' of the plugin/editor component '%s'. " + "This is not allowed because it would most probably cause the workspace " + "to malfunction. Please change the name of the endpoint in the devfile and try " + "to start the workspace again.", component.getId(), endpoint.getName())); } } }
Source:
private static boolean classHasNoAutoValueOrImmutableAnnotation(ClassTree tree) { for (AnnotationTree annotation : tree.modifiers().annotations()) { final TypeTree type = annotation.annotationType(); if (type.is(Tree.Kind.IDENTIFIER) && isAutoValueOrImmutable((IdentifierTree) type) || type.is(Tree.Kind.MEMBER_SELECT) && isAutoValueOrImmutable(((MemberSelectExpressionTree) type).identifier())) { return false; } } return true; }

Target:
private static boolean classHasNoAutoValueOrImmutableAnnotation(ClassTree tree) { return tree.modifiers().annotations().stream() .map(AnnotationTree::annotationType) .map(TypeTree::symbolType) .noneMatch(type -> type.is("com.google.auto.value.AutoValue") || type.is("org.immutables.value.Value$Immutable")); }
Source:
public RenameDetector(Repository repo) { objectReader = repo.newObjectReader(); renameLimit = repo.getConfig().get(DiffConfig.KEY).getRenameLimit(); reset(); }

Target:
public RenameDetector(Repository repo) { this(repo.newObjectReader(), repo.getConfig().get(DiffConfig.KEY)); }
Source:
public void saveApplicationWithApplicationDTONullShouldThrowIllegalArgumentException() { Long result = applicationsService.saveApplicaton(applicationDTO,null); }

Target:
public void saveApplicationWithApplicationDTONullShouldThrowIllegalArgumentException() { Long result = applicationsService.saveApplicaton(null,stateDTO); }
Source:
public GlowEntity(Location location) { this.origin = location.clone(); this.previousLocation = location.clone(); this.location = location.clone(); world = (GlowWorld) location.getWorld(); server = world.getServer(); if (this instanceof GlowPlayer) { location = EventFactory.getInstance() .callEvent(new PlayerInitialSpawnEvent((Player) this, location)) .getSpawnLocation(); location = EventFactory.getInstance() .callEvent(new PlayerSpawnLocationEvent((Player) this, location)) .getSpawnLocation(); Position.copyLocation(location, this.origin); Position.copyLocation(location, this.previousLocation); Position.copyLocation(location, this.location); } server.getEntityIdManager().allocate(this); world.getEntityManager().register(this); }

Target:
public GlowEntity(Location location) { this.origin = location.clone(); this.previousLocation = location.clone(); this.location = location.clone(); if (this instanceof GlowPlayer) { location = EventFactory.getInstance() .callEvent(new PlayerInitialSpawnEvent((Player) this, location)) .getSpawnLocation(); location = EventFactory.getInstance() .callEvent(new PlayerSpawnLocationEvent((Player) this, location)) .getSpawnLocation(); Position.copyLocation(location, this.origin); Position.copyLocation(location, this.previousLocation); Position.copyLocation(location, this.location); } world = (GlowWorld) location.getWorld(); server = world.getServer(); server.getEntityIdManager().allocate(this); world.getEntityManager().register(this); }
Source:
public void testVisibilityDefaultMemberFunction() throws Exception { IBinding[] classBindings = getAClass(); IBinding[] functionBindings = getMember("AClass", "defaultMemFun"); assertEquals(1, functionBindings.length); ICPPClassType aClass = (ICPPClassType) classBindings[0]; int visibility = aClass.getVisibility(functionBindings[0]); VisibilityHelper.assertVisibility(ICPPClassType.v_private, visibility); }

Target:
public void testVisibilityDefaultMemberFunction() throws Exception { int visibility = getMemberVisibility(getAClass(), "defaultMemFun", 1, 0); VisibilityAsserts.assertVisibility(ICPPClassType.v_private, visibility); }
Source:
public Action<?, ?> finishExtendMetadata() { return new AbstractStackUpscaleAction<>(CollectMetadataResult.class) { @Override protected void doExecute(StackScalingFlowContext context, CollectMetadataResult payload, Map<Object, Object> variables) throws TransactionExecutionException { Set<String> upscaleCandidateAddresses = stackUpscaleService.finishExtendMetadata(context.getStack(), context.getAdjustment(), payload); variables.put(UPSCALE_CANDIDATE_ADDRESSES, upscaleCandidateAddresses); InstanceGroup ig = instanceGroupService.findOneWithInstanceMetadataByGroupNameInStack(payload.getResourceId(), context.getInstanceGroupName()) .orElseThrow(NotFoundException.notFound("instanceGroup", context.getInstanceGroupName())); if (InstanceGroupType.GATEWAY == ig.getInstanceGroupType()) { Stack stack = stackService.getByIdWithListsInTransaction(context.getStack().getId()); InstanceMetaData gatewayMetaData = stack.getPrimaryGatewayInstance(); if (null == gatewayMetaData && isRepair(variables)) { throw new CloudbreakServiceException("Could not get instance metadata from the cloud provider."); } CloudInstance gatewayInstance = metadataConverter.convert(gatewayMetaData); Selectable sshFingerPrintReq = new GetSSHFingerprintsRequest<GetSSHFingerprintsResult>(context.getCloudContext(), context.getCloudCredential(), gatewayInstance); sendEvent(context, sshFingerPrintReq); } else { BootstrapNewNodesEvent bootstrapPayload = new BootstrapNewNodesEvent(context.getStack().getId()); sendEvent(context, StackUpscaleEvent.BOOTSTRAP_NEW_NODES_EVENT.event(), bootstrapPayload); } } }; }

Target:
public Action<?, ?> finishExtendMetadata() { return new AbstractStackUpscaleAction<>(CollectMetadataResult.class) { @Override protected void doExecute(StackScalingFlowContext context, CollectMetadataResult payload, Map<Object, Object> variables) throws TransactionExecutionException { Set<String> upscaleCandidateAddresses = stackUpscaleService.finishExtendMetadata(context.getStack(), context.getAdjustment(), payload); variables.put(UPSCALE_CANDIDATE_ADDRESSES, upscaleCandidateAddresses); InstanceGroup ig = instanceGroupService.findOneWithInstanceMetadataByGroupNameInStack(payload.getResourceId(), context.getInstanceGroupName()) .orElseThrow(NotFoundException.notFound("instanceGroup", context.getInstanceGroupName())); if (InstanceGroupType.GATEWAY == ig.getInstanceGroupType()) { Stack stack = stackService.getByIdWithListsInTransaction(context.getStack().getId()); InstanceMetaData gatewayMetaData = stack.getPrimaryGatewayInstance(); if (null == gatewayMetaData && isRepair(variables)) { throw new CloudbreakServiceException("Could not get gateway instance metadata from the cloud provider."); } CloudInstance gatewayInstance = metadataConverter.convert(gatewayMetaData); Selectable sshFingerPrintReq = new GetSSHFingerprintsRequest<GetSSHFingerprintsResult>(context.getCloudContext(), context.getCloudCredential(), gatewayInstance); sendEvent(context, sshFingerPrintReq); } else { BootstrapNewNodesEvent bootstrapPayload = new BootstrapNewNodesEvent(context.getStack().getId()); sendEvent(context, StackUpscaleEvent.BOOTSTRAP_NEW_NODES_EVENT.event(), bootstrapPayload); } } }; }
Source:
protected void updateInternal() { super.updateInternal(); if (!(getContainer().isNewStorage() || getContainer().isStorageActive())) { return; } VDS host = (VDS) getContainer().getHost().getSelectedItem(); if (host == null) { proposeDiscover(); return; } final List<EntityModel<?>> prevSelected = findSelectedItems(); clearItems(); initializeItems(null, null); AsyncQuery asyncQuery = new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { SanStorageModel model = (SanStorageModel) target; VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue; if (response.getSucceeded()) { model.applyData((ArrayList<LUNs>) response.getReturnValue(), false, prevSelected); model.setGetLUNsFailure(""); } else { model.setGetLUNsFailure( ConstantsManager.getInstance().getConstants().couldNotRetrieveLUNsLunsFailure()); } } }, true); asyncQuery.setContext(getHash()); Frontend.getInstance().runQuery(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(host.getId(), getType()), asyncQuery); }

Target:
protected void updateInternal() { super.updateInternal(); if (!(getContainer().isNewStorage() || getContainer().isStorageActive())) { return; } VDS host = (VDS) getContainer().getHost().getSelectedItem(); if (host == null) { proposeDiscover(); return; } final Collection<EntityModel<?>> prevSelected = Linq.findSelectedItems((Collection<EntityModel<?>>) getSelectedItem()); clearItems(); initializeItems(null, null); AsyncQuery asyncQuery = new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { SanStorageModel model = (SanStorageModel) target; VdcQueryReturnValue response = (VdcQueryReturnValue) returnValue; if (response.getSucceeded()) { model.applyData((ArrayList<LUNs>) response.getReturnValue(), false, prevSelected); model.setGetLUNsFailure(""); } else { model.setGetLUNsFailure( ConstantsManager.getInstance().getConstants().couldNotRetrieveLUNsLunsFailure()); } } }, true); asyncQuery.setContext(getHash()); Frontend.getInstance().runQuery(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(host.getId(), getType()), asyncQuery); }
Source:
static String fillLogRow(List<String> classList, String command, String description) { VelocityEngine ve = new VelocityEngine(); StringBuilder builder = new StringBuilder(); Template t = ve.getTemplate(LOG_ROW_TEMPLATE_PATH); VelocityContext context = new VelocityContext(); context.put("className", "\"" + classList.stream().collect(Collectors.joining(" ")) + "\""); context.put("command", command); context.put("description", description); StringWriter writer = new StringWriter(); t.merge(context, writer); builder.append(writer.toString()); return builder.toString(); }

Target:
static String fillLogRow(List<String> classList, String command, String description) { StringBuilder builder = new StringBuilder(); Template t = velocityEngine.getTemplate(LOG_ROW_TEMPLATE_PATH); VelocityContext context = new VelocityContext(); context.put("className", "\"" + classList.stream().collect(Collectors.joining(" ")) + "\""); context.put("command", command); context.put("description", description); StringWriter writer = new StringWriter(); t.merge(context, writer); builder.append(writer.toString()); return builder.toString(); }
Source:
public List<Class> getSupportedTypes() { return new ArrayList<>(Arrays.asList(LocalDate.class)); }

Target:
public List<Class> getSupportedTypes() { return Collections.singletonList(LocalDate.class); }
Source:
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException { if (!ninjaProperties.isProd()) { PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript> + "<script language=javascript> + "<script language=javascript> + "<script language=javascript> + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); pw.flush(); pw.close(); logger.error("Templating error.", te); } throw te; }

Target:
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException { if (ninjaProperties.isProd()) { throw te; } else { PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript> + "<script language=javascript> + "<script language=javascript> + "<script language=javascript> + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); logger.error("Templating error.", te); } }
Source:
public void localSucceedTest() { initialize(); ot = new SimpleOperationTracker(datanodes.get(0).getDatacenterName(), mockPartition, false, 2, 3); assertFalse(ot.hasSucceeded()); Iterator<ReplicaId> itr = ot.getReplicaIterator(); ReplicaId nextReplica; while (itr.hasNext()) { nextReplica = itr.next(); assertNotNull(nextReplica); sendReplica(nextReplica); itr.remove(); } assertEquals(3, inflightReplicas.size()); assertFalse(ot.hasSucceeded()); for (int i = 0; i < 2; i++) { ot.onResponse(inflightReplicas.poll(), null); } assertTrue(ot.hasSucceeded()); assertTrue(ot.isDone()); ot.onResponse(inflightReplicas.poll(), new Exception()); assertTrue(ot.hasSucceeded()); assertTrue(ot.isDone()); }

Target:
public void localSucceedTest() { initialize(); ot = new SimpleOperationTracker(localDcName, mockPartition, false, 2, 3); assertFalse("Operation should not succeed.", ot.hasSucceeded()); Iterator<ReplicaId> itr = ot.getReplicaIterator(); ReplicaId nextReplica; while (itr.hasNext()) { nextReplica = itr.next(); assertNotNull("", nextReplica); sendReplica(nextReplica); itr.remove(); } assertEquals(3, inflightReplicas.size()); assertFalse(ot.hasSucceeded()); for (int i = 0; i < 2; i++) { ot.onResponse(inflightReplicas.poll(), null); } assertTrue(ot.hasSucceeded()); assertTrue(ot.isDone()); ot.onResponse(inflightReplicas.poll(), new Exception()); assertTrue(ot.hasSucceeded()); assertTrue(ot.isDone()); }