auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void writeHeader(VCFHeader header) { if (isHeaderWritten) { throw new IllegalStateException("Header is already written"); } setVcfHeader(header); try { final ByteArrayOutputStream capture = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(capture); this.header = VCFWriter.writeHeader(header, writer, VCFWriter.getVersionLine(), "BCF2 stream"); writer.append('\0'); writer.close(); final byte[] headerBytes = capture.toByteArray(); new BCFVersion(MAJOR_VERSION, MINOR_VERSION).write(outputStream); BCF2Type.INT32.write(headerBytes.length, outputStream); outputStream.write(headerBytes); isHeaderWritten = true; } catch (IOException e) { throw new RuntimeIOException("BCF2 stream: Got IOException while trying to write BCF2 header", e); } }

Target:
public void writeHeader(VCFHeader header) { setVCFHeader(header); try { final ByteArrayOutputStream capture = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(capture); this.header = VCFWriter.writeHeader(this.header, writer, VCFWriter.getVersionLine(), "BCF2 stream"); writer.append('\0'); writer.close(); final byte[] headerBytes = capture.toByteArray(); new BCFVersion(MAJOR_VERSION, MINOR_VERSION).write(outputStream); BCF2Type.INT32.write(headerBytes.length, outputStream); outputStream.write(headerBytes); outputHasBeenWritten = true; } catch (IOException e) { throw new RuntimeIOException("BCF2 stream: Got IOException while trying to write BCF2 header", e); } }
Source:
public String getFullNameOfWorkspacesListItem(int index) { String itemXpath = String.format(Locators.WORKSPACE_LIST_ITEM, index); String fullNameXpath = itemXpath + " return seleniumWebDriverHelper .waitVisibility(By.xpath(fullNameXpath)) .getAttribute("id") .replace("ws-full-name-", ""); }

Target:
public String getFullNameOfWorkspacesListItem(int index) { String itemXpath = String.format(Locators.WORKSPACE_LIST_ITEM, index); String fullNameXpath = itemXpath + " return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(By.xpath(fullNameXpath), "id") .replace("ws-full-name-", ""); }
Source:
public void setAlignment(String value) { if (privateAlignment == null || !privateAlignment.equals(value)) { privateAlignment = value; onPropertyChanged(new PropertyChangedEventArgs("Alignment")); } }

Target:
public void setAlignment(String value) { if (!StringHelper.stringsEqual(privateAlignment, value)) { privateAlignment = value; onPropertyChanged(new PropertyChangedEventArgs("Alignment")); } }
Source:
protected int doWork() { final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, OUTPUT); writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); OverlapDetector overlapDetector = getOverlapDetectorFromIntervalListFile(INTERVAL_LIST, 0, 0); for (SAMRecord rec : reader) { if (!rec.getReadUnmappedFlag() && (overlapDetector == null || overlapDetector.overlapsAny(rec))) { setOATag(rec, OVERWRITE_TAG); } writer.addAlignment(rec); } CloserUtil.close(reader); writer.close(); return 0; }

Target:
protected int doWork() { try (final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(IOUtil.getPath(INPUT)); final SAMFileWriter writer = new SAMFileWriterFactory().makeWriter(reader.getFileHeader(), true, IOUtil.getPath(OUTPUT), REFERENCE_SEQUENCE)) { writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); final OverlapDetector overlapDetector = getOverlapDetectorFromIntervalListFile(INTERVAL_LIST, 0, 0); for (final SAMRecord rec : reader) { if (overlapDetector == null || overlapDetector.overlapsAny(rec)) { setOATag(rec); } writer.addAlignment(rec); } } catch (IOException e) { log.error(e); return 1; } return 0; }
Source:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { if (afterLRACounter.getAndIncrement() < 2) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }

Target:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { if (afterLRACounter.getAndIncrement() < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }
Source:
private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { throw new IOException("Could not transfer all bytes of " + from.toPath()); } } }

Target:
private static void copyFile(File from, File to, Filter onlyCopy) throws IOException { if (!onlyCopy.isRequired(from)) { return; } try (OutputStream out = new FileOutputStream(to)) { final long copied = Files.copy(from.toPath(), out); final long length = from.length(); if (copied != length) { throw new IOException("Could not transfer all bytes from " + from + " to " + to); } } }
Source:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { retriever = cache.getComponentRegistry().getComponent(EntryRetriever.class); this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }

Target:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { this.cache = cache; this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }
Source:
public static void getObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName) zero size object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(0)) { client.putObject(bucketName, objectName, is, 0, nullContentType); } try { client.getObject(bucketName, objectName).close(); } catch (final ErrorResponseException e) { if (!e.toString().contains("message=The requested range is not satisfiable")) { throw e; } } client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }

Target:
public static void getObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName) zero size object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(0)) { client.putObject(bucketName, objectName, is, 0, nullContentType); } client.getObject(bucketName, objectName) .close(); client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } }
Source:
public Long findPublishedEntries(String username) { final Query query = namedQuery("io.dockstore.webservice.core.User.countPublishedEntries").setParameter("username", username); return (Long)query.uniqueResult(); }

