auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<NameInformation> getInterfaceNames() { if (interfaceNames == null) { findAllNames(); Set<IVariable> externalReads = getVariablesReadOutside(); Set<IASTName> declarations = new HashSet<>(); interfaceNames = new ArrayList<>(); for (NameInformation nameInfo : names) { IASTName declarationName = nameInfo.getDeclarationName(); if (declarations.add(declarationName)) { if (isDeclaredInSelection(nameInfo)) { if (externalReads.contains(nameInfo.getName().resolveBinding())) { nameInfo.setMustBeReturnValue(true); interfaceNames.add(nameInfo); } } else { IASTDeclarator declarator = (IASTDeclarator) declarationName.getParent(); if (!hasReferenceOperator(declarator)) { for (NameInformation n2 : names) { if (n2.getDeclarationName() == declarationName) { Optional<Integer> flag = CPPVariableReadWriteFlags.getReadWriteFlags(n2.getName()); if (!flag.isPresent() || (flag.get() & PDOMName.WRITE_ACCESS) != 0) { nameInfo.setWriteAccess(true); break; } } } if (nameInfo.isWriteAccess() && externalReads.contains(nameInfo.getName().resolveBinding())) { nameInfo.setOutput(true); } } interfaceNames.add(nameInfo); } } } } return interfaceNames; }

Target:
private List<NameInformation> getInterfaceNames() { if (interfaceNames == null) { findAllNames(); Set<IVariable> externalReads = getVariablesReadOutside(); Set<IASTName> declarations = new HashSet<>(); interfaceNames = new ArrayList<>(); for (NameInformation nameInfo : names) { IASTName declarationName = nameInfo.getDeclarationName(); if (declarations.add(declarationName)) { if (isDeclaredInSelection(nameInfo)) { if (externalReads.contains(nameInfo.getName().resolveBinding())) { nameInfo.setMustBeReturnValue(true); interfaceNames.add(nameInfo); } } else { IASTDeclarator declarator = (IASTDeclarator) declarationName.getParent(); if (!hasReferenceOperator(declarator)) { for (NameInformation n2 : names) { if (n2.getDeclarationName() == declarationName) { Optional<Integer> flags = CPPVariableReadWriteFlags.getReadWriteFlags(n2.getName()); if (CPPVariableReadWriteFlags.mayBeWriteAccess(flags)) { nameInfo.setWriteAccess(true); break; } } } if (nameInfo.isWriteAccess() && externalReads.contains(nameInfo.getName().resolveBinding())) { nameInfo.setOutput(true); } } interfaceNames.add(nameInfo); } } } } return interfaceNames; }
Source:
public static void main(String[] args) { ZipkinTraceExporter.createAndRegister("http://localhost:9411/api/v2/spans", "tracing-to-zipkin-service"); TraceConfig traceConfig = Tracing.getTraceConfig(); TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); Tracer tracer = Tracing.getTracer(); Scope scope = tracer.spanBuilder("user-parent-span").startScopedSpan(); try { String queueURL = String.format("<LINK_0>", ACCOUNT_NAME, QUEUE_NAME, SAS_TOKEN); QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); queueAsyncClient.create() .doOnSuccess(response -> queueAsyncClient.enqueueMessage("This is message 1")) .then(queueAsyncClient.enqueueMessage("This is message 2")) .subscriberContext(Context.of(OPENCENSUS_SPAN_KEY, tracer.getCurrentSpan())) .subscribe( response -> System.out.printf("Message successfully enqueued by queueAsyncClient. Message id: %s%n", response.getMessageId()), err -> System.out.printf("Error thrown when enqueue the message. Error message: %s%n", err.getMessage()), () -> System.out.println("The enqueue has been completed.")); } finally { scope.close(); } Tracing.getExportComponent().shutdown(); }

Target:
public static void main(String[] args) throws InterruptedException { ZipkinTraceExporter.createAndRegister("http://localhost:9411/api/v2/spans", "tracing-to-zipkin-service"); TraceConfig traceConfig = Tracing.getTraceConfig(); TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); Tracer tracer = Tracing.getTracer(); Semaphore semaphore = new Semaphore(1); Scope scope = tracer.spanBuilder("user-parent-span").startScopedSpan(); semaphore.acquire(); String queueURL = String.format("<LINK_0>", ACCOUNT_NAME, QUEUE_NAME, "<GENERATED_SAS_TOKEN>"); QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); queueAsyncClient.create() .doOnSuccess(response -> queueAsyncClient.enqueueMessage("This is message 1")) .then(queueAsyncClient.enqueueMessage("This is message 2")) .subscriberContext(Context.of(OPENCENSUS_SPAN_KEY, tracer.getCurrentSpan())) .subscribe( response -> System.out.printf("Message successfully enqueued by queueAsyncClient. Message id: %s%n", response.getMessageId()), err -> { System.out.printf("Error thrown when enqueue the message. Error message: %s%n", err.getMessage()); scope.close(); semaphore.release(); }, () -> { scope.close(); semaphore.release(); System.out.println("The enqueue has been completed."); Tracing.getExportComponent().shutdown(); }); }
Source:
public static void main(String[] args) throws Exception { final String clientId = "user"; final String clientSecret = "password"; final String idpEndpoint = "http://idp-host:idp-port/auth/realms/master/protocol/openid-connect/token"; final String stsEndpoint = "http://sts-host:sts-port/sts"; final String idpClientId = "minio-client-id"; final CredentialsProvider credentialsProvider = new WebIdentityCredentialsProvider( stsEndpoint, () -> getTokenAndExpiry(clientId, clientSecret, idpClientId, idpEndpoint)); final MinioClient minioClient = MinioClient.builder() .endpoint("http://minio-host:minio-port") .credentialsProvider(credentialsProvider) .build(); final List<Bucket> buckets = minioClient.listBuckets(); for (Bucket bucket : buckets) { System.out.print(bucket.name() + " created at "); System.out.println(bucket.creationDate()); } }

