auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void zip(OutputStream outputStream, VirtualFile dir, String glob) throws IOException { ZipOutputStream zos = new ZipOutputStream(outputStream); zos.setEncoding(System.getProperty("file.encoding")); for (String n : dir.list(glob.length() == 0 ? "**" : glob)) { String relativePath; if (glob.length() == 0) { relativePath = dir.getName() + '/' + n; } else { relativePath = n; } ZipEntry e = new ZipEntry(File.separatorChar == '\\' ? relativePath.replace('\\', '/') : relativePath); VirtualFile f = dir.child(n); e.setTime(f.lastModified()); zos.putNextEntry(e); InputStream in = f.open(); try { Util.copyStream(in, zos); } finally { IOUtils.closeQuietly(in); } zos.closeEntry(); } zos.close(); }

Target:
private static void zip(OutputStream outputStream, VirtualFile dir, String glob) throws IOException { ZipOutputStream zos = new ZipOutputStream(outputStream); zos.setEncoding(System.getProperty("file.encoding")); for (String n : dir.list(glob.length() == 0 ? "**" : glob)) { String relativePath; if (glob.length() == 0) { relativePath = dir.getName() + '/' + n; } else { relativePath = n; } ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); VirtualFile f = dir.child(n); e.setTime(f.lastModified()); zos.putNextEntry(e); InputStream in = f.open(); try { Util.copyStream(in, zos); } finally { IOUtils.closeQuietly(in); } zos.closeEntry(); } zos.close(); }
Source:
public <K, JM extends Message<K, ?>, RM extends Message> MessageStream<RM> join(MessageStream<JM> otherStream, JoinFunction<M, JM, RM> joinFn) { MessageStreamImpl<RM> outputStream = new MessageStreamImpl<>(); BiFunction<M, JM, RM> parJoin1 = joinFn::apply; BiFunction<JM, M, RM> parJoin2 = (m, t1) -> joinFn.apply(t1, m); ((MessageStreamImpl<JM>) otherStream).getRegisteredOperatorSpecs().add( OperatorSpecs.<JM, K, M, RM>createPartialJoinOperator(parJoin2, outputStream)); this.getRegisteredOperatorSpecs().add(OperatorSpecs.<M, K, JM, RM>createPartialJoinOperator(parJoin1, outputStream)); return outputStream; }

Target:
public <K, JM extends MessageEnvelope<K, ?>, RM extends MessageEnvelope> MessageStream<RM> join( MessageStream<JM> otherStream, JoinFunction<M, JM, RM> joinFn) { MessageStreamImpl<RM> outputStream = new MessageStreamImpl<>(); BiFunction<M, JM, RM> parJoin1 = joinFn::apply; BiFunction<JM, M, RM> parJoin2 = (m, t1) -> joinFn.apply(t1, m); ((MessageStreamImpl<JM>) otherStream).registeredOperatorSpecs.add( OperatorSpecs.createPartialJoinOperator(parJoin2, outputStream)); this.registeredOperatorSpecs.add(OperatorSpecs.createPartialJoinOperator(parJoin1, outputStream)); return outputStream; }
Source:
private void closeMultiFiles() throws IOException { headerOut.close(); headerOutLong.close(); valuesOut.close(); Preconditions.checkState( headerOutLong.getCount() == (numWritten * 8), "numWritten[%s] number of rows should have [%s] bytes written to headerOutLong, had[%s]", numWritten, numWritten * 8, headerOutLong.getCount() ); Preconditions.checkState( headerOutLong.getCount() < Integer.MAX_VALUE, "Wrote[%s] bytes in header file, which is too many.", headerOutLong.getCount() ); }

Target:
private void closeMultiFiles() throws IOException { headerOutLong.close(); Preconditions.checkState( headerOutLong.getCount() == (numWritten * Longs.BYTES), "numWritten[%s] number of rows should have [%s] bytes written to headerOutLong, had[%s]", numWritten, numWritten * Longs.BYTES, headerOutLong.getCount() ); Preconditions.checkState( headerOutLong.getCount() < (Integer.MAX_VALUE & ~PAGE_SIZE), "Wrote[%s] bytes in header file, which is too many.", headerOutLong.getCount() ); }
Source:
public <T extends Throwable> boolean handle(final T throwable, final Object controller, final String controllerName, final String actionName) { Assert.requireNonNull(throwable, "throwable"); Assert.requireNonNull(controller, "controller"); Assert.requireNonBlank(controllerName, "controllerName"); Assert.requireNonBlank(actionName, "actionName"); final ActionExceptionEventImpl exceptionEvent = new ActionExceptionEventImpl(actionName, controllerName, throwable); final List<Consumer<ActionExceptionEvent<T>>> consumers = new ArrayList<>(); consumers.addAll(getConsumersForTypeInController(throwable.getClass(), controller)); LOG.debug("Found handlers to handle action exception of type {}", consumers.size(), throwable.getClass()); final Iterator<Consumer<ActionExceptionEvent<T>>> iterator = consumers.iterator(); while (!exceptionEvent.isAborted() && iterator.hasNext()) { final Consumer<ActionExceptionEvent<T>> handler = iterator.next(); try { handler.accept(exceptionEvent); } catch (Exception e) { LOG.error("Error in calling exception handler for error of type '" + throwable.getClass() + "' thrown by action '" + exceptionEvent.getActionName() + "' of controller '" + exceptionEvent.getControllerName() + "'!", e); } } return exceptionEvent.isAborted(); }