Target:
public long findPublishedEntries(String username) { final Query query = namedQuery("io.dockstore.webservice.core.User.countPublishedEntries").setParameter("username", username); return (long)query.uniqueResult(); }
Source:
public byte[] contentMD5() { return contentMD5; }

Target:
public byte[] contentMD5() { return ImplUtils.clone(contentMD5); }
Source:
public void testEqualsAndHashCode(final CigarElement element, final Object other, final boolean isEquals) { Assert.assertEquals(element.equals(other), isEquals); Assert.assertEquals(element.hashCode() == other.hashCode(), isEquals); }

Target:
public void testEqualsAndHashCode(final CigarElement element, final Object other, final boolean isEquals) { Assert.assertEquals(element.equals(other), isEquals); if (isEquals) { Assert.assertEquals(element.hashCode(), other.hashCode()); } }
Source:
protected Collection<Artifact> setRelationsOfType(AtsArtifactConfigCache cache, Artifact artifact, Collection<? extends IAtsObject> atsObjects, IRelationTypeSide side) throws OseeCoreException { List<Artifact> newArts = new ArrayList<Artifact>(); for (IAtsObject version : atsObjects) { Artifact verArt = cache.getSoleArtifact(version); newArts.add(verArt); } artifact.setRelations(side, newArts); return newArts; }

Target:
protected Collection<Artifact> setRelationsOfType(AtsArtifactConfigCache cache, Artifact artifact, Collection<? extends IAtsObject> atsObjects, IRelationTypeSide side) throws OseeCoreException { Conditions.checkNotNull(artifact, "artifact"); List<Artifact> newArts = new ArrayList<Artifact>(); for (IAtsObject version : atsObjects) { Artifact verArt = cache.getSoleArtifact(version); newArts.add(verArt); } artifact.setRelations(side, newArts); return newArts; }
Source:
public void queueEvent(Event event) { if (log.isDebugEnabled()) { log.debug("Queuing event: " + event); } getEventQueue().add(event); }

Target:
public void queueEvent(Event event) { log.debug("Queuing event: " + event); getEventQueue().add(event); }
Source:
public void setPageBufferClientMaxCallbackThreads(int pageBufferClientMaxCallbackThreads) { this.pageBufferClientMaxCallbackThreads = pageBufferClientMaxCallbackThreads; }

Target:
public ExchangeClientConfig setPageBufferClientMaxCallbackThreads(int pageBufferClientMaxCallbackThreads) { this.pageBufferClientMaxCallbackThreads = pageBufferClientMaxCallbackThreads; return this; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fieldName = getArguments().getString(NAME); listener.setActionBarTitle(fieldName); } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { fieldName = getArguments().getString(NAME); changeListener.setActionBarTitle(fieldName); } }
Source:
void setTopics(ArrayList<String> topics) { this.topics = topics; }

Target:
public void setTopics(ArrayList<String> topics) { this.topics = topics; }
Source:
private VM mockVm(VMStatus vmStatus) { vm.setStatus(vmStatus); vm.setId(vmId); vm.setRunOnVds(Guid.newGuid()); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); return vm; }

Target:
private void mockVm(VMStatus vmStatus) { vm.setStatus(vmStatus); vm.setId(vmId); vm.setRunOnVds(Guid.newGuid()); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); }
Source:
protected boolean canDoAction() { if (!(!Guid.Empty.equals(getVds().getstorage_pool_id()) && DbFacade.getInstance().getVdsSpmIdMapDao().get(getVdsId()) == null)) { return false; } vds_spm_id_mapList = DbFacade.getInstance().getVdsSpmIdMapDao().getAll( getVds().getstorage_pool_id()); if (vds_spm_id_mapList.size() >= Config.<Integer> GetValue(ConfigValues.MaxNumberOfHostsInStoragePool)) { VdcFault fault = new VdcFault(); fault.setMessage("The maximum number of Hosts allowed in the Data Center has been reached"); getReturnValue().setFault(fault); return false; } return true; }

Target:
protected boolean canDoAction() { if (Guid.Empty.equals(getVds().getstorage_pool_id()) || DbFacade.getInstance().getVdsSpmIdMapDao().get(getVdsId()) != null) { return false; } vds_spm_id_mapList = DbFacade.getInstance().getVdsSpmIdMapDao().getAll( getVds().getstorage_pool_id()); if (vds_spm_id_mapList.size() >= Config.<Integer> GetValue(ConfigValues.MaxNumberOfHostsInStoragePool)) { VdcFault fault = new VdcFault(); fault.setError(VdcBllErrors.ReachedMaxNumberOfHostsInDC); fault.setMessage(Backend.getInstance() .getVdsErrorsTranslator() .TranslateErrorTextSingle(fault.getError().toString())); getReturnValue().setFault(fault); return false; } return true; }
Source:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs, final Span publishingSpan) { if (!isPublishingRequest(requestLogInfo)) { return; } final Scope scope = TracingService.activateSpan(publishingSpan, false); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength > 50000 || requestLogInfo.contentLength == 0) { sloBucket = ">50K"; } else if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); TracingService.setCustomTags(scope, ImmutableMap.<String, Object>builder() .put("event_type", eventType) .put("http.status_code", statusCode) .put("slo_bucket", sloBucket) .put("content_length", requestLogInfo.contentLength) .put("error", statusCode == 207 || statusCode >= 500).build()); }

