auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public OptionalInt tryConvertToDirect(int maxDirectBytes) { checkState(!closed); checkState(!directEncoded); if (directColumnWriter == null) { directColumnWriter = new SliceDirectColumnWriter(column, type, compression, bufferSize, orcEncoding, this::newStringStatisticsBuilder); } checkState(directColumnWriter.getBufferedBytes() == 0); Block dictionaryValues = dictionary.getElementBlock(); for (DictionaryRowGroup rowGroup : rowGroups) { directColumnWriter.beginRowGroup(); if (!writeDictionaryRowGroup(dictionaryValues, rowGroup.getValueCount(), rowGroup.getDictionaryIndexes(), maxDirectBytes)) { return OptionalInt.empty(); } directColumnWriter.finishRowGroup(); } if (inRowGroup) { directColumnWriter.beginRowGroup(); if (!writeDictionaryRowGroup(dictionaryValues, rowGroupValueCount, values, maxDirectBytes)) { return OptionalInt.empty(); } } else { checkState(rowGroupValueCount == 0); } rowGroups.clear(); dictionary.clear(); rawBytes = 0; totalValueCount = 0; totalNonNullValueCount = 0; rowGroupValueCount = 0; statisticsBuilder = newStringStatisticsBuilder(); directEncoded = true; return OptionalInt.of(toIntExact(directColumnWriter.getBufferedBytes())); }

Target:
public OptionalInt tryConvertToDirect(int maxDirectBytes) { checkState(!closed); checkState(!directEncoded); if (directColumnWriter == null) { directColumnWriter = new SliceDirectColumnWriter(column, type, compression, bufferSize, orcEncoding, this::newStringStatisticsBuilder); } checkState(directColumnWriter.getBufferedBytes() == 0); Block dictionaryValues = dictionary.getElementBlock(); for (DictionaryRowGroup rowGroup : rowGroups) { directColumnWriter.beginRowGroup(); boolean success = writeDictionaryRowGroup(dictionaryValues, rowGroup.getValueCount(), rowGroup.getDictionaryIndexes(), maxDirectBytes); directColumnWriter.finishRowGroup(); if (!success) { directColumnWriter.close(); directColumnWriter.reset(); return OptionalInt.empty(); } } if (inRowGroup) { directColumnWriter.beginRowGroup(); if (!writeDictionaryRowGroup(dictionaryValues, rowGroupValueCount, values, maxDirectBytes)) { directColumnWriter.close(); directColumnWriter.reset(); return OptionalInt.empty(); } } else { checkState(rowGroupValueCount == 0); } rowGroups.clear(); dictionary.clear(); rawBytes = 0; totalValueCount = 0; totalNonNullValueCount = 0; rowGroupValueCount = 0; statisticsBuilder = newStringStatisticsBuilder(); directEncoded = true; return OptionalInt.of(toIntExact(directColumnWriter.getBufferedBytes())); }
Source:
private void sendUnauthorized(HttpServletResponse response, boolean close) { try { if (close) { response.setHeader(IWAConstants.AUTHENTICATE_HEADER, IWAConstants.NEGOTIATE_HEADER); response.addHeader(IWAConstants.HTTP_CONNECTION_HEADER, IWAConstants.CONNECTION_CLOSE); } else { response.setHeader(IWAConstants.AUTHENTICATE_HEADER, IWAConstants.NEGOTIATE_HEADER); response.addHeader(IWAConstants.HTTP_CONNECTION_HEADER, IWAConstants.CONNECTION_KEEP_ALIVE); } response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.flushBuffer(); } catch (IOException e) { log.error("Error when sending unauthorized response." + e); } }

Target:
private void sendUnauthorized(HttpServletResponse response, boolean close) { try { if (close) { response.setHeader(IWAConstants.AUTHENTICATE_HEADER, IWAConstants.NEGOTIATE_HEADER); response.addHeader(IWAConstants.HTTP_CONNECTION_HEADER, IWAConstants.CONNECTION_CLOSE); } else { response.setHeader(IWAConstants.AUTHENTICATE_HEADER, IWAConstants.NEGOTIATE_HEADER); response.addHeader(IWAConstants.HTTP_CONNECTION_HEADER, IWAConstants.CONNECTION_KEEP_ALIVE); } response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.flushBuffer(); } catch (IOException e) { log.error("Error when sending unauthorized response.", e); } }
Source:
private static byte[] serializeBookieServiceInfo(BookieServiceInfo bookieServiceInfo) { log.info("serialize BookieServiceInfo {}", bookieServiceInfo); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { BookieServiceInfoFormat.Builder builder = BookieServiceInfoFormat.newBuilder(); List<BookieServiceInfoFormat.Endpoint> bsiEndpoints = bookieServiceInfo.getEndpoints().stream() .map(e -> { return BookieServiceInfoFormat.Endpoint.newBuilder() .setId(e.getId()) .setPort(e.getPort()) .setHost(e.getHost()) .setProtocol(e.getProtocol()) .addAllAuth(e.getAuth()) .addAllExtensions(e.getExtensions()) .build(); }) .collect(Collectors.toList()); builder.addAllEndpoints(bsiEndpoints); builder.putAllProperties(bookieServiceInfo.getProperties()); builder.build().writeTo(os); return os.toByteArray(); } catch (IOException err) { log.error("Cannot serialize bookieServiceInfo from " + bookieServiceInfo); throw new RuntimeException(err); } }