Target:
public <T extends Throwable> boolean handle(final T throwable, final Object controller, final String controllerName, final String actionName) { Assert.requireNonNull(throwable, "throwable"); Assert.requireNonNull(controller, "controller"); Assert.requireNonBlank(controllerName, "controllerName"); Assert.requireNonBlank(actionName, "actionName"); final ActionExceptionEventImpl exceptionEvent = new ActionExceptionEventImpl(actionName, controllerName, throwable); final List<Consumer<ActionExceptionEvent<T>>> consumers = new ArrayList<>(); consumers.addAll(getConsumersForTypeInController(throwable.getClass(), controller)); LOG.debug("Found handlers to handle action exception of type {}", consumers.size(), throwable.getClass()); final Iterator<Consumer<ActionExceptionEvent<T>>> iterator = consumers.iterator(); while (!exceptionEvent.isAborted() && iterator.hasNext()) { final Consumer<ActionExceptionEvent<T>> handler = iterator.next(); try { handler.accept(exceptionEvent); } catch (final Exception e) { LOG.error("Error in calling exception handler for error of type '" + throwable.getClass() + "' thrown by action '" + exceptionEvent.getActionName() + "' of controller '" + exceptionEvent.getControllerName() + "'!", e); } } return exceptionEvent.isAborted(); }
Source:
public MotorIdle(Motor motor) { super("MotorIdle"); this.motor = motor; requires(motor); setInterruptible(true); LogKitten.d("MotorIdle created"); }

Target:
public MotorIdle(Motor motor) { this("MotorIdle", motor); }
Source:
private boolean check(File fingerprintFile, TaskListener listener) { try { Fingerprint fp = loadFingerprint(fingerprintFile); if (fp == null || (!fp.isAlive() && fp.getFacetBlockingDeletion() == null) ) { listener.getLogger().println("deleting obsolete " + fingerprintFile); fingerprintFile.delete(); return true; } else { if (!fp.isAlive()) { FingerprintFacet deletionBlockerFacet = fp.getFacetBlockingDeletion(); listener.getLogger().println(deletionBlockerFacet.getClass().getName() + " created at timestamp: " + deletionBlockerFacet.getTimestamp() + " blocked deletion of " + fingerprintFile); } fp = getFingerprint(fp); return fp.trim(); } } catch (IOException e) { Functions.printStackTrace(e, listener.error("Failed to process " + fingerprintFile)); return false; } }

Target:
private boolean check(File fingerprintFile, TaskListener listener) { try { Fingerprint fp = loadFingerprint(fingerprintFile); if (fp == null || (!fp.isAlive() && fp.getFacetBlockingDeletion() == null) ) { listener.getLogger().println("deleting obsolete " + fingerprintFile); fingerprintFile.delete(); return true; } else { if (!fp.isAlive()) { FingerprintFacet deletionBlockerFacet = fp.getFacetBlockingDeletion(); listener.getLogger().println(deletionBlockerFacet.getClass().getName() + " created on " + new Date(deletionBlockerFacet.getTimestamp()) + " blocked deletion of " + fingerprintFile); } fp = getFingerprint(fp); return fp.trim(); } } catch (IOException e) { Functions.printStackTrace(e, listener.error("Failed to process " + fingerprintFile)); return false; } }
Source:
protected String[] customCommandLineValidation() { if (BARCODE_PARAMS != null) { LIBRARY_PARAMS = BARCODE_PARAMS; } final ArrayList<String> messages = new ArrayList<String>(); readStructure = new ReadStructure(READ_STRUCTURE); if (!readStructure.sampleBarcodes.isEmpty() && LIBRARY_PARAMS == null) { messages.add("BARCODE_PARAMS or LIBRARY_PARAMS is missing. If READ_STRUCTURE contains a B (barcode)" + " then either LIBRARY_PARAMS or BARCODE_PARAMS(deprecated) must be provided!"); } if (READ_GROUP_ID == null) { READ_GROUP_ID = RUN_BARCODE.substring(0, 5) + "." + LANE; } if (!TAG_PER_MOLECULAR_INDEX.isEmpty() && TAG_PER_MOLECULAR_INDEX.size() != readStructure.molecularBarcode.length()) { messages.add("The number of tags given in TAG_PER_MOLECULAR_INDEX does not match the number of molecular indexes in READ_STRUCTURE"); } if ((FIVE_PRIME_ADAPTER != null && THREE_PRIME_ADAPTER == null) || (THREE_PRIME_ADAPTER != null && FIVE_PRIME_ADAPTER == null)) { messages.add("Either both or neither of THREE_PRIME_ADAPTER and FIVE_PRIME_ADAPTER must be set."); } if (messages.isEmpty()) { return null; } return messages.toArray(new String[messages.size()]); }

Target:
protected String[] customCommandLineValidation() { if (BARCODE_PARAMS != null) { LIBRARY_PARAMS = BARCODE_PARAMS; } final ArrayList<String> messages = new ArrayList<String>(); readStructure = new ReadStructure(READ_STRUCTURE); if (!readStructure.sampleBarcodes.isEmpty() && LIBRARY_PARAMS == null) { messages.add("BARCODE_PARAMS or LIBRARY_PARAMS is missing. If READ_STRUCTURE contains a B (barcode)" + " then either LIBRARY_PARAMS or BARCODE_PARAMS(deprecated) must be provided!"); } if (READ_GROUP_ID == null) { READ_GROUP_ID = RUN_BARCODE.substring(0, 5) + "." + LANE; } if (!TAG_PER_MOLECULAR_INDEX.isEmpty() && TAG_PER_MOLECULAR_INDEX.size() != readStructure.molecularBarcode.length()) { messages.add("The number of tags given in TAG_PER_MOLECULAR_INDEX does not match the number of molecular indexes in READ_STRUCTURE"); } if ((FIVE_PRIME_ADAPTER == null) != (THREE_PRIME_ADAPTER == null)) { messages.add("THREE_PRIME_ADAPTER and FIVE_PRIME_ADAPTER must either both be null or both be set."); } if (messages.isEmpty()) { return null; } return messages.toArray(new String[messages.size()]); }
Source:
public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, parent); }

Target:
public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); }
Source:
public static void populateChoicePanel(Context context, Button choicePanel, DialogChoiceItem item, boolean iconToLeft) { choicePanel.setText(item.text); choicePanel.setOnClickListener(item.listener); if (item.iconResId != -1) { Drawable icon = context.getResources().getDrawable(item.iconResId); if (iconToLeft) { choicePanel.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } else { choicePanel.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null); } } }

