auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MethodOutcome createFHIRDiagnosticReport(@ResourceParam DiagnosticReport diagnosticReport) { System.out.println("DiagnosticReport: createFHIRDiagnosticReport"); diagnosticReport = diagnosticReportResource.createFHIRDiagnosticReport(diagnosticReport); MethodOutcome retVal = new MethodOutcome(); retVal.setId(new IdDt("DiagnosticReport", "2889127246021897")); OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Diagnostic Report is successfully created"); retVal.setOperationOutcome(outcome); return retVal; }

Target:
public MethodOutcome createFHIRDiagnosticReport(@ResourceParam DiagnosticReport diagnosticReport) { System.out.println("DiagnosticReport: createFHIRDiagnosticReport"); diagnosticReport = diagnosticReportResource.createFHIRDiagnosticReport(diagnosticReport); MethodOutcome retVal = new MethodOutcome(); retVal.setId(new IdDt("DiagnosticReport", diagnosticReport.getId().getIdPart())); OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Diagnostic Report is successfully created"); retVal.setOperationOutcome(outcome); return retVal; }
Source:
public List<HTNode> selectNextChildren(CoreNode currentNode, long t) throws ClosedChannelException { assert (currentNode.getNbChildren() > 0); int potentialNextSeqNb = currentNode.getSequenceNumber(); List<HTNode> nextChildren = new LinkedList<>(); for (int i = 0; i < currentNode.getNbChildren(); i++) { if (t >= currentNode.getChildStart(i) && t <= currentNode.getChildEnd(i)) { potentialNextSeqNb = currentNode.getChild(i); if (currentNode.isOnDisk()) { nextChildren.add( fTreeIO.readNode(potentialNextSeqNb) ); }else{ nextChildren.add( readNode(potentialNextSeqNb) ); } } } return nextChildren; }

Target:
public Collection<HTNode> selectNextChildren(CoreNode currentNode, long t) throws ClosedChannelException { assert (currentNode.getNbChildren() > 0); int potentialNextSeqNb = currentNode.getSequenceNumber(); List<HTNode> nextChildren = new ArrayList<>(); for (int i = 0; i < currentNode.getNbChildren(); i++) { if (t >= currentNode.getChildStart(i) && t <= currentNode.getChildEnd(i)) { potentialNextSeqNb = currentNode.getChild(i); if (currentNode.isOnDisk()) { nextChildren.add(fTreeIO.readNode(potentialNextSeqNb)); } else { nextChildren.add(readNode(potentialNextSeqNb)); } } } return nextChildren; }
Source:
public CDPStructuredNotificationEvent(CDPOperationDetails operation, CDPStructuredNotificationDetails notificationDetails) { super(CDPStructuredNotificationEvent.class.getSimpleName(), operation); this.notificationDetails = notificationDetails; ldapNotificationDetails = null; rdsNotificationDetails = null; }

Target:
public CDPStructuredNotificationEvent(CDPOperationDetails operation, CDPStructuredNotificationDetails notificationDetails) { super(CDPStructuredNotificationEvent.class.getSimpleName(), operation); this.notificationDetails = notificationDetails; }
Source:
public void testQuerySerdeWithAlphaNumericTopNMetricSpec() throws IOException{ TopNQuery query = new TopNQueryBuilder() .dataSource(dataSource) .granularity(allGran) .dimension(marketDimension) .metric(new AlphaNumericTopNMetricSpec(null)) .threshold(2) .intervals(fullOnInterval) .aggregators(Lists.<AggregatorFactory>newArrayList(commonAggregators)) .build(); String json = jsonMapper.writeValueAsString(query); Query serdeQuery = jsonMapper.readValue(json, Query.class); Assert.assertEquals(query, serdeQuery); }

Target:
public void testQuerySerdeWithAlphaNumericTopNMetricSpec() throws IOException{ TopNQuery expectedQuery = new TopNQueryBuilder() .dataSource(dataSource) .granularity(allGran) .dimension(new LegacyDimensionSpec(marketDimension)) .metric(new AlphaNumericTopNMetricSpec(null)) .threshold(2) .intervals(fullOnInterval.getIntervals()) .aggregators(Lists.<AggregatorFactory>newArrayList(rowsCount)) .build(); String jsonQuery = "{\n" + " \"queryType\": \"topN\",\n" + " \"dataSource\": \"testing\",\n" + " \"dimension\": \"market\",\n" + " \"threshold\": 2,\n" + " \"metric\": {\n" + " \"type\": \"alphaNumeric\"\n" + " },\n" + " \"granularity\": \"all\",\n" + " \"aggregations\": [\n" + " {\n" + " \"type\": \"count\",\n" + " \"name\": \"rows\"\n" + " }\n" + " ],\n" + " \"intervals\": [\n" + " \"1970-01-01T00:00:00.000Z/2020-01-01T00:00:00.000Z\"\n" + " ]\n" + "}"; TopNQuery actualQuery = jsonMapper.readValue(jsonMapper.writeValueAsString(jsonMapper.readValue(jsonQuery, TopNQuery.class)), TopNQuery.class); Assert.assertEquals(expectedQuery, actualQuery); }
Source:
private void processFile(File file) throws Exception { final ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); Log.d(TAG, "Processing entry: " + entry.getName()); String parts[] = entry.getName().split("/"); String filename = parts[parts.length - 1]; String id = surveyIdGenerator.getSurveyIdFromFilePath(parts); if (entry.isDirectory() || filename.startsWith(".") || ConstantUtil.BOOTSTRAP_ROLLBACK_FILE.equalsIgnoreCase(filename)) { continue; } if (filename.endsWith(ConstantUtil.BOOTSTRAP_DB_FILE)) { processDbInstructions(FileUtil.readText(zipFile.getInputStream(entry)), true); } else if (filename.endsWith(ConstantUtil.CASCADE_RES_SUFFIX)) { FileUtil.extract(new ZipInputStream(zipFile.getInputStream(entry)), FileUtil.getFilesDir(FileType.RES)); } else if (filename.endsWith(ConstantUtil.XML_SUFFIX)) { processSurveyFile(zipFile, entry, filename, id); } else { File helpDir = new File(FileUtil.getFilesDir(FileType.FORMS), id); if (!helpDir.exists()) { helpDir.mkdir(); } FileUtil.copy(zipFile.getInputStream(entry), new FileOutputStream(new File(helpDir, filename))); } } file.renameTo(new File(file.getAbsolutePath() + ConstantUtil.PROCESSED_OK_SUFFIX)); }