Target:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs, final Span publishingSpan) { if (!isPublishingRequest(requestLogInfo)) { return; } final Scope scope = TracingService.activateSpan(publishingSpan, false); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength > 50000 || requestLogInfo.contentLength == 0) { sloBucket = ">50K"; } else if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); TracingService.setCustomTags(scope, ImmutableMap.<String, Object>builder() .put("event_type", eventType) .put("http.status_code", statusCode) .put("slo_bucket", sloBucket) .put("content_length", requestLogInfo.contentLength).build()); }
Source:
private void checkFieldType(int field, Set<Type> expectedTypes) { checkArgument(expectedTypes.contains(getType(field)), "Field %s expected type inconsistent with %s", field, getType(field)); }

Target:
private void checkFieldType(int field, Set<Type> expectedTypes) { checkArgument(expectedTypes.contains(getType(field)), "Field %s has unexpected type %s", field, getType(field)); }
Source:
public <T> T makeRequest(Invocation<T> invocation, boolean countForTx) throws OperationLogic.RequestException { if (recording()) { requests = stats.requestSet(); } if (useTransactions && txRemainingOperations <= 0) { try { ongoingTx = stage.transactional.getTransaction(); logic.transactionStarted(); Request beginRequest = startTransaction(); if (requests != null && beginRequest != null) { requests.add(beginRequest); } txRemainingOperations = stage.transactionSize; } catch (TransactionException e) { throw new OperationLogic.RequestException(e); } } T result = null; Exception exception = null; Request request = nextRequest(); Operation operation = isUseTransactions() ? invocation.txOperation() : invocation.operation(); try { result = invocation.invoke(); succeeded(request, operation); Blackhole.consume(result); if (countForTx) { txRemainingOperations--; } } catch (Exception e) { failed(request, operation); log.warn("Error in request", e); txRemainingOperations = 0; exception = e; } endTransactionAndRegisterStats(useTransactions && txRemainingOperations <= 0, request); if (exception != null) { throw new OperationLogic.RequestException(exception); } return result; }

Target:
public <T> T makeRequest(Invocation<T> invocation, boolean countForTx) throws OperationLogic.RequestException { if (useTransactions && txRemainingOperations <= 0) { try { ongoingTx = stage.transactional.getTransaction(); logic.transactionStarted(); if (recording()) { requests = stats.requestSet(); } Request beginRequest = startTransaction(); if (requests != null && beginRequest != null) { requests.add(beginRequest); } txRemainingOperations = stage.transactionSize; } catch (TransactionException e) { throw new OperationLogic.RequestException(e); } } T result = null; Exception exception = null; Request request = nextRequest(); try { result = invocation.invoke(); succeeded(request, invocation.operation()); Blackhole.consume(result); if (countForTx) { txRemainingOperations--; } } catch (Exception e) { failed(request, invocation.operation()); log.warn("Error in request", e); txRemainingOperations = 0; exception = e; } if (requests != null && request != null && recording()) { requests.add(request); } if (useTransactions && txRemainingOperations <= 0) { endTransactionAndRegisterStats(stage.isSingleTxType() ? invocation.txOperation() : null); } if (exception != null) { throw new OperationLogic.RequestException(exception); } return result; }
Source:
public String openDialog(String title) { if (this.m_parent == null) { this.m_parent = new Frame(); } if (this.m_fileDialog == null) { this.m_fileDialog = new FileDialog(this.m_parent, title, 0); } this.m_fileDialog.setVisible(true); this.m_fileDialog.toFront(); String file = this.m_fileDialog.getFile(); String directory = this.m_fileDialog.getDirectory(); this.m_fileDialog.setVisible(false); this.m_parent.setVisible(false); if ((file == null) || (file.length() == 0)) { return "{success:false,path:\"\"}"; } else { String path = directory + file; path = path.replace("\\", "\\\\"); return "{\"success\":\"true\",\"path\":\"" + path + "\"}"; } }

Target:
public String openDialog(String title) { if (this.m_parent == null) { this.m_parent = new Frame(); } if (this.m_fileDialog == null) { this.m_fileDialog = new FileDialog(this.m_parent, title, 0); } this.m_fileDialog.setVisible(true); this.m_fileDialog.toFront(); String file = this.m_fileDialog.getFile(); String directory = this.m_fileDialog.getDirectory(); this.m_fileDialog.setVisible(false); this.m_parent.setVisible(false); if ((file == null) || (file.length() == 0)) { return "{\"success\":\"false\",\"path\":\"\"}"; } else { String path = directory + file; path = path.replace("\\", "\\\\"); return "{\"success\":\"true\",\"path\":\"" + path + "\"}"; } }
Source:
public DataBucket(String commandId, long count, byte[] data) { this(commandId, count, data, new byte[]{}, new byte[]{}); }

