auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Deallocator allocate(final PublisherPackSlice slice) throws PublisherException { if (loadedSlices.contains(slice)) throw new IllegalStateException("Slice " + slice + " already allocated"); size.addAndGet(slice.getSize()); synchronized (this) { for (PublisherPackSlice s : loadedSlices) { if (size.get() <= capacity) break; try { s.store(); } catch (IOException e) { throw new PublisherException( "Error deallocating pack slice " + slice, e); } } } loadedSlices.add(slice); return new Deallocator() { public void deallocate() throws PublisherException { if (!loadedSlices.remove(slice)) throw new PublisherException("Slice " + slice + " already deallocated"); size.addAndGet(-slice.getSize()); } }; }

Target:
public Deallocator allocate(final PublisherPackSlice slice) throws PublisherException { if (loadedSlices.contains(slice)) throw new IllegalStateException("Slice " + slice + " already allocated"); size.addAndGet(slice.getSize()); if (size.get() > capacity) { synchronized (this) { for (PublisherPackSlice s : loadedSlices) { if (size.get() <= capacity) break; try { s.store(); } catch (IOException e) { throw new PublisherException( "Error deallocating pack slice " + slice, e); } } } } loadedSlices.add(slice); return new Deallocator() { public void deallocate() throws PublisherException { if (!loadedSlices.remove(slice)) throw new PublisherException("Slice " + slice + " already deallocated"); size.addAndGet(-slice.getSize()); } }; }
Source:
private void raiseIssueForVariable(SubscriptionContext ctx, Name variable) { if (variable.symbol() != null) { Symbol variableSymbol = variable.symbol(); if (variableIssuesRaised.containsKey(variableSymbol)) { variableIssuesRaised.get(variableSymbol).secondary(variable, REPEATED_VAR_MESSAGE); } else { variableIssuesRaised.put(variableSymbol, ctx.addIssue(variable, String.format(MESSAGE, VRBL_ISSUE_TYPE))); } } }

Target:
private void raiseIssueForVariable(SubscriptionContext ctx, Name variable) { Symbol variableSymbol = variable.symbol(); if (variableSymbol != null) { PreciseIssue existingIssue = variableIssuesRaised.get(variableSymbol); if (existingIssue != null) { existingIssue.secondary(variable, REPEATED_VAR_MESSAGE); } else { variableIssuesRaised.put(variableSymbol, ctx.addIssue(variable, MESSAGE)); } } }
Source:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } if (restRequest.getRestMethod() == RestMethod.DELETE || restRequest.getRestMethod().equals(RestMethod.PUT)) { try { accountAndContainerNamePreconditionCheck(restRequest); } catch (Exception e) { exception = e; } } frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }

Target:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } if (restRequest.getRestMethod() == RestMethod.DELETE || restRequest.getRestMethod() == RestMethod.PUT) { try { accountAndContainerNamePreconditionCheck(restRequest); } catch (Exception e) { exception = e; } } frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }
Source:
public void awaitUpToDate( long oldestAcceptableTxId, Duration timeout ) throws TransactionFailureException { if ( oldestAcceptableTxId <= BASE_TX_ID ) { return; } if ( !availabilityGuard.isAvailable() ) { throw new TransactionFailureException( Status.General.DatabaseUnavailable, "Database had become unavailable while waiting for requested version %d.", oldestAcceptableTxId ); } try { transactionIdStore().awaitClosedTransactionId( oldestAcceptableTxId, timeout.toMillis() ); } catch ( InterruptedException | TimeoutException e ) { throw new TransactionFailureException( Status.Transaction.InstanceStateChanged, e, "Database not up to the requested version: %d. Latest database version is %d", oldestAcceptableTxId, transactionIdStore().getLastClosedTransactionId() ); } }

Target:
public void awaitUpToDate( long oldestAcceptableTxId, Duration timeout ) throws TransactionFailureException { if ( oldestAcceptableTxId <= BASE_TX_ID ) { return; } if ( !availabilityGuard.isAvailable() ) { throw new TransactionFailureException( Status.General.DatabaseUnavailable, "Database unavailable" ); } try { transactionIdStore().awaitClosedTransactionId( oldestAcceptableTxId, timeout.toMillis() ); } catch ( InterruptedException | TimeoutException e ) { if ( e instanceof InterruptedException ) { Thread.currentThread().interrupt(); } throw new TransactionFailureException( Status.Transaction.InstanceStateChanged, e, "Database not up to the requested version: %d. Latest database version is %d", oldestAcceptableTxId, transactionIdStore().getLastClosedTransactionId() ); } }
Source:
public void testTaskJobLauncherCLRSuccessFail() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", "--spring.batch.job.enabled=false"}; boolean isExceptionThrown = false; try { this.applicationContext = SpringApplication .run(new Class[] { TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class}, enabledArgs); } catch (IllegalStateException exception) { isExceptionThrown = true; } assertThat(isExceptionThrown).isTrue(); }

Target:
public void testTaskJobLauncherCLRSuccessFail() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true"}; validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class, enabledArgs); }
Source:
protected long executeTimers() { assert (Thread.currentThread() == worker); changed = false; if (timers.isEmpty()) { return 0L; } long current = clock(); for (Entry<TimerInfo, Long> entry : timers.entries()) { final TimerInfo timerInfo = entry.getKey(); if (timerInfo.cancelled) { timers.remove(entry.getValue(), timerInfo); continue; } final Long key = entry.getValue(); if (key > current) { return key - current; } timers.remove(key, timerInfo); timerInfo.sink.timerEvent(timerInfo.id); } for (Entry<TimerInfo, Long> entry : timers.entries()) { final Long key = entry.getValue(); if (timers.getValues(key).isEmpty()) { timers.remove(key); } } if (changed) { return executeTimers(); } return 0L; }

