auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) { int port; if (args.length == 0) { System.err.println("You must specify a port number."); System.exit(1); } port = Integer.parseInt(args[0]); GatewayServer gatewayServer = new GatewayServer(null, port); gatewayServer.start(); int listening_port = gatewayServer.getListeningPort(); System.out.println("" + listening_port); BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); try { stdin.readLine(); System.exit(0); } catch (java.io.IOException e) { System.exit(0); } }

Target:
public static void main(String[] args) { int port; boolean dieOnBrokenPipe = false; String usage = "usage: [--die-on-broken-pipe] port"; if (args.length == 0) { System.err.println(usage); System.exit(1); } else if (args.length == 2) { if (!args[0].equals("--die-on-broken-pipe")) { System.err.println(usage); System.exit(1); } dieOnBrokenPipe = true; } port = Integer.parseInt(args[args.length - 1]); GatewayServer gatewayServer = new GatewayServer(null, port); gatewayServer.start(); int listening_port = gatewayServer.getListeningPort(); System.out.println("" + listening_port); if (dieOnBrokenPipe) { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); try { stdin.readLine(); System.exit(0); } catch (java.io.IOException e) { System.exit(1); } } }
Source:
public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) { synchronized (buffers) { checkState(!isReleased); if (readView != null) { LOG.info("{} ReadView for Subpartition of has not been released!", parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); releaseView(); } LOG.debug("{}: Creating read view for subpartition of partition {}.", parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); readView = new PipelinedApproximateSubpartitionView(this, availabilityListener); } return readView; }

Target:
public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) { synchronized (buffers) { checkState(!isReleased); releaseView(); LOG.debug("{}: Creating read view for subpartition of partition {}.", parent.getOwningTaskName(), getSubPartitionIndex(), parent.getPartitionId()); readView = new PipelinedApproximateSubpartitionView(this, availabilityListener); } return readView; }
Source:
public void repositoryChanged(TaskRepositoryChangeEvent event) { Type type = event.getDelta().getType(); if (type == TaskRepositoryDelta.Type.PROPERTY) { Object key = event.getDelta().getKey(); if (IBugzillaConstants.BUGZILLA_USE_XMLRPC.equals(key) || IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE.equals(key)) { final TaskRepository repository = event.getRepository(); boolean startJob; synchronized (repository) { startJob = !repository.isUpdating(); if (startJob) { repository.setUpdating(true); } } if (startJob) { TaskJob updateJob = new UpdateRepositoryConfigurationJob( Messages.BugzillaClientManager_Refreshing_repository_configuration, repository, connector); updateJob.setPriority(Job.INTERACTIVE); updateJob.addJobChangeListener(repositoryConfigurationUpdateJobChangeAdapter); updateJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { synchronized (repository) { repository.setUpdating(false); } } }); updateJob.schedule(); } } } }

Target:
public void repositoryChanged(TaskRepositoryChangeEvent event) { Type type = event.getDelta().getType(); if (type == TaskRepositoryDelta.Type.PROPERTY) { Object key = event.getDelta().getKey(); if (IBugzillaConstants.BUGZILLA_USE_XMLRPC.equals(key) || IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE.equals(key)) { final TaskRepository repository = event.getRepository(); boolean startJob; synchronized (updateList) { startJob = !updateList.contains(repository); if (startJob) { updateList.add(repository); } } if (startJob) { TaskJob updateJob = new UpdateRepositoryConfigurationJob( Messages.BugzillaClientManager_Refreshing_repository_configuration, repository, connector); updateJob.setPriority(Job.INTERACTIVE); updateJob.addJobChangeListener(repositoryConfigurationUpdateJobChangeAdapter); updateJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { synchronized (updateList) { updateList.remove(repository); } } }); updateJob.schedule(); } } } }
Source:
public ResponseDto callback(String responseData) { logger.info("[register callback] data is {}", responseData); ResponseDto<RegisterContentDto> responseDto = ApiType.REGISTER.getParser().parse(responseData); if (responseDto == null) { logger.error("[register callback] parse callback data error, data is {}", responseData); return null; } if (responseDto.isSuccess()) { RegisterContentDto registerContentDto = responseDto.getContent(); ExtMarkDto extMarkDto = new GsonBuilder().create().fromJson(registerContentDto.getExtMark(), ExtMarkDto.class); this.messageQueueClient.publishMessage(MessageTopic.CertificationSuccess, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("loginName", extMarkDto.getLoginName()) .put("mobilePhone", registerContentDto.getMobilePhone()) .put("identityCode", registerContentDto.getIdentityCode()) .put("realName", registerContentDto.getRealName()) .put("accountNo", registerContentDto.getAccountNo()) .put("userName", registerContentDto.getUserName()) .put("orderDate", registerContentDto.getRegDate()) .put("orderNo", registerContentDto.getOrderNo()) .build())); } responseDto.setReqData(responseData); updateMapper.updateRegister(responseDto); return responseDto; }