Target:
public static void main(String[] args) throws Exception { final String clientId = "user"; final String clientSecret = "password"; final String idpEndpoint = "http://idp-host:idp-port/auth/realms/master/protocol/openid-connect/token"; final String stsEndpoint = "http://sts-host:sts-port/"; final String idpClientId = "minio-client-id"; final Provider credentialsProvider = new WebIdentityProvider( stsEndpoint, () -> getTokenAndExpiry(clientId, clientSecret, idpClientId, idpEndpoint)); final MinioClient minioClient = MinioClient.builder() .endpoint("http://minio-host:minio-port") .credentialsProvider(credentialsProvider) .build(); final List<Bucket> buckets = minioClient.listBuckets(); for (Bucket bucket : buckets) { System.out.print(bucket.name() + " created at "); System.out.println(bucket.creationDate()); } }
Source:
public DDF transformScaleStandard(List<String> columns, Boolean inPlace) throws DDFException { Summary[] summaryArr = this.getDDF().getSummary(); StringBuilder sqlCmdBuffer = new StringBuilder("SELECT "); for (int colIndex = 0; colIndex < this.getDDF().getSchema().getNumColumns(); colIndex++) { Column col = this.getDDF().getSchema().getColumn(colIndex); if (!isColumnEligibleToScale(col, columns)) { sqlCmdBuffer.append(col.getName()).append(","); } else { if (summaryArr[colIndex] == null) { LOG.warn("Missing column summary. transformScaleStandard ignored for column: " + col.getName()); sqlCmdBuffer.append(col.getName()).append(" "); } else if (summaryArr[colIndex].stdev() == 0) { LOG.warn("standard deviation equals zero. transformScaleStandard ignored for column: " + col.getName()); sqlCmdBuffer.append(col.getName()).append(" "); } else { sqlCmdBuffer.append(String .format("((%s - %s) / %s) as %s ", col.getName(), summaryArr[colIndex].mean(), summaryArr[colIndex].stdev(), col.getName())); } sqlCmdBuffer.append(","); } } sqlCmdBuffer.setLength(sqlCmdBuffer.length() - 1); sqlCmdBuffer.append(" FROM ").append(this.getDDF().getTableName()); DDF newddf = this.getManager().sql2ddf(sqlCmdBuffer.toString(), this.getEngine()); newddf.getMetaDataHandler().copyFactor(this.getDDF()); return inPlace ? this.getDDF().updateInplace(newddf) : newddf; }

Target:
public DDF transformScaleStandard(List<String> columns, Boolean inPlace) throws DDFException { Summary[] summaryArr = this.getDDF().getSummary(); Schema schema = this.getDDF().getSchema(); StringBuilder sqlCmdBuffer = new StringBuilder("SELECT "); for (int colIndex = 0; colIndex < schema.getNumColumns(); colIndex++) { Column col = schema.getColumn(colIndex); String escapedColName = StringEscapeUtils.escapeJava(col.getName()); if (!isColumnEligibleToScale(col, columns)) { sqlCmdBuffer.append(escapedColName).append(","); } else { if (summaryArr[colIndex] == null) { LOG.warn("Missing column summary. transformScaleStandard ignored for column: " + col.getName()); sqlCmdBuffer.append(escapedColName).append(" "); } else if (summaryArr[colIndex].stdev() == 0) { LOG.warn("standard deviation equals zero. transformScaleStandard ignored for column: " + col.getName()); sqlCmdBuffer.append(escapedColName).append(" "); } else { sqlCmdBuffer.append(String .format("((%s - %s) / %s) as %s ", escapedColName, summaryArr[colIndex].mean(), summaryArr[colIndex].stdev(), escapedColName)); } sqlCmdBuffer.append(","); } } sqlCmdBuffer.setLength(sqlCmdBuffer.length() - 1); sqlCmdBuffer.append(" FROM ").append(StringEscapeUtils.escapeJava(schema.getTableName())); DDF newddf = this.getManager().sql2ddf(sqlCmdBuffer.toString(), this.getEngine()); newddf.getMetaDataHandler().copyFactor(this.getDDF()); return inPlace ? this.getDDF().updateInplace(newddf) : newddf; }
Source:
void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> prms = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction(getRemoveActionType(), prms, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }

Target:
private void onRemove() { if (getWindow() != null) { return; } ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> prms = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), prms, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }
Source:
public Builder services(Object... services) { if (services == null) { this.services = new Object[0]; } else { this.services = services; } return this; }

Target:
public Builder services(Object... services) { checkNotNull(services); if (services != null) { this.services = services; } return this; }
Source:
public NodeScheduler(NetworkTopology networkTopology, InternalNodeManager nodeManager, NodeSchedulerConfig config, NodeTaskMap nodeTaskMap) { this(new NetworkLocationCache(networkTopology), networkTopology, nodeManager, config, nodeTaskMap, Duration.valueOf("5s")); }

Target:
public NodeScheduler(NetworkTopology networkTopology, InternalNodeManager nodeManager, NodeSchedulerConfig config, NodeTaskMap nodeTaskMap) { this(new NetworkLocationCache(networkTopology), networkTopology, nodeManager, config, nodeTaskMap, new Duration(5, SECONDS)); }
Source:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); if (vertex.getAverageCoverage() <= minAverageCoverage || vertex.getAverageCoverage() >= maxAverageCoverage) { broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); }

Target:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); if (vertex.getAverageCoverage() < minAverageCoverage || vertex.getAverageCoverage() > maxAverageCoverage) { broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); }
Source:
static DateTimeDataValue toInstant(DataValueDescriptor s) throws StandardException { if(s == null) { return null; } String hex = toHBaseEscaped(s.getString()); long value = Bytes.toLong(Bytes.toBytesBinary(hex)); long ts = System.currentTimeMillis() & (~TIMESTAMP_MASK); ts |= (value >> TIMESTAMP_SHIFT) & TIMESTAMP_MASK; return new SQLTimestamp(new Timestamp(ts)); }