Target:
private void processFile(File file) throws Exception { final ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); Log.d(TAG, "Processing entry: " + entryName); int fileSeparatorPosition = entryName.lastIndexOf("/"); String filename = entryName.substring(fileSeparatorPosition + 1); String id = surveyIdGenerator .getSurveyIdFromFilePath(entryName.substring(0, fileSeparatorPosition)); if (entry.isDirectory() || filename.startsWith(".") || ConstantUtil.BOOTSTRAP_ROLLBACK_FILE.equalsIgnoreCase(filename)) { continue; } if (filename.endsWith(ConstantUtil.BOOTSTRAP_DB_FILE)) { processDbInstructions(FileUtil.readText(zipFile.getInputStream(entry)), true); } else if (filename.endsWith(ConstantUtil.CASCADE_RES_SUFFIX)) { FileUtil.extract(new ZipInputStream(zipFile.getInputStream(entry)), FileUtil.getFilesDir(FileType.RES)); } else if (filename.endsWith(ConstantUtil.XML_SUFFIX)) { processSurveyFile(zipFile, entry, filename, id); } else { File helpDir = new File(FileUtil.getFilesDir(FileType.FORMS), id); if (!helpDir.exists()) { helpDir.mkdir(); } FileUtil.copy(zipFile.getInputStream(entry), new FileOutputStream(new File(helpDir, filename))); } } file.renameTo(new File(file.getAbsolutePath() + ConstantUtil.PROCESSED_OK_SUFFIX)); }
Source:
static JSONObject copyOperatorNewName(JSONObject op, String name){ try{ op = OrderedJSONObject.parse(op.serialize()); } catch(Exception e){ e.printStackTrace(); System.exit(-1); } JSONObject op_new=null; try { op_new = JSONObject.parse(op.serialize()); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } op_new.put("name", name); @SuppressWarnings("unchecked") Collection<JSONObject> inputs = (Collection<JSONObject>)op_new.get("inputs"); @SuppressWarnings("unchecked") Collection<JSONObject> outputs = (Collection<JSONObject>)op_new.get("outputs"); for(JSONObject input : inputs){ input.put("name", name + "_IN" + input.get("index").toString()); JSONArray conns = (JSONArray) input.get("connections"); conns.clear(); } for(JSONObject output : outputs){ output.put("name", name + "_OUT" + output.get("index").toString()); JSONArray conns = (JSONArray) output.get("connections"); conns.clear(); } return op_new; }

Target:
static JSONObject copyOperatorNewName(JSONObject op, String name){ JSONObject op_new=null; try { op_new = JSONObject.parse(op.serialize()); } catch (IOException e) { throw new RuntimeException("Error copying operator " + (String)op.get("name"), e); } op_new.put("name", name); @SuppressWarnings("unchecked") Collection<JSONObject> inputs = (Collection<JSONObject>)op_new.get("inputs"); @SuppressWarnings("unchecked") Collection<JSONObject> outputs = (Collection<JSONObject>)op_new.get("outputs"); for(JSONObject input : inputs){ input.put("name", name + "_IN" + input.get("index").toString()); JSONArray conns = (JSONArray) input.get("connections"); conns.clear(); } for(JSONObject output : outputs){ output.put("name", name + "_OUT" + output.get("index").toString()); JSONArray conns = (JSONArray) output.get("connections"); conns.clear(); } return op_new; }
Source:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType())) { if (providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); forceReload = true; } } }

Target:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType()) && providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); forceReload = true; } }
Source:
public BufferBuilder requestNewBufferBuilder(int targetChannel) throws IOException, InterruptedException { checkState(bufferBuilder == null || bufferBuilder.isFinished()); BufferBuilder builder = super.requestNewBufferBuilder(targetChannel); if (randomTriggered) { addBufferConsumer(randomConsumer = builder.createBufferConsumer(), targetChannel); } else { try (BufferConsumer bufferConsumer = builder.createBufferConsumer()) { for (int channel = 0; channel < numberOfChannels; channel++) { addBufferConsumer(bufferConsumer.copy(), channel); } } } bufferBuilder = builder; return builder; }

Target:
public BufferBuilder requestNewBufferBuilder(int targetChannel) throws IOException, InterruptedException { checkState(bufferBuilder == null || bufferBuilder.isFinished()); BufferBuilder builder = super.requestNewBufferBuilder(targetChannel); if (randomTriggered) { addBufferConsumer(randomTriggeredConsumer = builder.createBufferConsumer(), targetChannel); } else { try (BufferConsumer bufferConsumer = builder.createBufferConsumer()) { for (int channel = 0; channel < numberOfChannels; channel++) { addBufferConsumer(bufferConsumer.copy(), channel); } } } bufferBuilder = builder; return builder; }
Source:
public void testIsEmpty() throws Exception { assertThat( Strings.isEmpty( null ) ).isTrue(); assertThat( Strings.isEmpty( "" ) ).isTrue(); assertThat( Strings.isEmpty( "not empty" ) ).isFalse(); }