Target:
public DataBucket(String commandId, long count, byte[] data) { this(commandId, count, data, new byte[0], new byte[0]); }
Source:
private PreparedStatement prepareStatementFromFieldsAndTableName() { StringBuilder queryfields = new StringBuilder(); StringBuilder values = new StringBuilder(); for (FieldInfo fieldInfo : fieldInfos) { if (queryfields.length() == 0) { queryfields.append(fieldInfo.getColumnName()); values.append("?"); } else { queryfields.append(",").append(fieldInfo.getColumnName()); values.append(",").append("?"); } } String statement = "INSERT INTO " + store.keyspace + "." + tablename + " (" + queryfields.toString() + ") " + "VALUES (" + values.toString() + ");"; return store.getSession().prepare(statement); }

Target:
private PreparedStatement prepareStatementFromFieldsAndTableName() { if (tablename == null || tablename.length() == 0) { throw new RuntimeException("Please sepcify query or table name."); } StringBuilder queryfields = new StringBuilder(); StringBuilder values = new StringBuilder(); for (FieldInfo fieldInfo : fieldInfos) { if (queryfields.length() == 0) { queryfields.append(fieldInfo.getColumnName()); values.append("?"); } else { queryfields.append(",").append(fieldInfo.getColumnName()); values.append(",").append("?"); } } String statement = "INSERT INTO " + store.keyspace + "." + tablename + " (" + queryfields.toString() + ") " + "VALUES (" + values.toString() + ");"; return store.getSession().prepare(statement); }
Source:
public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { Log.v(TAG, "Requesting Unity Ads Banner"); bannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); bannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, bannerPlacementId)) { if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (context == null || !(context instanceof Activity)) { Log.e(TAG, "Context is not an Activity. Unity Ads requires an Activity context to load " + "ads."); if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } Activity activity = (Activity) context; UnitySingleton.getInstance().initializeUnityAds(activity, gameId); UnityBannerSize size = new UnityBannerSize(adSize.getWidth(), adSize.getHeight()); if (mBannerView == null){ mBannerView = new BannerView((Activity)context, bannerPlacementId, size); } mBannerView.setListener(this); mBannerView.load(); }