Target:
public ResponseDto callback(String responseData) { logger.info("[register callback] data is {}", responseData); ResponseDto<RegisterContentDto> responseDto = ApiType.REGISTER.getParser().parse(responseData); if (responseDto == null) { logger.error("[register callback] parse callback data error, data is {}", responseData); return null; } if (responseDto.isSuccess()) { RegisterContentDto registerContentDto = responseDto.getContent(); ExtMarkDto extMarkDto = new GsonBuilder().create().fromJson(registerContentDto.getExtMark(), ExtMarkDto.class); this.messageQueueClient.publishMessage(MessageTopic.RegisterBankAccount, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("loginName", extMarkDto.getLoginName()) .put("mobile", registerContentDto.getMobilePhone()) .put("identityCode", registerContentDto.getIdentityCode()) .put("realName", registerContentDto.getRealName()) .put("accountNo", registerContentDto.getAccountNo()) .put("userName", registerContentDto.getUserName()) .put("orderDate", registerContentDto.getRegDate()) .put("orderNo", registerContentDto.getOrderNo()) .build())); } responseDto.setReqData(responseData); updateMapper.updateRegister(responseDto); return responseDto; }
Source:
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || "".equals(notify)) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || "".equals(sessions); String sessionEndpoint = null; if (invalidSessionsEndpoint) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }

Target:
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty(); String sessionEndpoint = null; if (invalidSessionsEndpoint) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }
Source:
protected void sendMessage(Message<?> message) { if (message == null) { throw new MessagingException("cannot send a null message"); } if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } try { this.messagingTemplate.send(getOutputChannel(), message); } catch (RuntimeException e) { MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { this.messagingTemplate.send(errorChannel, buildErrorMessage(e)); } else { throw e; } } }

Target:
protected void sendMessage(Message<?> message) { if (message == null) { throw new MessagingException("cannot send a null message"); } if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } try { this.messagingTemplate.send(getOutputChannel(), message); } catch (RuntimeException e) { MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { this.messagingTemplate.send(errorChannel, this.errorMessageStrategy.buildErrorMessage(e, ErrorMessageUtils.getAttributeAccessor(message, null))); } else { throw e; } } }
Source:
default List<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); List<T> list = this; List<T> result = List.empty(); boolean testFailed = false; while (!list.isEmpty()) { if (predicate.test(list.head())) { result = result.prepend(list.head()); } else { testFailed = true; } list = list.tail(); } return testFailed ? result.reverse() : this; }

Target:
default List<T> filter(Predicate<? super T> predicate) { final List<T> filtered = foldLeft(List.<T> empty(), (xs, x) -> predicate.test(x) ? xs.prepend(x) : xs); return this.length() == filtered.length() ? this : filtered.reverse(); }
Source:
public String execute(final LnClientConnection conn, final DlmsDevice device, final DataObject object) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress attributeAddress = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); LOGGER.info("Retrieving configuration objects for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final List<GetResult> getResultList = conn.get(attributeAddress); if (getResultList.isEmpty()) { throw new ProtocolAdapterException("No GetResult received while retrieving configuration objects."); } if (getResultList.size() > 1 || getResultList.get(0) == null) { throw new ProtocolAdapterException("Expected 1 GetResult while retrieving configuration objects, got " + getResultList.size()); } final DataObject resultData = getResultList.get(0).resultData(); if (!resultData.isComplex()) { this.throwUnexpectedTypeProtocolAdapterException(); } @SuppressWarnings("unchecked") final List<DataObject> resultDataValue = (List<DataObject>) getResultList.get(0).resultData().value(); final List<ClassIdObisAttr> allObisCodes = this.getAllObisCodes(resultDataValue); this.logAllObisCodes(allObisCodes); final String output = this.createOutput(conn, allObisCodes); LOGGER.info("Total output is: {}", output); return output; }

Target:
public String execute(final LnClientConnection conn, final DlmsDevice device, final DataObject object) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress attributeAddress = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); LOGGER.debug("Retrieving configuration objects for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final List<GetResult> getResultList = conn.get(attributeAddress); if (getResultList.isEmpty()) { throw new ProtocolAdapterException("No GetResult received while retrieving configuration objects."); } if (getResultList.size() > 1 || getResultList.get(0) == null) { throw new ProtocolAdapterException("Expected 1 GetResult while retrieving configuration objects, got " + getResultList.size()); } final DataObject resultData = getResultList.get(0).resultData(); if (!resultData.isComplex()) { this.throwUnexpectedTypeProtocolAdapterException(); } @SuppressWarnings("unchecked") final List<DataObject> resultDataValue = (List<DataObject>) getResultList.get(0).resultData().value(); final List<ClassIdObisAttr> allObisCodes = this.getAllObisCodes(resultDataValue); this.logAllObisCodes(allObisCodes); final String output = this.createOutput(conn, allObisCodes); LOGGER.debug("Total output is: {}", output); return output; }
Source:
protected void ExecuteVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); String[] deviceList = getParameters().getDeviceList().toArray(new String[] {}); boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> GetValue( ConfigValues.SupportForceCreateVG, getVds().getvds_group_compatibility_version().toString()); _result = supportForceCreateVG ? getBroker().createVG(storageDomainId, deviceList, isForce) : getBroker().createVG(storageDomainId, deviceList); ProceedProxyReturnValue(); setReturnValue(_result.mUuid); }