Target:
public void testIsEmpty() throws Exception { assertThat( Strings.isEmpty( null ) ).isTrue(); assertThat( Strings.isEmpty( "" ) ).isTrue(); assertThat( Strings.isEmpty( " " ) ).isFalse(); assertThat( Strings.isEmpty( "not empty" ) ).isFalse(); }
Source:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(GSE); } else { logger.error("Unknown type of job seen"); } } } }

Target:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } } }
Source:
protected synchronized void timerExpired(final Integer timerId) { if (m_kieSession == null) { LOG.info("No valid session"); return; } LOG.info("Begin correlation for Timer {}", timerId); TimerExpired expiration = new TimerExpired(timerId); m_kieSession.insert(expiration); try { if (!m_isStreaming) m_kieSession.fireAllRules(); } catch (Exception e) { LOG.error("Exception while firing rules ", e); } LOG.debug("Begin correlation for Timer {}", timerId); }

Target:
protected synchronized void timerExpired(final Integer timerId) { if (m_kieSession == null) { LOG.info("No valid session, Timer with Id will not be added as a fact.", timerId); return; } LOG.info("Begin correlation for Timer {}", timerId); TimerExpired expiration = new TimerExpired(timerId); m_kieSession.insert(expiration); try { if (!m_isStreaming) m_kieSession.fireAllRules(); } catch (Exception e) { LOG.error("Exception while firing rules ", e); } LOG.debug("Begin correlation for Timer {}", timerId); }
Source:
public void initialize(VM vm, List<Disk> disksToSparsify, ICommandTarget target) { this.disksToSparsify = disksToSparsify; UIConstants uiConstants = ConstantsManager.getInstance().getConstants(); setTitle(uiConstants.sparsifyDisksTitle()); setMessage(uiConstants.sparsifyConfirmationPopupMessage()); setHelpTag(HelpTag.sparsify_disk); setHashName("sparsify_disk"); getLatch().setEntity(false); List<DiskModel> items = new ArrayList<>(); for (Disk disk : disksToSparsify) { DiskModel diskModel = new DiskModel(); diskModel.setDisk(disk); diskModel.setVm(vm); items.add(diskModel); if (disk.getNumberOfVms() > 1) { getLatch().setIsChangeable(false); } } setItems(items); UICommand okCommand = UICommand.createDefaultOkUiCommand(ON_SPARSIFY, target); getCommands().add(okCommand); cancelCommand = UICommand.createCancelUiCommand(CANCEL_SPARSIFY, target); getCommands().add(cancelCommand); }

Target:
public void initialize(VM vm, List<Disk> disksToSparsify, ICommandTarget target) { this.disksToSparsify = disksToSparsify; UIConstants uiConstants = ConstantsManager.getInstance().getConstants(); setTitle(uiConstants.sparsifyDisksTitle()); setMessage(uiConstants.sparsifyConfirmationPopupMessage()); setHelpTag(HelpTag.sparsify_disk); setHashName("sparsify_disk"); List<DiskModel> items = new ArrayList<>(); for (Disk disk : disksToSparsify) { DiskModel diskModel = new DiskModel(); diskModel.setDisk(disk); diskModel.setVm(vm); items.add(diskModel); } setItems(items); UICommand okCommand = UICommand.createDefaultOkUiCommand(ON_SPARSIFY, target); getCommands().add(okCommand); cancelCommand = UICommand.createCancelUiCommand(CANCEL_SPARSIFY, target); getCommands().add(cancelCommand); }
Source:
public Iterable<IEventDeclaration> getEventDeclarations() { return ImmutableSet.copyOf(fStreamInput.getStream().getEventDeclarations()); }

Target:
public Iterable<IEventDeclaration> getEventDeclarations() { return ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations()); }
Source:
protected void destroyVm() { boolean wasPaused = false; VmStatic vmStatic = getVm().getStaticData(); if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } if (getVm().getStatus() == VMStatus.Paused && getVm().getVmPauseStatus() == VmPauseStatus.NOERR) { wasPaused = true; } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); if (wasPaused) { VmHandler.decreasePendingVms(getVm().getRunOnVds(), vmStatic.getNumOfCpus(), vmStatic.getMinAllocatedMem(), vmStatic.getName()); } }

Target:
protected void destroyVm() { boolean wasPaused = (getVm().getStatus() == VMStatus.Paused && getVm().getVmPauseStatus() == VmPauseStatus.NOERR); if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); if (wasPaused) { VmHandler.decreasePendingVms(getVm(), getVdsId()); } }
Source:
private void setTabIndex() { String tabIndexProperty = $selectElement.attr(TABINDEX_PROPERTY); if (options.isRemoveFromTabIndexWhenDisabled()) { if (isDisabled) { tabIndexProperty = "-1"; } else { tabIndexProperty = "0"; } } if (tabIndexProperty != null && tabIndexProperty.length() > 0) { $selectElement.attr(TABINDEX_PROPERTY, -1); if (isMultiple) { searchField.attr(TABINDEX_PROPERTY, tabIndexProperty); } else { selectedItem.attr(TABINDEX_PROPERTY, tabIndexProperty); searchField.attr(TABINDEX_PROPERTY, -1); } } }