Target:
static DateTimeDataValue toInstant(DataValueDescriptor s) throws StandardException { if(s == null) { return null; } long value; try { String hex = toHBaseEscaped(s.getString()); value = Bytes.toLong(Bytes.toBytesBinary(hex)); } catch(IllegalArgumentException e) { throw StandardException.newException(SQLState.LANG_INVALID_FUNCTION_ARGUMENT, s, "TO_INSTANT"); } long ts = System.currentTimeMillis() & (~TIMESTAMP_MASK); ts |= (value >> TIMESTAMP_SHIFT) & TIMESTAMP_MASK; return new SQLTimestamp(new Timestamp(ts)); }
Source:
public B setAccumuloUser(String user) { Preconditions.checkNotNull(user, "User cannot be null."); this.user = user; return confBuilder(); }

Target:
public B setAccumuloUser(String user) { this.user = user; return confBuilder(); }
Source:
public FetchGerritChangeWizard(Repository repository) { this(); Assert.isNotNull(repository); this.repository = repository; }

Target:
public FetchGerritChangeWizard(Repository repository) { this(); this.repository = repository; }
Source:
private void autosetEccFieldsForReleaseWithDownloadUrl(Release release, String contactPerson) { String url = release.getDownloadurl(); if (url != null && !url.isEmpty()) { if (CommonUtils.isValidUrl(url)) { autosetEccUpdaterInfo(release, contactPerson, ASSESSOR_DEFAULT_GROUP); EccInformation eccInfo = release.getEccInformation(); eccInfo.setAL("N"); eccInfo.setECCN("N"); eccInfo.setEccStatus(ECCStatus.APPROVED); } else { log.warn("Could not set ECC options for unmodified OSS because download url is not valid: " + url); } } }

Target:
private void autosetEccFieldsForReleaseWithDownloadUrl(Release release, String contactPerson) { String url = release.getDownloadurl(); if (!isNullOrEmpty(url)) { if (CommonUtils.isValidUrl(url)) { autosetEccUpdaterInfo(release, contactPerson, ASSESSOR_DEFAULT_GROUP); EccInformation eccInfo = release.getEccInformation(); eccInfo.setAL(ECC_AUTOSET_VALUE); eccInfo.setECCN(ECC_AUTOSET_VALUE); eccInfo.setEccStatus(ECCStatus.APPROVED); } else { log.warn("Could not set ECC options for unmodified OSS because download url is not valid: " + url); } } }
Source:
protected void deleteUnexportedConfigurationsAfterCompletion(MigrationReport report) { if (isValid) { Stream.concat( managedServicesToDelete.values().stream(), managedServiceFactoriesToDelete.values().stream().flatMap(List::stream)) .forEach(this::delete); } }

Target:
void deleteUnexportedConfigurationsAfterCompletion(MigrationReport report) { if (isValid) { Stream.concat( managedServicesToDelete.values().stream(), managedServiceFactoriesToDelete.values().stream().flatMap(List::stream)) .forEach(this::delete); } }
Source:
protected void doAttack(double distanceToEntity) { npc.removeAITask(TASK_MOVE); if (getAttackDelay() <= 0) { npc.swingArm(EnumHand.MAIN_HAND); npc.attackEntityAsMob(getTarget()); setAttackDelay(getCoolDown()); npc.addExperience(AWNPCStatics.npcXpFromAttack); if ((Math.random() < 0.2 && npc instanceof NpcFaction)) { ((NpcFaction) npc).playAttackSound(); } } }

Target:
protected void doAttack(double distanceToEntity) { npc.removeAITask(TASK_MOVE); if (getAttackDelay() <= 0) { npc.swingArm(EnumHand.MAIN_HAND); npc.attackEntityAsMob(getTarget()); setAttackDelay(getCoolDown()); npc.addExperience(AWNPCStatics.npcXpFromAttack); } }
Source:
private Optional<NodeDocument> getNodeInfoFromMetadataContext(ContextKey contextKey, String value) { OnmsNode onmsNode = null; if (contextKey != null && !Strings.isNullOrEmpty(value)) { final List<OnmsNode> nodes = nodeDao.findNodeWithMetaData(contextKey.getContext(), contextKey.getKey(), value); if (!nodes.isEmpty()) { onmsNode = nodes.get(0); } } if (onmsNode != null) { return mapOnmsNodeToNodeDocument(onmsNode); } return Optional.empty(); }

Target:
private Optional<NodeDocument> getNodeInfoFromMetadataContext(ContextKey contextKey, String value) { List<OnmsNode> nodes = new ArrayList<>(); try (Timer.Context ctx = nodeLoadTimer.time()) { nodes = nodeDao.findNodeWithMetaData(contextKey.getContext(), contextKey.getKey(), value); } if(nodes.isEmpty()) { return Optional.empty(); } return mapOnmsNodeToNodeDocument(nodes.get(0)); }
Source:
public void testIsComplexWrongExpression() { assertTrue(!isComplexTemplate("${t${a:${cb}_${c:d}}")); }