Target:
public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { Log.v(TAG, "Requesting Unity Ads Banner"); bannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); bannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, bannerPlacementId)) { if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (context == null || !(context instanceof Activity)) { Log.e(TAG, "Context is not an Activity. Unity Ads requires an Activity context to load " + "ads."); if (bannerListener != null) { bannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } Activity activity = (Activity) context; UnitySingleton.getInstance().initializeUnityAds(activity, gameId); float density = context.getResources().getDisplayMetrics().density; int bannerWidth = Math.round(adSize.getWidthInPixels(context) / density); int bannerHeight = Math.round(adSize.getHeightInPixels(context) / density); UnityBannerSize size = new UnityBannerSize(bannerWidth, bannerHeight); if (mBannerView == null){ mBannerView = new BannerView((Activity)context, bannerPlacementId, size); } mBannerView.setListener(this); mBannerView.load(); }
Source:
static void deleteFolder(File fileOrDirectory) throws IOException { if (fileOrDirectory.getCanonicalFile().equals(fileOrDirectory.getAbsoluteFile())) { File[] children = fileOrDirectory.listFiles(); if (children != null) { for (File child : children) { if (child.getCanonicalFile().equals(child.getAbsoluteFile())) { deleteFolder(child); } else { child.delete(); } } } } if (!fileOrDirectory.delete()) { throw new RuntimeException("Unable to delete " + (fileOrDirectory.isDirectory() ? "directory " : "file ") + fileOrDirectory.getAbsolutePath()); } }

Target:
static void deleteFolder(File fileOrDirectory) throws IOException { if (fileOrDirectory.getCanonicalPath().equals(fileOrDirectory.getAbsolutePath()) && fileOrDirectory.isDirectory()) { File[] children = fileOrDirectory.listFiles(); if (children != null) { for (File child : children) { deleteFolder(child); } } } if (!fileOrDirectory.delete()) { throw new RuntimeException("Unable to delete " + (fileOrDirectory.isDirectory() ? "directory " : "file ") + fileOrDirectory.getAbsolutePath()); } }
Source:
void changeIndexSegments(List<File> segmentFilesToAdd, Set<Offset> segmentsToRemove) throws StoreException { TreeMap<Offset, IndexSegment> segmentsToAdd = new TreeMap<>(); Offset journalFirstOffset = journal.getFirstOffset(); for (File indexSegmentFile : segmentFilesToAdd) { IndexSegment indexSegment = new IndexSegment(indexSegmentFile, true, factory, config, metrics, journal); if (indexSegment.getEndOffset().compareTo(journalFirstOffset) > 0) { throw new IllegalArgumentException("One of the index segments has an end offset " + indexSegment.getEndOffset() + " that is higher than the first offset in the journal " + journalFirstOffset); } segmentsToAdd.put(indexSegment.getStartOffset(), indexSegment); } indexesChangeLock.lock(); try { ConcurrentSkipListMap<Offset, IndexSegment> oldIndexSegments = indexesRef.get(); ConcurrentSkipListMap<Offset, IndexSegment> newIndexSegments = new ConcurrentSkipListMap<>(); for (Map.Entry<Offset, IndexSegment> entry : oldIndexSegments.entrySet()) { if (!segmentsToRemove.contains(entry.getKey())) { newIndexSegments.put(entry.getKey(), entry.getValue()); } else if (entry.getKey().compareTo(journal.getFirstOffset()) >= 0) { throw new IllegalArgumentException("Offset of the one of the segments to remove [" + entry.getKey() + "] is" + " higher than the first offset in the journal"); } } newIndexSegments.putAll(segmentsToAdd); indexesRef.set(newIndexSegments); } finally { indexesChangeLock.unlock(); } }

Target:
void changeIndexSegments(List<File> segmentFilesToAdd, Set<Offset> segmentsToRemove) throws StoreException { Offset journalFirstOffset = journal.getFirstOffset(); TreeMap<Offset, IndexSegment> segmentsToAdd = new TreeMap<>(); for (File indexSegmentFile : segmentFilesToAdd) { IndexSegment indexSegment = new IndexSegment(indexSegmentFile, true, factory, config, metrics, journal); if (indexSegment.getEndOffset().compareTo(journalFirstOffset) > 0) { throw new IllegalArgumentException("One of the index segments has an end offset " + indexSegment.getEndOffset() + " that is higher than the first offset in the journal " + journalFirstOffset); } segmentsToAdd.put(indexSegment.getStartOffset(), indexSegment); } for (Offset offset : segmentsToRemove) { IndexSegment segmentToRemove = validIndexSegments.get(offset); if (segmentToRemove.getEndOffset().compareTo(journalFirstOffset) >= 0) { throw new IllegalArgumentException( "End Offset of the one of the segments to remove [" + segmentToRemove.getFile() + "] is" + " higher than the first offset in the journal"); } } inFluxIndexSegments = new ConcurrentSkipListMap<>(); inFluxIndexSegments.putAll(validIndexSegments); inFluxIndexSegments.keySet().removeAll(segmentsToRemove); inFluxIndexSegments.putAll(segmentsToAdd); validIndexSegments = inFluxIndexSegments; }
Source:
@Override public void setId(String id) { this.id = id; }

Target:
public void setId(String id) { this.id = id; }
Source:
public Description matchTry (TryTree tree, VisitorState state) { List<? extends CatchTree> catchList = tree.getCatches(); if (catchList == null || catchList.size() == 0) { return Description.NO_MATCH; } CatchTree lastCatch = catchList.get(tree.getCatches().size() - 1); if (overcatch(lastCatch, state)) { if (abortInCatch(lastCatch, state)) { LineMap lineMap = state.getPath().getCompilationUnit().getLineMap(); return describeMatch(lastCatch); } } return Description.NO_MATCH; }

Target:
public Description matchTry (TryTree tree, VisitorState state) { List<? extends CatchTree> catchList = tree.getCatches(); if (catchList == null || catchList.size() == 0) { return Description.NO_MATCH; } CatchTree lastCatch = Iterables.getLast(catchList); if (overcatch(lastCatch, state)) { if (abortInCatch(lastCatch, state)) { return describeMatch(lastCatch); } } return Description.NO_MATCH; }
Source:
public void initialize(Bootstrap<ConnectorConfiguration> bootstrap) { bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(NON_STRICT_VARIABLE_SUBSTITUTOR) ) ); bootstrap.addBundle(new MigrationsBundle<ConnectorConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(ConnectorConfiguration configuration) { return configuration.getDataSourceFactory(); } }); bootstrap.addCommand(new DependentResourceWaitCommand()); bootstrap.addCommand(new RenderStateTransitionGraphCommand()); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(LogstashConsoleAppenderFactory.class); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(GovUkPayDropwizardRequestJsonLogLayoutFactory.class); java.security.Security.setProperty("networkaddress.cache.ttl" , "15"); }