Target:
static byte[] serializeBookieServiceInfo(BookieServiceInfo bookieServiceInfo) { if (log.isDebugEnabled()) { log.debug("serialize BookieServiceInfo {}", bookieServiceInfo); } try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { BookieServiceInfoFormat.Builder builder = BookieServiceInfoFormat.newBuilder(); List<BookieServiceInfoFormat.Endpoint> bsiEndpoints = bookieServiceInfo.getEndpoints().stream() .map(e -> { return BookieServiceInfoFormat.Endpoint.newBuilder() .setId(e.getId()) .setPort(e.getPort()) .setHost(e.getHost()) .setProtocol(e.getProtocol()) .addAllAuth(e.getAuth()) .addAllExtensions(e.getExtensions()) .build(); }) .collect(Collectors.toList()); builder.addAllEndpoints(bsiEndpoints); builder.putAllProperties(bookieServiceInfo.getProperties()); builder.build().writeTo(os); return os.toByteArray(); } catch (IOException err) { log.error("Cannot serialize bookieServiceInfo from " + bookieServiceInfo); throw new RuntimeException(err); } }
Source:
private void setInstructorsIsArchivedInCourse(CourseAttributes course) throws InvalidParametersException, EntityDoesNotExistException { System.out.println("Updating instructors of old archived course: " + course.id); List<InstructorAttributes> instructorList = logic.getInstructorsForCourse(course.id); for (InstructorAttributes instructor: instructorList) { if (isPreview) { System.out.println("Instructor: " + instructor.googleId + " : " + instructor.isArchived); if (instructor.isArchived == null) { System.out.println("======= Migration has not been done yet ======="); } } else { if (instructor.isArchived == null) { instructor.isArchived = true; logic.updateInstructorByEmail(instructor.email, instructor); System.out.println("Successfully updated instructor: [" + instructor.email + "] " + instructor.name); } } } System.out.println(""); }

Target:
private void setInstructorsIsArchivedInCourse(CourseAttributes course) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertEquals(false, isPreview); Assumption.assertTrue(course.isArchived); System.out.println("Updating instructors of old archived course: " + course.id); List<InstructorAttributes> instructorsOfCourse = logic.getInstructorsForCourse(course.id); for (InstructorAttributes instructor: instructorsOfCourse) { if (instructor.isArchived == null) { instructor.isArchived = true; logic.updateInstructorByEmail(instructor.email, instructor); System.out.println("Successfully updated instructor: [" + instructor.email + "] " + instructor.name); } } System.out.println(""); }
Source:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { Map<String, String> retMap = super.getEventHoverToolTipInfo(event, hoverTime); if (retMap == null) { retMap = new LinkedHashMap<>(1); } if (!(event instanceof TimeEvent) || !((TimeEvent) event).hasValue() || !(event.getEntry() instanceof TimeGraphEntry)) { return retMap; } TimeGraphEntry entry = (TimeGraphEntry) event.getEntry(); ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = BaseDataProviderTimeGraphView.getProvider(entry); Map<String, Object> parameters = FetchParametersUtils.selectionTimeQueryToMap(new SelectionTimeQueryFilter(hoverTime, hoverTime, 1, Collections.singletonList(entry.getEntryModel().getId()))); TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> response = dataProvider.fetchTooltip(parameters, null); Map<@NonNull String, @NonNull String> map = response.getModel(); if (map != null) { retMap.putAll(map); } return retMap; }

Target:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { Map<String, String> retMap = super.getEventHoverToolTipInfo(event, hoverTime); if (retMap == null) { retMap = new LinkedHashMap<>(1); } if (!(event instanceof TimeEvent) || !((TimeEvent) event).hasValue() || !(event.getEntry() instanceof TimeGraphEntry)) { return retMap; } TimeGraphEntry entry = (TimeGraphEntry) event.getEntry(); ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = BaseDataProviderTimeGraphView.getProvider(entry); Map<@NonNull String, @NonNull Object> parameters = FetchParametersUtils.selectionTimeQueryToMap(new SelectionTimeQueryFilter(hoverTime, hoverTime, 1, Collections.singletonList(entry.getEntryModel().getId()))); TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> response = dataProvider.fetchTooltip(parameters, null); Map<@NonNull String, @NonNull String> map = response.getModel(); if (map != null) { retMap.putAll(map); } return retMap; }
Source:
private static String applyMappings(String text, Map<String, String> mappings, List<String> keys) { TreeSet<Range> ranges = new TreeSet<Range>(new Comparator<Range>() { @Override public int compare(Range r1, Range r2) { int maxStart = Math.max(r1.start, r2.start); int minEnd = Math.min(r1.end, r2.end); if (maxStart < minEnd) { return 0; } else { return Integer.compare(r2.end, r1.end); } } }); for (String key : keys) { Pattern keyPattern = Pattern.compile(Pattern.quote(key)); Matcher matcher = keyPattern.matcher(text); String replacement = mappings.get(key); while (matcher.find()) { int startId = matcher.start(); int endId = matcher.end(); Range range = new Range(startId, endId, replacement); ranges.add(range); } } for (Range range : ranges) { String left = text.substring(0, range.start); String middle = range.text; String end = text.substring(range.end); text = left + middle + end; } return text; }

Target:
private static String applyMappings(String text, Map<String, String> mappings, List<String> keys) { TreeSet<Range> ranges = new TreeSet<Range>(rangeComparator); for (String key : keys) { Pattern keyPattern = Pattern.compile(Pattern.quote(key)); Matcher matcher = keyPattern.matcher(text); String replacement = mappings.get(key); while (matcher.find()) { int startId = matcher.start(); int endId = matcher.end(); Range range = new Range(startId, endId, replacement); ranges.add(range); } } for (Range range : ranges) { String left = text.substring(0, range.start); String middle = range.text; String end = text.substring(range.end); text = left + middle + end; } return text; }
Source:
private void executeRequest(Weather weather, String url, LocationConfig locationConfig) throws Exception { try { logger.trace("{}[{}]: request : {}", getProviderName(), locationConfig.getLocationId(), url); String response = StringUtils.trimToEmpty(HttpUtil.executeUrl( "GET", url, 15000)); if ((weather.getProvider() == ProviderName.WEATHERBIT) && StringUtils.contains(url, "forecast/daily")) { response = StringUtils.replace(response, "data", "forecast"); } if (logger.isTraceEnabled()) { response = StringUtils.remove(response, "\n"); response = StringUtils.trim(response); logger.trace("{}[{}]: response: {}", getProviderName(), locationConfig.getLocationId(), response); } if (!response.isEmpty()) { parser.parseInto(response, weather); } if ((weather.getProvider() == ProviderName.OPENWEATHERMAP) && (weather.getResponseCode() != null) && (weather.getResponseCode() == 200)) { weather.setError(null); } if (!weather.hasError() && response.isEmpty()) { weather.setError("Error: response is empty!"); } if (weather.hasError()) { logger.error("{}[{}]: Can't retreive weather data: {}", getProviderName(), locationConfig.getLocationId(), weather.getError()); } else { setLastUpdate(weather); } } catch (Exception ex) { logger.error(getProviderName() + ": " + ex.getMessage()); weather.setError(ex.getClass().getSimpleName() + ": " + ex.getMessage()); throw ex; } }