Target:
protected long executeTimers() { assert (Thread.currentThread() == worker); changed = false; if (timers.isEmpty()) { return 0L; } long current = clock(); for (Entry<TimerInfo, Long> entry : timers.entries()) { final TimerInfo timerInfo = entry.getKey(); if (timerInfo.cancelled) { timers.remove(entry.getValue(), timerInfo); continue; } final Long key = entry.getValue(); if (key > current) { return key - current; } timers.remove(key, timerInfo); timerInfo.sink.timerEvent(timerInfo.id); } for (Entry<TimerInfo, Long> entry : timers.entries()) { final Long key = entry.getValue(); if (!timers.hasValues(key)) { timers.remove(key); } } if (changed) { return executeTimers(); } return 0L; }
Source:
private void createSelector(Type type, @Nonnull Block projector, @Nonnull ChestMenu menu) { double currentOffset = DoubleHandler.fixDouble(Double.parseDouble(BlockStorage.getLocationInfo( projector.getLocation(), type.parameter))); menu.addItem(type.slot, new CustomItem(type.button.getAsItemStack(), "&7" + type.coordinate + " Offset (" + type.direction + ") &e" + currentOffset, "", "&eLeft Click: &7" + type.direction + Math.abs(type.smallChange), "&eRight Click: &7" + type.direction + Math.abs(type.smallChange))); menu.addMenuClickHandler(type.slot, (pl, slot, item, action) -> { double storedOffset = DoubleHandler.fixDouble(Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), type.parameter))); double offset = action.isRightClicked() ? type.largeChange : type.smallChange; if ((type.coordinate == 'X' || type.coordinate == 'Z') && offset + storedOffset > maxDistance.getValue()) { offset = maxDistance.getValue() - storedOffset; } ArmorStand hologram = getArmorStand(projector, true); if (type.coordinate == 'X') { hologram.teleport(hologram.getLocation().add(offset, 0, 0)); } else if (type.coordinate == 'Y') { hologram.teleport(hologram.getLocation().add(0, offset, 0)); } else { hologram.teleport(hologram.getLocation().add(0, 0, offset)); } BlockStorage.addBlockInfo(projector, type.parameter, String.valueOf(storedOffset + offset)); openEditor(pl, projector); return false; }); }

Target:
private void createSelector(Type type, @Nonnull Block projector, @Nonnull ChestMenu menu) { double currentOffset = DoubleHandler.fixDouble(Double.parseDouble(BlockStorage.getLocationInfo( projector.getLocation(), type.parameter))); menu.addItem(type.slot, new CustomItem(type.button.getAsItemStack(), "&7" + type.coordinate + " Offset (" + type.direction + ") &e" + currentOffset, "", "&eLeft Click: &7" + type.direction + Math.abs(type.smallChange), "&eRight Click: &7" + type.direction + Math.abs(type.largeChange))); menu.addMenuClickHandler(type.slot, (pl, slot, item, action) -> { double storedOffset = DoubleHandler.fixDouble(Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), type.parameter))); double offset = action.isRightClicked() ? type.largeChange : type.smallChange; if ((type.coordinate == 'X' || type.coordinate == 'Z') && offset + storedOffset > maxDistance.getValue()) { offset = maxDistance.getValue() - storedOffset; } ArmorStand hologram = getArmorStand(projector, true); if (type.coordinate == 'X') { hologram.teleport(hologram.getLocation().add(offset, 0, 0)); } else if (type.coordinate == 'Y') { hologram.teleport(hologram.getLocation().add(0, offset, 0)); } else { hologram.teleport(hologram.getLocation().add(0, 0, offset)); } BlockStorage.addBlockInfo(projector, type.parameter, String.valueOf(storedOffset + offset)); openEditor(pl, projector); return false; }); }
Source:
public CgroupOOMDetector(URI dockerDaemonUri, DockerConnector dockerConnector) { this.dockerDaemonUri = dockerDaemonUri; this.dockerConnector = dockerConnector; oomDetectors = new ConcurrentHashMap<>(); executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("CgroupOOMDetector-%d").setDaemon(true).build()); }

Target:
public CgroupOOMDetector(URI dockerDaemonUri, DockerConnector dockerConnector) { this.dockerDaemonUri = dockerDaemonUri; this.dockerConnector = dockerConnector; this.oomDetectors = new ConcurrentHashMap<>(); this.executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("CgroupOOMDetector-%d") .setDaemon(true) .build()); }
Source:
private String getParamJson(final String msg) { Map<String, Object> param = Maps.newLinkedHashMap(); param.put("msgtype", "text"); param.put("text", Collections.singletonMap("content", msg)); return GsonFactory.getGson().toJson(param); }

Target:
private String getParamJson(final String msg) { return GsonFactory.getGson().toJson(ImmutableMap.of("msgtype", "text", "text", Collections.singletonMap("content", msg))); }
Source:
public void triggerRecovery() { doTriggerRecovery(null, System.getProperty(NarayanaLRAClient.LRA_COORDINATOR_HOST_KEY), Integer.parseInt(System.getProperty(NarayanaLRAClient.LRA_COORDINATOR_PORT_KEY))); }

Target:
public void triggerRecovery() { recoverLRAs( System.getProperty(NarayanaLRAClient.LRA_COORDINATOR_HOST_KEY, "localhost"), Integer.parseInt(System.getProperty(NarayanaLRAClient.LRA_COORDINATOR_PORT_KEY, "8080"))); }
Source:
protected GitModelObjectContainer(GitModelObject parent, RevCommit commit, int direction) throws IOException { super(parent); kind = direction; if (commit != null) { baseCommit = commit; RevCommit[] parents = baseCommit.getParents(); if (parents != null && parents.length > 0) remoteCommit = new ObjectWalk(getRepository()) .parseCommit(baseCommit.getParent(0)); else { remoteCommit = null; } } else { baseCommit = null; remoteCommit = null; } }