Target:
public void testIsComplexWrongExpression() { assertFalse(isComplexTemplate("${t${a:${cb}_${c:d}}")); }
Source:
public void failedDataProviderShouldCauseSkip() { InvokedMethodNameListener listener = run(DependentSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("method1(ok)", "method2"); assertThat(listener.getFailedMethodNames()).containsExactly("method1(not ok)"); }

Target:
public void failedDataProviderShouldCauseSkip() { InvokedMethodNameListener listener = run(DependentSample.class); assertThat(listener.getSucceedMethodNames()).containsExactly("method1(ok)"); assertThat(listener.getSkippedMethodNames()).containsExactly("method2"); assertThat(listener.getFailedMethodNames()).containsExactly("method1(not ok)"); }
Source:
public static String parseIdFromPath(String path) { if (!Strings.isNullOrEmpty(path)) return path.substring(path.indexOf(PROCESSOR_ID_PREFIX)); return null; }

Target:
public static String parseIdFromPath(String path) { if (!Strings.isNullOrEmpty(path)) return path.substring(path.lastIndexOf("/") + 1); return null; }
Source:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!isSupported) { return; } if (!Sse42Crc32C.isSupported()) { log.error("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); isSupported = false; } }

Target:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { log.warn("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); nonSupportedMessagePrinted = true; } }
Source:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { final RangeQueryBuilder filter = rangeQuery("_id").gte(startkey); final SearchResponse response = client.prepareSearch(indexKey) .setTypes(table) .setQuery(matchAllQuery()) .setSize(recordcount) .execute() .actionGet(); HashMap<String, ByteIterator> entry; for (SearchHit hit : response.getHits()) { entry = new HashMap<String, ByteIterator>(fields.size()); for (String field : fields) { entry.put(field, new StringByteIterator((String) hit.getSource().get(field))); } result.add(entry); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }

Target:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try { final RangeQueryBuilder rangeQuery = rangeQuery("_id").gte(startkey); final SearchResponse response = client.prepareSearch(indexKey) .setTypes(table) .setQuery(rangeQuery) .setSize(recordcount) .execute() .actionGet(); HashMap<String, ByteIterator> entry; for (SearchHit hit : response.getHits()) { entry = new HashMap<String, ByteIterator>(fields.size()); for (String field : fields) { entry.put(field, new StringByteIterator((String) hit.getSource().get(field))); } result.add(entry); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }
Source:
AccountInfoMap(AccountServiceMetrics accountServiceMetrics, Map<String, String> accountMap) throws JSONException { nameToAccountMap = new HashMap<>(); idToAccountMap = new HashMap<>(); for (Map.Entry<String, String> entry : accountMap.entrySet()) { String idKey = entry.getKey(); String valueString = entry.getValue(); Account account; JSONObject accountJson = new JSONObject(valueString); if (idKey == null) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey=null"); } account = Account.fromJson(accountJson); if (account.getId() != Short.valueOf(idKey)) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey and accountId do not match. idKey=" + idKey + " accountId=" + account.getId()); } if (idToAccountMap.containsKey(account.getId()) || nameToAccountMap.containsKey(account.getName())) { throw new IllegalStateException( "Duplicate account id or name exists. id=" + account.getId() + " name=" + account.getName()); } idToAccountMap.put(account.getId(), account); nameToAccountMap.put(account.getName(), account); } }

Target:
AccountInfoMap(AccountServiceMetrics accountServiceMetrics, Map<String, String> accountMap) throws JSONException { nameToAccountMap = new HashMap<>(); idToAccountMap = new HashMap<>(); for (Map.Entry<String, String> entry : accountMap.entrySet()) { String idKey = entry.getKey(); String valueString = entry.getValue(); Account account; JSONObject accountJson = new JSONObject(valueString); if (idKey == null) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey=null"); } account = Account.fromJson(accountJson); if (account.getId() != Short.parseShort(idKey)) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey and accountId do not match. idKey=" + idKey + " accountId=" + account.getId()); } if (idToAccountMap.containsKey(account.getId()) || nameToAccountMap.containsKey(account.getName())) { throw new IllegalStateException( "Duplicate account id or name exists. id=" + account.getId() + " name=" + account.getName()); } idToAccountMap.put(account.getId(), account); nameToAccountMap.put(account.getName(), account); } }
Source:
public void render(BaseViewHolder tag, DiscussionTopicDepth discussionTopic) { ViewHolder holder = (ViewHolder) tag; holder.discussionTopicNameTextView.setText(discussionTopic.getDiscussionTopic().getName()); holder.discussionTopicNameTextView.setPadding(childPadding * (1 + discussionTopic.getDepth()), childPadding, childPadding, childPadding); }

Target:
public void render(BaseViewHolder tag, DiscussionTopicDepth discussionTopic) { ViewHolder holder = (ViewHolder) tag; holder.discussionTopicNameTextView.setText(discussionTopic.getDiscussionTopic().getName()); ViewCompat.setPaddingRelative(holder.discussionTopicNameTextView, childPadding * (1 + discussionTopic.getDepth()), childPadding, childPadding, childPadding); }
Source:
public DTreeUserInteraction expandAll(IProgressMonitor monitor) { for (DTreeItem child : tree.getOwnedTreeItems()) { new DTreeItemUserInteraction(child, ctx).expandAll(monitor); } return this; }

Target:
public DTreeUserInteraction expandAll(IProgressMonitor monitor) { try { monitor.beginTask("Tree item expandion", tree.getOwnedTreeItems().size()); for (DTreeItem child : tree.getOwnedTreeItems()) { new DTreeItemUserInteraction(child, ctx).expandAll(new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); } return this; }
Source:
public void testCreatingProjectWithExistingName() { if (isMacOrWindowsOS()) { IProject project = createViewpointSpecificationProject(bot, VSM_PROJECT_NAME, VSM); assertTrue("The created VSM project should exist.", ResourcesPlugin.getWorkspace().getRoot().getProject(VSM_PROJECT_NAME).exists()); assertTrue("The created VSM project should be open.", ResourcesPlugin.getWorkspace().getRoot().getProject(VSM_PROJECT_NAME).isOpen()); createProjectWithExistingProjectName("A project with " + VSM_PROJECT_NAME + " name should exists in workspace and the Next button should not be enabled"); closeAllEditors(); try { project.delete(false, true, new NullProgressMonitor()); } catch (CoreException e) { fail("Cannot delete the VSM Project"); } SWTBotUtils.waitAllUiEvents(); createProjectWithExistingProjectName("A project with " + VSM_PROJECT_NAME + " name should exists on the disk and the Next button should not be enabled"); } }

Target:
public void testCreatingProjectWithExistingName() { if (isMacOrWindowsOS()) { IProject project = createViewpointSpecificationProject(bot, VSM_PROJECT_NAME, VSM); assertTrue("The created VSM project should exist.", ResourcesPlugin.getWorkspace().getRoot().getProject(VSM_PROJECT_NAME).exists()); assertTrue("The created VSM project should be open.", ResourcesPlugin.getWorkspace().getRoot().getProject(VSM_PROJECT_NAME).isOpen()); tryToCreateProjectWithExistingProjectName("A project with " + VSM_PROJECT_NAME + " name should exist in workspace and the Next button should not be enabled"); closeAllEditors(); try { project.delete(false, true, new NullProgressMonitor()); } catch (CoreException e) { fail("Cannot delete the VSM Project"); } SWTBotUtils.waitAllUiEvents(); tryToCreateProjectWithExistingProjectName("A project with " + VSM_PROJECT_NAME + " name should exist on the disk and the Next button should not be enabled"); } }
Source:
private static void setStatus(ITmfStateSystemBuilder ss, long status, int curThreadNode, @Nullable Long cpu, long timestamp, long type) { ITmfStateValue value; if (ss.queryOngoingState(curThreadNode).isNull()) { value = ProcessStatus.getStatusFromStatedump(status).getStateValue(); ss.modifyAttribute(timestamp, value.unboxValue(), curThreadNode); if (status == LinuxValues.STATEDUMP_PROCESS_STATUS_WAIT_CPU) { setRunQueue(ss, curThreadNode, cpu, timestamp); } } if (type != 0) { int sysallQuark = ss.getQuarkRelativeAndAdd(curThreadNode, Attributes.SYSTEM_CALL); ss.modifyAttribute(timestamp, "", sysallQuark); } }

Target:
private static void setStatus(ITmfStateSystemBuilder ss, long status, int curThreadNode, @Nullable Long cpu, long timestamp, long type) { ITmfStateValue value; if (ss.queryOngoingState(curThreadNode).isNull()) { value = ProcessStatus.getStatusFromStatedump(status).getStateValue(); ss.modifyAttribute(timestamp, value.unboxValue(), curThreadNode); if (status == LinuxValues.STATEDUMP_PROCESS_STATUS_WAIT_CPU) { setRunQueue(ss, curThreadNode, cpu, timestamp); } } if (type != 0) { int sysallQuark = ss.getQuarkRelativeAndAdd(curThreadNode, Attributes.SYSTEM_CALL); ss.updateOngoingState("", sysallQuark); } }
Source:
static void initKerberosENV(String principal, String keytab, boolean debugEnabled) { try { Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "kerberos"); if (debugEnabled) { System.setProperty("sun.security.krb5.debug", "true"); } UserGroupInformation.setConfiguration(conf); UserGroupInformation.loginUserFromKeytab(principal, keytab); log.info("Getting connection from kudu with kerberos"); log.info("Current user: " + UserGroupInformation.getCurrentUser()); log.info("Login user: " + UserGroupInformation.getLoginUser()); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
static void initKerberosENV(String principal, String keytab, boolean debugEnabled) { try { Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "kerberos"); if (debugEnabled) { System.setProperty("sun.security.krb5.debug", "true"); } UserGroupInformation.setConfiguration(conf); UserGroupInformation.loginUserFromKeytab(principal, keytab); log.info("Connecting to kudu with kerberos authentication"); log.info("Current user: " + UserGroupInformation.getCurrentUser()); log.info("Login user: " + UserGroupInformation.getLoginUser()); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public void defaultLoggersAtInfo() { final Logger logger = LoggerFactory.getLogger("com.azure.cosmos.internal.query.aggregation"); final Logger logger2 = LoggerFactory.getLogger("com.azure.cosmos"); Assert.assertTrue(logger.isInfoEnabled()); Assert.assertTrue(logger2.isInfoEnabled()); Assert.assertFalse(logger.isDebugEnabled()); Assert.assertFalse(logger2.isDebugEnabled()); }

Target:
public void defaultLoggersAtInfo() { final Logger logger = LoggerFactory.getLogger("com.azure.cosmos.internal.query.aggregation"); final Logger logger2 = LoggerFactory.getLogger("com.azure.cosmos"); assertThat(logger.isInfoEnabled()).isTrue(); assertThat(logger2.isInfoEnabled()).isTrue(); assertThat(logger.isDebugEnabled()).isFalse(); assertThat(logger2.isDebugEnabled()).isFalse(); }
Source:
private void trackUploadedStockMediaEvent(@NonNull List<MediaModel> mediaList) { if (mediaList.size() == 0) { AppLog.e(AppLog.T.MEDIA, "Cannot track uploaded stock media event if mediaList is empty"); return; } boolean isMultiselect = mediaList.size() > 1; for (MediaModel media : mediaList) { if (media.getUrl() != null) { Uri mediaUri = Uri.parse(media.getUrl()); Map<String, Object> properties = AnalyticsUtils.getMediaProperties(this, false, mediaUri, null); properties.put("is_part_of_multiselection", isMultiselect); if (isMultiselect) { properties.put("number_of_media_selected", mediaList.size()); } AnalyticsTracker.track(AnalyticsTracker.Stat.STOCK_MEDIA_UPLOADED, properties); } } }

Target:
private void trackUploadedStockMediaEvent(@NonNull List<MediaModel> mediaList) { if (mediaList.size() == 0) { AppLog.e(AppLog.T.MEDIA, "Cannot track uploaded stock media event if mediaList is empty"); return; } boolean isMultiselect = mediaList.size() > 1; Map<String, Object> properties = new HashMap<>(); properties.put("is_part_of_multiselection", isMultiselect); properties.put("number_of_media_selected", mediaList.size()); AnalyticsTracker.track(AnalyticsTracker.Stat.STOCK_MEDIA_UPLOADED, properties); }
Source:
private Element getAssertionElement() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new DOMUtils.NullResolver()); return db.parse(SecureCxfClientFactoryTest.class.getResourceAsStream("/samlAssertion.xml")) .getDocumentElement(); }

Target:
private Element getAssertionElement() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new DOMUtils.NullResolver()); return db.parse(SecureCxfClientFactoryTest.class.getResourceAsStream("/SAMLAssertion.xml")) .getDocumentElement(); }
Source:
public void testLaunchWithAppProperties() throws Exception { repository.save(new TaskDefinition("myTask2", "foo2 --common.prop2=wizz")); this.registry.register("task.foo2", new URI("file:src/test/resources/apps/foo-task")); mockMvc.perform(post("/tasks/executions").param("name", "myTask2") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .accept(MediaType.APPLICATION_JSON)) .andDo(print()).andExpect(status().isCreated()); ArgumentCaptor<AppDeploymentRequest> argumentCaptor = ArgumentCaptor.forClass(AppDeploymentRequest.class); verify(this.taskLauncher, atLeast(1)).launch(argumentCaptor.capture()); AppDeploymentRequest request = argumentCaptor.getValue(); assertThat(request.getDefinition().getProperties(), hasEntry("common.prop2", "wizz")); assertEquals("myTask2", request.getDefinition().getProperties().get("spring.cloud.task.name")); }

Target:
public void testLaunchWithAppProperties() throws Exception { repository.save(new TaskDefinition("myTask2", "foo2 --common.prop2=wizz")); this.registry.register("task.foo2", new URI("file:src/test/resources/apps/foo-task")); mockMvc.perform(post("/tasks/executions").param("name", "myTask2") .accept(MediaType.APPLICATION_JSON)) .andDo(print()).andExpect(status().isCreated()); ArgumentCaptor<AppDeploymentRequest> argumentCaptor = ArgumentCaptor.forClass(AppDeploymentRequest.class); verify(this.taskLauncher, atLeast(1)).launch(argumentCaptor.capture()); AppDeploymentRequest request = argumentCaptor.getValue(); assertThat(request.getDefinition().getProperties(), hasEntry("common.prop2", "wizz")); assertEquals("myTask2", request.getDefinition().getProperties().get("spring.cloud.task.name")); }
Source:
private void parse(String expression) throws IllegalArgumentException { if (expression == null) { throw new IllegalArgumentException("Cron expression cannot be null!"); } String[] fields = StringUtils.tokenizeToStringArray(expression, " "); if (!areValidCronFields(fields)) { throw new IllegalArgumentException(String.format( "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression)); } setNumberHits(this.seconds, fields[0], 0, 60); setNumberHits(this.minutes, fields[1], 0, 60); setNumberHits(this.hours, fields[2], 0, 24); setDaysOfMonth(this.daysOfMonth, fields[3]); setMonths(this.months, fields[4]); setDays(this.daysOfWeek, replaceOrdinals(fields[5], "SUN,MON,TUE,WED,THU,FRI,SAT"), 8); if (this.daysOfWeek.get(7)) { this.daysOfWeek.set(0); this.daysOfWeek.clear(7); } }

Target:
private void parse(String expression) throws IllegalArgumentException { Assert.notNull(expression, "Cron expression cannot be null!"); String[] fields = StringUtils.tokenizeToStringArray(expression, " "); if (!areValidCronFields(fields)) { throw new IllegalArgumentException(String.format( "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression)); } setNumberHits(this.seconds, fields[0], 0, 60); setNumberHits(this.minutes, fields[1], 0, 60); setNumberHits(this.hours, fields[2], 0, 24); setDaysOfMonth(this.daysOfMonth, fields[3]); setMonths(this.months, fields[4]); setDays(this.daysOfWeek, replaceOrdinals(fields[5], "SUN,MON,TUE,WED,THU,FRI,SAT"), 8); if (this.daysOfWeek.get(7)) { this.daysOfWeek.set(0); this.daysOfWeek.clear(7); } }
Source:
public String docs() { return "mixed {string, closure} Synchronizes the code in the closure for all calls with the same string argument." + " This means that if two threads will call " + getName() + "('example', @someClosure), the second call" + " will hang the thread until the code in the closure of the first call has finished executing." + " If you call this function from within a closure in this function, the closure will simply be executed." + " Returns the return value of the closure."; }

Target:
public String docs() { return "void {syncObject, code} Synchronizes access to the code block for all calls (from different" + " threads) with the same syncObject argument." + " This means that if two threads will call " + getName() + "('example', <code>), the second" + " call will hang the thread until the passed code of the first call has finished executing." + " If you call this function from within this function on the same thread using the same" + " syncObject, the code will simply be executed." + " For more information about synchronization, see:" + " <LINK_0>"; }
Source:
public Collection<SituationsMonitor> getSituationsMonitors(final Long serviceInstanceId) { Collection<SituationsMonitor> results = Lists.newArrayList(); for (final SituationsMonitor monitor : this.getSituationsMonitors()) { if (monitor.getServiceInstance() != null && monitor.getServiceInstance().getId().equals(serviceInstanceId)) { results.add(monitor); } } return results; }

Target:
public Collection<SituationsMonitor> getSituationsMonitors(final Long serviceInstanceId) { return this.getSituationsMonitors().stream().filter(monitor -> monitor.getServiceInstance() != null && monitor.getServiceInstance().getId().equals(serviceInstanceId)).collect(Collectors.toList()); }
Source:
public V get(final K key) { getObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); try { final Store.ValueHolder<V> valueHolder = store.get(key); if (valueHolder == null) { getObserver.end(org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome.MISS_NO_LOADER); return null; } else { getObserver.end(org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome.HIT_NO_LOADER); return valueHolder.value(); } } catch (StoreAccessException e) { try { return resilienceStrategy.getFailure(key, e); } finally { getObserver.end(org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome.FAILURE); } } }

Target:
public V get(final K key) { getObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); try { final Store.ValueHolder<V> valueHolder = store.get(key); if (valueHolder == null) { getObserver.end(GetOutcome.MISS_NO_LOADER); return null; } else { getObserver.end(GetOutcome.HIT_NO_LOADER); return valueHolder.value(); } } catch (StoreAccessException e) { try { return resilienceStrategy.getFailure(key, e); } finally { getObserver.end(GetOutcome.FAILURE); } } }
Source:
private RollingUpdateOp rollingUpdateDeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final Deployment deployment = Deployment.of(deploymentGroup.getJobId(), Goal.START, Deployment.EMTPY_DEPLOYER_USER, this.name, deploymentGroup.getName()); try { final String token = deploymentGroup.getRolloutOptions().getToken() == null ? Job.EMPTY_TOKEN : deploymentGroup.getRolloutOptions().getToken(); return opFactory.nextTask(getDeployOperations(client, host, deployment, token)); } catch (JobDoesNotExistException e) { return opFactory.error(e, host, RollingUpdateError.JOB_NOT_FOUND); } catch (TokenVerificationException e) { return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR); } catch (HostNotFoundException e) { return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND); } catch (JobPortAllocationConflictException e) { return opFactory.error(e, host, RollingUpdateError.PORT_CONFLICT); } catch (JobAlreadyDeployedException e) { return opFactory.nextTask(); } }

Target:
private RollingUpdateOp rollingUpdateDeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final Deployment deployment = Deployment.of(deploymentGroup.getJobId(), Goal.START, Deployment.EMTPY_DEPLOYER_USER, this.name, deploymentGroup.getName()); try { final String token = firstNonNull(deploymentGroup.getRolloutOptions().getToken(), Job.EMPTY_TOKEN); return opFactory.nextTask(getDeployOperations(client, host, deployment, token)); } catch (JobDoesNotExistException e) { return opFactory.error(e, host, RollingUpdateError.JOB_NOT_FOUND); } catch (TokenVerificationException e) { return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR); } catch (HostNotFoundException e) { return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND); } catch (JobPortAllocationConflictException e) { return opFactory.error(e, host, RollingUpdateError.PORT_CONFLICT); } catch (JobAlreadyDeployedException e) { return opFactory.nextTask(); } }
Source:
private double findSortWeight(int index) { int size = getOrders().size(); if (size == 1) return 10.0; if (index == 0) return getOrders().get(1).getSortWeight() / 2; if (index == size - 1) return getOrders().get(index - 1).getSortWeight() + 10.0; return (getOrders().get(index - 1).getSortWeight() + getOrders().get(index + 1).getSortWeight()) / 2; }

Target:
private double findSortWeight(int index) { int size = getOrders().size(); if (size == 1) { return 10.0; } if (index == 0) { return getOrders().get(1).getSortWeight() / 2; } if (index == size - 1) { return getOrders().get(index - 1).getSortWeight() + 10.0; } return (getOrders().get(index - 1).getSortWeight() + getOrders().get(index + 1).getSortWeight()) / 2; }
Source:
protected void setUp() throws Exception { super.setUp(); knownRepositories = KnownRepositories.getInstance(); savedRepositories = knownRepositories.getRepositories(); for (ICVSRepositoryLocation savedRepositorie : savedRepositories) { knownRepositories.disposeRepository(savedRepositorie); } }

Target:
protected void setUp() throws Exception { super.setUp(); knownRepositories = KnownRepositories.getInstance(); savedRepositories = knownRepositories.getRepositories(); for (ICVSRepositoryLocation savedRepository : savedRepositories) { knownRepositories.disposeRepository(savedRepository); } }
Source:
public void notifySuperUsers(String messageCode, Exception cause, Object... messageArguments) { String message = Context.getMessageSourceService().getMessage(messageCode, messageArguments, Context.getLocale()); if (cause != null) { StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement traceElement : cause.getStackTrace()) { stackTrace.append(traceElement); stackTrace.append("\n"); if (stackTrace.length() >= Alert.TEXT_MAX_LENGTH) { break; } } message = message + ":" + stackTrace; message = message.substring(0, Math.min(message.length(), Alert.TEXT_MAX_LENGTH)); } Alert alert = new Alert(message, Context.getUserService().getUsersByRole(new Role(RoleConstants.SUPERUSER))); alert.setSatisfiedByAny(true); if (alert.getCreator() == null) { try{ JdbcConnection connection = (JdbcConnection) DatabaseUpdater.getConnection(); Integer userId = getInt(connection, "SELECT min(user_id) FROM users"); if (userId >= 1) { alert.setCreator(new User(userId)); } } catch(Exception e){ } } Context.getAlertService().saveAlert(alert); }