Target:
protected void ExecuteVdsBrokerCommand() { String storageDomainId = getParameters().getStorageDomainId().toString(); List<String> deviceList = getParameters().getDeviceList(); String[] deviceArray = deviceList.toArray(new String[deviceList.size()]); boolean isForce = getParameters().isForce(); boolean supportForceCreateVG = Config.<Boolean> GetValue( ConfigValues.SupportForceCreateVG, getVds().getvds_group_compatibility_version().toString()); _result = supportForceCreateVG ? getBroker().createVG(storageDomainId, deviceArray, isForce) : getBroker().createVG(storageDomainId, deviceArray); ProceedProxyReturnValue(); setReturnValue(_result.mUuid); }
Source:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { sizeCalculator = i -> offHeapEntryFactory.getSize(i) + OffHeapLruNode.getSize(); } this.lruLock = new ReentrantLock(); firstAddress = 0; }

Target:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { sizeCalculator = i -> offHeapEntryFactory.getSize(i); } this.lruLock = new ReentrantLock(); firstAddress = 0; }
Source:
public UserPortalNewTemplateVmModelBehavior() { super(); }

Target:
public UserPortalNewTemplateVmModelBehavior() { }
Source:
public static <K, V, K2> Map<K2, V> mapKeys(Map<K, V> map, Function<K, K2> keyMapper) { final Map<K2, V> result = Maps.newHashMapWithExpectedSize(map.size()); map.forEach((k, v) -> { final K2 k2 = keyMapper.apply(k); if (result.containsKey(k2)) { throw new ISE("Conflicting key[%s] calculated via keyMapper for original key[%s]", k2, k); } result.put(k2, v); }); return result; }

Target:
public static <K, V, K2> Map<K2, V> mapKeys(Map<K, V> map, Function<K, K2> keyMapper) { final Map<K2, V> result = Maps.newHashMapWithExpectedSize(map.size()); map.forEach((k, v) -> { final K2 k2 = keyMapper.apply(k); if (result.putIfAbsent(k2, v) != null) { throw new ISE("Conflicting key[%s] calculated via keyMapper for original key[%s]", k2, k); } }); return result; }
Source:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; }

Target:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
Source:
public static Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put(CLASSNAME + MetricsAware.KEY_REGEX + TOTAL_EVENTS_COUNT, new Counter()); return metrics; }

Target:
public static Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put(CLASSNAME + MetricsAware.KEY_REGEX + TOTAL_EVENTS_COUNT, new Counter()); return Collections.unmodifiableMap(metrics); }
Source:
public static ConditionEvaluationResult disabled(String reason, String customReason) { if (customReason.isEmpty()) { return disabled(reason); } return disabled(String.format("%s ==> %s", reason, customReason)); }

Target:
public static ConditionEvaluationResult disabled(String reason, String customReason) { if (StringUtils.isBlank(customReason)) { return disabled(reason); } return disabled(String.format("%s ==> %s", reason, customReason)); }
Source:
public XAResourceRecord(TransactionImple tx, XAResource res, Xid xid, Object[] params) { if (jtaxLogger.logger.isTraceEnabled()) { jtaxLogger.logger.trace("XAResourceRecord.XAResourceRecord ( " + xid + " )"); } _theXAResource = res; _recoveryObject = null; _tranID = xid; _valid = true; if (params != null) { if (params.length >= XACONNECTION + 1) { if (params[XACONNECTION] instanceof RecoverableXAConnection) _recoveryObject = (RecoverableXAConnection) params[XACONNECTION]; } } _prepared = false; _committed = false; _heuristic = TwoPhaseOutcome.FINISH_OK; _participantStore = null; _theUid = new Uid(); _theReference = null; _recoveryCoordinator = null; _theTransaction = tx; if (_theXAResource instanceof FirstResource) _cachedUidStringForm = START_XARESOURCE.stringForm(); else if (_theXAResource instanceof LastResource) _cachedUidStringForm = END_XARESOURCE.stringForm(); }