Target:
protected GitModelObjectContainer(GitModelObject parent, RevCommit commit, int direction) throws IOException { super(parent); kind = direction; if (commit != null) { baseCommit = commit; RevCommit[] parents = baseCommit.getParents(); if (parents != null && parents.length > 0) remoteCommit = new RevWalk(getRepository()) .parseCommit(getParentRevCommit()); else { remoteCommit = null; } } else { baseCommit = null; remoteCommit = null; } }
Source:
public final Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) { if ( original == null && target == null ) { return null; } if ( original == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return target; } if ( target == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return getReplacement( (T) original, null, session ); } return getReplacement( (T) original, (T) target, session ); }

Target:
public final Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) { if ( original == null && target == null ) { return null; } return getReplacement( (T) original, (T) target, session ); }
Source:
private static void installDefaultExceptionHandler() { sOriginalUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { sendAnalyticsException(e, true); sOriginalUncaughtExceptionHandler.uncaughtException(t, e); }); }

Target:
synchronized private static void installDefaultExceptionHandler() { sOriginalUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { sendAnalyticsException(throwable, true); sOriginalUncaughtExceptionHandler.uncaughtException(thread, throwable); }); }
Source:
protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(@NonNull ITmfTrace trace) { CallStackAnalysis fModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, CallStackAnalysis.class, CallStackAnalysis.ID); if (fModule == null) { return null; } fModule.schedule(); Job job = new Job("CallStack analysis") { @Override protected IStatus run(IProgressMonitor monitor) { fModule.waitForCompletion(monitor); if(monitor.isCanceled()) { return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; job.schedule(); return fModule; }

Target:
protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(@NonNull ITmfTrace trace) { CallStackAnalysis fModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, CallStackAnalysis.class, CallStackAnalysis.ID); if (fModule == null) { return null; } fModule.schedule(); Job job = new Job(Messages.CallStackTableViewer_) { @Override protected IStatus run(IProgressMonitor monitor) { fModule.waitForCompletion(monitor); if(monitor.isCanceled()) { return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; job.schedule(); return fModule; }
Source:
private WorkflowRun runProject() throws Exception { return j.assertBuildStatusSuccess(project.scheduleBuild2(0)); }

Target:
private WorkflowRun runProject() throws Exception { return j.buildAndAssertSuccess(project); }
Source:
public Set<LayoutOptionData> getSupportedOptions(final ILayoutConfigurationStore config) { LayoutMetaDataService layoutDataService = LayoutMetaDataService.getInstance(); Set<LayoutOptionData> optionData = new HashSet<LayoutOptionData>(); Set<LayoutOptionData.Target> optionTargets = config.getOptionTargets(); if (optionTargets.contains(LayoutOptionData.Target.PARENTS)) { LayoutAlgorithmData algoData = getAlgorithm(config); if (algoData != null) { optionData.addAll(layoutDataService.getOptionData(algoData, LayoutOptionData.Target.PARENTS)); } } ILayoutConfigurationStore parentConfig = config.getParent(); if (parentConfig != null) { LayoutAlgorithmData algoData = getAlgorithm(parentConfig); if (algoData != null) { for (LayoutOptionData.Target target : optionTargets) { if (target != LayoutOptionData.Target.PARENTS) { optionData.addAll(layoutDataService.getOptionData(algoData, target)); } } } } return optionData; }

Target:
public Set<LayoutOptionData> getSupportedOptions(final ILayoutConfigurationStore config) { LayoutMetaDataService layoutDataService = LayoutMetaDataService.getInstance(); Set<LayoutOptionData> optionData = new LinkedHashSet<LayoutOptionData>(); Set<LayoutOptionData.Target> optionTargets = config.getOptionTargets(); if (optionTargets.contains(LayoutOptionData.Target.PARENTS)) { LayoutAlgorithmData algoData = getAlgorithm(config); if (algoData != null) { optionData.addAll(layoutDataService.getOptionData(algoData, LayoutOptionData.Target.PARENTS)); } } ILayoutConfigurationStore parentConfig = config.getParent(); if (parentConfig != null) { LayoutAlgorithmData algoData = getAlgorithm(parentConfig); if (algoData != null) { for (LayoutOptionData.Target target : optionTargets) { if (target != LayoutOptionData.Target.PARENTS) { optionData.addAll(layoutDataService.getOptionData(algoData, target)); } } } } return optionData; }
Source:
public void shouldEnrollSubject() throws IOException { try { fakeNow(newDateTime(2015, 8, 1, 0, 0, 0)); Subject subject = createSubjectWithRequireData("1"); InputStream inputStream = getClass().getResourceAsStream("/enrollSimple.csv"); raveImportService.importCsv(new InputStreamReader(inputStream), "/enrollSimple.csv"); inputStream.close(); SubjectEnrollments subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); ebodacEnrollmentService.unenrollSubject(subjectEnrollments.getSubject().getSubjectId()); ebodacEnrollmentService.enrollSubject(subject.getSubjectId()); subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); assertEquals(3, subjectEnrollments.getEnrollments().size()); } finally { stopFakingTime(); } }

Target:
public void shouldEnrollSubject() throws IOException { try { fakeNow(newDateTime(2015, 8, 1, 0, 0, 0)); Subject subject = createSubjectWithRequireData("1"); InputStream inputStream = getClass().getResourceAsStream("/enrollSimple.csv"); raveImportService.importCsv(new InputStreamReader(inputStream), "/enrollSimple.csv"); inputStream.close(); SubjectEnrollments subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); ebodacEnrollmentService.unenrollSubject(subjectEnrollments.getSubject().getSubjectId()); subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); for(Enrollment enrollment : subjectEnrollments.getEnrollments()) { assertEquals(EnrollmentStatus.UNENROLLED, enrollment.getStatus()); } ebodacEnrollmentService.enrollSubject(subject.getSubjectId()); subjectEnrollments = subjectEnrollmentsDataService.findEnrollmentBySubjectId(subject.getSubjectId()); assertEquals(3, subjectEnrollments.getEnrollments().size()); for(Enrollment enrollment : subjectEnrollments.getEnrollments()) { assertEquals(EnrollmentStatus.ENROLLED, enrollment.getStatus()); } } finally { stopFakingTime(); } }
Source:
public Set<SecurityGroup> listSecurityGroupsForNode(String nodeId) { logger.debug(">> getting security groups for node %s...", nodeId); final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(nodeId); VirtualMachine vm = api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).get( resourceGroupAndName.name()); if (vm == null) { throw new IllegalArgumentException("Node " + nodeId + " was not found"); } List<NetworkInterface> networkInterfacesIdReferences = vm.properties().networkProfile().networkInterfaces(); List<NetworkSecurityGroup> networkGroups = new ArrayList<NetworkSecurityGroup>(); for (NetworkInterface networkInterfaceCardIdReference : networkInterfacesIdReferences) { String nicName = extractName(networkInterfaceCardIdReference.id()); String nicResourceGroup = extractResourceGroup(networkInterfaceCardIdReference.id()); NetworkInterfaceCard card = api.getNetworkInterfaceCardApi(nicResourceGroup).get(nicName); if (card != null && card.properties().networkSecurityGroup() != null) { String secGroupName = card.properties().networkSecurityGroup().name(); String sgResourceGroup = card.properties().networkSecurityGroup().resourceGroup(); NetworkSecurityGroup group = api.getNetworkSecurityGroupApi(sgResourceGroup).get(secGroupName); networkGroups.add(group); } } return ImmutableSet.copyOf(transform(filter(networkGroups, notNull()), securityGroupConverter)); }