Target:
public void notifySuperUsers(String messageCode, Exception cause, Object... messageArguments) { String message = Context.getMessageSourceService().getMessage(messageCode, messageArguments, Context.getLocale()); if (cause != null) { StringBuilder stackTrace = new StringBuilder(); for (StackTraceElement traceElement : cause.getStackTrace()) { stackTrace.append(traceElement); stackTrace.append("\n"); if (stackTrace.length() >= Alert.TEXT_MAX_LENGTH) { break; } } message = message + ":" + stackTrace; message = message.substring(0, Math.min(message.length(), Alert.TEXT_MAX_LENGTH)); } Alert alert = new Alert(message, Context.getUserService().getUsersByRole(new Role(RoleConstants.SUPERUSER))); alert.setSatisfiedByAny(true); if (alert.getCreator() == null) { try { JdbcConnection connection = (JdbcConnection) DatabaseUpdater.getConnection(); Integer userId = getInt(connection, "SELECT min(user_id) FROM users"); if (userId >= 1) { alert.setCreator(new User(userId)); } } } Context.getAlertService().saveAlert(alert); }
Source:
public List<String> getColumnsCopy() { return new ArrayList<String>(m_columns); }

Target:
public List<String> getColumnsCopy() { List<String> list = new ArrayList<String>(); for (String string : m_columns) { if (StringConstants.UNICODE_NULL.equals(string)) { list.add(null); } else { list.add(string); } } return list; }
Source:
protected void onDestroy() { super.onDestroy(); if (mapboxMap != null) { mapboxMap.removeOnMapClickListener(this); } mapView.onDestroy(); }