Target:
private void executeRequest(Weather weather, String url, LocationConfig locationConfig) throws Exception { try { logger.trace("{}[{}]: request : {}", getProviderName(), locationConfig.getLocationId(), url); String response = StringUtils.trimToEmpty(HttpUtil.executeUrl( "GET", url, 15000)); if ((weather.getProvider() == ProviderName.WEATHERBIT) && StringUtils.contains(url, "forecast/daily")) { response = StringUtils.replace(response, "data", "forecast"); } if (logger.isTraceEnabled()) { response = StringUtils.remove(response, "\n"); response = StringUtils.trim(response); logger.trace("{}[{}]: response: {}", getProviderName(), locationConfig.getLocationId(), response); } if (!response.isEmpty()) { parser.parseInto(response, weather); } if (weather.getProvider() == ProviderName.OPENWEATHERMAP && weather.getResponseCode() != null && weather.getResponseCode() == 200) { weather.setError(null); } if (!weather.hasError() && response.isEmpty()) { weather.setError("Error: response is empty!"); } if (weather.hasError()) { logger.error("{}[{}]: Can't retrieve weather data: {}", getProviderName(), locationConfig.getLocationId(), weather.getError()); } else { setLastUpdate(weather); } } catch (Exception ex) { logger.error(getProviderName() + ": " + ex.getMessage()); weather.setError(ex.getClass().getSimpleName() + ": " + ex.getMessage()); throw ex; } }
Source:
public static Object convert(Object source, Attribute attr) { try { switch (attr.getDataType()) { case BOOL: return toBoolean(source); case XREF: case CATEGORICAL: case CATEGORICAL_MREF: case MREF: case FILE: case ONE_TO_MANY: return source; case COMPOUND: throw new UnsupportedOperationException(); case DATE: return toLocalDate(source); case DATE_TIME: return toInstant(source); case DECIMAL: return toDouble(source); case INT: return toInt(source); case LONG: return toLong(source); default: return toString(source); } } catch (ConversionFailedException cfe) { throw new AttributeValueConversionFailedException(attr, source); } }