Target:
public XAResourceRecord(TransactionImple tx, XAResource res, Xid xid, Object[] params) { if (jtaxLogger.logger.isTraceEnabled()) { jtaxLogger.logger.trace("XAResourceRecord.XAResourceRecord ( " + xid + " )"); } _theXAResource = res; _recoveryObject = null; _tranID = xid; _valid = true; if (params != null) { if (params.length > XACONNECTION) { if (params[XACONNECTION] instanceof RecoverableXAConnection) _recoveryObject = (RecoverableXAConnection) params[XACONNECTION]; } } _prepared = false; _committed = false; _heuristic = TwoPhaseOutcome.FINISH_OK; _participantStore = null; _theUid = new Uid(); _theReference = null; _recoveryCoordinator = null; _theTransaction = tx; if (_theXAResource instanceof FirstResource) _cachedUidStringForm = START_XARESOURCE.stringForm(); else if (_theXAResource instanceof LastResource) _cachedUidStringForm = END_XARESOURCE.stringForm(); }
Source:
public void testTumblingWindowsDiscardingMode() throws Exception { StreamGraphBuilder sgb = new KeyedTumblingWindowStreamGraphBuilder(AccumulationMode.DISCARDING); StreamOperatorTask task = new StreamOperatorTask(sgb); task.init(config, taskContext); integers.forEach(n -> task.process(new IntegerMessageEnvelope(n, n), messageCollector, taskCoordinator)); Thread.sleep(1000); task.window(messageCollector, taskCoordinator); Assert.assertEquals(windowPanes.size(), 5); Assert.assertEquals(windowPanes.get(0).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection) windowPanes.get(0).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(1).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection) windowPanes.get(1).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(2).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection) windowPanes.get(2).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(3).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection) windowPanes.get(3).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(4).getKey().getKey(), new Integer(3)); Assert.assertEquals(((Collection) windowPanes.get(4).getMessage()).size(), 1); }

Target:
public void testTumblingWindowsDiscardingMode() throws Exception { StreamApplication sgb = new KeyedTumblingWindowStreamApplication(AccumulationMode.DISCARDING, Duration.ofSeconds(1), Triggers.repeat(Triggers.count(2))); TestClock testClock = new TestClock(); StreamOperatorTask task = new StreamOperatorTask(sgb, testClock, runner); task.init(config, taskContext); integers.forEach(n -> task.process(new IntegerMessageEnvelope(n, n), messageCollector, taskCoordinator)); testClock.advanceTime(Duration.ofSeconds(1)); task.window(messageCollector, taskCoordinator); Assert.assertEquals(windowPanes.size(), 5); Assert.assertEquals(windowPanes.get(0).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(0).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(1).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(1).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(2).getKey().getKey(), new Integer(1)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(2).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(3).getKey().getKey(), new Integer(2)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(3).getMessage()).size(), 2); Assert.assertEquals(windowPanes.get(4).getKey().getKey(), new Integer(3)); Assert.assertEquals(((Collection<MessageEnvelope<Integer, Integer>>) windowPanes.get(4).getMessage()).size(), 1); }
Source:
private Repository getRepository(boolean warn, IStructuredSelection selection, Shell shell) { RepositoryMapping mapping = null; for (IResource respource : getSelectedResources(selection)) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(respource); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_multiRepoSelectionTitle, UIText.RepositoryAction_multiRepoSelection); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); return null; } final Repository repository = mapping.getRepository(); return repository; }

Target:
private Repository getRepository(boolean warn, IStructuredSelection selection, Shell shell) { RepositoryMapping mapping = null; for (IResource resource : getSelectedResources(selection)) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(resource); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_multiRepoSelectionTitle, UIText.RepositoryAction_multiRepoSelection); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); return null; } final Repository repository = mapping.getRepository(); return repository; }
Source:
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); EdgeStyleDescription esd = StyleFactory.eINSTANCE.createEdgeStyleDescription(); esd.setSizeComputationExpression("2"); esd.setCenterLabelStyleDescription(StyleFactory.eINSTANCE.createCenterLabelStyleDescription()); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__STYLE, esd)); BracketEdgeStyleDescription bsd = StyleFactory.eINSTANCE.createBracketEdgeStyleDescription(); bsd.setSizeComputationExpression("2"); bsd.setCenterLabelStyleDescription(StyleFactory.eINSTANCE.createCenterLabelStyleDescription()); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__STYLE, bsd)); ConditionalEdgeStyleDescription conditionalEdgeStyle = DescriptionFactory.eINSTANCE.createConditionalEdgeStyleDescription(); EdgeStyleDescription edgeStyle = ((EdgeMapping) object).getStyle(); EdgeStyleDescription newStyle; if (edgeStyle != null && edgeStyle.eClass() == StylePackage.eINSTANCE.getBracketEdgeStyleDescription()) { newStyle = StyleFactory.eINSTANCE.createBracketEdgeStyleDescription(); } else { newStyle = StyleFactory.eINSTANCE.createEdgeStyleDescription(); } newStyle.setSizeComputationExpression("2"); newStyle.setCenterLabelStyleDescription(StyleFactory.eINSTANCE.createCenterLabelStyleDescription()); conditionalEdgeStyle.setStyle(newStyle); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__CONDITIONNAL_STYLES, conditionalEdgeStyle)); }