Target:
private void setTabIndex() { final String selectElementOriginalTabIndexProperty = $selectElement.attr(TABINDEX_PROPERTY); String tabIndexProperty = selectElementOriginalTabIndexProperty; if (isDisabled) { tabIndexProperty = "-1"; } if (tabIndexProperty != null && tabIndexProperty.length() > 0) { if (isMultiple) { searchField.attr(TABINDEX_PROPERTY, tabIndexProperty); } else { selectedItem.attr(TABINDEX_PROPERTY, tabIndexProperty); searchField.attr(TABINDEX_PROPERTY, -1); } } }
Source:
private static BlockBuilder createBlockBuilder(Type type, long count) { checkCondition(count <= MAX_LENGTH, INVALID_FUNCTION_ARGUMENT, "repeat count should be no greater than " + MAX_LENGTH); checkCondition(count >= 0, INVALID_FUNCTION_ARGUMENT, "repeat count must be no smaller than zero"); return type.createBlockBuilder(new BlockBuilderStatus(), toIntExact(count)); }

Target:
private static BlockBuilder createBlockBuilder(Type type, long count) { checkCondition(count <= MAX_RESULT_ENTRIES, INVALID_FUNCTION_ARGUMENT, "count argument of repeat function must be less than or equal to 10000"); checkCondition(count >= 0, INVALID_FUNCTION_ARGUMENT, "count argument of repeat function must be greater than or equal to 0"); return type.createBlockBuilder(new BlockBuilderStatus(), toIntExact(count)); }
Source:
public boolean dequeueOutGoingMessageQueue() { if (null == messageClient) { return false; } String message = outGoingMessageQueue.poll(); if (null == message) { return false; } try { Friend receiver = MessageFactory.buildMessageByJson(message).getReceiver(); messageClient.sendMsg(receiver.getIp(), receiver.getPort(), message); return true; } catch (JSONException ex) { ex.printStackTrace(); } catch (UnknownHostException ex) { ex.printStackTrace(); } return false; }

Target:
public boolean dequeueOutGoingMessageQueue() { String message = outGoingMessageQueue.poll(); if (null == message) { return false; } try { Friend receiver = MessageFactory.buildMessageByJson(message).getReceiver(); messageClient.sendMsg(receiver.getIp(), receiver.getPort(), message); return true; } catch (JSONException ex) { ex.printStackTrace(); } catch (UnknownHostException ex) { ex.printStackTrace(); } return false; }
Source:
public void loadObjectsExceptionThrownTest() throws Exception { Mockito.reset(queryLogger); Object result = null; try { query = Query.builder().table(playerStatsTable).bypassingCache(true).build(); SQLQuery myQuery = SQLQuery.builder().clientQuery(query) .fromClause(query.getTable().getName()) .projectionClause(" ").build(); when(queryEngine.executeQuery(query, qeTransaction)).thenReturn(null); when(queryEngine.explain(query)).thenReturn(myQuery.toString()); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache, queryLogger); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); transaction.loadObjects(entityProjection, scope); } catch (Exception e) { result = e.getMessage(); } finally { Object finalResult = result; Mockito.verify(queryLogger, times(1)).acceptQuery( Mockito.eq(scope.getRequestId()), any(), any(), any(), any(), any()); Mockito.verify(queryLogger, times(1)).processQuery( Mockito.eq(scope.getRequestId()), any(), any(), Mockito.eq(false)); Mockito.verify(queryLogger, times(1)).completeQuery( Mockito.eq(scope.getRequestId()), any()); Mockito.verify(queryLogger).completeQuery(Mockito.eq(scope.getRequestId()), argThat((QueryResponse qResponse) -> qResponse.getErrorMessage() == finalResult)); } }

Target:
public void loadObjectsExceptionThrownTest() throws Exception { Mockito.reset(queryLogger); String nullPointerExceptionMessage = "Cannot dereference an object with value Null"; try { query = Query.builder().table(playerStatsTable).bypassingCache(true).build(); doThrow(new NullPointerException(nullPointerExceptionMessage)) .when(queryEngine).executeQuery(query, qeTransaction); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache, queryLogger); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); transaction.loadObjects(entityProjection, scope); } catch (Exception e) { assertEquals(nullPointerExceptionMessage, e.getMessage()); Mockito.verify(queryLogger).completeQuery(Mockito.eq(scope.getRequestId()), argThat((QueryResponse qResponse) -> qResponse.getErrorMessage() == e.getMessage())); } Mockito.verify(queryLogger, times(1)).acceptQuery( Mockito.eq(scope.getRequestId()), any(), any(), any(), any(), any()); Mockito.verify(queryLogger, times(1)).processQuery( Mockito.eq(scope.getRequestId()), any(), any(), Mockito.eq(false)); Mockito.verify(queryLogger, times(1)).completeQuery( Mockito.eq(scope.getRequestId()), any()); }
Source:
@Test public void failWhenWriteToParcelAlreadyDefinedTest() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", "" + "package test;\n" + "import android.os.Parcel;\n" + "import android.os.Parcelable;\n" + "import com.google.auto.value.AutoValue;\n" + "@AutoValue public abstract class Test implements Parcelable {\n" + " public abstract String name();\n" + " @Override\n" + " public void writeToParcel(Parcel dest, int flags) {\n" + " }\n" + "}" ); assertAbout(javaSources()) .that(Arrays.asList(parcel, parcelable, source)) .processedWith(new AutoValueProcessor()) .failsToCompile(); }