Target:
public static Object convert(Object source, Attribute attr) { try { switch (attr.getDataType()) { case BOOL: return toBoolean(source); case XREF: case CATEGORICAL: case CATEGORICAL_MREF: case MREF: case FILE: case ONE_TO_MANY: return source; case COMPOUND: throw new UnsupportedOperationException(); case DATE: return toLocalDate(source); case DATE_TIME: return toInstant(source); case DECIMAL: return toDouble(source); case INT: return toInt(source); case LONG: return toLong(source); default: return toString(source); } } catch (ConversionFailedException cfe) { throw new AttributeValueConversionException(attr, source, cfe); } }
Source:
public void debugClearLocalData() throws MessagingException { if (!K9.DEVELOPER_MODE) { throw new AssertionError("method must only be used in debug build!"); } try { localStore.getDatabase().execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException { ContentValues cv = new ContentValues(); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(databaseId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } setFlag(Flag.X_DOWNLOADED_FULL, false); setFlag(Flag.X_DOWNLOADED_PARTIAL, false); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); }

Target:
public void debugClearLocalData() throws MessagingException { if (!K9.DEVELOPER_MODE) { throw new AssertionError("method must only be used in developer mode!"); } try { localStore.getDatabase().execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException { ContentValues cv = new ContentValues(); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(databaseId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } setFlag(Flag.X_DOWNLOADED_FULL, false); setFlag(Flag.X_DOWNLOADED_PARTIAL, false); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); }
Source:
public <T extends Component> T getModuleConfig(SimpleUri uri, String key, Class<T> clazz) { Map<String, JsonElement> map = moduleConfigs.get(uri); if (map == null) { return null; } JsonElement element = map.get(key); Gson gson = new Gson(); return gson.fromJson(element, clazz); }

Target:
public <T extends Component> T getModuleConfig(SimpleUri uri, String key, Class<T> clazz) { Map<String, JsonElement> map = moduleConfigs.get(uri); if (map == null) { return null; } JsonElement element = map.get(key); Gson gson = createGsonForModules(); return gson.fromJson(element, clazz); }
Source:
public static void export(Path exportDir, BriefcaseFormDefinition formDefinition, String baseFilename, boolean exportMedia, boolean overwriteFiles, Optional<LocalDate> startDate, Optional<LocalDate> endDate) { log.info("exporting to : " + exportDir); ExportToCsv action = new ExportToCsv( new TerminationFuture(), exportDir.toFile(), formDefinition, baseFilename, exportMedia, overwriteFiles, startDate.map((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null), endDate.map((LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant())).orElse(null) ); try { boolean allSuccessful = action.doAction(); if (allSuccessful && action.someSkipped()) EventBus.publish(new ExportSucceededWithErrorsEvent(action.getFormDefinition())); if (allSuccessful && action.noneSkipped()) EventBus.publish(new ExportSucceededEvent(action.getFormDefinition())); if (allSuccessful && action.allSkipped()) throw new ExportException(formDefinition, "None of the instances where exported"); if (!allSuccessful) throw new ExportException(formDefinition); } catch (Throwable t) { throw new ExportException(formDefinition); } }

Target:
public static void export(Path exportDir, BriefcaseFormDefinition formDefinition, String baseFilename, boolean exportMedia, boolean overwriteFiles, Optional<LocalDate> startDate, Optional<LocalDate> endDate) { log.info("exporting to : " + exportDir); ExportToCsv action = new ExportToCsv( new TerminationFuture(), exportDir.toFile(), formDefinition, baseFilename, exportMedia, overwriteFiles, startDate.map(ld -> Date.from(ld.atStartOfDay(systemDefault()).toInstant())).orElse(null), endDate.map(ld -> Date.from(ld.atStartOfDay(systemDefault()).toInstant())).orElse(null) ); try { boolean allSuccessful = action.doAction(); if (allSuccessful && action.someSkipped()) EventBus.publish(new ExportSucceededWithErrorsEvent(action.getFormDefinition())); if (allSuccessful && action.noneSkipped()) EventBus.publish(new ExportSucceededEvent(action.getFormDefinition())); if (allSuccessful && action.allSkipped()) throw new ExportException(formDefinition, "None of the instances where exported"); if (!allSuccessful) throw new ExportException(formDefinition); } catch (Throwable t) { throw new ExportException(formDefinition); } }
Source:
private static void readSliceHeader(final int major, final Slice slice, final InputStream readInputStream) throws IOException { slice.headerBlock = Block.read(major, readInputStream); if (slice.headerBlock.getContentType() != BlockContentType.MAPPED_SLICE) throw new RuntimeException("Content type does not match: " + slice.headerBlock.getContentType().name()); final InputStream parseInputStream = new ByteArrayInputStream(slice.headerBlock.getUncompressedContent()); slice.sequenceId = ITF8.readUnsignedITF8(parseInputStream); slice.alignmentStart = ITF8.readUnsignedITF8(parseInputStream); slice.alignmentSpan = ITF8.readUnsignedITF8(parseInputStream); slice.nofRecords = ITF8.readUnsignedITF8(parseInputStream); slice.globalRecordCounter = LTF8.readUnsignedLTF8(parseInputStream); slice.nofBlocks = ITF8.readUnsignedITF8(parseInputStream); slice.contentIDs = CramIntArray.array(parseInputStream); slice.embeddedRefBlockContentID = ITF8.readUnsignedITF8(parseInputStream); slice.refMD5 = new byte[16]; InputStreamUtils.readFully(parseInputStream, slice.refMD5, 0, slice.refMD5.length); final byte[] bytes = InputStreamUtils.readFully(parseInputStream); if (major >= CramVersions.CRAM_v3.major) { slice.sliceTags = BinaryTagCodec.readTags(bytes, 0, bytes.length, ValidationStringency.DEFAULT_STRINGENCY); SAMBinaryTagAndValue tags = slice.sliceTags; while (tags != null) { log.debug(String.format("Found slice tag: %s", SAMTag.makeStringTag(tags.tag))); tags = tags.getNext(); } } }

Target:
private static void readSliceHeader(final int major, final Slice slice, final InputStream readInputStream) throws IOException { slice.headerBlock = Block.read(major, readInputStream); if (slice.headerBlock.getContentType() != BlockContentType.MAPPED_SLICE) throw new RuntimeException("Slice Header Block expected, found: " + slice.headerBlock.getContentType().name()); final InputStream parseInputStream = new ByteArrayInputStream(slice.headerBlock.getUncompressedContent()); slice.sequenceId = ITF8.readUnsignedITF8(parseInputStream); slice.alignmentStart = ITF8.readUnsignedITF8(parseInputStream); slice.alignmentSpan = ITF8.readUnsignedITF8(parseInputStream); slice.nofRecords = ITF8.readUnsignedITF8(parseInputStream); slice.globalRecordCounter = LTF8.readUnsignedLTF8(parseInputStream); slice.nofBlocks = ITF8.readUnsignedITF8(parseInputStream); slice.contentIDs = CramIntArray.array(parseInputStream); slice.embeddedRefBlockContentID = ITF8.readUnsignedITF8(parseInputStream); slice.refMD5 = new byte[16]; InputStreamUtils.readFully(parseInputStream, slice.refMD5, 0, slice.refMD5.length); final byte[] bytes = InputStreamUtils.readFully(parseInputStream); if (major >= CramVersions.CRAM_v3.major) { slice.sliceTags = BinaryTagCodec.readTags(bytes, 0, bytes.length, ValidationStringency.DEFAULT_STRINGENCY); SAMBinaryTagAndValue tags = slice.sliceTags; while (tags != null) { log.debug(String.format("Found slice tag: %s", SAMTag.makeStringTag(tags.tag))); tags = tags.getNext(); } } }
Source:
void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.vaultUrl = (tokens.length >= 1 ? tokens[1] : null); this.name = (tokens.length >= 3 ? tokens[2] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } }

Target:
void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.vaultUrl = (tokens.length >= 2 ? tokens[1] : null); this.name = (tokens.length >= 3 ? tokens[2] : null); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault endpoint url is malformed.", e)); } } }
Source:
public void validateSurveillanceAuthority(Surveillance surv) { Boolean hasOncStaff = Util.isUserRoleOncStaff(); Boolean hasAcbAdmin = Util.isUserRoleAcbAdmin(); if(surv.getAuthority() == null){ if(hasAcbAdmin && hasOncStaff){ surv.getErrorMessages().add("User cannot have authority for " + Authority.ROLE_ONC_STAFF + " and " + Authority.ROLE_ACB_ADMIN + "."); } } else { if(!surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ACB_ADMIN) && !surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ONC_STAFF)){ surv.getErrorMessages().add("Surveillance must have authority for " + Authority.ROLE_ONC_STAFF + " or " + Authority.ROLE_ACB_ADMIN); } else if(surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ONC_STAFF) && !hasOncStaff){ surv.getErrorMessages().add("User must have authority " + Authority.ROLE_ONC_STAFF); } } }

Target:
public void validateSurveillanceAuthority(Surveillance surv) { if(!StringUtils.isEmpty(surv.getAuthority())){ if(!surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ADMIN) && !surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ACB_ADMIN) && !surv.getAuthority().equalsIgnoreCase(Authority.ROLE_ACB_STAFF)){ surv.getErrorMessages().add("Surveillance must have authority for " + Authority.ROLE_ADMIN + " or " + Authority.ROLE_ACB_ADMIN + " or " + Authority.ROLE_ACB_STAFF); } } }
Source:
protected Configuration createConfiguration(String name) throws Exception { FileConfiguration fc = new FileConfiguration(); fc.setPagingDirectory(getTestDir() + "/" + name + "/" + fc.getPagingDirectory()); fc.setLargeMessagesDirectory(getTestDir() + "/" + name + "/" + fc.getLargeMessagesDirectory()); fc.setJournalDirectory(getTestDir() + "/" + name + "/" + fc.getJournalDirectory()); fc.setBindingsDirectory(getTestDir() + "/" + name + "/" + fc.getBindingsDirectory()); addMqttTransportConfiguration(fc); addWildCardConfiguration(fc); fc.setSecurityEnabled(true); return fc; }