Target:
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); EdgeStyleDescription esd = StyleFactory.eINSTANCE.createEdgeStyleDescription(); edgeStyleInit(esd); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__STYLE, esd)); BracketEdgeStyleDescription bsd = StyleFactory.eINSTANCE.createBracketEdgeStyleDescription(); edgeStyleInit(bsd); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__STYLE, bsd)); ConditionalEdgeStyleDescription conditionalEdgeStyle = DescriptionFactory.eINSTANCE.createConditionalEdgeStyleDescription(); EdgeStyleDescription edgeStyle = ((EdgeMapping) object).getStyle(); EdgeStyleDescription newStyle; if (edgeStyle != null && edgeStyle.eClass() == StylePackage.eINSTANCE.getBracketEdgeStyleDescription()) { newStyle = StyleFactory.eINSTANCE.createBracketEdgeStyleDescription(); } else { newStyle = StyleFactory.eINSTANCE.createEdgeStyleDescription(); } edgeStyleInit(newStyle); conditionalEdgeStyle.setStyle(newStyle); newChildDescriptors.add(createChildParameter(org.eclipse.sirius.diagram.description.DescriptionPackage.Literals.EDGE_MAPPING__CONDITIONNAL_STYLES, conditionalEdgeStyle)); }
Source:
protected ProgramInformation parseProgramInformation(XmlPullParser xpp) throws IOException, XmlPullParserException { String title = ""; String source = ""; String copyright = ""; List<byte[]> customEvents = new ArrayList<>(); do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "Title")) { title = xpp.getText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Source")) { source = xpp.getText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Copyright")) { copyright = xpp.getText(); } else { byte[] customElement = parseCustomElement(xpp, new ByteArrayOutputStream(512)); if (customElement.length > 0) { customEvents.add(customElement); } } } while (!XmlPullParserUtil.isEndTag(xpp, "ProgramInformation")); return new ProgramInformation(title, source, copyright, customEvents); }

Target:
protected ProgramInformation parseProgramInformation(XmlPullParser xpp) throws IOException, XmlPullParserException { String title = null; String source = null; String copyright = null; String moreInformationURL = parseString(xpp, "moreInformationURL", null); String lang = parseString(xpp, "lang", null); do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "Title")) { title = xpp.nextText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Source")) { source = xpp.nextText(); } else if (XmlPullParserUtil.isStartTag(xpp, "Copyright")) { copyright = xpp.nextText(); } else { maybeSkipTag(xpp); } } while (!XmlPullParserUtil.isEndTag(xpp, "ProgramInformation")); return new ProgramInformation(title, source, copyright, moreInformationURL, lang); }
Source:
protected Map<ComponentType, String> buildCustomVersionDisplayNames() { Map<ComponentType, String> result = new HashMap<>(); return result; }

Target:
protected Map<ComponentType, String> buildCustomVersionDisplayNames() { Map<ComponentType, String> result = new HashMap<>(); result.put(ComponentType.HIVE, "Qubole Hadoop2 (Hive 2.1.1 Beta)"); result.put(ComponentType.PIG, "Qubole Hadoop2"); result.put(ComponentType.PIGOUTPUT, "Qubole Hadoop2"); return result; }
Source:
public void deliverAll(MessageKind kind) { this.delivering = true; for (Tuple update : this.queue.keySet()) { int count = this.queue.get(update); assert count != 0; Direction direction = count < 0 ? Direction.REVOKE : Direction.INSERT; for (int i = 0; i < Math.abs(count); i++) { this.receiver.update(direction, update); } } this.delivering = false; Map<Tuple, Integer> tmp = this.queue; this.queue = this.buffer; this.buffer = tmp; this.buffer.clear(); }

Target:
public void deliverAll(MessageKind kind) { this.delivering = true; for (Tuple update : this.queue.keySet()) { int count = this.queue.get(update); Direction direction = count < 0 ? Direction.REVOKE : Direction.INSERT; for (int i = 0; i < Math.abs(count); i++) { this.receiver.update(direction, update); } } this.delivering = false; Map<Tuple, Integer> tmp = this.queue; this.queue = this.buffer; this.buffer = tmp; this.buffer.clear(); }
Source:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } children.put(field.getName().getPrefixedName(), property); setIsModified(); }

Target:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } children.put(property.getName(), property); setIsModified(); }
Source:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { Blob blob = (Blob) input; mpinput.setBlob(blob); } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }

Target:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { mpinput.setBlob((Blob) input); } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }
Source:
private void invalidateMediaViewIfNeed(View containerView) { int containerViewWidth = containerView.getWidth(); int containerViewHeight = containerView.getHeight(); if (containerViewWidth <= 0 || containerViewHeight <= 0) { return; } boolean isContainerViewLandscape = containerViewWidth > containerViewHeight; ViewGroup.LayoutParams params = mediaView.getLayoutParams(); if (mediaView.getWidth() == 0 && params.width == ViewGroup.LayoutParams.MATCH_PARENT && mediaView.getHeight() == 0 && params.height == ViewGroup.LayoutParams.MATCH_PARENT) { if (containerViewWidth == containerViewHeight) { mediaView.setMinimumWidth(containerViewWidth); mediaView.setMinimumHeight(containerViewHeight); } else { int width = ( isContainerViewLandscape ? containerViewWidth : ( nativeVideo.getVideoOrientation() == VERTICAL ? (int)(containerViewHeight * RATIO_9_TO_16) : (int)(containerViewHeight / RATIO_16_TO_9) ) ); int height = ( !isContainerViewLandscape ? containerViewHeight : ( nativeVideo.getVideoOrientation() == VERTICAL ? (int)(containerViewWidth * RATIO_9_TO_16) : (int)(containerViewWidth / RATIO_16_TO_9) ) ); mediaView.setMinimumWidth(width); mediaView.setMinimumHeight(height); } mediaView.invalidate(); } }