Target:
@Test public void failWhenWriteToParcelAlreadyDefinedTest() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", "" + "package test;\n" + "import android.os.Parcel;\n" + "import android.os.Parcelable;\n" + "import com.google.auto.value.AutoValue;\n" + "@AutoValue public abstract class Test implements Parcelable {\n" + " public abstract String name();\n" + " @Override\n" + " public void writeToParcel(Parcel dest, int flags) {\n" + " }\n" + "}" ); assertAbout(javaSources()) .that(Arrays.asList(parcel, parcelable, source)) .processedWith(new AutoValueProcessor()) .failsToCompile() .withErrorContaining("Manual implementation of Parcelable#writeToParcel(Parcel,int) found when " + "processing test.Test. Remove this so auto-value-parcel can automatically " + "generate the implementation for you.") .in(source) .onLine(8); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final EventAuthField that = (EventAuthField) o; return (this.type.equals(that.type) && this.path.equals(that.path)); }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final EventAuthField that = (EventAuthField) o; return Objects.equals(this.type, that.type) && Objects.equals(this.path, that.path); }
Source:
Multimap<String, String> buildMultiMapHeaders(Map<String, String> headers) { Multimap<String, String> multimap = ArrayListMultimap.create(); for (Map.Entry<String, String> entry : headers.entrySet()) { multimap.put(entry.getKey(), entry.getValue()); } return multimap; }

Target:
private Multimap<String, String> buildMultiMapHeaders(Map<String, String> headers) { Multimap<String, String> multimap = ArrayListMultimap.create(); for (Map.Entry<String, String> entry : headers.entrySet()) { multimap.put(entry.getKey(), entry.getValue()); } return multimap; }
Source:
public Object getAdapter(Class adapter) { if (adapter == IResource.class) { return resource; } return null; }

Target:
public Object getAdapter(Class adapter) { if (adapter == IResource.class) return resource; return null; }
Source:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = bitmapResult; }

Target:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = bitmap; }
Source:
private Group drawStackContainer(final StackedMutationContainer stack, final double width) { Group root = new Group(); int stacks = stack.getStack().size(); for (int index = 0; index < stacks; index++) { StackView stackView = new StackView(stack.getStack().get(index), width / stacks, stack.getMaxMutations()); stackView.setLayoutX(index * width / stacks); root.getChildren().add(stackView); } return root; }

Target:
private Group drawStackContainer(final StackedMutationContainer stack, final double width) { Group root = new Group(); int stacks = stack.getStack().size(); double stackWidth = width / stacks; for (int index = 0; index < stacks; index++) { StackView stackView = new StackView(stack.getStack().get(index), stackWidth, stack.getMaxMutations()); stackView.setLayoutX(index * stackWidth); root.getChildren().add(stackView); } return root; }
Source:
public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.DIFFER_BY_TIMESTAMP) return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }

Target:
public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL) return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }
Source:
@Test public void destinationIsAFileExecutorTest() throws IOException { TestUtils.createFile(SAMPLE_TEXT_FILE); executeConversion(TestConstants.SAMPLE_JAR_FILE, SAMPLE_TEXT_FILE); if (Files.exists(SAMPLE_TEXT_FILE)) { BundleGeneratorUtils.delete(SAMPLE_TEXT_FILE); } Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(SAMPLE_TEXT_FILE.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }

Target:
public void destinationIsAFileExecutorTest() throws IOException { TestUtils.createFile(SAMPLE_TEXT_FILE); executeConversion(TestConstants.SAMPLE_JAR_FILE, SAMPLE_TEXT_FILE); if (Files.exists(SAMPLE_TEXT_FILE)) { BundleGeneratorUtils.delete(SAMPLE_TEXT_FILE); } Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(SAMPLE_TEXT_FILE.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }
Source:
private KubernetesList unmarshal(Tool tool, String recipeContent) throws DevfileRecipeFormatException { try { return Serialization.unmarshal(recipeContent, KubernetesList.class); } catch (KubernetesClientException e) { throw new DevfileRecipeFormatException( format( "Error occurred during parsing list from file %s for tool '%s'", tool.getLocal(), tool.getName())); } }

Target:
private KubernetesList unmarshal(Tool tool, String recipeContent) throws DevfileRecipeFormatException { try { return Serialization.unmarshal(recipeContent, KubernetesList.class); } catch (KubernetesClientException e) { throw new DevfileRecipeFormatException( format( "Error occurred during parsing list from file %s for tool '%s': %s", tool.getLocal(), tool.getName(), e.getMessage())); } }
Source:
private SortedMap<Long, List<CircuitStatistics>> parseCSV(String csvStatistics) throws IllegalArgumentException, IOException { CSVReader reader = new CSVReader(new StringReader(csvStatistics)); try { SortedMap<Long, List<CircuitStatistics>> circuitsStatistics = new TreeMap<Long, List<CircuitStatistics>>(); List<String[]> records = reader.readAll(); log.debug("Storing the new " + records.size() + " received circuits statistics."); for (String[] currentRecord : records) { if (currentRecord.length != 7) throw new IllegalArgumentException("Invalid record length: it should contain 7 fields."); CircuitStatistics currentStatistics = new CircuitStatistics(); if (!StringUtils.isNumeric(currentRecord[0].trim())) throw new IllegalArgumentException("Records should start with timestamp."); Long timestamp = Long.valueOf(currentRecord[0].trim()); currentStatistics.setSlaFlowId(currentRecord[1].trim()); currentStatistics.setThroughput(currentRecord[2].trim()); currentStatistics.setPacketLoss(currentRecord[3].trim()); currentStatistics.setDelay(currentRecord[4].trim()); currentStatistics.setJitter(currentRecord[5].trim()); currentStatistics.setFlowData(currentRecord[6].trim()); if (circuitsStatistics.keySet().contains(timestamp)) circuitsStatistics.get(timestamp).add(currentStatistics); else { List<CircuitStatistics> circuitStatisticsList = new ArrayList<CircuitStatistics>(); circuitStatisticsList.add(currentStatistics); circuitsStatistics.put(timestamp, circuitStatisticsList); } } return circuitsStatistics; } finally { reader.close(); } }

Target:
private SortedMap<Long, List<CircuitStatistics>> parseCSV(String csvStatistics) throws IllegalArgumentException, IOException { CSVReader reader = new CSVReader(new StringReader(csvStatistics)); try { SortedMap<Long, List<CircuitStatistics>> circuitsStatistics = new TreeMap<Long, List<CircuitStatistics>>(); List<String[]> records = reader.readAll(); log.debug("Storing the new " + records.size() + " received circuits statistics."); for (String[] currentRecord : records) { if (currentRecord.length != 7) throw new IllegalArgumentException("Invalid record length: it should contain 7 fields."); CircuitStatistics currentStatistics = new CircuitStatistics(); if (!StringUtils.isNumeric(currentRecord[0].trim())) throw new IllegalArgumentException("Records should start with timestamp."); Long timestamp = Long.valueOf(currentRecord[0].trim()); currentStatistics.setSlaFlowId(currentRecord[1].trim()); currentStatistics.setThroughput(currentRecord[2].trim()); currentStatistics.setPacketLoss(currentRecord[3].trim()); currentStatistics.setDelay(currentRecord[4].trim()); currentStatistics.setJitter(currentRecord[5].trim()); currentStatistics.setFlowData(currentRecord[6].trim()); if (circuitsStatistics.containsKey(timestamp)) circuitsStatistics.get(timestamp).add(currentStatistics); else { List<CircuitStatistics> circuitStatisticsList = new ArrayList<CircuitStatistics>(); circuitStatisticsList.add(currentStatistics); circuitsStatistics.put(timestamp, circuitStatisticsList); } } return circuitsStatistics; } finally { reader.close(); } }
Source:
private Response validateCacheWithServer(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read) throws IOException { final Response rspCached = this.cache.get(req); final Collection<Map.Entry<String, String>> hdrs = this.enrich( headers, rspCached ); Response rsp = this.origin.send( req, home, method, hdrs, content, connect, read ); if (rsp.status() == HttpURLConnection.HTTP_NOT_MODIFIED) { rsp = rspCached; } else { this.updateCache(req, rsp); } return rsp; }

Target:
private Response validateCacheWithServer(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read) throws IOException { final Response rsp = this.cache.get(req); final Collection<Map.Entry<String, String>> hdrs = this.enrich( headers, rsp ); Response result = this.origin.send( req, home, method, hdrs, content, connect, read ); if (result.status() == HttpURLConnection.HTTP_NOT_MODIFIED) { result = rsp; } else { this.updateCache(req, result); } return result; }
Source:
protected void run(Date lastRun) { WikipediaApp app = (WikipediaApp) context.getApplicationContext(); try { for (String[] styleSpec : STYLE_SPECS) { String url = getRemoteURLFor(styleSpec[1]); OutputStream fo = context.openFileOutput(styleSpec[0], Context.MODE_PRIVATE); Utils.copyStreams(HttpRequest.get(url).userAgent(app.getUserAgent()).stream(), fo); fo.close(); Log.d("Wikipedia", String.format("Downloaded %s into %s", url, context.getFileStreamPath(styleSpec[0]).getAbsolutePath())); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); } catch (HttpRequest.HttpRequestException e) { e.printStackTrace(); } }

Target:
protected void run(Date lastRun) { WikipediaApp app = (WikipediaApp) context.getApplicationContext(); try { for (String[] styleSpec : STYLE_SPECS) { String url = getRemoteURLFor(styleSpec[1]); OutputStream fo = context.openFileOutput(styleSpec[0], Context.MODE_PRIVATE); Utils.copyStreams(HttpRequest.get(url).userAgent(app.getUserAgent()).stream(), fo); fo.close(); Log.d("Wikipedia", String.format("Downloaded %s into %s", url, context.getFileStreamPath(styleSpec[0]).getAbsolutePath())); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { Log.d("StyleFetcherTask", e.getMessage()); e.printStackTrace(); } catch (HttpRequest.HttpRequestException e) { Log.d("StyleFetcherTask", e.getMessage()); e.printStackTrace(); } }
Source:
public static String unescape(String text) { return StringEscapeUtils.unescapeHtml(text); }

Target:
private String unescape(String text) { return StringEscapeUtils.unescapeHtml(text); }
Source:
public void setupTest() { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.hypervisorType = new ConsumerType(ConsumerTypeEnum.HYPERVISOR); ConsumerBindUtil consumerBindUtil = new ConsumerBindUtil( null, null, null, null, mockedServiceLevelValidator); this.consumerResource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, this.eventFactory, null, null, this.userService, null, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, new CandlepinCommonTestConfig(), null, null, null, consumerBindUtil); hypervisorResource = new HypervisorResource(consumerResource, consumerCurator, i18n, ownerCurator); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class))) .thenReturn(new ComplianceStatus(new Date())); when(ownerCurator.lookupByKey(any(String.class))).thenReturn(new Owner()); when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setNewEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setOldEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); }

Target:
public void setupTest() { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.hypervisorType = new ConsumerType(ConsumerTypeEnum.HYPERVISOR); this.consumerResource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, this.eventFactory, null, null, this.userService, null, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, new CandlepinCommonTestConfig(), null, null, null, this.consumerBindUtil); hypervisorResource = new HypervisorResource(consumerResource, consumerCurator, i18n, ownerCurator); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class))) .thenReturn(new ComplianceStatus(new Date())); when(ownerCurator.lookupByKey(any(String.class))).thenReturn(new Owner()); when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setNewEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setOldEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); }
Source:
protected static int isReadme(String name) { boolean isDoc = name.startsWith(DOC_PREFIX); boolean isParentDoc = name.startsWith(PARENT_DOC_PREFIX); if (isDoc || isParentDoc) { String filename = new Path(name).lastSegment(); if (filename.length() >= 6 && filename.substring(0, 6).equalsIgnoreCase("readme")) { return isDoc ? 1 : 2; } } return 0; }