Target:
public void initialize(Bootstrap<ConnectorConfiguration> bootstrap) { java.security.Security.setProperty("networkaddress.cache.ttl" , "15"); bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(NON_STRICT_VARIABLE_SUBSTITUTOR) ) ); bootstrap.addBundle(new MigrationsBundle<ConnectorConfiguration>() { @Override public DataSourceFactory getDataSourceFactory(ConnectorConfiguration configuration) { return configuration.getDataSourceFactory(); } }); bootstrap.addCommand(new DependentResourceWaitCommand()); bootstrap.addCommand(new RenderStateTransitionGraphCommand()); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(LogstashConsoleAppenderFactory.class); bootstrap.getObjectMapper().getSubtypeResolver().registerSubtypes(GovUkPayDropwizardRequestJsonLogLayoutFactory.class); }
Source:
public boolean chkAuthorization(String userName, Object accessObject, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { boolean haveAccess; haveAccess = false; String networkId = (String) accessObject; haveAccess = accessManager.checkIsNetworkEditor(networkId, userName); return haveAccess; }

Target:
public boolean chkAuthorization(String userName, Object accessObject, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { String networkId = null; if (accessObject instanceof String) { networkId = (String) accessObject; } else { try { INetwork nwObj = (Network) accessObject; networkId = nwObj.getNetworkId(); } catch (ClassCastException cce) { throw new IllegalObjectException(cce); } } return accessManager.checkIsNetworkEditor(networkId, userName); }
Source:
public CannedAccessControlList getAccessControlList() { return accessControlList; }

Target:
public CannedAccessControlList getAccessControlList() { CannedAccessControlList accessControlList; if(access.equalsIgnoreCase("private")) { accessControlList = CannedAccessControlList.BucketOwnerFullControl; } else { accessControlList = CannedAccessControlList.PublicRead; } return accessControlList; }
Source:
Transformations(Map<String, String> transformations) { this.map = unmodifiableMap(transformations); int min = Integer.MAX_VALUE; for (String key : map.keySet()) { int len = key.length(); if (len < min) { min = len; } } minLen = min; }

Target:
Transformations(Map<String, String> transformations) { this.map = transformations; int min = Integer.MAX_VALUE; int max = 0; for (String key : map.keySet()) { int len = key.length(); if (len < min) min = len; if (len > max) max = len; } minLen = min; maxLen = max; }
Source:
public static Boolean getPropertyAsBoolean(String name) { String value = getProperty(name); if (value == null) { return null; } return Boolean.valueOf(value); }

Target:
public static boolean getPropertyAsBoolean(String name) { String value = getProperty(name); if (value != null && value.equalsIgnoreCase("true")) { return true; } return false; }
Source:
public BulkLightblueResponse(String responseText, AbstractBulkLightblueRequest<? extends AbstractLightblueRequest> reqs) throws LightblueResponseParseException, LightblueException { this(new ArrayList<LightblueResponse>(), reqs); try { json = JSON.getDefaultObjectMapper().readTree(responseText); ArrayNode resps = (ArrayNode) json.get("responses"); for (Iterator<JsonNode> it = resps.iterator(); it.hasNext();) { JsonNode resp = it.next(); LightblueResponse response = new DefaultLightblueResponse(resp.get("response").toString()); JsonNode seq = resp.get("seq"); if (!seq.isNumber()) { throw new LightblueException("Invalid sequence.", response); } responses.add(resp.get("seq").intValue(), response); } } catch (IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + responseText + "\n", e); } }

Target:
public BulkLightblueResponse(String responseText, AbstractBulkLightblueRequest<? extends AbstractLightblueRequest> reqs) throws LightblueResponseParseException, LightblueException { requests = reqs.getRequests(); this.text = responseText; try { json = JSON.getDefaultObjectMapper().readTree(responseText); ArrayNode resps = (ArrayNode) json.get("responses"); for (Iterator<JsonNode> it = resps.iterator(); it.hasNext();) { JsonNode resp = it.next(); LightblueResponse response = new DefaultLightblueResponse(resp.get("response").toString()); JsonNode seq = resp.get("seq"); if (!seq.isNumber()) { throw new LightblueException("Invalid sequence.", response); } responses.put(resp.get("seq").intValue(), response); } } catch (IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + responseText + "\n", e); } }
Source:
public boolean unlockSimple(SimpleHeldLocksToken token) { Preconditions.checkNotNull(token); LockDescriptor fakeLockDesc = StringLockDescriptor.of("unlockSimple"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); return unlock(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, token.getCreationDateMs(), 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "fakeThread-unlockSimple")); }

Target:
public boolean unlockSimple(SimpleHeldLocksToken token) { Preconditions.checkNotNull(token); LockDescriptor fakeLockDesc = StringLockDescriptor.of("unlockSimple"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); return unlock(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, token.getCreationDateMs(), 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "UnknownThread-unlockSimple")); }
Source:
public int getSpinnerId() { return R.id.hide_variable_spinner; }

Target:
protected int getSpinnerId() { return R.id.hide_variable_spinner; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DefaultDockerClientConfig that = (DefaultDockerClientConfig) o; return EqualsBuilder.reflectionEquals(this, that); }

Target:
public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); }
Source:
private PreparedStatement getDeleteSqlForSession(SessionId sessionId) throws SQLException{ PreparedStatement deleteSessionStatement = connection.prepareStatement("delete from " + tableName + " where " + sessionIdCol + " like ?"); deleteSessionStatement.setString(1, sessionUri(sessionId).concat("%")); return deleteSessionStatement; }

Target:
private PreparedStatement getDeleteSqlForSession(SessionId sessionId) throws SQLException{ PreparedStatement deleteSessionStatement = connection.prepareStatement(String.format("delete from %1$s where %2$s = ?", TABLE_NAME, SESSION_ID_COL)); deleteSessionStatement.setString(1, sessionId.toString()); return deleteSessionStatement; }
Source:
public void networkTopologyStrategyNoNodesInDCTest() { long t1 = System.currentTimeMillis(); Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2)) .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing); assertThat((System.currentTimeMillis() - t1) < 45000); for (int node = 0; node < 99; node++) { for (int vnodes = 0; vnodes < 256; vnodes++) { Token token = token("" + ((node * 256) + vnodes)); assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1)); } } assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0"); }