Target:
private void invalidateMediaViewIfNeed(View containerView) { int containerViewWidth = containerView.getWidth(); int containerViewHeight = containerView.getHeight(); if (containerViewWidth <= 0 || containerViewHeight <= 0) { return; } boolean isContainerViewLandscape = containerViewWidth > containerViewHeight; ViewGroup.LayoutParams params = mediaView.getLayoutParams(); if (mediaView.getWidth() == 0 && params.width == ViewGroup.LayoutParams.MATCH_PARENT && mediaView.getHeight() == 0 && params.height == ViewGroup.LayoutParams.MATCH_PARENT) { if (containerViewWidth == containerViewHeight) { mediaView.setMinimumWidth(containerViewWidth); mediaView.setMinimumHeight(containerViewHeight); } else { int width = getOffsetSide(containerViewHeight, containerViewWidth, isContainerViewLandscape); int height = getOffsetSide(containerViewWidth, containerViewHeight, !isContainerViewLandscape); mediaView.setMinimumWidth(width); mediaView.setMinimumHeight(height); } mediaView.invalidate(); } }
Source:
public boolean onKill(Scheduler.KillTopologyRequest request) { return false; }

Target:
public boolean onKill(Scheduler.KillTopologyRequest request) { StringBuilder stdout = new StringBuilder(); StringBuilder stderr = new StringBuilder(); List<String> taskList = getJobLinks(); for (String taskId : taskList) { StringBuilder killJob = new StringBuilder(); killJob.append(EcsContext.composeStopCmd(config)); killJob.append(" "); killJob.append(taskId); int status = ShellUtils.runProcess(killJob.toString(), null); if (status != 0) { LOG.severe(String.format( "Failed to run process. Command=%s, STDOUT=%s, STDERR=%s", EcsContext.composeStopCmd(config), stdout, stderr)); isTopologyKilled = false; } else { LOG.info("Topology Task stop Successful"); isTopologyKilled = true; } } return isTopologyKilled; }
Source:
private void notifyBridgeAboutChildHandlerDisposal(final Thing thing, final ThingHandler thingHandler) { final Bridge bridge = getBridge(thing.getBridgeUID()); if (bridge != null) { ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { BridgeHandler bridgeHandler = bridge.getHandler(); if (bridgeHandler != null) { bridgeHandler.childHandlerDisposed(thingHandler, thing); } } catch (Exception ex) { logger.error("Exception occured during bridge handler notification ('" + bridge.getUID() + "') about handler disposal of child '{}' '" + thing.getUID() + "': " + ex.getMessage(), ex); } } }); } }

Target:
private void notifyBridgeAboutChildHandlerDisposal(final Thing thing, final ThingHandler thingHandler) { final Bridge bridge = getBridge(thing.getBridgeUID()); if (bridge != null) { ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { BridgeHandler bridgeHandler = bridge.getHandler(); if (bridgeHandler != null) { bridgeHandler.childHandlerDisposed(thingHandler, thing); } } catch (Exception ex) { logger.error( "Exception occured during bridge handler ('{}') notification about handler disposal of child '{}': {}", bridge.getUID(), thing.getUID(), ex.getMessage(), ex); } } }); } }
Source:
private void checkArgument(FunctionCallTree tree, int argNumber) { if (argNumber > tree.arguments().size()) { return; } ExpressionTree arg = tree.arguments().get(argNumber - 1); if(arg.is(Kind.REGULAR_STRING_LITERAL) && ((LiteralTree)arg).value().length() - 2 >= MIN_LENGTH_OF_HARDCODED_PASSWORD) { context().newIssue(this, arg, MESSAGE_ARGUMENTS); } }