Target:
public Set<SecurityGroup> listSecurityGroupsForNode(String nodeId) { logger.debug(">> getting security groups for node %s...", nodeId); final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(nodeId); VirtualMachine vm = api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).get( resourceGroupAndName.name()); if (vm == null) { throw new IllegalArgumentException("Node " + nodeId + " was not found"); } List<NetworkInterface> networkInterfaces = vm.properties().networkProfile().networkInterfaces(); List<NetworkSecurityGroup> networkGroups = new ArrayList<NetworkSecurityGroup>(); for (NetworkInterface networkInterfaceCardIdReference : networkInterfaces) { String nicName = extractName(networkInterfaceCardIdReference.id()); String nicResourceGroup = extractResourceGroup(networkInterfaceCardIdReference.id()); NetworkInterfaceCard card = api.getNetworkInterfaceCardApi(nicResourceGroup).get(nicName); if (card != null && card.properties().networkSecurityGroup() != null) { String secGroupName = card.properties().networkSecurityGroup().name(); String sgResourceGroup = card.properties().networkSecurityGroup().resourceGroup(); NetworkSecurityGroup group = api.getNetworkSecurityGroupApi(sgResourceGroup).get(secGroupName); networkGroups.add(group); } } return ImmutableSet.copyOf(transform(filter(networkGroups, notNull()), securityGroupConverter)); }
Source:
private String getBrokerURL() { return String.format( "%s/druid/v2/", router ); }

Target:
private String getBrokerURL() { return String.format( "%s/druid/v2/", routerUrl ); }
Source:
public void bytesRead(long bytes) { ioStatisticsStore.incrementCounter(STREAM_READ_BYTES, bytes); }

Target:
public void bytesRead(long bytes) { bytesRead.addAndGet(bytes); }
Source:
public static XBeePacket parsePacket(byte[] packet) throws PacketParsingException { if (packet.length > 1 && ((packet[0] &0xFF) != SpecialByte.HEADER_BYTE.getValue())) throw new PacketParsingException("Invalid start delimiter."); if (packet.length < 4) throw new PacketParsingException("Packet length is too short."); int length = ByteUtils.byteArrayToInt(new byte[] {packet[1], packet[2]}); if (length != packet.length - 4) throw new PacketParsingException("Invalid packet length."); byte[] data = new byte[length]; System.arraycopy(packet, 3, data, 0, length); byte packetChecksum = packet[packet.length - 1]; XBeeChecksum checksum = new XBeeChecksum(); checksum.add(data); byte generatedChecksum = (byte)(checksum.generate() & 0xFF); if (packetChecksum != generatedChecksum) throw new PacketParsingException("Invalid '" + packetChecksum + "' checksum. It should be " + generatedChecksum); XBeePacketParser parser = new XBeePacketParser(new ByteArrayInputStream(packet, 1, packet.length - 1), XBeeMode.API); XBeePacket xbeePacket = parser.parsePacket(); return xbeePacket; }