Target:
protected void onDestroy() { super.onDestroy(); if (mapboxMap != null) { mapboxMap.removeOnMapClickListener(this); } if (markerAnimator != null) { markerAnimator.cancel(); } mapView.onDestroy(); }
Source:
public MultipleColumnPrefixFilter(final byte [][] prefixes) { if (prefixes != null) { for (int i = 0; i < prefixes.length; i++) { if (!sortedPrefixes.add(prefixes[i])) { LOG.error("prefix is repeated", Bytes.toString(prefixes[i])); throw new IllegalArgumentException("prefixes must be distinct"); } } } }

Target:
public MultipleColumnPrefixFilter(final byte [][] prefixes) { if (prefixes != null) { for (byte[] prefix : prefixes) { if (!sortedPrefixes.add(prefix)) { LOG.error("prefix is repeated", Bytes.toString(prefix)); throw new IllegalArgumentException("prefixes must be distinct"); } } } }
Source:
public static String configureDemoCertWithDN(String[] dn, @Nullable String[] subjectAltNames) { CertificateSigningRequest csr = new CertificateSigningRequest(); csr.setDistinguishedName(dn); if (subjectAltNames != null) { csr.addSubjectAlternativeNames(subjectAltNames); } String commonName = Arrays.stream(dn) .filter(str -> str.startsWith("cn=")) .findFirst() .orElseThrow(() -> new IllegalArgumentException("CN is a required attribute on the DN")) .split("=")[1]; csr.addSubjectAlternativeNames(String.format("DNS:%s", commonName)); RDN[] rdns = csr.getSubjectName().getRDNs(BCStyle.CN); Validate.isTrue( rdns != null && rdns.length == 1, "CN attribute must be included in distinguished name"); return configureCert(rdns[0].getFirst().getValue().toString(), csr); }