Target:
public static int isReadme(String name) { if (name == null) { return 0; } boolean isDoc = name.startsWith(DOC_PREFIX); boolean isParentDoc = name.startsWith(PARENT_DOC_PREFIX); if (isDoc || isParentDoc) { Path path = new Path(name); String filename = path.lastSegment(); if ("md".equals(path.getFileExtension()) && filename.length() >= 6 && filename.substring(0, 6).equalsIgnoreCase("readme")) { return isDoc ? 1 : 2; } } return 0; }
Source:
public void testGlobalOutstandingRequestThrottlingWithRequestThrottlerDisabled() throws Exception { System.setProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT, GLOBAL_OUTSTANDING_LIMIT); ServerMetrics.getMetrics().resetAll(); RequestThrottler.setMaxRequests(0); resumeProcess = new CountDownLatch(1); int totalRequests = 10; submitted = new CountDownLatch(totalRequests); for (int i = 0; i < totalRequests; i++) { zk.create("/request_throttle_test- " + i, ("/request_throttle_test- " + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, null); } submitted.await(5, TimeUnit.SECONDS); resumeProcess.countDown(); assertEquals(Integer.parseInt(GLOBAL_OUTSTANDING_LIMIT) + 2, (long) MetricsUtils.currentServerMetrics().get("prep_processor_request_queued")); System.clearProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT); }

Target:
public void testGlobalOutstandingRequestThrottlingWithRequestThrottlerDisabled() throws Exception { try { System.setProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT, GLOBAL_OUTSTANDING_LIMIT); ServerMetrics.getMetrics().resetAll(); RequestThrottler.setMaxRequests(0); resumeProcess = new CountDownLatch(1); int totalRequests = 10; submitted = new CountDownLatch(totalRequests); for (int i = 0; i < totalRequests; i++) { zk.create("/request_throttle_test- " + i, ("/request_throttle_test- " + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, null); } submitted.await(5, TimeUnit.SECONDS); resumeProcess.countDown(); assertEquals(Integer.parseInt(GLOBAL_OUTSTANDING_LIMIT) + 2, (long) MetricsUtils.currentServerMetrics().get("prep_processor_request_queued")); } catch (Exception e) { throw e; } finally { System.clearProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT); } }
Source:
private void addBootProtocol(Map<String, String> opts, VdsNetworkInterface iface) { if (iface.getBootProtocol() != null) { switch (iface.getBootProtocol()) { case DHCP: opts.put(BOOT_PROTOCOL, DHCP_BOOT_PROTOCOL); break; case STATIC_IP: putIfNotEmpty(opts, "ipaddr", iface.getAddress()); putIfNotEmpty(opts, "netmask", iface.getSubnet()); putIfNotEmpty(opts, "gateway", iface.getGateway()); break; } } }

Target:
private void addBootProtocol(Map<String, String> opts, VdsNetworkInterface iface) { switch (iface.getBootProtocol()) { case DHCP: opts.put(BOOT_PROTOCOL, DHCP_BOOT_PROTOCOL); break; case STATIC_IP: putIfNotEmpty(opts, "ipaddr", iface.getAddress()); putIfNotEmpty(opts, "netmask", iface.getSubnet()); putIfNotEmpty(opts, "gateway", iface.getGateway()); break; default: break; } }
Source:
public void validateSessions() { Byte[] fake = null; fake[0].toString(); }

Target:
public void validateSessions() throws RuntimeException { throw new RuntimeException("Session test exception"); }
Source:
public void testFilePollHdfsJob() { String data = UUID.randomUUID().toString(); String sourceFileName = UUID.randomUUID().toString(); SimpleFileSource fileSource = sources.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName + ".out").reference( true); job(jobs.filePollHdfsJob(DEFAULT_NAMES).toDSL()); waitForXD(); stream(fileSource + XD_TAP_DELIMETER + " queue:job:" + JOB_NAME); waitForXD(); stream("DataReceiver", sources.http() + XD_DELIMETER + sinks.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName).toDSL("REPLACE", "true"), WAIT_TIME); waitForXD(); sources.http().postData(data); assertValidHdfs(data, FilePollHdfsJob.DEFAULT_DIRECTORY + "/" + FilePollHdfsJob.DEFAULT_FILE_NAME + "-0.csv"); }

Target:
public void testFilePollHdfsJob() { String data = UUID.randomUUID().toString(); String sourceFileName = UUID.randomUUID().toString(); SimpleFileSource fileSource = sources.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName + ".out").reference( true); waitForXD(); job(jobs.filePollHdfsJob(DEFAULT_NAMES).toDSL()); waitForXD(); stream(fileSource + XD_TAP_DELIMETER + " queue:job:" + JOB_NAME); waitForXD(); stream("DataReceiver", sources.http() + XD_DELIMETER + sinks.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName), WAIT_TIME); waitForXD(); sources.http().postData(data); assertValidHdfs(data, FilePollHdfsJob.DEFAULT_DIRECTORY + "/" + FilePollHdfsJob.DEFAULT_FILE_NAME + "-0.csv"); }
Source:
public void create(final String name) throws IOException { if (name.length() < DyAttachments.MIN || name.length() > DyAttachments.MAX) { throw new Attachments.InvalidNameException( String.format( "invalid attachment name length \"%s\". %s%s", name, "The length of the attachment name must be ", "between 3-100 characters" ) ); } else if (!name.matches("[a-zA-Z\\.\\-0-9]{3,100}")) { throw new Attachments.InvalidNameException( String.format( "invalid attachment name \"%s\". %s%s", name, "Attachment name can contains letters in upper ", "or lower case, numbers, dots, dashes." ) ); } this.region.table(DyAttachments.TBL).put( new Attributes() .with(DyAttachments.HASH, this.bout) .with(DyAttachments.RANGE, name) .with(DyAttachments.ATTR_ALIAS, this.self) .with(DyAttachments.ATTR_CTYPE, "text/plain") .with(DyAttachments.ATTR_DATA, " ") .with(DyAttachments.ATTR_ETAG, "empty") ); Logger.info(this, "attachment %s created in #%d", name, this.bout); }