Target:
public static XBeePacket parsePacket(byte[] packet) throws PacketParsingException { if (packet == null) throw new NullPointerException("Packet byte array cannot be null."); if (packet.length > 1 && ((packet[0] &0xFF) != SpecialByte.HEADER_BYTE.getValue())) throw new PacketParsingException("Invalid start delimiter."); if (packet.length < 4) throw new PacketParsingException("Packet length is too short."); int length = ByteUtils.byteArrayToInt(new byte[] {packet[1], packet[2]}); if (length != packet.length - 4) throw new PacketParsingException("Invalid packet length."); byte[] data = new byte[length]; System.arraycopy(packet, 3, data, 0, length); byte packetChecksum = packet[packet.length - 1]; XBeeChecksum checksum = new XBeeChecksum(); checksum.add(data); byte generatedChecksum = (byte)(checksum.generate() & 0xFF); if (packetChecksum != generatedChecksum) throw new PacketParsingException("Invalid '" + packetChecksum + "' checksum. It should be " + generatedChecksum); XBeePacketParser parser = new XBeePacketParser(new ByteArrayInputStream(packet, 1, packet.length - 1), OperatingMode.API); XBeePacket xbeePacket = parser.parsePacket(); return xbeePacket; }
Source:
private KeyValPair<String, ? extends Class<?>> getGetterForVariable(String var, Class<?> inputClassType) { try { final Field field = inputClassType.getField(var); if (Modifier.isPublic(field.getModifiers())) { return new KeyValPair<>(var, field.getType()); } logger.debug("Field is not publicly accessible. Proceeding to locate a getter method.", var); } catch (NoSuchFieldException | SecurityException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", inputClassType.getName(), var); } String methodName = GET + var.substring(0, 1).toUpperCase() + var.substring(1); try { Method method = inputClassType.getMethod(methodName); if (Modifier.isPublic(method.getModifiers())) { return new KeyValPair<>(methodName + "()", method.getReturnType()); } logger.debug("Method of is not accessible. Proceeding to locate another getter method.", methodName, inputClassType.getName()); } catch (NoSuchMethodException | SecurityException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method", inputClassType.getName(), methodName); } methodName = IS + var.substring(0, 1).toUpperCase() + var.substring(1); try { Method method = inputClassType.getMethod(methodName); if (Modifier.isPublic(method.getModifiers())) { return new KeyValPair<>(methodName + "()", method.getReturnType()); } logger.debug("Method of is not accessible. Proceeding to locate another getter method.", methodName, inputClassType.getName()); } catch (NoSuchMethodException | SecurityException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method", inputClassType.getName(), methodName); } return new KeyValPair<>(var, inputClassType); }

Target:
private KeyValPair<String, ? extends Class<?>> getGetterForVariable(String var, Class<?> inputClassType) { try { final Field field = inputClassType.getField(var); if (Modifier.isPublic(field.getModifiers())) { return new KeyValPair<>(var, field.getType()); } logger.debug("Field is not publicly accessible. Proceeding to locate a getter method.", var); } catch (NoSuchFieldException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", inputClassType.getName(), var); } String[] methodAccessors = new String[]{GET, IS}; for (String m : methodAccessors) { String methodName = m + var.substring(0, 1).toUpperCase() + var.substring(1); try { Method method = inputClassType.getMethod(methodName); if (Modifier.isPublic(method.getModifiers())) { return new KeyValPair<>(methodName + "()", method.getReturnType()); } logger.debug("Method of is not accessible. Proceeding to locate another getter method.", methodName, inputClassType.getName()); } catch (NoSuchMethodException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method", inputClassType.getName(), methodName); } } return new KeyValPair<>(var, inputClassType); }
Source:
UpdatesFromMixpanel constructUpdatesFromMixpanel(final Context context, final String token) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API) { Log.i(LOGTAG, "Web Configuration, A/B Testing, and Dynamic Tweaks are not supported on this Android OS Version"); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else if (mConfig.getDisableViewCrawler()) { return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else { return new ViewCrawler(mContext, mToken, this, sSharedTweaks); } }

Target:
UpdatesFromMixpanel constructUpdatesFromMixpanel(final Context context, final String token) { if (Build.VERSION.SDK_INT < MPConfig.UI_FEATURES_MIN_API || mConfig.getDisableViewCrawler()) { Log.i(LOGTAG, "Web Configuration, A/B Testing, and Dynamic Tweaks are disabled."); return new NoOpUpdatesFromMixpanel(sSharedTweaks); } else { return new ViewCrawler(mContext, mToken, this, sSharedTweaks); } }
Source:
} catch (IOException e) { Activator.getDefault().logError("Cannot read the file from URL due to ", e); }

Target:
} catch (IOException e) { Activator.getDefault().logError("Cannot read the file from URL ", e); }
Source:
protected void updatePotionEffectsMetadata() { metadata.set(MetadataIndex.POTION_COLOR, potionEffects.size() > 0 ? 1 : 0); metadata.set(MetadataIndex.POTION_AMBIENT, potionEffects.values().stream().allMatch(PotionEffect::isAmbient)); }

Target:
protected void updatePotionEffectsMetadata() { int color = 0; if (this.potionEffects.size() > 0) { Color[] colors = this.potionEffects.values().stream() .filter(PotionEffect::hasParticles) .map(effect -> effect.getColor() != null ? effect.getColor() : effect.getType().getColor()) .toArray(Color[]::new); color = Color.BLACK.mixColors(colors).asRGB(); } metadata.set(MetadataIndex.POTION_COLOR, color); metadata.set(MetadataIndex.POTION_AMBIENT, this.potionEffects.values().stream().allMatch(PotionEffect::isAmbient)); }
Source:
public ProcessedClaimCollection retrieveClaimValues( ClaimCollection claims, ClaimsParameters parameters) { ProcessedClaimCollection claimsColl = new ProcessedClaimCollection(); Principal principal = parameters.getPrincipal(); Map<String, Object> additionalProperties = parameters.getAdditionalProperties(); if (additionalProperties != null) { if (LOGGER.isTraceEnabled()) { StringBuffer output = new StringBuffer(); String prefix = "\n"; output.append("CAS attributes returned: {"); for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) { output.append(prefix); prefix = ", \n"; output.append(entry.getKey()); output.append("="); output.append(entry.getValue()); } output.append("\n}"); LOGGER.trace(output.toString()); } claims .stream() .distinct() .forEach( claim -> { URI claimType = claim.getClaimType(); String claimTypeString = claimType.toString(); String mappedClaimType = attributeMap.getOrDefault(claimTypeString, claimTypeString); buildClaim( claimsColl, principal, claimType, additionalProperties.get(mappedClaimType)); }); } if (LOGGER.isTraceEnabled()) { StringBuffer output = new StringBuffer(); output.append("Claims map returned: {"); String prefix = "\n"; for (ProcessedClaim claim : claimsColl) { output.append(prefix); prefix = ", \n"; output.append(claim.toString()); } output.append("\n}"); LOGGER.trace(output.toString()); } return claimsColl; }