Target:
private void checkArgument(FunctionCallTree tree, int argNumber) { if (argNumber > tree.arguments().size()) { return; } ExpressionTree arg = tree.arguments().get(argNumber - 1); if (arg.is(Kind.REGULAR_STRING_LITERAL) && !isEmptyStringLiteral((LiteralTree) arg)) { context().newIssue(this, arg, MESSAGE_ARGUMENTS); } }
Source:
protected MongoPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(MongoPersistentProperty property) { Assert.notNull(property); if (!property.isIdProperty()) { return null; } MongoPersistentProperty currentIdProperty = getIdProperty(); boolean currentIdPropertyIsSet = currentIdProperty != null; @SuppressWarnings("null") boolean currentIdPropertyIsExplicit = currentIdPropertyIsSet ? currentIdProperty.isExplicitIdProperty() : false; boolean newIdPropertyIsExplicit = property.isExplicitIdProperty(); if (!currentIdPropertyIsSet) { return property; } else { @SuppressWarnings("null") Field currentIdPropertyField = currentIdProperty.getField(); if (newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { throw new MappingException(String.format( "Attempt to add explicit id property %s but already have an property %s registered " + "as explicit id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } else if (newIdPropertyIsExplicit && !currentIdPropertyIsExplicit) { return property; } else if (!newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { } else { throw new MappingException(String.format( "Attempt to add id property %s but already have an property %s registered " + "as id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } } return null; }

Target:
protected MongoPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(MongoPersistentProperty property) { Assert.notNull(property); if (!property.isIdProperty()) { return null; } MongoPersistentProperty currentIdProperty = getIdProperty(); boolean currentIdPropertyIsSet = currentIdProperty != null; @SuppressWarnings("null") boolean currentIdPropertyIsExplicit = currentIdPropertyIsSet ? currentIdProperty.isExplicitIdProperty() : false; boolean newIdPropertyIsExplicit = property.isExplicitIdProperty(); if (!currentIdPropertyIsSet) { return property; } @SuppressWarnings("null") Field currentIdPropertyField = currentIdProperty.getField(); if (newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { throw new MappingException(String.format( "Attempt to add explicit id property %s but already have an property %s registered " + "as explicit id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } else if (newIdPropertyIsExplicit && !currentIdPropertyIsExplicit) { return property; } else if (!newIdPropertyIsExplicit && currentIdPropertyIsExplicit) { } else { throw new MappingException(String.format( "Attempt to add id property %s but already have an property %s registered " + "as id. Check your mapping configuration!", property.getField(), currentIdPropertyField)); } return null; }
Source:
public void should_create_issue_pom_xml() { assumeTrue(orchestrator.getServer().version().isGreaterThanOrEquals(6, 3)); orchestrator.getServer().restoreProfile(FileLocation.ofClasspath("/profile-pom-xml.xml")); orchestrator.getServer().provisionProject("org.sonarsource.java:test-project", "Test Project"); orchestrator.getServer().associateProjectToQualityProfile("org.sonarsource.java:test-project", "java", "java-pom-xml"); MavenBuild build = MavenBuild.create() .setPom(TestUtils.projectPom("pom-xml")) .setCleanPackageSonarGoals(); orchestrator.executeBuild(build); IssueClient issueClient = orchestrator.getServer().wsClient().issueClient(); List<Issue> issues = issueClient.find(IssueQuery.create().components("org.sonarsource.java:test-project:pom.xml")).list(); assertThat(issues).hasSize(1); assertThat(issues.iterator().next().ruleKey()).isEqualTo("squid:S3423"); }

Target:
public void should_create_issue_pom_xml() { orchestrator.getServer().restoreProfile(FileLocation.ofClasspath("/profile-pom-xml.xml")); orchestrator.getServer().provisionProject("org.sonarsource.java:test-project", "Test Project"); orchestrator.getServer().associateProjectToQualityProfile("org.sonarsource.java:test-project", "java", "java-pom-xml"); MavenBuild build = MavenBuild.create() .setPom(TestUtils.projectPom("pom-xml")) .setCleanPackageSonarGoals(); orchestrator.executeBuild(build); IssueClient issueClient = orchestrator.getServer().wsClient().issueClient(); List<Issue> issues = issueClient.find(IssueQuery.create().components("org.sonarsource.java:test-project:pom.xml")).list(); assertThat(issues).hasSize(1); assertThat(issues.iterator().next().ruleKey()).isEqualTo("squid:S3423"); }
Source:
private boolean hasEnoughNumberOfSpecialChars(String value) { int numberOfSpecialChars = 0; for (char c : value.toCharArray()) { if (SPECIAL_CHARS.contains(c)) { numberOfSpecialChars++; } } return numberOfSpecialChars >= 2; }

Target:
private boolean hasEnoughNumberOfSpecialChars(String value) { int numberOfSpecialChars = 0; for (char c : value.toCharArray()) { if (SPECIAL_CHARS.contains(c)) { numberOfSpecialChars++; } if (numberOfSpecialChars == 2) { return true; } } return false; }
Source:
public Set<String> getKnoxGatewayGroups(Stack stack) { LOGGER.info("Fetching list of instance groups with Knox gateway installed"); Set<String> groupNames = new HashSet<>(); Cluster cluster = stack.getCluster(); if (cluster != null) { CmTemplateProcessor cmTemplateProcessor = new CmTemplateProcessor(cluster.getBlueprint().getBlueprintText()); Map<String, Set<ServiceComponent>> components = cmTemplateProcessor.getServiceComponentsByHostGroup(); LOGGER.info("Checking if Knox gateway is explicitly defined"); groupNames = components.entrySet().stream() .filter(e -> e.getValue().stream().anyMatch(c -> KnoxRoles.KNOX_GATEWAY.equals(c.getComponent()))) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } if (groupNames.isEmpty()) { LOGGER.info("Knox gateway is not explicitly defined; searching for CM gateway hosts"); groupNames = stack.getInstanceGroups().stream() .filter(i -> InstanceGroupType.isGateway(i.getInstanceGroupType())) .map(InstanceGroup::getGroupName) .collect(Collectors.toSet()); } if (groupNames.isEmpty()) { LOGGER.info("No Knox gateway instance groups found"); } return groupNames; }

Target:
public Set<String> getKnoxGatewayGroups(Stack stack) { LOGGER.info("Fetching list of instance groups with Knox gateway installed"); Set<String> groupNames = new HashSet<>(); Cluster cluster = stack.getCluster(); if (cluster != null) { LOGGER.debug("Checking if Knox gateway is explicitly defined"); CmTemplateProcessor cmTemplateProcessor = new CmTemplateProcessor(cluster.getBlueprint().getBlueprintText()); groupNames = cmTemplateProcessor.getHostGroupsWithComponent(KnoxRoles.KNOX_GATEWAY); } if (groupNames.isEmpty()) { LOGGER.info("Knox gateway is not explicitly defined; searching for CM gateway hosts"); groupNames = stack.getInstanceGroups().stream() .filter(i -> InstanceGroupType.isGateway(i.getInstanceGroupType())) .map(InstanceGroup::getGroupName) .collect(Collectors.toSet()); } if (groupNames.isEmpty()) { LOGGER.info("No Knox gateway instance groups found"); } return groupNames; }
Source:
private String getHTML(Alert alert) { StringBuilder httpMessage = new StringBuilder(); HttpMessage message = alert.getMessage(); if (message == null) { LOGGER.warn(String.format(Constant.messages.getString("codedx.error.httpMessage"), alert.getAlertId())); return httpMessage.toString(); } String requestHeader = message.getRequestHeader().toString(); String requestBody = message.getRequestBody().toString(); String responseHeader = message.getResponseHeader().toString(); String responseBody = message.getResponseBody().toString(); httpMessage.append("<requestdata>"); httpMessage.append(ReportGenerator.entityEncode(requestHeader)); httpMessage.append(ReportGenerator.entityEncode(requestBody)); httpMessage.append("\n</requestdata>\n"); httpMessage.append("<responsedata>"); httpMessage.append(ReportGenerator.entityEncode(responseHeader)); httpMessage.append(ReportGenerator.entityEncode(responseBody)); httpMessage.append("\n</responsedata>\n"); return httpMessage.toString(); }

Target:
private String getHTML(Alert alert) { StringBuilder httpMessage = new StringBuilder(); HttpMessage message = alert.getMessage(); if (message == null) { LOGGER.warn(Constant.messages.getString("codedx.error.httpMessage", alert.getAlertId())); return httpMessage.toString(); } String requestHeader = message.getRequestHeader().toString(); String requestBody = message.getRequestBody().toString(); String responseHeader = message.getResponseHeader().toString(); String responseBody = message.getResponseBody().toString(); httpMessage.append("<requestdata>"); httpMessage.append(ReportGenerator.entityEncode(requestHeader)); httpMessage.append(ReportGenerator.entityEncode(requestBody)); httpMessage.append("\n</requestdata>\n"); httpMessage.append("<responsedata>"); httpMessage.append(ReportGenerator.entityEncode(responseHeader)); httpMessage.append(ReportGenerator.entityEncode(responseBody)); httpMessage.append("\n</responsedata>\n"); return httpMessage.toString(); }
Source:
private byte[] marshall(final ActorMapping model) throws XmlParseException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){ final JAXBContext contextObj = JAXBContext.newInstance(model.getClass()); final Marshaller m = contextObj.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(model, baos); return baos.toByteArray(); } catch (JAXBException| IOException e){ throw new XmlParseException("Failed to serialize the ActorMapping",e); } }

Target:
private byte[] marshall(final ActorMapping model) throws XmlMarshallException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { final JAXBContext contextObj = JAXBContext.newInstance(model.getClass()); final Marshaller m = contextObj.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(model, baos); return baos.toByteArray(); } catch (JAXBException | IOException e) { throw new XmlMarshallException("Failed to serialize the ActorMapping", e); } }
Source:
private static int bufferPadding(int numBytes) { if (numBytes == 3) { return Ints.BYTES - numBytes; } else { return 0; } }

Target:
private static int bufferPadding(int numBytes) { switch (numBytes) { case Shorts.BYTES: case 1: return 0; default: return Ints.BYTES - numBytes; } }
Source:
protected InterProcessMutex(CuratorFramework client, String path, LockInternalsDriver driver) { this(client, path, LOCK_NAME, 1, driver); }

Target:
public InterProcessMutex(CuratorFramework client, String path, LockInternalsDriver driver) { this(client, path, LOCK_NAME, 1, driver); }