Target:
protected Configuration createConfiguration(String name) throws Exception { Configuration configuration = createDefaultNettyConfig(); configuration.setPagingDirectory(getTestDir() + "/" + name + "/" + configuration.getPagingDirectory()); configuration.setLargeMessagesDirectory(getTestDir() + "/" + name + "/" + configuration.getLargeMessagesDirectory()); configuration.setJournalDirectory(getTestDir() + "/" + name + "/" + configuration.getJournalDirectory()); configuration.setBindingsDirectory(getTestDir() + "/" + name + "/" + configuration.getBindingsDirectory()); addMqttTransportConfiguration(configuration); addWildCardConfiguration(configuration); configuration.setSecurityEnabled(true); return configuration; }
Source:
public boolean matchEvents() { if (!(fTraces.length > 0)) { return false; } initMatching(); for (int i = 0; i < fTraces.length; i++) { EventMatchingBuildRequest request = new EventMatchingBuildRequest(this, i); fTraces[i].sendRequest(request); try { request.waitForCompletion(); } catch (InterruptedException e) { } } finalizeMatching(); return true; }

Target:
public boolean matchEvents() { if (!(fTraces.length > 0)) { return false; } initMatching(); for (int i = 0; i < fTraces.length; i++) { EventMatchingBuildRequest request = new EventMatchingBuildRequest(this, i); fTraces[i].sendRequest(request); try { request.waitForCompletion(); } catch (InterruptedException e) { Activator.logInfo(e.getMessage()); } } finalizeMatching(); return true; }
Source:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (!first.eCrossReferences().isEmpty() && !second.eCrossReferences().isEmpty()) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; }

Target:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (first.eCrossReferences() != null && second.eCrossReferences() != null) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; }
Source:
void initialize(boolean engineStartup, List<String> macsForMacPool) { log.info("Initializing %s", this); this.macsStorage = createMacsStorage(this.rangesBoundaries); System.out.println(String.format("Initializing %s with macs: %s", this, macsForMacPool)); List<String> notAddedMacs = addMacs(macsForMacPool); if (!notAddedMacs.isEmpty()) { if (engineStartup) { String auditLogMessage = "Following MACs violates duplicity restriction, and was pushed into MAC pool without respect to it:" + notAddedMacs; auditLogDirector.log(new AuditLogableImpl(), AuditLogType.MAC_ADDRESS_VIOLATES_NO_DUPLICATES_SETTING, auditLogMessage); forceAddMacs(notAddedMacs); } else { throw new EngineException(EngineError.MAC_POOL_INITIALIZATION_FAILED, "Unable to initialize MAC pool due to existing duplicates"); } } log.info("Finished initializing %s. Available MACs in pool: %s", this, macsStorage.getAvailableMacsCount()); }

Target:
void initialize(boolean engineStartup, List<String> macsForMacPool) { log.info("Initializing {}", this); this.macsStorage = createMacsStorage(this.rangesBoundaries); log.debug("Initializing with macs: {}", this, macsForMacPool); List<String> notAddedMacs = addMacs(macsForMacPool); if (!notAddedMacs.isEmpty()) { if (engineStartup) { String auditLogMessage = "Following MACs violates duplicity restriction, and was pushed into MAC pool without respect to it:" + notAddedMacs; auditLogDirector.log(new AuditLogableImpl(), AuditLogType.MAC_ADDRESS_VIOLATES_NO_DUPLICATES_SETTING, auditLogMessage); forceAddMacs(notAddedMacs); } else { throw new EngineException(EngineError.MAC_POOL_INITIALIZATION_FAILED, "Unable to initialize MAC pool due to existing duplicates"); } } log.info("Finished initializing {}. Available MACs in pool: {}", this, macsStorage.getAvailableMacsCount()); }
Source:
public Disk update(Disk incoming) { if (incoming.isSetQcowVersion()) { return performUpdate( incoming, new QueryIdResolver<>(QueryType.GetDiskByDiskId, IdQueryParameters.class), ActionType.AmendImageGroupVolumes, new UpdateParametersProvider()); } throw new WebApplicationException(Response.Status.CONFLICT); }

Target:
public Disk update(Disk incoming) { if (incoming.isSetQcowVersion()) { return performUpdate( incoming, new QueryIdResolver<>(QueryType.GetDiskByDiskId, IdQueryParameters.class), ActionType.AmendImageGroupVolumes, new UpdateParametersProvider()); } throw new WebFaultException(null, localize(Messages.DISK_UPDATE_NOT_PERMITTED), Response.Status.CONFLICT); }
Source:
public static ServiceCachingPolicy getMultiThreadedClientPolicy() { return DEFAULT_MULTI_THREAD_CLIENTS_POLICY; }

Target:
public static ServiceCachingPolicy getMultiThreadedClientPolicy() { return DEFAULT_MULTI_THREADED_CLIENTS_POLICY; }
Source:
String[] getProgramArguments() throws IOException { LOGGER.entering(); List<String> args = new LinkedList<String>(); args.addAll(Arrays.asList(super.getProgramArguments())); Iterator<Entry<String, JsonElement>> iterator = defaultArgs.entrySet().iterator(); while (iterator.hasNext()) { String key = iterator.next().getKey(); if (!args.contains(key)) { args.add(key); String val = defaultArgs.get(key).getAsString(); if (StringUtils.isNotBlank(val)) { args.add(val); } } } List<String> filteredArgs = new LinkedList<String>(); filteredArgs.add(SELION_CONFIG_ARG); filteredArgs.add(SELION_NOCONTINUOS_ARG); for (String filter : filteredArgs) { if (!filter.equals(SELION_NOCONTINUOS_ARG)) { args.remove(args.indexOf(filter) + 1); } args.remove(filter); } LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); }