Target:
public ProcessedClaimCollection retrieveClaimValues( ClaimCollection claims, ClaimsParameters parameters) { ProcessedClaimCollection claimsColl = new ProcessedClaimCollection(); Principal principal = parameters.getPrincipal(); Map<String, Object> additionalProperties = parameters.getAdditionalProperties(); if (additionalProperties != null) { if (LOGGER.isTraceEnabled()) { StringBuilder output = new StringBuilder(); String prefix = "\n"; output.append("CAS attributes returned: {"); for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) { output.append(prefix); prefix = ", \n"; output.append(entry.getKey()); output.append("="); output.append(entry.getValue()); } output.append("\n}"); LOGGER.trace(output.toString()); } claims .stream() .distinct() .forEach( claim -> { URI claimType = claim.getClaimType(); String claimTypeString = claimType.toString(); String mappedClaimType = attributeMap.getOrDefault(claimTypeString, claimTypeString); buildClaim( claimsColl, principal, claimType, additionalProperties.get(mappedClaimType)); }); } if (LOGGER.isTraceEnabled()) { StringBuilder output = new StringBuilder(); output.append("Claims map returned: {"); String prefix = "\n"; for (ProcessedClaim claim : claimsColl) { output.append(prefix); prefix = ", \n"; output.append(claim.toString()); } output.append("\n}"); LOGGER.trace(output.toString()); } return claimsColl; }
Source:
public @Nullable StateDescription getStateDescription(Channel channel, @Nullable StateDescription original, @Nullable Locale locale) { List<StateOption> options = channelOptionsMap.get(channel.getUID()); if (options == null) { return null; } if (original != null) { return new StateDescription(original.getMinimum(), original.getMaximum(), original.getStep(), original.getPattern(), original.isReadOnly(), options); } return new StateDescription(null, null, null, null, false, options); }

Target:
public @Nullable StateDescription getStateDescription(Channel channel, @Nullable StateDescription original, @Nullable Locale locale) { List<StateOption> options = channelOptionsMap.get(channel.getUID()); if (options == null) { return original; } if (original != null) { return new StateDescription(original.getMinimum(), original.getMaximum(), original.getStep(), original.getPattern(), original.isReadOnly(), options); } return new StateDescription(null, null, null, null, false, options); }
Source:
public MergedByteBuffers encrypt(final MergedByteBuffers lmbb) { final MergedByteBuffers mbb = new MergedByteBuffers(false); if(!startedHandshake.get()){ mbb.add(lmbb); return mbb; } tempBuffers.add(lmbb); ByteBuffer oldBB = tempBuffers.pull(tempBuffers.remaining()); ByteBuffer newBB; ByteBuffer tmpBB; boolean gotFinished = false; while (ssle.getHandshakeStatus() == NEED_WRAP || oldBB.remaining() > 0) { newBB = getAppWriteBuffer(); tmpBB = newBB.duplicate(); try { final SSLEngineResult res = ssle.wrap(oldBB, newBB); if(!finishedHandshake.get() && oldBB.remaining() > 0) { tempBuffers.add(oldBB); oldBB.position(oldBB.limit()); } if(!finishedHandshake.get() && res.getHandshakeStatus() == FINISHED) { gotFinished = true; } else { while (ssle.getHandshakeStatus() == NEED_TASK) { runTasks(); } } } catch (SSLHandshakeException e) { this.handshakeFuture.setFailure(e); client.close(); break; } catch (SSLException e) { throw new EncryptionException(e); } if(tmpBB.hasRemaining()) { tmpBB.limit(newBB.position()); mbb.add(tmpBB); } if(client.isClosed()) { break; } } writeBuffer = null; if(gotFinished && finishedHandshake.compareAndSet(false, true)) { handshakeFuture.setResult(ssle.getSession()); if(tempBuffers.remaining() > 0) { mbb.add(encrypt(IOUtils.EMPTY_BYTEBUFFER)); } } return mbb; }

Target:
public MergedByteBuffers encrypt(final MergedByteBuffers lmbb) { if(!startedHandshake.get()){ return lmbb; } final MergedByteBuffers mbb = new MergedByteBuffers(false); tempBuffers.add(lmbb); ByteBuffer oldBB = tempBuffers.pull(tempBuffers.remaining()); ByteBuffer newBB; ByteBuffer tmpBB; boolean gotFinished = false; while (ssle.getHandshakeStatus() == NEED_WRAP || oldBB.remaining() > 0) { newBB = getAppWriteBuffer(); tmpBB = newBB.duplicate(); try { final SSLEngineResult res = ssle.wrap(oldBB, newBB); if(!finishedHandshake.get() && oldBB.remaining() > 0) { tempBuffers.add(oldBB); oldBB.position(oldBB.limit()); } if(!finishedHandshake.get() && res.getHandshakeStatus() == FINISHED) { gotFinished = true; } else { while (ssle.getHandshakeStatus() == NEED_TASK) { runTasks(); } } } catch (SSLHandshakeException e) { this.handshakeFuture.setFailure(e); client.close(); break; } catch (SSLException e) { throw new EncryptionException(e); } if(tmpBB.hasRemaining()) { tmpBB.limit(newBB.position()); mbb.add(tmpBB); } if(client.isClosed()) { break; } } writeBuffer = null; if(gotFinished && finishedHandshake.compareAndSet(false, true)) { handshakeFuture.setResult(ssle.getSession()); if(tempBuffers.remaining() > 0) { mbb.add(encrypt(IOUtils.EMPTY_BYTEBUFFER)); } } return mbb; }
Source:
private Iterator<Row> useLegacyTableFactory(StreamExecutionEnvironment env, StreamTableEnvironment tEnv) { Table t = tEnv.fromDataStream(env.fromCollection(Arrays.asList( new Tuple2<>(1, "1"), new Tuple2<>(1, "1"), new Tuple2<>(2, "3"), new Tuple2<>(2, "5"), new Tuple2<>(3, "5"), new Tuple2<>(3, "8") )), $("id1"), $("id2")); tEnv.registerTable("T", t); JdbcTableSource.Builder builder = JdbcTableSource.builder() .setOptions(JdbcOptions.builder() .setDBUrl(DB_URL) .setTableName(LOOKUP_TABLE) .build()) .setSchema(TableSchema.builder().fields( new String[]{"id1", "comment1", "comment2", "id2"}, new DataType[]{DataTypes.INT(), DataTypes.STRING(), DataTypes.STRING(), DataTypes.STRING()}) .build()); if (useCache) { builder.setLookupOptions(JdbcLookupOptions.builder() .setCacheMaxSize(1000).setCacheExpireMs(1000 * 1000).setMaxRetryTimes(0).build()); } tEnv.registerFunction("jdbcLookup", builder.build().getLookupFunction(t.getSchema().getFieldNames())); String sqlQuery = "SELECT id1, id2, comment1, comment2 FROM T, " + "LATERAL TABLE(jdbcLookup(id1, id2)) AS S(l_id1, comment1, comment2, l_id2)"; return tEnv.executeSql(sqlQuery).collect(); }