Target:
public void create(final String name) throws IOException { if (!name.matches("[a-zA-Z\\.\\-0-9]{3,100}")) { if (name.length() < DyAttachments.MIN || name.length() > DyAttachments.MAX) { throw new Attachments.InvalidNameException( String.format( "invalid attachment name length \"%s\". %s%s", name, "The length of the attachment name must be ", "between 3-100 characters" ) ); } throw new Attachments.InvalidNameException( String.format( "invalid attachment name \"%s\". %s%s", name, "Attachment name can contains letters in upper ", "or lower case, numbers, dots, dashes." ) ); } this.region.table(DyAttachments.TBL).put( new Attributes() .with(DyAttachments.HASH, this.bout) .with(DyAttachments.RANGE, name) .with(DyAttachments.ATTR_ALIAS, this.self) .with(DyAttachments.ATTR_CTYPE, "text/plain") .with(DyAttachments.ATTR_DATA, " ") .with(DyAttachments.ATTR_ETAG, "empty") ); Logger.info(this, "attachment %s created in #%d", name, this.bout); }
Source:
public void csarFilesHaveImmutableStorageAddresses() throws Exception { Map<String, Object> exportConfiguration = new HashMap<>(); exportConfiguration.put(STORE_IMMUTABLY.name(), new HashMap<>()); try (InputStream inputStream = this.createOutputAndInputStream( "origin/plain", new ServiceTemplateId("<LINK_0>", "ServiceTemplateWithAllReqCapVariants", false), exportConfiguration); ZipInputStream zis = new ZipInputStream(inputStream)) { ManifestContents manifestContents = parseManifest(zis); assertNotNull(manifestContents); for (String section : manifestContents.getSectionNames()) { assertNotNull(manifestContents.getAttributesForSection(section).get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS)); } } }

Target:
public void csarFilesHaveImmutableStorageAddresses() throws Exception { Map<String, Object> exportConfiguration = new HashMap<>(); exportConfiguration.put(STORE_IMMUTABLY.name(), null); try (InputStream inputStream = this.createOutputAndInputStream( "origin/plain", new ServiceTemplateId("<LINK_0>", "ServiceTemplateWithAllReqCapVariants", false), exportConfiguration); ZipInputStream zis = new ZipInputStream(inputStream)) { ManifestContents manifestContents = parseManifest(zis); assertNotNull(manifestContents); for (String section : manifestContents.getSectionNames()) { assertNotNull(manifestContents.getAttributesForSection(section).get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS)); } } }
Source:
private String getSshServerAddress(Machine machine) { Map<String, ? extends Server> servers = machine.getRuntime().getServers(); return servers.containsKey(SSH_PORT + "/tcp") ? servers.get(SSH_PORT + "/tcp").getAddress() : null; }

Target:
private String getSshServerAddress(Machine machine) { Map<String, ? extends Server> servers = machine.getRuntime().getServers(); final Server sshServer = servers.get(SSH_PORT + "/tcp"); return sshServer != null ? sshServer.getAddress() : null; }
Source:
net.sf.launch4j.config.ClassPath toL4j(Set<Artifact> dependencies, List<Artifact> runtimeDependencies) { net.sf.launch4j.config.ClassPath ret = new net.sf.launch4j.config.ClassPath(); ret.setMainClass(mainClass); List<String> cp = new ArrayList<String>(); if (preCp != null) addToCp(cp, preCp); if (addDependencies) { if (jarLocation == null) jarLocation = ""; else if ( ! jarLocation.endsWith("/")) jarLocation += "/"; dependencies.addAll(runtimeDependencies); for (Artifact dependency : dependencies) { Artifact dep = (Artifact) dependency; if (Artifact.SCOPE_COMPILE.equals(dep.getScope()) || Artifact.SCOPE_RUNTIME.equals(dep.getScope())) { String depFilename; depFilename = dep.getFile().getName(); cp.add(jarLocation + depFilename); } } } if (postCp != null) addToCp(cp, postCp); ret.setPaths(cp); return ret; }

Target:
net.sf.launch4j.config.ClassPath toL4j(Set<Artifact> dependencies, List<Artifact> runtimeDependencies) { net.sf.launch4j.config.ClassPath ret = new net.sf.launch4j.config.ClassPath(); ret.setMainClass(mainClass); List<String> cp = new ArrayList<String>(); if (preCp != null) addToCp(cp, preCp); if (addDependencies) { if (jarLocation == null) jarLocation = ""; else if ( ! jarLocation.endsWith("/")) jarLocation += "/"; dependencies.addAll(runtimeDependencies); for (Artifact dependency : dependencies) { if (Artifact.SCOPE_COMPILE.equals(dependency.getScope()) || Artifact.SCOPE_RUNTIME.equals(dependency.getScope())) { String depFilename; depFilename = dependency.getFile().getName(); cp.add(jarLocation + depFilename); } } } if (postCp != null) addToCp(cp, postCp); ret.setPaths(cp); return ret; }