Target:
public static String configureDemoCertWithDN(String[] dn, @Nullable String[] subjectAltNames) { CertificateSigningRequest csr = new CertificateSigningRequest(); csr.setDistinguishedName(dn); String commonName = csr.getSubjectName().getRDNs(BCStyle.CN)[0].getFirst().getValue().toString(); csr.addSubjectAlternativeNames(String.format("DNS:%s", commonName)); if (subjectAltNames != null) { csr.addSubjectAlternativeNames(subjectAltNames); } RDN[] rdns = csr.getSubjectName().getRDNs(BCStyle.CN); Validate.notNull(rdns, "RDN Array cannot be null"); Validate.isTrue(rdns.length == 1, "CN attribute must be included in distinguished name"); return configureCert(rdns[0].getFirst().getValue().toString(), csr); }
Source:
private String outputAttachments(Resource assignmentResource, Set<String> attachments, String prefix) throws PermissionException, IdUnusedException, TypeException, ServerOverloadException { StringBuilder sb = new StringBuilder("<ul>"); for (String sakaiId: attachments) { if (sakaiId.startsWith("/content/")) { sakaiId = sakaiId.substring("/content".length()); } String URL = null; if (!sakaiId.startsWith(" ContentResource res = exportUtil.getContentResource(sakaiId); if (exportUtil.isLink(res)) { URL = new String(res.getContent()); } } String location = attachmentMap.get(sakaiId).getLocation(); int lastSlash = sakaiId.lastIndexOf("/"); String lastAtom = sakaiId.substring(lastSlash + 1); if (URL != null) { sb.append("<li><a href=\"" + URL + "\">" + StringEscapeUtils.escapeHtml(URL) + "</a></li>"); } else { URL = prefix + Validator.escapeUrl(location); URL = URL.replaceAll(" sb.append("<li><a href=\"" + URL + "\">" + StringEscapeUtils.escapeHtml(lastAtom) + "</a></li><br/>"); } sb.append("</ul>"); } return sb.toString(); }

Target:
private String outputAttachments(Resource assignmentResource, Set<String> attachments, String prefix) throws PermissionException, IdUnusedException, TypeException, ServerOverloadException { StringBuilder sb = new StringBuilder("<ul>"); for (String sakaiId: attachments) { if (sakaiId.startsWith("/content/")) { sakaiId = sakaiId.substring("/content".length()); } String url = null; if (!sakaiId.startsWith(" ContentResource res = exportUtil.getContentResource(sakaiId); if (exportUtil.isLink(res)) { url = new String(res.getContent()); } } String location = attachmentMap.get(sakaiId).getLocation(); int lastSlash = sakaiId.lastIndexOf("/"); String lastAtom = sakaiId.substring(lastSlash + 1); if (url != null) { sb.append("<li><a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(url) + "</a></li>"); } else { url = prefix + Validator.escapeUrl(location); url = url.replaceAll(" sb.append("<li><a href=\"" + url + "\">" + StringEscapeUtils.escapeHtml(lastAtom) + "</a></li><br/>"); } sb.append("</ul>"); } return sb.toString(); }