Target:
private Iterator<Row> useLegacyTableFactory(StreamExecutionEnvironment env, StreamTableEnvironment tEnv) { Table t = tEnv.fromDataStream(env.fromCollection(Arrays.asList( new Tuple2<>(1, "1"), new Tuple2<>(1, "1"), new Tuple2<>(2, "3"), new Tuple2<>(2, "5"), new Tuple2<>(3, "5"), new Tuple2<>(3, "8") )), $("id1"), $("id2")); tEnv.registerTable("T", t); JdbcTableSource.Builder builder = JdbcTableSource.builder() .setOptions(JdbcOptions.builder() .setDBUrl(DB_URL) .setTableName(LOOKUP_TABLE) .build()) .setSchema(TableSchema.builder().fields( new String[]{"id1", "comment1", "comment2", "id2"}, new DataType[]{DataTypes.INT(), DataTypes.STRING(), DataTypes.STRING(), DataTypes.STRING()}) .build()); JdbcLookupOptions.Builder lookupOptionsBuilder = JdbcLookupOptions.builder().setMaxRetryTimes(0); if (useCache) { lookupOptionsBuilder.setCacheMaxSize(1000).setCacheExpireMs(1000 * 1000); } builder.setLookupOptions(lookupOptionsBuilder.build()); tEnv.registerFunction("jdbcLookup", builder.build().getLookupFunction(t.getSchema().getFieldNames())); String sqlQuery = "SELECT id1, id2, comment1, comment2 FROM T, " + "LATERAL TABLE(jdbcLookup(id1, id2)) AS S(l_id1, comment1, comment2, l_id2)"; return tEnv.executeSql(sqlQuery).collect(); }
Source:
public Collection<GoogleComputeInstance> find(GoogleComputeInstanceTemplate template, Collection<String> instanceIds) throws InterruptedException { List<GoogleComputeInstance> result = new ArrayList<GoogleComputeInstance>(); for (String currentId : instanceIds) { Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String zone = getConfigurationValue(GoogleComputeProviderConfigurationProperty.ZONE); String decoratedInstanceName = decorateInstanceName(template, currentId); try { Instance instance = compute.instances().get(projectId, zone, decoratedInstanceName).execute(); result.add(new GoogleComputeInstance(template, instance.getName(), getInetAddressFromInstance(instance))); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { LOG.info("Instance '" + decoratedInstanceName + "' not found."); } else { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } return result; }

Target:
public Collection<GoogleComputeInstance> find(GoogleComputeInstanceTemplate template, Collection<String> instanceIds) throws InterruptedException { List<GoogleComputeInstance> result = new ArrayList<GoogleComputeInstance>(); for (String currentId : instanceIds) { Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String zone = getConfigurationValue(GoogleComputeInstanceTemplateConfigurationProperty.ZONE); String decoratedInstanceName = decorateInstanceName(template, currentId); try { Instance instance = compute.instances().get(projectId, zone, decoratedInstanceName).execute(); result.add(new GoogleComputeInstance(template, instance.getName(), getInetAddressFromInstance(instance))); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { LOG.info("Instance '" + decoratedInstanceName + "' not found."); } else { throw new RuntimeException(e); } } catch (IOException e) { throw new RuntimeException(e); } } return result; }
Source:
private void updateSuggestedRepositories(String query) { suggestedRepositories.clear(); repositories.stream().forEach(repo -> { if (isMatching(repo, query)) { suggestedRepositories.add(repo); } }); Optional<PickerRepository> possibleExactMatch = getPickerRepositoryById(suggestedRepositories, query); if (!possibleExactMatch.isPresent() && !query.isEmpty()) { PickerRepository newRepository = new PickerRepository(query); newRepository.setSelected(true); suggestedRepositories.add(0, newRepository); } else if (!query.isEmpty()) { PickerRepository exactMatch = possibleExactMatch.get(); exactMatch.setSelected(true); } else { assert !suggestedRepositories.isEmpty(); PickerRepository firstMatching = suggestedRepositories.get(0); firstMatching.setSelected(true); } }

Target:
private void updateSuggestedRepositories(String query) { suggestedRepositories.clear(); repositories.stream().forEach(repo -> { if (isMatching(repo, query)) { suggestedRepositories.add(repo); } }); Optional<PickerRepository> possibleExactMatch = getPickerRepositoryById(suggestedRepositories, query); if (query.isEmpty()) { assert !suggestedRepositories.isEmpty(); PickerRepository firstMatching = suggestedRepositories.get(0); firstMatching.setSelected(true); return; } if (!possibleExactMatch.isPresent()) { PickerRepository newRepository = new PickerRepository(query); newRepository.setSelected(true); suggestedRepositories.add(0, newRepository); return; } PickerRepository exactMatch = possibleExactMatch.get(); exactMatch.setSelected(true); }
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (!Objects.isNull(requestIdPolicyOptions)) { HttpHeaders httpHeaders = requestIdPolicyOptions.getIdHeaderSupplier().get(); if (!Objects.isNull(httpHeaders)) { httpHeaders.stream().forEach(httpHeader -> context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()) ); } } else { context.getHttpRequest().getHeaders().put(REQUEST_ID_HEADER, UUID.randomUUID().toString()); } return next.process(); }

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String requestId = context.getHttpRequest().getHeaders().getValue(REQUEST_ID_HEADER); if (!Objects.isNull(requestIdPolicyOptions)) { HttpHeaders httpHeaders = requestIdPolicyOptions.getIdHeaderSupplier().get(); if (!Objects.isNull(httpHeaders)) { httpHeaders.stream().forEach(httpHeader -> { String requestIdHeaderValue = context.getHttpRequest().getHeaders().getValue(httpHeader.getName()); if (requestIdHeaderValue == null) { context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()); } }); }else { if (requestId == null) { context.getHttpRequest().getHeaders().put(REQUEST_ID_HEADER, UUID.randomUUID().toString()); } } } else { if (requestId == null) { context.getHttpRequest().getHeaders().put(REQUEST_ID_HEADER, UUID.randomUUID().toString()); } } return next.process(); }
Source:
private Identity fetch(final String token) throws IOException { final String uri = new Href( String.format( "%s/user", this.getUrl("<LINK_0>") ) ).with("access_token", token).toString(); return PsGithub.parse( new JdkRequest(uri) .header("accept", "application/json") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class).json().readObject() ); }