Target:
public static void populateChoicePanel(Context context, Button choicePanel, DialogChoiceItem item, boolean iconToLeft) { choicePanel.setText(item.text); choicePanel.setOnClickListener(item.listener); if (item.iconResId != -1) { Drawable icon = ContextCompat.getDrawable(context, item.iconResId); if (iconToLeft) { choicePanel.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } else { choicePanel.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null); } } }
Source:
private void parityCheckAndExpungeIfMet(ChargeEntity chargeEntity) { if (!inTerminalState(chargeEntity)) { logger.info("Charge not expunged because it is not in a terminal state {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else if (parityCheckService.parityCheckChargeForExpunger(chargeEntity)) { chargeDao.expungeCharge(chargeEntity.getId()); logger.info("Charge expunged from connector {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else { if (chargeEntity.getParityCheckDate() == null) { chargeDao.updateChargeParityCheckDate(chargeEntity.getId(), ZonedDateTime.now(UTC)); logger.info("Charge cannot be expunged because parity check with ledger failed {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else { chargeDao.updateChargeParityCheckDate(chargeEntity.getId(), ZonedDateTime.now(UTC)); logger.error("Charge cannot be expunged because parity check with ledger repeatedly failed {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } } }

Target:
private void parityCheckAndExpungeIfMet(ChargeEntity chargeEntity) { boolean hasChargeBeenParityCheckedBefore = chargeEntity.getParityCheckDate() != null; if (!inTerminalState(chargeEntity)) { logger.info("Charge not expunged because it is not in a terminal state {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else if (parityCheckService.parityCheckChargeForExpunger(chargeEntity)) { chargeDao.expungeCharge(chargeEntity.getId()); logger.info("Charge expunged from connector {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else { if (hasChargeBeenParityCheckedBefore) { logger.error("Charge cannot be expunged because parity check with ledger repeatedly failed {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else { logger.info("Charge cannot be expunged because parity check with ledger failed {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } } }
Source:
private final void verifyKeptExistingData(ResultSet res, String tableName) throws Exception { res = executeString("select * from " + tableName + " where col2 = 1"); String resultSetData = resultSetToString(res); res.close(); String expected = "col4,col1,col2,col3\n" + "-------------------------------\n" + "N,1,1,17.0\n" + "N,1,1,17.0\n" + "N,1,1,30.0\n" + "N,1,1,36.0\n" + "N,1,1,36.0\n"; assertEquals(expected, resultSetData); }

Target:
private final void verifyKeptExistingData(ResultSet res, String tableName) throws Exception { res = executeString("select * from " + tableName + " where col2 = 1 order by col4, col1, col2, col3"); String resultSetData = resultSetToString(res); res.close(); String expected = "col4,col1,col2,col3\n" + "-------------------------------\n" + "N,1,1,17.0\n" + "N,1,1,17.0\n" + "N,1,1,30.0\n" + "N,1,1,36.0\n" + "N,1,1,36.0\n"; assertEquals(expected, resultSetData); }
Source:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { CreateAllSnapshotsFromVmCommand createAllSnapshotsFromVmCommand = (CreateAllSnapshotsFromVmCommand) command; if (!createAllSnapshotsFromVmCommand.finishCommand()) { setCommandEndStatus(command, true, status, childCmdIds); } else { setCommandEndStatus(command, false, status, childCmdIds); } }

Target:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { CreateAllSnapshotsFromVmCommand createAllSnapshotsFromVmCommand = (CreateAllSnapshotsFromVmCommand) command; boolean failed = createAllSnapshotsFromVmCommand.finishCommand(); setCommandEndStatus(command, failed, status, childCmdIds); }
Source:
public static void getHiveOperations(MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> hiveOperationEntities = extractor.extractMetadata(marker, "sourceType: HIVE AND type:OPERATION_EXECUTION", null).getEntities(); getFirstResult(hiveOperationEntities); Iterable<Map<String, Object>> hiveOperationRelations = extractor.extractMetadata(marker, "sourceType: HIVE AND type:OPERATION_EXECUTION", "type:LOGICAL_PHYSICAL " + "AND endpoint1SourceType:HIVE AND endpoint1Type:OPERATION_EXECUTION").getRelations(); getFirstResult(hiveOperationRelations); }

Target:
public static void getHiveOperations(MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> hiveOpEntities = extractor.extractMetadata( marker, null, "sourceType:HIVE AND type:OPERATION_EXECUTION", null) .getEntities(); getFirstResult(hiveOpEntities); Iterable<Map<String, Object>> hiveOpRelations = extractor.extractMetadata( marker, null, "sourceType:HIVE AND type:OPERATION_EXECUTION", "type:LOGICAL_PHYSICAL AND endpoint1SourceType:HIVE " + "AND endpoint1Type:OPERATION_EXECUTION").getRelations(); getFirstResult(hiveOpRelations); }
Source:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round(seconds * FACTOR); } }

Target:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round((double) seconds * FACTOR); } }
Source:
public void testServeAppInactiveApp() throws Exception { PluginIdentity pluginIdentity = new PluginIdentity("app/uri/"); when(userPermissionEvaluator.hasPermission(pluginIdentity, VIEW_PLUGIN)).thenReturn(true); App app = mock(App.class); when(app.getId()).thenReturn("id"); when(app.getUri()).thenReturn("app/uri"); when(app.getLabel()).thenReturn("label"); when(app.getDescription()).thenReturn("description"); when(app.getAppVersion()).thenReturn("v1.0.0"); when(app.includeMenuAndFooter()).thenReturn(true); when(app.getTemplateContent()).thenReturn("<h1>Test</h1>"); when(app.getAppConfig()).thenReturn("{'config': 'test'}"); when(app.getResourceFolder()).thenReturn("foo/bar"); when(app.isActive()).thenReturn(false); AppResponse appResponse = AppResponse.create(app); when(appManagerService.getAppByUri("uri")).thenReturn(appResponse); mockMvc.perform(get(AppController.URI + "/uri/")) .andExpect(status().is4xxClientError()) .andExpect(model().attribute("errorMessageResponse", ErrorMessageResponse.create("Access denied for inactive app at location /app/uri", "AM07"))) .andExpect(view().name("view-exception")); }

Target:
public void testServeAppInactiveApp() throws Exception { PluginIdentity pluginIdentity = new PluginIdentity("app/uri/"); when(userPermissionEvaluator.hasPermission(pluginIdentity, VIEW_PLUGIN)).thenReturn(true); App app = mock(App.class); when(app.getId()).thenReturn("id"); when(app.getUri()).thenReturn("uri"); when(app.getLabel()).thenReturn("label"); when(app.getDescription()).thenReturn("description"); when(app.getAppVersion()).thenReturn("v1.0.0"); when(app.includeMenuAndFooter()).thenReturn(true); when(app.getTemplateContent()).thenReturn("<h1>Test</h1>"); when(app.getAppConfig()).thenReturn("{'config': 'test'}"); when(app.getResourceFolder()).thenReturn("foo/bar"); when(app.isActive()).thenReturn(false); AppResponse appResponse = AppResponse.create(app); when(appManagerService.getAppByName("uri")).thenReturn(appResponse); mockMvc.perform(get(AppController.URI + "/uri/")) .andExpect(status().is4xxClientError()) .andExpect(model().attribute("errorMessageResponse", ErrorMessageResponse.create("Access denied for inactive app at location /app/uri", "AM07"))) .andExpect(view().name("view-exception")); }
Source:
public synchronized void evict(ServiceEndPoint endPoint) { String uniqueId = buildUniqueId(endPoint); Map<String, ServiceHandle<S>> instancesPerEndPointCopy = Maps.newHashMap(_instancesPerEndpoint); ServiceHandle<S> serviceHandle = instancesPerEndPointCopy.remove(uniqueId); _instancesPerEndpoint = instancesPerEndPointCopy; destroyService(serviceHandle); }

Target:
public synchronized void evict(ServiceEndPoint endPoint) { checkNotNull(endPoint); Timer.Context context = _evictionTimer.time(); if(_instancesPerEndpoint.containsKey(endPoint)) { ServiceHandle<S> serviceHandle = _instancesPerEndpoint.get(endPoint); _evictedList.put(endPoint, serviceHandle); } context.stop(); }
Source:
private void queryTLVInformation() { List<QueryType> queryTypes = new ArrayList<>(); List<QueryParametersBase> queryParameters = new ArrayList<>(); allExistingNics.stream().forEach(nic -> { queryTypes.add(QueryType.GetTlvsByHostNicId); queryParameters.add(new IdQueryParameters(nic.getId())); }); Frontend.getInstance().runMultipleQueries(queryTypes, queryParameters, result -> { networkTlvsByGuid = new HashMap<>(); List<QueryReturnValue> returnValues = result.getReturnValues(); IntStream.range(0, result.getReturnValues().size()).forEach(index -> { IdQueryParameters param = (IdQueryParameters) result.getParameters().get(index); List<Tlv> tlvs = returnValues.get(index).getReturnValue(); if (param != null) { networkTlvsByGuid.put(param.getId(), tlvs); } }); if (getProgress() == null) { redraw(); } }); }

Target:
private void queryTLVInformation() { List<QueryType> queryTypes = new ArrayList<>(); List<QueryParametersBase> queryParameters = new ArrayList<>(); allExistingNics.stream().forEach(nic -> { queryTypes.add(QueryType.GetTlvsByHostNicId); queryParameters.add(new IdQueryParameters(nic.getId())); }); Frontend.getInstance().runMultipleQueries(queryTypes, queryParameters, result -> { networkTlvsByGuid = new HashMap<>(); List<QueryReturnValue> returnValues = result.getReturnValues(); for (int index = 0; index < result.getReturnValues().size(); index++) { IdQueryParameters param = (IdQueryParameters) result.getParameters().get(index); List<Tlv> tlvs = returnValues.get(index).getReturnValue(); if (param != null) { networkTlvsByGuid.put(param.getId(), tlvs); } } if (getProgress() == null) { redraw(); } }); }
Source:
private BasicContentDescriptionType generateBasicDescription(Content content, @Nullable Item item) { BasicContentDescriptionType basicDescription = new BasicContentDescriptionType(); basicDescription.getSynopsis().addAll(generateSynopses(content)); basicDescription.getGenre().addAll(generateGenres(content)); basicDescription.getGenre().add(generateGenreFromSpecialization(content)); basicDescription.getGenre().add(generateGenreFromMediaType(content)); basicDescription.getLanguage().addAll(generateLanguage(content)); basicDescription.setCreditsList(generateCreditsList(content)); Optional<RelatedMaterialType> relatedMaterial; if (content instanceof Series) { relatedMaterial = Strings.isNullOrEmpty(content.getImage()) ? generateRelatedMaterial(item) : generateRelatedMaterial(content); } else if (content instanceof Brand) { relatedMaterial = generateRelatedMaterial(item); } else { relatedMaterial = generateRelatedMaterial(content); } if (relatedMaterial.isPresent()) { basicDescription.getRelatedMaterial().add(relatedMaterial.get()); } return basicDescription; }

Target:
private BasicContentDescriptionType generateBasicDescription(Content content, @Nullable Item item) { BasicContentDescriptionType basicDescription = new BasicContentDescriptionType(); basicDescription.getSynopsis().addAll(generateSynopses(content)); basicDescription.getGenre().addAll(generateGenres(content)); basicDescription.getGenre().add(generateGenreFromSpecialization(content)); basicDescription.getGenre().add(generateGenreFromMediaType(content)); basicDescription.getLanguage().addAll(generateLanguage(content)); basicDescription.setCreditsList(generateCreditsList(content)); Optional<RelatedMaterialType> relatedMaterial; if (content instanceof Series) { relatedMaterial = generateRelatedMaterial(content); if (!relatedMaterial.isPresent()) { relatedMaterial = generateRelatedMaterial(item); } } else if (content instanceof Brand) { relatedMaterial = generateRelatedMaterial(item); } else { relatedMaterial = generateRelatedMaterial(content); } if (relatedMaterial.isPresent()) { basicDescription.getRelatedMaterial().add(relatedMaterial.get()); } return basicDescription; }
Source:
public static <T extends APIObject> T constructFromJson(String json, Class <T> klass, String path) { T instance; try { instance = klass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } Type type = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> map = APIObject.fromJson(json, type); instance.setAll(map); instance.path_prefix = path; return instance; }

Target:
public static <T extends APIObject> T constructFromJson(String json, Class <T> klass, String path) { T instance; try { instance = klass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } Type type = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> map = APIObject.fromJson(json, type); instance.setAll(map); instance.pathPrefix = path; return instance; }
Source:
protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception { cancel(false); teleportee.setLastLocation(); PaperLib.getChunkAtAsync(target.getLocation()).thenAccept(chunk -> { Location loc = target.getLocation(); if (LocationUtil.isBlockUnsafeForUser(teleportee, chunk, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { if (ess.getSettings().isTeleportSafetyEnabled()) { if (ess.getSettings().isForceDisableTeleportSafety()) { PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } else { try { PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause); } catch (Exception e) { e.printStackTrace(); } } } else { try { throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } catch (Exception e) { e.printStackTrace(); } } } else { if (ess.getSettings().isForceDisableTeleportSafety()) { PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } else { if (ess.getSettings().isTeleportToCenterLocation()) { loc = LocationUtil.getRoundedDestination(loc); } PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } } }); }

Target:
protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception { cancel(false); Location loc = target.getLocation(); UserTeleportEvent event = new UserTeleportEvent(teleportee, cause, loc); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } if (teleportee.isAuthorized("essentials.back.onteleport")) { teleportee.setLastLocation(); } if (!teleportee.getBase().isEmpty()) { if (!ess.getSettings().isTeleportPassengerDismount()) { throw new Exception(tl("passengerTeleportFail")); } teleportee.getBase().eject(); } if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { if (ess.getSettings().isTeleportSafetyEnabled()) { if (ess.getSettings().isForceDisableTeleportSafety()) { PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } else { PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause); } } else { throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } } else { if (ess.getSettings().isForceDisableTeleportSafety()) { PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } else { if (ess.getSettings().isTeleportToCenterLocation()) { loc = LocationUtil.getRoundedDestination(loc); } PaperLib.teleportAsync(teleportee.getBase(), loc, cause); } } }
Source:
protected Guid getSourceStorageDomainId(Disk disk) { if (disk.getStorageDomains() != null) { StorageDomain storageDomain = disk.getStorageDomains().getStorageDomains().get(0); if (storageDomain != null) { return asGuid(storageDomain.getId()); } } return null; }

Target:
protected Guid getSourceStorageDomainId(Disk disk) { if (disk.isSetStorageDomains()) { StorageDomain storageDomain = disk.getStorageDomains().getStorageDomains().get(0); if (storageDomain != null) { return asGuid(storageDomain.getId()); } } return null; }
Source:
public ContainerCreateConfig environment(String envPropsFile, Map<String, String> env, Map mavenProps) throws IllegalArgumentException { Properties envProps = new Properties(); if (env != null && env.size() > 0) { for (Map.Entry<String, String> entry : env.entrySet()) { String value = entry.getValue(); if (value == null) { value = ""; } else if(value.contains("+")) { value = value.substring(1, value.length()); } envProps.put(entry.getKey(), StrSubstitutor.replace(value, mavenProps)); } } if (envPropsFile != null) { addPropertiesFromFile(envPropsFile, envProps); } if (envProps.size() > 0) { addEnvironment(envProps); } return this; }

Target:
public ContainerCreateConfig environment(String envPropsFile, Map<String, String> env, Map mavenProps) throws IllegalArgumentException { Properties envProps = new Properties(); if (env != null && env.size() > 0) { for (Map.Entry<String, String> entry : env.entrySet()) { String value = entry.getValue(); if (value == null) { value = ""; } else if(value.matches("^\\+\\$\\{.*\\}$")) { value = value.substring(1, value.length()); } envProps.put(entry.getKey(), StrSubstitutor.replace(value, mavenProps)); } } if (envPropsFile != null) { addPropertiesFromFile(envPropsFile, envProps); } if (envProps.size() > 0) { addEnvironment(envProps); } return this; }
Source:
public static Predicate<Resource> scalarValueAtLeast(final long v) { return new Predicate<Resource>() { @Override public boolean apply(Resource resource) { return resource.getType() == Protos.Value.Type.SCALAR && resource.getScalar().getValue() > v; } }; }

Target:
public static Predicate<Resource> scalarValueAtLeast(final long v) { return new ScalarValueAtLeast(v); }
Source:
public long getCommittedWindowId(String appId, int operatorId) { logger.debug("Getting committed windowId appId operatorId {}", appId, operatorId); try { beginTransaction(); BytesMessage message = (BytesMessage)consumer.receive(); logger.debug("Retrieved committed window messageId: {}, messageAppOperatorIdProp: {}", message.getJMSMessageID(), message.getStringProperty(APP_OPERATOR_ID)); long windowId = message.readLong(); message = getBase().getSession().createBytesMessage(); message.setStringProperty(APP_OPERATOR_ID, appId + "_" + operatorId); message.writeLong(windowId); producer.send(message); commitTransaction(); logger.debug("metaQueueName: " + metaQueueName); logger.debug("Retrieved windowId {}", windowId); return windowId; } catch (JMSException ex) { throw new RuntimeException(ex); } }

Target:
public long getCommittedWindowId(String appId, int operatorId) { logger.debug("Getting committed windowId appId operatorId {}", appId, operatorId); try { beginTransaction(); BytesMessage message = (BytesMessage)consumer.receive(); logger.debug("Retrieved committed window messageId: {}, messageAppOperatorIdProp: {}", message.getJMSMessageID(), message.getStringProperty(APP_OPERATOR_ID)); long windowId = message.readLong(); writeWindowId(appId, operatorId, windowId); commitTransaction(); logger.debug("metaQueueName: " + metaQueueName); logger.debug("Retrieved windowId {}", windowId); return windowId; } catch (JMSException ex) { throw new RuntimeException(ex); } }
Source:
public String getExitsString () { String exitsString = ""; if (this.exits != null) { int i = 1; exitsString = exitsString + " Exits: ["; for (TransportStopExit e : this.exits ) { if (e != null) { exitsString = exitsString + " " + i + ") " + e.getName() + " " + e.getLocation(); i++; } exitsString = exitsString + " ]"; } } return exitsString; }

Target:
public String getExitsString () { String exitsString = ""; String refString = ""; if (this.exits != null) { int i = 1; exitsString = exitsString + " Exits: ["; for (TransportStopExit e : this.exits ) { if (e.getRef() != null) { refString = " [ref:" + e.getRef() + "] "; } exitsString = exitsString + " " + i + ")" + refString + e.getName() + " " + e.getLocation() + " ]"; i++; } } return exitsString; }
Source:
private void createCenterLabelFigure(final EObject element) { attachmentToEdgeNameFigure = new Polyline(); attachmentToEdgeNameFigure.setLineStyle(Graphics.LINE_DASHDOT); attachmentToEdgeNameFigure.setForegroundColor(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_SELECTION)); attachmentToEdgeNameFigure.setVisible(false); this.add(attachmentToEdgeNameFigure); fFigureViewEdgeNameFigure = new SiriusWrapLabelWithAttachment(LabelViewConstants.MIDDLE_LOCATION, attachmentToEdgeNameFigure); if (element instanceof DEdge) { DEdge edge = (DEdge) element; fFigureViewEdgeNameFigure.setText(edge.getName()); fFigureViewEdgeNameFigure.setVisible(!StringUtil.isEmpty(edge.getName())); } else { fFigureViewEdgeNameFigure.setVisible(false); } fFigureViewEdgeNameFigure.setLabelAlignment(PositionConstants.CENTER); fFigureViewEdgeNameFigure.setTextWrap(true); fFigureViewEdgeNameFigure.setTextWrapAlignment(PositionConstants.CENTER); this.add(fFigureViewEdgeNameFigure); }

Target:
private void createCenterLabelFigure(final EObject element) { attachmentToEdgeNameFigure = addNewAttachmentFigure(); fFigureViewEdgeNameFigure = new SiriusWrapLabelWithAttachment(LabelViewConstants.MIDDLE_LOCATION, attachmentToEdgeNameFigure); if (element instanceof DEdge) { DEdge edge = (DEdge) element; fFigureViewEdgeNameFigure.setText(edge.getName()); fFigureViewEdgeNameFigure.setVisible(!StringUtil.isEmpty(edge.getName())); } else { fFigureViewEdgeNameFigure.setVisible(false); } fFigureViewEdgeNameFigure.setLabelAlignment(PositionConstants.CENTER); fFigureViewEdgeNameFigure.setTextWrap(true); fFigureViewEdgeNameFigure.setTextWrapAlignment(PositionConstants.CENTER); this.add(fFigureViewEdgeNameFigure); }
Source:
private void checkUserCredentialsWithOrgUnit(Credentials credentials, boolean fromNetWorkError) { if (insertedCredentials.getUsername().equals(credentials.getUsername()) && insertedCredentials.getPassword().equals(credentials.getPassword()) && (fromNetWorkError || insertedCredentials.getServerURL().equals( credentials.getServerURL()))) { notifyLoginSuccess(); } else { if (fromNetWorkError) { notifyNetworkError(); } else { if (insertedCredentials.getUsername().equals(credentials.getUsername()) && !insertedCredentials.getPassword().equals(credentials.getPassword()) && (fromNetWorkError || insertedCredentials.getServerURL().equals( credentials.getServerURL()))){ System.out.println("Pin changed!!!"); notifyUnexpectedError(); }else{ notifyInvalidCredentials(); } } } }

Target:
private void checkUserCredentialsWithOrgUnit(Credentials credentials, boolean fromNetWorkError) { if (insertedCredentials.getUsername().equals(credentials.getUsername()) && insertedCredentials.getPassword().equals(credentials.getPassword()) && (fromNetWorkError || insertedCredentials.getServerURL().equals( credentials.getServerURL()))) { notifyLoginSuccess(); } else { if (fromNetWorkError) { notifyNetworkError(); } else { if (insertedCredentials.getUsername().equals(credentials.getUsername()) && !insertedCredentials.getPassword().equals(credentials.getPassword()) && (fromNetWorkError || insertedCredentials.getServerURL().equals( credentials.getServerURL()))){ notifyOnServerPinChanged(); }else{ notifyInvalidCredentials(); } } } }
Source:
private void maybeScheduleCompressData(List<JobDetails> backgroundJobs) { String configId = "org.hawkular.metrics.jobs." + CompressData.JOB_NAME; Configuration config = configurationService.load(configId).toBlocking() .firstOrDefault(new Configuration(configId, new HashMap<>())); if (config.get("jobId") == null) { logger.info("Preparing to create and schedule " + CompressData.JOB_NAME + " job"); long nextStart = LocalDateTime.now(ZoneOffset.UTC) .with(DateTimeService.startOfNextOddHour()) .toInstant(ZoneOffset.UTC).toEpochMilli(); JobDetails JobDetails = scheduler.scheduleJob(CompressData.JOB_NAME, CompressData.JOB_NAME, ImmutableMap.of(), new RepeatingTrigger.Builder().withTriggerTime(nextStart) .withInterval(2, TimeUnit.HOURS).build()).toBlocking().value(); backgroundJobs.add(JobDetails); configurationService.save(configId, "jobId", JobDetails.getJobId().toString()).toBlocking(); logger.info("Created and scheduled " + JobDetails); } }

Target:
private void maybeScheduleCompressData(List<JobDetails> backgroundJobs) { String configId = "org.hawkular.metrics.jobs." + CompressData.JOB_NAME; Configuration config = configurationService.load(configId).toBlocking() .firstOrDefault(new Configuration(configId, new HashMap<>())); if (config.get("jobId") == null) { logger.info("Preparing to create and schedule " + CompressData.JOB_NAME + " job"); long nextStart = LocalDateTime.now(ZoneOffset.UTC) .with(DateTimeService.startOfNextOddHour()) .toInstant(ZoneOffset.UTC).toEpochMilli(); JobDetails jobDetails = scheduler.scheduleJob(CompressData.JOB_NAME, CompressData.JOB_NAME, ImmutableMap.of(), new RepeatingTrigger.Builder().withTriggerTime(nextStart) .withInterval(2, TimeUnit.HOURS).build()).toBlocking().value(); backgroundJobs.add(jobDetails); configurationService.save(configId, "jobId", jobDetails.getJobId().toString()).toBlocking(); logger.info("Created and scheduled " + jobDetails); } }
Source:
public void addDisposeListener(Consumer<ISideEffect> disposalConsumer) { checkRealm(); if (isDisposed()) { return; } if (this.disposeListeners == null) { this.disposeListeners = new CopyOnWriteArrayList<>(); } this.disposeListeners.add(disposalConsumer); }

Target:
public void addDisposeListener(Consumer<ISideEffect> disposalConsumer) { checkRealm(); if (isDisposed()) { return; } if (this.disposeListeners == null) { this.disposeListeners = new ArrayList<>(); } this.disposeListeners.add(disposalConsumer); }
Source:
private void checkVersionForProfileLI(PackageSetting ps, PackageParser.Package pkg) { if (isUpgrade() && ps != null && pkg != null) { if (ps.versionCode != pkg.mVersionCode) { Slog.d(TAG, ps.name + " clear profile due to version change " + ps.versionCode + " != " + pkg.mVersionCode); clearAppProfilesLIF(pkg, UserHandle.USER_ALL); return true; } if (DEBUG_INSTALL) { Slog.d(TAG, "Package " + ps.name + " keep profile"); } } }

Target:
private void checkVersionForProfileLI(PackageSetting ps, PackageParser.Package pkg) { if (isUpgrade() && ps != null && pkg != null) { if (ps.versionCode != pkg.mVersionCode) { Slog.d(TAG, ps.name + " clear profile due to version change " + ps.versionCode + " != " + pkg.mVersionCode); clearAppProfilesLIF(pkg, UserHandle.USER_ALL); return; } if (DEBUG_INSTALL) { Slog.d(TAG, "Package " + ps.name + " keep profile"); } } }
Source:
public static EntityResolver getEntityResolver(Hints hints) { if (hints != null && hints.containsKey(Hints.ENTITY_RESOLVER)) { Object resolver = hints.get(Hints.ENTITY_RESOLVER); if (resolver == null) { return NullEntityResolver.INSTANCE; } else if (resolver instanceof EntityResolver){ return (EntityResolver) resolver; } } Hints defaults = GeoTools.getDefaultHints(); if (defaults.containsKey(Hints.ENTITY_RESOLVER)) { Object hint = defaults.get(Hints.ENTITY_RESOLVER); if (hint instanceof EntityResolver) { return (EntityResolver) hint; } if (hint instanceof String) { final Logger LOGGER = Logging.getLogger("org.geotools.GeoTools"); try { String className = (String) hint; Class<?> type = Class.forName(className); for (Field field : type.getDeclaredFields()) { int modifier = field.getModifiers(); if ("INSTANCE".equals(field.getName()) && Modifier.isStatic(modifier) && Modifier.isPublic(modifier)) { try { Object value = field.get(null); if (value != null && value instanceof EntityResolver) { return (EntityResolver) value; } } catch (Throwable t) { LOGGER.log(Level.FINER, "Unable to instantiate ENTITY_RESOLVER: " + className + ".INSTANCE", t); return PreventLocalEntityResolver.INSTANCE; } } } try { Object value = type.newInstance(); if (value instanceof EntityResolver) { return (EntityResolver) value; } } catch (InstantiationException | IllegalAccessException e) { LOGGER.log(Level.FINER, "Unable to instantiate ENTITY_RESOLVER: " + e.getMessage(), e); } } catch (ClassNotFoundException notFound) { LOGGER.log(Level.FINER, "Unable to instantiate ENTITY_RESOLVER: " + notFound.getMessage(), notFound); } } } return PreventLocalEntityResolver.INSTANCE; }

Target:
public static EntityResolver getEntityResolver(Hints hints) { if (hints == null) { hints = getDefaultHints(); } if (hints.containsKey(Hints.ENTITY_RESOLVER)) { Object hint = hints.get(Hints.ENTITY_RESOLVER); if (hint == null) { return NullEntityResolver.INSTANCE; } else if (hint instanceof EntityResolver) { return (EntityResolver) hint; } else if (hint instanceof String) { String className = (String) hint; return instantiate(className,EntityResolver.class, PreventLocalEntityResolver.INSTANCE); } } return PreventLocalEntityResolver.INSTANCE; }
Source:
public NettyTransportConnectionStats(EmbeddedCacheManager cacheManager, ChannelGroup acceptedChannels, String threadNamePrefix) { this.cacheManager = cacheManager; this.isGlobalStatsEnabled = cacheManager != null ? cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled() : false; this.acceptedChannels = acceptedChannels; this.threadNamePrefix = threadNamePrefix; }

Target:
public NettyTransportConnectionStats(EmbeddedCacheManager cacheManager, ChannelGroup acceptedChannels, String threadNamePrefix) { this.cacheManager = cacheManager; this.isGlobalStatsEnabled = cacheManager != null && cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled(); this.acceptedChannels = acceptedChannels; this.threadNamePrefix = threadNamePrefix; }
Source:
synchronized List<Integer> chooseBlocksToMove(final String evalId, final int numBlocks) { final int storeId = getMemoryStoreId(evalId); final Set<Integer> blockIds = storeIdToBlockIds.get(storeId); if (blockIds == null) { throw new RuntimeException("Evaluator " + evalId + " is not registered"); } final List<Integer> blockIdList = new ArrayList<>(Math.min(blockIds.size(), numBlocks)); int count = 0; for (final Integer blockId : blockIds) { if (!movingBlocks.contains(blockId)) { blockIdList.add(blockId); movingBlocks.add(blockId); count++; } if (count == numBlocks) { break; } } LOG.log(Level.FINEST, "{0} blocks are chosen from store {1} in evaluator {2}. Blocks: {3}", new Object[] {numBlocks, storeId, evalId, blockIdList}); if (blockIdList.size() < numBlocks) { LOG.log(Level.WARNING, "{0} blocks are chosen from store {1} in evaluator {2}, while {1} blocks are requested", new Object[] {blockIdList.size(), storeId, evalId, numBlocks}); } return blockIdList; }

Target:
synchronized List<Integer> chooseBlocksToMove(final String evalId, final int numBlocks) { final int storeId = getMemoryStoreId(evalId); final Set<Integer> blockIds = storeIdToBlockIds.get(storeId); if (blockIds == null) { throw new RuntimeException("Evaluator " + evalId + " is not registered"); } final List<Integer> blockIdList = new ArrayList<>(Math.min(blockIds.size(), numBlocks)); int count = 0; for (final Integer blockId : blockIds) { if (!movingBlocks.contains(blockId)) { blockIdList.add(blockId); movingBlocks.add(blockId); count++; } if (count == numBlocks) { break; } } if (blockIdList.size() < numBlocks) { LOG.log(Level.WARNING, "{0} blocks are chosen from store {1} in evaluator {2}," + " while {3} blocks are requested. Blocks: {4}", new Object[] {blockIdList.size(), storeId, evalId, numBlocks, blockIdList}); } else { LOG.log(Level.FINEST, "{0} blocks are chosen from store {1} in evaluator {2}. Blocks: {3}", new Object[] {numBlocks, storeId, evalId, blockIdList}); } return blockIdList; }
Source:
void layerRenderGroups() { if (body != null) { add(body); add(bodySelections); } if (header != null) { add(header); } if (floatingBody != null) { add(floatingBody); add(floatingBodySelections); } if (floatingHeader != null) { add(floatingHeader); } if (isSelected) { add(selection); } }

Target:
private void layerRenderGroups() { if (body != null) { add(body); } if (bodySelections != null) { add(bodySelections); } if (header != null) { add(header); } if (floatingBody != null) { add(floatingBody); } if (floatingBodySelections != null) { add(floatingBodySelections); } if (floatingHeader != null) { add(floatingHeader); } if (boundary != null) { add(boundary); } if (isSelected) { add(selection); } }
Source:
public Response post(CharSetCustomer cust) throws UnsupportedEncodingException { logger.info(cust.getName()); String name = "bill\u00E9"; boolean equal = false; String test = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (test.compareTo(cust.getName()) == 0) { equal = true; } return equal ? Response.ok().build() : Response.serverError().build(); }

Target:
public Response post(CharSetCustomer cust) { logger.info(cust.getName()); String name = "bill\u00E9"; boolean equal = false; String test = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (test.compareTo(cust.getName()) == 0) { equal = true; } return equal ? Response.ok().build() : Response.serverError().build(); }
Source:
public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Position) { Position position = (Position) msg; try { Context.getDeviceManager().updateLatestPosition(position); } catch (SQLException error) { LOGGER.warn("Failed to update device", error); } String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId(); StringBuilder s = new StringBuilder(); s.append(formatChannel(ctx.channel())).append(" "); s.append("id: ").append(uniqueId); s.append(", time: ").append(DateUtil.formatDate(position.getFixTime(), false)); s.append(", lat: ").append(String.format("%.5f", position.getLatitude())); s.append(", lon: ").append(String.format("%.5f", position.getLongitude())); if (position.getSpeed() > 0) { s.append(", speed: ").append(String.format("%.1f", position.getSpeed())); } s.append(", course: ").append(String.format("%.1f", position.getCourse())); if (position.getAccuracy() > 0) { s.append(", accuracy: ").append(String.format("%.1f", position.getAccuracy())); } if (position.getOutdated()) { s.append(", outdated"); } if (!position.getValid()) { s.append(", invalid"); } Object batteryLevel = position.getInteger(Position.KEY_BATTERY_LEVEL, null); if (batteryLevel != null) { s.append(", battery: ").append(batteryLevel).append('%'); } Object cmdResult = position.getAttributes().get(Position.KEY_RESULT); if (cmdResult != null) { s.append(", result: ").append(cmdResult); } LOGGER.info(s.toString()); Context.getStatisticsManager().registerMessageStored(position.getDeviceId()); } }

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Position) { Position position = (Position) msg; try { Context.getDeviceManager().updateLatestPosition(position); } catch (SQLException error) { LOGGER.warn("Failed to update device", error); } String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId(); StringBuilder s = new StringBuilder(); s.append(formatChannel(ctx.channel())).append(" "); s.append("id: ").append(uniqueId); for (String event : logEvents) { switch (event) { case "time": s.append(", time: ").append(DateUtil.formatDate(position.getFixTime(), false)); break; case "position": s.append(", lat: ").append(String.format("%.5f", position.getLatitude())); s.append(", lon: ").append(String.format("%.5f", position.getLongitude())); break; case "speed": if (position.getSpeed() > 0) { s.append(", speed: ").append(String.format("%.1f", position.getSpeed())); } break; case "course": s.append(", course: ").append(String.format("%.1f", position.getCourse())); break; case "accuracy": if (position.getAccuracy() > 0) { s.append(", accuracy: ").append(String.format("%.1f", position.getAccuracy())); } break; case "outdated": if (position.getOutdated()) { s.append(", outdated"); } break; case "invalid": if (!position.getValid()) { s.append(", invalid"); } break; default: Object value = position.getAttributes().get(event); if (value != null) { s.append(", ").append(event).append(": ").append(value); } break; } } LOGGER.info(s.toString()); Context.getStatisticsManager().registerMessageStored(position.getDeviceId()); } }