Target:
String[] getProgramArguments() throws IOException { LOGGER.entering(); List<String> args = new LinkedList<String>(Arrays.asList(super.getProgramArguments())); for (Entry<String, JsonElement> entry : defaultArgs.entrySet()) { String key = entry.getKey(); if (!args.contains(key)) { args.add(key); String val = defaultArgs.get(key).getAsString(); if (StringUtils.isNotBlank(val)) { args.add(val); } } } List<String> filteredArgs = new LinkedList<String>(); filteredArgs.add(SELION_CONFIG_ARG); filteredArgs.add(SELION_NOCONTINUOUS_ARG); for (String filter : filteredArgs) { if (!filter.equals(SELION_NOCONTINUOUS_ARG)) { args.remove(args.indexOf(filter) + 1); } args.remove(filter); } LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); }
Source:
public void testAdsOnFilePageOasis() throws Exception { AdsBaseObject ads = buildAdsObjectForPage("File:Example.jpg"); String adUnit = "wka.life/_project43 verifySlotHasCorrectAd( ads, "TOP_LEADERBOARD", adUnit, "271491732" ); verifySlotHasCorrectAd( ads, "TOP_RIGHT_BOXAD", adUnit, "271491732" ); ads.scrollToPosition("#articleCategories"); verifySlotHasCorrectAd( ads, "BOTTOM_LEADERBOARD", adUnit, "271491732" ); }

Target:
public void testAdsOnFilePageOasis() throws Exception { AdsBaseObject ads = buildAdsObjectForPage("File:Example.jpg"); String adUnit = "wka.life/_project43 verifySlotHasCorrectAd( ads, AdsContent.TOP_LB, adUnit, PROJECT43_TEST_LINE_ITEM_ID ); verifySlotHasCorrectAd( ads, AdsContent.MEDREC, adUnit, PROJECT43_TEST_LINE_ITEM_ID ); ads.scrollToPosition("#articleCategories"); verifySlotHasCorrectAd( ads, AdsContent.BOTTOM_LB, adUnit, PROJECT43_TEST_LINE_ITEM_ID ); }
Source:
public <T extends Rollup> Points<T> getDataToRoll(Class<T> type, final Locator locator, Range range, ColumnFamily<Locator, Long> cf) throws IOException { AbstractSerializer serializer = Serializers.serializerFor(type); if (cf == CassandraModel.CF_METRICS_FULL) { serializer = Serializers.simpleNumberSerializer; } else if ( cf == CassandraModel.CF_METRICS_PREAGGREGATED_FULL) { if (type.equals(BluefloodTimerRollup.class)) { serializer = Serializers.timerRollupInstance; } else if (type.equals(BluefloodSetRollup.class)) { serializer = Serializers.setRollupInstance; } else if (type.equals(BluefloodGaugeRollup.class)) { serializer = Serializers.gaugeRollupInstance; } else if (type.equals(BluefloodCounterRollup.class)) { serializer = Serializers.counterRollupInstance; } else { serializer = Serializers.simpleNumberSerializer; } } ColumnList<Long> cols = getColumnsFromDB(locator, cf, range); Points<T> points = new Points<T>(); try { for (Column<Long> col : cols) { points.add(new Points.Point<T>(col.getName(), (T)col.getValue(serializer))); } if ( cf == CassandraModel.CF_METRICS_FULL || cf == CassandraModel.CF_METRICS_PREAGGREGATED_FULL ) { Instrumentation.getRawPointsIn5MinHistogram().update(points.getPoints().size()); } } catch (RuntimeException ex) { log.error("Problem deserializing data for " + locator + " (" + range + ") from " + cf.getName(), ex); throw new IOException(ex); } return points; }

Target:
public <T extends Rollup> Points<T> getDataToRoll(Class<T> type, final Locator locator, Range range, ColumnFamily<Locator, Long> cf) throws IOException { AbstractSerializer serializer = Serializers.serializerFor(type); if (cf == CassandraModel.CF_METRICS_FULL) { serializer = Serializers.simpleNumberSerializer; } else if ( cf == CassandraModel.CF_METRICS_PREAGGREGATED_FULL) { if (type.equals(BluefloodTimerRollup.class)) { serializer = Serializers.timerRollupInstance; } else if (type.equals(BluefloodSetRollup.class)) { serializer = Serializers.setRollupInstance; } else if (type.equals(BluefloodGaugeRollup.class)) { serializer = Serializers.gaugeRollupInstance; } else if (type.equals(BluefloodCounterRollup.class)) { serializer = Serializers.counterRollupInstance; } else { serializer = Serializers.simpleNumberSerializer; } } ColumnList<Long> cols = getColumnsFromDB(locator, cf, range); Points<T> points = new Points<T>(); try { for (Column<Long> col : cols) { points.add(new Points.Point<T>(col.getName(), (T)col.getValue(serializer))); } if ( cf == CassandraModel.CF_METRICS_FULL ) { Instrumentation.getRawPointsIn5MinHistogram().update(points.getPoints().size()); } } catch (RuntimeException ex) { log.error("Problem deserializing data for " + locator + " (" + range + ") from " + cf.getName(), ex); throw new IOException(ex); } return points; }
Source:
public void testParseHeader() { Bundle carbonCoreBundle = Arrays.asList(bundleContext.getBundles()).stream() .filter(b -> b.getSymbolicName().equals("org.wso2.carbon.sample.deployer.mgt")).findFirst().get(); String headerValue = carbonCoreBundle.getHeaders().get(CARBON_COMPONENT); try { List<ManifestElement> elements = ManifestElement .parseHeader(CARBON_COMPONENT, headerValue, bundleContext.getBundle()); Assert.assertTrue(elements.size() > 0); ManifestElement firstElement = elements.get(0); String value = firstElement.getValue(); String strRepresentation = firstElement.toString(); String[] elementsInManifest = strRepresentation.split(";"); List<String> keys = Collections.list(firstElement.getKeys()); Assert.assertEquals("startup.listener", value); Assert.assertEquals(elementsInManifest.length, 3); Assert.assertEquals(keys.size(), 2); } catch (ManifestElementParserException e) { Assert.assertTrue(false); } }

Target:
public void testParseHeader() { Bundle carbonCoreBundle = Arrays.stream(bundleContext.getBundles()) .filter(b -> b.getSymbolicName().equals("org.wso2.carbon.sample.deployer.mgt")) .findFirst() .get(); String headerValue = carbonCoreBundle.getHeaders().get(CARBON_COMPONENT); try { List<ManifestElement> elements = ManifestElement .parseHeader(CARBON_COMPONENT, headerValue, bundleContext.getBundle()); Assert.assertTrue(elements.size() > 0); ManifestElement firstElement = elements.get(0); String value = firstElement.getValue(); String strRepresentation = firstElement.toString(); String[] elementsInManifest = strRepresentation.split(";"); List<String> keys = Collections.list(firstElement.getKeys()); Assert.assertEquals("startup.listener", value); Assert.assertEquals(elementsInManifest.length, 3); Assert.assertEquals(keys.size(), 2); } catch (ManifestElementParserException e) { Assert.assertTrue(false); } }
Source:
public Response toResponse(RemoteException exception) { String errorId = UUID.randomUUID().toString(); Status status = Status.fromStatusCode(exception.getStatus()); if (CLIENT_ERROR.equals(status.getFamily())) { log.error("Received response status code from server handling request. errorId: {}", SafeArg.of("statusCode", status.getStatusCode()), SafeArg.of("errorId", errorId), exception); } else { log.warn("Received response status code from server handling request. errorId: {}", SafeArg.of("statusCode", status.getStatusCode()), SafeArg.of("errorId", errorId), exception); } SerializableError error = exception.getRemoteException(); ResponseBuilder builder = Response.status(status); try { builder.type(MediaType.APPLICATION_JSON); String json = JsonExceptionMapper.MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorId", errorId), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(error.getMessage()); } return builder.build(); }

Target:
public Response toResponse(RemoteException exception) { String errorId = UUID.randomUUID().toString(); Status status = Status.fromStatusCode(exception.getStatus()); if (Status.Family.CLIENT_ERROR.equals(status.getFamily())) { log.error("Received response status code from server handling request. errorId: {}", SafeArg.of("statusCode", status.getStatusCode()), SafeArg.of("errorId", errorId), exception); } else { log.info("Received response status code from server handling request. errorId: {}", SafeArg.of("statusCode", status.getStatusCode()), SafeArg.of("errorId", errorId), exception); } SerializableError error = exception.getRemoteException(); ResponseBuilder builder = Response.status(status); try { builder.type(MediaType.APPLICATION_JSON); String json = JsonExceptionMapper.MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorId", errorId), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(error.getMessage()); } return builder.build(); }
Source:
public void warnOnActiveVm() { if (activeVmAttachedToClusterPredicate.eval(networkCluster.getClusterId())) { AuditLogableBase loggable = createLoggable(); commandBase.auditLog(loggable, AuditLogType.NETWORK_UPDATE_DISPLAY_FOR_CLUSTER_WITH_ACTIVE_VM); } }

Target:
public void warnOnActiveVm() { if (activeVmAttachedToClusterPredicate.eval(networkCluster.getClusterId())) { AuditLogableBase loggable = createLoggable(); auditLog.log(loggable, AuditLogType.NETWORK_UPDATE_DISPLAY_FOR_CLUSTER_WITH_ACTIVE_VM); } }
Source:
public URI read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return Problem.DEFAULT_TYPE; } try { String nextString = in.nextString(); return "null".equals(nextString) ? Problem.DEFAULT_TYPE : new URI(nextString); } catch (URISyntaxException e) { throw new JsonIOException(e); } }

Target:
public URI read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return Problem.DEFAULT_TYPE; } try { String nextString = in.nextString(); return new URI(nextString); } catch (URISyntaxException e) { throw new JsonIOException(e); } }
Source:
@Override public void set(String key, Bitmap bitmap) { if (key == null || bitmap == null) { throw new NullPointerException("key == null || bitmap == null"); } Bitmap previous; synchronized (this) { int addedSize = Utils.getBitmapBytes(bitmap); if (addedSize > maxSize) { return; } putCount++; size += addedSize; previous = map.put(key, bitmap); if (previous != null) { size -= Utils.getBitmapBytes(previous); } } trimToSize(maxSize); }

Target:
@Override public void set(String key, Bitmap bitmap) { if (key == null || bitmap == null) { throw new NullPointerException("key == null || bitmap == null"); } int addedSize = Utils.getBitmapBytes(bitmap); if (addedSize > maxSize) { return; } synchronized (this) { putCount++; size += addedSize; Bitmap previous = map.put(key, bitmap); if (previous != null) { size -= Utils.getBitmapBytes(previous); } } trimToSize(maxSize); }
Source:
public void onDelete(@NonNull ReadingList readingList) { showDeleteListUndoSnackbar(readingList); ReadingList.DAO.removeList(readingList); funnel.logDeleteList(readingList, readingLists.size()); updateLists(); if (callback() != null) { callback().onReadingListModified(); } }

Target:
public void onDelete(@NonNull ReadingList readingList) { showDeleteListUndoSnackbar(readingList); ReadingList.DAO.removeList(readingList); funnel.logDeleteList(readingList, readingLists.size()); updateLists(); }
Source:
protected abstract JDBCLoaderProperties createConfig() throws IOException; protected abstract String[] getScripts(); protected abstract String[] getSampleConfigurations(); protected String pref(String s) { return s.replace("${pref}", prefix); }

Target:
protected abstract JDBCLoaderProperties createConfig() throws IOException; protected abstract String[] getScripts(); protected abstract String[] getSampleConfigurations(); protected String replacePrefix(String s) { return s.replace("${prefix}", prefix); }
Source:
private ConfigurationDto mergeOutputSettings(final ConfigurationDto originalConfig, final List<DeviceOutputSetting> outputSettings) { if (originalConfig.getRelayConfiguration() != null) { return originalConfig; } List<RelayMapDto> relayMap = new ArrayList<>(); RelayConfigurationDto relayConfig = new RelayConfigurationDto(relayMap); outputSettings.forEach(outputSetting -> relayMap.add(new com.alliander.osgp.dto.valueobjects.RelayMapDto( outputSetting.getExternalId(), outputSetting.getInternalId(), RelayTypeDto.valueOf(outputSetting.getOutputType().toString()), outputSetting.getAlias())) ); return new ConfigurationDto(originalConfig.getLightType(), originalConfig.getDaliConfiguration(), relayConfig, originalConfig.getShortTermHistoryIntervalMinutes(), originalConfig.getPreferredLinkType(), originalConfig.getMeterType(), originalConfig.getLongTermHistoryInterval(), originalConfig.getLongTermHistoryIntervalType()); }

Target:
private ConfigurationDto mergeOutputSettings(final ConfigurationDto originalConfig, final List<DeviceOutputSetting> outputSettings) { if (originalConfig.getRelayConfiguration() != null && originalConfig.getRelayConfiguration().getRelayMap() != null && !originalConfig.getRelayConfiguration().getRelayMap().isEmpty()) { return originalConfig; } final List<RelayMapDto> relayMap = new ArrayList<>(); outputSettings.forEach(outputSetting -> relayMap.add(new com.alliander.osgp.dto.valueobjects.RelayMapDto( outputSetting.getExternalId(), outputSetting.getInternalId(), RelayTypeDto.valueOf(outputSetting.getOutputType().toString()), outputSetting.getAlias())) ); final RelayConfigurationDto relayConfig = new RelayConfigurationDto(relayMap); return new ConfigurationDto(originalConfig.getLightType(), originalConfig.getDaliConfiguration(), relayConfig, originalConfig.getShortTermHistoryIntervalMinutes(), originalConfig.getPreferredLinkType(), originalConfig.getMeterType(), originalConfig.getLongTermHistoryInterval(), originalConfig.getLongTermHistoryIntervalType()); }
Source:
public void testGetRangerAWSCloudStorageServiceConfigs() { CmTemplateProcessor templateProcessor = mock(CmTemplateProcessor.class); TemplatePreparationObject preparationObject = getTemplatePreparationObjectForAWS(true) .withBlueprintView(mock(BlueprintView.class)) .withProductDetails(new ClouderaManagerRepo().withVersion("7.2.1"), List.of()) .build(); List<ApiClusterTemplateConfig> serviceConfigs = underTest.getServiceConfigs(templateProcessor, preparationObject); assertEquals(1, serviceConfigs.size()); assertEquals(RANGER_HDFS_AUDIT_URL, serviceConfigs.get(0).getName()); assertEquals("s3a://bucket/ranger/auditlogs", serviceConfigs.get(0).getValue()); }

Target:
public void testGetRangerAWSCloudStorageServiceConfigs() { CmTemplateProcessor templateProcessor = mock(CmTemplateProcessor.class); TemplatePreparationObject preparationObject = getTemplatePreparationObjectForAWS(true) .withBlueprintView(mock(BlueprintView.class)) .withProductDetails(new ClouderaManagerRepo().withVersion("7.2.1"), List.of()) .build(); List<ApiClusterTemplateConfig> serviceConfigs = underTest.getServiceConfigs(templateProcessor, preparationObject); assertEquals(1, serviceConfigs.size()); assertEquals("ranger_plugin_hdfs_audit_url", serviceConfigs.get(0).getName()); assertEquals("s3a://bucket/ranger/auditlogs", serviceConfigs.get(0).getValue()); }
Source:
public Collection<List<String>> getLinesToDisplay(JobOutput output){ if(this.model.getSelectionTarget() == SelectionTarget.TASK_TARGET){ Task task = this.parentController.getSelectedTask(); List<String> lines = output.getLines(task); Collection<List<String>> result = new ArrayList<List<String>>(); if(lines != null){ result.add(lines); } return result; } else{ return output.getLines(); } }

Target:
public Collection<List<String>> getLinesToDisplay(JobOutput output){ if(this.model.getSelectionTarget() == SelectionTarget.TASK_TARGET){ Task task = this.parentController.getSelectedTask(); List<String> lines = output.getLines(task); Collection<List<String>> result = new ArrayList<List<String>>(1); if(lines != null){ result.add(lines); } return result; } else{ return output.getLines(); } }
Source:
private void verboseTroubleStatusHandler(EventObject event) { DSCAlarmEvent dscAlarmEvent = (DSCAlarmEvent) event; APIMessage apiMessage = dscAlarmEvent.getAPIMessage(); DSCAlarmItemType[] dscAlarmItemTypes = { DSCAlarmItemType.PANEL_SERVICE_REQUIRED, DSCAlarmItemType.PANEL_AC_TROUBLE, DSCAlarmItemType.PANEL_TELEPHONE_TROUBLE, DSCAlarmItemType.PANEL_FTC_TROUBLE, DSCAlarmItemType.PANEL_ZONE_FAULT, DSCAlarmItemType.PANEL_ZONE_TAMPER, DSCAlarmItemType.PANEL_ZONE_LOW_BATTERY, DSCAlarmItemType.PANEL_TIME_LOSS }; String itemName; int bitField = Integer.decode("0x" + apiMessage.getAPIData()); int[] masks = { 1, 2, 4, 8, 16, 32, 64, 128 }; int[] bits = new int[8]; for (int i = 0; i < 8; i++) { bits[i] = bitField & masks[i]; itemName = getItemName(dscAlarmItemTypes[i], 0, 0); if (itemName != "") { updateItem(itemName, bits[i] != 0 ? 1 : 0, ""); } } }

Target:
private void verboseTroubleStatusHandler(EventObject event) { DSCAlarmEvent dscAlarmEvent = (DSCAlarmEvent) event; APIMessage apiMessage = dscAlarmEvent.getAPIMessage(); DSCAlarmItemType[] dscAlarmItemTypes = { DSCAlarmItemType.PANEL_SERVICE_REQUIRED, DSCAlarmItemType.PANEL_AC_TROUBLE, DSCAlarmItemType.PANEL_TELEPHONE_TROUBLE, DSCAlarmItemType.PANEL_FTC_TROUBLE, DSCAlarmItemType.PANEL_ZONE_FAULT, DSCAlarmItemType.PANEL_ZONE_TAMPER, DSCAlarmItemType.PANEL_ZONE_LOW_BATTERY, DSCAlarmItemType.PANEL_TIME_LOSS }; String itemName; int bitField = Integer.decode("0x" + apiMessage.getAPIData()); int[] masks = { 1, 2, 4, 8, 16, 32, 64, 128 }; int[] bits = new int[8]; for (int i = 0; i < 8; i++) { bits[i] = bitField & masks[i]; itemName = getItemName(dscAlarmItemTypes[i], 0, 0); if (StringUtils.isNotEmpty(itemName)) { updateItem(itemName, bits[i] != 0 ? 1 : 0, ""); } } }
Source:
public LObject<T> nextObject() { LObject<T> object = queue.poll(); if (object != null) { queue.add(object); } return object; }

Target:
public LObject<T> nextObject() { return queue.peek(); }