Target:
public void networkTopologyStrategyNoNodesInDCTest() { long t1 = System.currentTimeMillis(); Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2)) .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing); assertThat(System.currentTimeMillis() - t1).isLessThan(10000); for (int node = 0; node < 99; node++) { for (int vnodes = 0; vnodes < 256; vnodes++) { Token token = token("" + ((node * 256) + vnodes)); assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1)); } } assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0"); }
Source:
public TmfModelResponse<List<ITmfTreeDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<ITmfTreeDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { long id = fAtomicLong.getAndIncrement(); new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault()); model.add(new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); fAspectMap.put(id, aspect); } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }

Target:
public TmfModelResponse<List<ColumnDataModel>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<ColumnDataModel> model = new ArrayList<>(); for (ITmfEventAspect<?> aspect : getTraceAspects(getTrace())) { Long id = fAspectMap.inverse().computeIfAbsent(aspect, a -> fAtomicLong.getAndIncrement()); model.add(new ColumnDataModel(id, -1, aspect.getName(), aspect.getHelpText(), aspect.isHiddenByDefault())); } return new TmfModelResponse<>(model, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); return (ch instanceof Http2StreamChannel) ? ch.parent() : ch; }

Target:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); return ch instanceof Http2StreamChannel ? ch.parent() : ch; }
Source:
public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIdIsNull() { given(applicationsRepository.findOne(null)).willThrow(IllegalArgumentException.class); statesService.getStatesByApplicationId(null); }

Target:
public void getStatesByApplicationIdShouldThrowIllegalArgumentExceptionWhenApplicationIdIsNull() { statesService.getStatesByApplicationId(null); }
Source:
private Optional<Session> findCurrentSession() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final IWorkbenchPage activePage = window.getActivePage(); final IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor instanceof SessionEditor) { return Optional.ofNullable(((SessionEditor) activeEditor).getSession()); } else { return Optional.empty(); } }

Target:
private Optional<Session> findCurrentSession() { final IEditorPart activeEditor = EclipseUIUtil.getActiveEditor(); if (activeEditor instanceof SessionEditor) { return Optional.ofNullable(((SessionEditor) activeEditor).getSession()); } else { return Optional.empty(); } }
Source:
public Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSource) { if (jsonSource instanceof JSONObject) { LOGGER.log(Level.FINE, "potentially converting {0} {1} {2}", new Object[] {targetType, targetTypeErasure, jsonSource}); return instantiate(targetTypeErasure, (JSONObject) jsonSource); } else { LOGGER.log(Level.FINE, "ignoring non-object {0}", jsonSource); return oldInterceptor.onConvert(targetType, targetTypeErasure, jsonSource); } }

Target:
public Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSource) { if (jsonSource instanceof JSONObject) { JSONObject json = (JSONObject) jsonSource; if (isApplicable(targetTypeErasure, json)) { LOGGER.log(Level.FINE, "switching to newInstance {0} {1}", new Object[] {targetTypeErasure.getName(), json}); try { return Jenkins.getActiveInstance().getDescriptor(targetTypeErasure).newInstance(Stapler.getCurrentRequest(), json); } catch (Exception x) { LOGGER.log(Level.WARNING, "falling back to default instantiation " + targetTypeErasure.getName() + " " + json, x); } } } else { LOGGER.log(Level.FINER, "ignoring non-object {0}", jsonSource); } return oldInterceptor.onConvert(targetType, targetTypeErasure, jsonSource); }
Source:
private CompletionStage<RestResponse> getConfig(RestRequest request) { NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); GlobalConfiguration globalConfiguration = Security.doAs(request.getSubject(), (PrivilegedAction<GlobalConfiguration>) () -> cacheManager.getCacheManagerConfiguration()); MediaType format = MediaTypeUtils.negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); parserRegistry.serialize(baos, globalConfiguration, emptyMap()); if (format.match(APPLICATION_XML)) { responseBuilder.contentType(APPLICATION_XML); responseBuilder.entity(baos.toByteArray()); } else { responseBuilder.contentType(APPLICATION_JSON); responseBuilder.entity(jsonWriter.toJSON(globalConfiguration)); } } catch (XMLStreamException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }

Target:
private CompletionStage<RestResponse> getConfig(RestRequest request) { NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); EmbeddedCacheManager embeddedCacheManager = cacheManager.withSubject(request.getSubject()); GlobalConfiguration globalConfiguration = SecurityActions.getCacheManagerConfiguration(embeddedCacheManager); MediaType format = MediaTypeUtils.negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); parserRegistry.serialize(baos, globalConfiguration, emptyMap()); if (format.match(APPLICATION_XML)) { responseBuilder.contentType(APPLICATION_XML); responseBuilder.entity(baos.toByteArray()); } else { responseBuilder.contentType(APPLICATION_JSON); responseBuilder.entity(jsonWriter.toJSON(globalConfiguration)); } } catch (XMLStreamException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }
Source:
public void seek(long position) throws IOException { inputStream.seek(position); originInputStream.seek(position); }

Target:
public void seek(long position) throws IOException { inputStream.seek(position); if (cacheValidationEnabled) { dataTierInputStream.get().seek(position); } }
Source:
public List<Room> getBuildingRooms(String campusCode, String buildingCode) { Criteria criteria = new Criteria(); criteria.addEqualTo(CuCamsConstants.CapAssetApi.CAMPUS_CODE_PARAMETER, campusCode); criteria.addEqualTo("buildingCode", buildingCode); Query query = QueryFactory.newQuery(Room.class, criteria); return (List<Room>) getPersistenceBrokerTemplate().getCollectionByQuery(query); }