Target:
private Identity fetch(final String token) throws IOException { final String uri = new Href(this.api).path("user") .with("access_token", token).toString(); return PsGithub.parse( new JdkRequest(uri) .header("accept", "application/json") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class).json().readObject() ); }
Source:
public void spec104_mustSignalOnErrorWhenFails() throws Throwable { try { errorPublisherTest(new PublisherTestRun<T>() { @Override public void run(final Publisher<T> pub) throws InterruptedException { final Latch latch = new Latch(env); pub.subscribe(new TestEnvironment.TestSubscriber<T>(env) { @Override public void onError(Throwable cause) { latch.assertOpen(String.format("Error-state Publisher %s called `onError` twice on new Subscriber", pub)); latch.close(); } }); latch.expectClose(String.format("Error-state Publisher %s did not call `onError` on new Subscriber", pub)); env.verifyNoAsyncErrors(env.defaultTimeoutMillis()); } }); } catch (Throwable ex) { if (ex instanceof SkipException) { throw ex; } else { throw new RuntimeException(String.format("Publisher threw exception (%s) instead of signalling error via onError!", ex.getMessage()), ex); } } }

Target:
public void spec104_mustSignalOnErrorWhenFails() throws Throwable { try { errorPublisherTest(new PublisherTestRun<T>() { @Override public void run(final Publisher<T> pub) throws InterruptedException { final Latch latch = new Latch(env); pub.subscribe(new TestEnvironment.TestSubscriber<T>(env) { @Override public void onError(Throwable cause) { latch.assertOpen(String.format("Error-state Publisher %s called `onError` twice on new Subscriber", pub)); latch.close(); } }); latch.expectClose(String.format("Error-state Publisher %s did not call `onError` on new Subscriber", pub)); env.verifyNoAsyncErrors(env.defaultTimeoutMillis()); } }); } catch (SkipException ex) { throw ex; } catch (Throwable ex) { throw new RuntimeException(String.format("Publisher threw exception (%s) instead of signalling error via onError!", ex.getMessage()), ex); } }
Source:
private double computeRetryFactor() { final long deltaBackoff = this.maxBackoff.minus(this.minBackoff).getSeconds(); if (deltaBackoff <= 0 || super.maxRetryCount() <= 0) { return 0; } return Math.log(deltaBackoff) / Math.log(super.maxRetryCount()); }

Target:
private double computeRetryFactor() { final long deltaBackoff = maxBackoff.minus(minBackoff).getSeconds(); if (deltaBackoff <= 0 || super.maxRetryCount() <= 0) { return 0; } return Math.log(deltaBackoff) / Math.log(super.maxRetryCount()); }
Source:
protected void sendJsonMessage(ChatRoom chatRoom, T jsonMessage) { if (chatRoom == null) { logger.error("Cannot sent message as chatRoom is null"); return; } String messageString = jsonMessage.toString(); Message chatRoomMessage = chatRoom.createMessage(null); try { if(chatRoom instanceof ChatRoomJabberImpl) ((ChatRoomJabberImpl)chatRoom).sendJsonMessage(chatRoomMessage, messageString); if (logger.isDebugEnabled()) logger.debug("Sending json message: \"" + messageString + "\""); } catch (OperationFailedException e) { logger.warn("Failed to send json message " + messageString, e); } }

Target:
protected void sendJsonMessage(ChatRoom chatRoom, T jsonMessage) { if (chatRoom == null) { logger.error("Cannot sent message as chatRoom is null"); return; } if (!(chatRoom instanceof ChatRoomJabberImpl)) { logger.error("Cannot sent message as chatRoom is not an" + "instance of ChatRoomJabberImpl"); return; } String messageString = jsonMessage.toString(); try { ((ChatRoomJabberImpl)chatRoom).sendJsonMessage(messageString); if (logger.isTraceEnabled()) logger.trace("Sending json message: \"" + messageString + "\""); } catch (OperationFailedException e) { logger.warn("Failed to send json message " + messageString, e); } }