Target:
public List<Room> getBuildingRooms(String campusCode, String buildingCode) { Criteria criteria = new Criteria(); criteria.addEqualTo(CuCamsConstants.CapAssetApi.CAMPUS_CODE_PARAMETER, campusCode); criteria.addEqualTo(KFSPropertyConstants.BUILDING_CODE, buildingCode); Query query = QueryFactory.newQuery(Room.class, criteria); return (List<Room>) getPersistenceBrokerTemplate().getCollectionByQuery(query); }
Source:
switch (platform) { case "win32": COLUMN_TRIM= 4; break; case "cocoa": COLUMN_TRIM= 24; break; default: COLUMN_TRIM= 3; break; }

Target:
switch (platform) { case "win32": COLUMN_TRIM= 4; break; case "carbon": COLUMN_TRIM= 24; break; default: COLUMN_TRIM= 3; break; }
Source:
public <T> T doWithRetries(Callable<T> action, String actionName, String partitionPath) throws CloudStorageException { int attempts = 0; while (attempts < maxAttempts) { try { return action.call(); } catch (Exception e) { attempts++; throwOrDelay(e, actionName, partitionPath, attempts); } } throw new CloudStorageException( actionName + (!Utils.isNullOrEmpty(partitionPath) ? (" failed partition " + partitionPath) : "") + " made " + attempts + " attempts"); }

Target:
public <T> T doWithRetries(Callable<T> action, String actionName, String partitionPath) throws CloudStorageException { int attempts = 0; while (attempts < maxAttempts) { try { return action.call(); } catch (Exception e) { attempts++; throwOrDelay(e, actionName, partitionPath, attempts); } } throw new CloudStorageException( actionName + " failed, " + (!Utils.isNullOrEmpty(partitionPath) ? ("partition " + partitionPath) : "") + " made " + attempts + " attempts"); }
Source:
public void testBuildBlobId() throws Exception { for (Short version : versions) { for (Boolean shouldUseSetter : setterChoice) { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, null, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, null, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, null, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, null, null, null, referencePartitionId, shouldUseSetter); } } }

Target:
public void testBuildBlobId() throws Exception { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); }
Source:
protected Boolean visitBetweenPredicate(BetweenPredicate actual, Expression expectedExpression) { if (expectedExpression instanceof BetweenPredicate) { BetweenPredicate expected = (BetweenPredicate) expectedExpression; return process(actual.getMin(), expected.getMin()) && process(actual.getMax(), expected.getMax()); } return false; }

Target:
protected Boolean visitBetweenPredicate(BetweenPredicate actual, Expression expectedExpression) { if (expectedExpression instanceof BetweenPredicate) { BetweenPredicate expected = (BetweenPredicate) expectedExpression; return process(actual.getValue(), expected.getValue()) && process(actual.getMin(), expected.getMin()) && process(actual.getMax(), expected.getMax()); } return false; }
Source:
public List<Host> addHosts(PerunSession sess, List<Host> hosts, Facility facility) throws FacilityNotExistsException, InternalErrorException, PrivilegeException, HostExistsException { Utils.checkPerunSession(sess); getFacilitiesManagerBl().checkFacilityExists(sess, facility); if (!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "addHosts"); } Utils.notNull(hosts, "hosts"); for(Host host: hosts) { List<Facility> facilitiesByHostname = getFacilitiesManagerBl().getFacilitiesByHostName(sess, host.getHostname()); List<Facility> facilitiesByDestination = getFacilitiesByDestination(sess, host.getHostname()); if(facilitiesByHostname.isEmpty() && facilitiesByDestination.isEmpty()) { continue; } if(!facilitiesByHostname.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByHostname) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } if(!facilitiesByDestination.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByDestination) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } throw new PrivilegeException(sess, "You can't add these hosts."); } return getFacilitiesManagerBl().addHosts(sess, hosts, facility); }

Target:
public List<Host> addHosts(PerunSession sess, List<Host> hosts, Facility facility) throws FacilityNotExistsException, InternalErrorException, PrivilegeException, HostExistsException { Utils.checkPerunSession(sess); getFacilitiesManagerBl().checkFacilityExists(sess, facility); if (!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "addHosts"); } Utils.notNull(hosts, "hosts"); for(Host host: hosts) { List<Facility> facilitiesByHostname = getFacilitiesManagerBl().getFacilitiesByHostName(sess, host.getHostname()); List<Facility> facilitiesByDestination = getFacilitiesByDestination(sess, host.getHostname()); if(facilitiesByHostname.isEmpty() && facilitiesByDestination.isEmpty()) { continue; } if(!facilitiesByHostname.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByHostname) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } if(!facilitiesByDestination.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByDestination) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } throw new PrivilegeException(sess, "You can't add host " + host + ", because you don't have privileges to use this hostName"); } return getFacilitiesManagerBl().addHosts(sess, hosts, facility); }