auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean nextFromTxState() { if ( txTypeIterator == null && !txTypes.isEmpty() ) { txTypeIterator = txTypes.iterator(); } if ( txTypeIterator != null && txTypeIterator.hasNext() ) { setType( txTypeIterator.next() ); return true; } return false; }

Target:
private boolean nextFromTxState() { if ( txTypeIterator == null && !txTypes.isEmpty() ) { txTypeIterator = txTypes.iterator(); } if ( txTypeIterator != null && txTypeIterator.hasNext() ) { setType( txTypeIterator.next() ); setFirstOut( NO_ID ); setFirstIn( NO_ID ); setFirstLoop( NO_ID ); return true; } return false; }
Source:
public JSONObject fetchDiff() throws IOException, ConduitAPIException { Map params = new HashMap<String, String>(); params.put("ids[]", diffID); JSONObject query = this.callConduit("differential.querydiffs", params); JSONObject response; try { response = query.getJSONObject("result"); } catch (JSONException e) { throw new ConduitAPIException( String.format("No 'result' object found in conduit call: (%s) %s", e.getMessage(), query.toString(2))); } try { return response.getJSONObject(diffID); } catch (JSONException e) { throw new ConduitAPIException( String.format("Unable to find '%s' key in response: (%s) %s", diffID, e.getMessage(), response.toString(2))); } }

Target:
public JSONObject fetchDiff() throws IOException, ConduitAPIException { Map params = new HashMap<String, String>(); params.put("ids[]", diffID); JSONObject query = this.callConduit("differential.querydiffs", params); JSONObject response; try { response = query.getJSONObject("result"); } catch (JSONException e) { throw new ConduitAPIException( String.format("No 'result' object found in conduit call: (%s) %s", e.getMessage(), query.toString(2))); } try { return response.getJSONObject(diffID); } catch (JSONException e) { throw new ConduitAPIException( String.format("Unable to find '%s' key in 'result': (%s) %s", diffID, e.getMessage(), response.toString(2))); } }
Source:
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_main, container, false); unbinder = ButterKnife.bind(this, view); disposables.add(WikipediaApp.getInstance().getBus().subscribe(new EventBusConsumer())); viewPager.setUserInputEnabled(false); viewPager.setAdapter(new NavTabFragmentPagerAdapter(this)); viewPager.registerOnPageChangeCallback(pageChangeCallback); FeedbackUtil.setButtonLongPressToast(moreContainer); tabLayout.setOnNavigationItemSelectedListener(item -> { if (getCurrentFragment() instanceof FeedFragment && item.getOrder() == 0) { ((FeedFragment) getCurrentFragment()).scrollToTop(); } if (getCurrentFragment() instanceof HistoryFragment && item.getOrder() == NavTab.SEARCH.code()) { openSearchActivity(NAV_MENU, null); } viewPager.setCurrentItem(item.getOrder(), false); return true; }); maybeShowEditsTooltip(); if (savedInstanceState == null) { handleIntent(requireActivity().getIntent()); } return view; }

Target:
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_main, container, false); unbinder = ButterKnife.bind(this, view); disposables.add(WikipediaApp.getInstance().getBus().subscribe(new EventBusConsumer())); viewPager.setUserInputEnabled(false); viewPager.setAdapter(new NavTabFragmentPagerAdapter(this)); viewPager.registerOnPageChangeCallback(pageChangeCallback); FeedbackUtil.setButtonLongPressToast(moreContainer); tabLayout.setOnNavigationItemSelectedListener(item -> { if (getCurrentFragment() instanceof FeedFragment && item.getOrder() == 0) { ((FeedFragment) getCurrentFragment()).scrollToTop(); } if (getCurrentFragment() instanceof HistoryFragment && item.getOrder() == NavTab.SEARCH.code()) { openSearchActivity(NAV_MENU, null); return true; } viewPager.setCurrentItem(item.getOrder(), false); return true; }); maybeShowEditsTooltip(); if (savedInstanceState == null) { handleIntent(requireActivity().getIntent()); } return view; }
Source:
public ModuleDefinition getModuleDefinition() { if (moduleDefinition == null) { moduleDefinition = ModuleDefinitions.dummy(moduleName, type); } return moduleDefinition; }

Target:
public ModuleDefinition getModuleDefinition() { if (moduleDefinition == null) { moduleDefinition = new ModuleDefinition(moduleName, type) { @Override public boolean isComposed() { return false; } }; } return moduleDefinition; }
Source:
public void initialize() { try { address = new BluetoothAddress(getConfig().get(BluetoothBindingConstants.CONFIGURATION_ADDRESS).toString()); } catch (IllegalArgumentException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getLocalizedMessage()); return; } Bridge bridge = getBridge(); if (bridge == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Not associated with any bridge"); return; } BridgeHandler bridgeHandler = bridge.getHandler(); if (!(bridgeHandler instanceof BluetoothAdapter)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Associated with an unsupported bridge"); return; } adapter = (BluetoothAdapter) bridgeHandler; deviceLock.lock(); device = adapter.getDevice(address); device.addListener(this); deviceLock.unlock(); updateStatus(ThingStatus.UNKNOWN); }

Target:
public void initialize() { try { address = new BluetoothAddress(getConfig().get(BluetoothBindingConstants.CONFIGURATION_ADDRESS).toString()); } catch (IllegalArgumentException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getLocalizedMessage()); return; } Bridge bridge = getBridge(); if (bridge == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Not associated with any bridge"); return; } BridgeHandler bridgeHandler = bridge.getHandler(); if (!(bridgeHandler instanceof BluetoothAdapter)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Associated with an unsupported bridge"); return; } adapter = (BluetoothAdapter) bridgeHandler; try { deviceLock.lock(); device = adapter.getDevice(address); device.addListener(this); } finally { deviceLock.unlock(); } updateStatus(ThingStatus.UNKNOWN); }
Source:
public static Builder builder(String packageName, TypeSpec typeSpec) { Objects.requireNonNull(packageName, "packageName == null"); Objects.requireNonNull(typeSpec, "typeSpec == null"); return new Builder(packageName, typeSpec); }

Target:
public static Builder builder(String packageName, TypeSpec typeSpec) { requireNonNull(packageName, "packageName == null"); requireNonNull(typeSpec, "typeSpec == null"); return new Builder(packageName, typeSpec); }
Source:
private Pair<View, TreeReference> loadTile(Activity activity) { AndroidSessionWrapper asw; try { asw = CommCareApplication._().getCurrentSessionWrapper(); } catch (SessionStateUninitException e) { return null; } CommCareSession session = asw.getSession(); StackFrameStep stepToFrame = null; Vector<StackFrameStep> v = session.getFrame().getSteps(); for(int i = v.size() -1 ; i >= 0; i--){ StackFrameStep step = v.elementAt(i); if(SessionFrame.STATE_DATUM_VAL.equals(step.getType())) { SessionDatum d = asw.getSession().findDatumDefinition(step.getId()); if(d.getPersistentDetail() != null) { stepToFrame = step; } } } Pair<View, TreeReference> tile = buildContextTile(stepToFrame, asw); if(tile == null && activity instanceof CommCareActivity) { Pair<Detail, TreeReference> entityContext = ((CommCareActivity)activity).requestEntityContext(); if(entityContext != null) { tile = buildContextTile(entityContext.first, entityContext.second, asw); } } return tile; }

Target:
private Pair<View, TreeReference> loadTile(Activity activity) { AndroidSessionWrapper asw; try { asw = CommCareApplication._().getCurrentSessionWrapper(); } catch (SessionStateUninitException e) { return null; } CommCareSession session = asw.getSession(); StackFrameStep stepToFrame = null; Vector<StackFrameStep> v = session.getFrame().getSteps(); for(int i = v.size() -1 ; i >= 0; i--){ StackFrameStep step = v.elementAt(i); if(SessionFrame.STATE_DATUM_VAL.equals(step.getType())) { SessionDatum d = asw.getSession().findDatumDefinition(step.getId()); if(d != null && d.getPersistentDetail() != null) { stepToFrame = step; } } } Pair<View, TreeReference> tile = buildContextTile(stepToFrame, asw); if(tile == null && activity instanceof CommCareActivity) { Pair<Detail, TreeReference> entityContext = ((CommCareActivity)activity).requestEntityContext(); if(entityContext != null) { tile = buildContextTile(entityContext.first, entityContext.second, asw); } } return tile; }
Source:
public static UserProvider login(Map<String, Object> conf, Configuration hbaseConfig) throws IOException { if (UserGroupInformation.isSecurityEnabled()) { List<String> autoCredentials = (List) conf.get(TOPOLOGY_AUTO_CREDENTIALS); if ((autoCredentials == null) || (!autoCredentials.contains(AutoHBase.class.getName()) && !autoCredentials.contains(AutoTGT.class.getName()))) { LOG.info("Logging in using keytab as either AutoHBase or AutoTGT is specified for " + TOPOLOGY_AUTO_CREDENTIALS); if (legacyProvider == null) { synchronized (HBaseSecurityUtil.class) { if (legacyProvider == null) { legacyProvider = UserProvider.instantiate(hbaseConfig); String keytab = (String) conf.get(STORM_KEYTAB_FILE_KEY); if (keytab != null) { hbaseConfig.set(STORM_KEYTAB_FILE_KEY, keytab); } String userName = (String) conf.get(STORM_USER_NAME_KEY); if (userName != null) { hbaseConfig.set(STORM_USER_NAME_KEY, userName); } legacyProvider.login(STORM_KEYTAB_FILE_KEY, STORM_USER_NAME_KEY, InetAddress.getLocalHost().getCanonicalHostName()); } } } } return legacyProvider; } else { return null; } }

Target:
public static UserProvider login(Map<String, Object> conf, Configuration hbaseConfig) throws IOException { if (UserGroupInformation.isSecurityEnabled()) { List<String> autoCredentials = (List) conf.get(TOPOLOGY_AUTO_CREDENTIALS); if ((autoCredentials == null) || (!autoCredentials.contains(AutoHBase.class.getName()) && !autoCredentials.contains(AutoTGT.class.getName()))) { LOG.info("Logging in using keytab as neither AutoHBase or AutoTGT is specified for " + TOPOLOGY_AUTO_CREDENTIALS); if (legacyProvider == null) { synchronized (HBaseSecurityUtil.class) { if (legacyProvider == null) { legacyProvider = UserProvider.instantiate(hbaseConfig); String keytab = (String) conf.get(STORM_KEYTAB_FILE_KEY); if (keytab != null) { hbaseConfig.set(STORM_KEYTAB_FILE_KEY, keytab); } String userName = (String) conf.get(STORM_USER_NAME_KEY); if (userName != null) { hbaseConfig.set(STORM_USER_NAME_KEY, userName); } legacyProvider.login(STORM_KEYTAB_FILE_KEY, STORM_USER_NAME_KEY, InetAddress.getLocalHost().getCanonicalHostName()); } } } } return legacyProvider; } else { return null; } }
Source:
public void shouldLogAuditIfRequestAreMade() throws IOException { MotechEvent motechEvent = new MotechEvent(EventSubjects.HTTP_REQUEST, new HashMap<String, Object>() {{ put(EventDataKeys.URL, url); put(EventDataKeys.DATA, data); put(EventDataKeys.METHOD, Method.DELETE); put(EventDataKeys.HEADERS, headers); }}); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("key1", "value1"); httpHeaders.add("key2", "value2"); request = new HttpEntity<String>(data,httpHeaders); responseEntity = new ResponseEntity<String>(body,HttpStatus.OK); when(restTempate.exchange(eq(url),eq(HttpMethod.DELETE),eq(request), eq(String.class))).thenReturn((ResponseEntity<String>) responseEntity); httpClientEventListener.handle(motechEvent); HTTPActionAudit httpActionAudit = new HTTPActionAudit(url, request.toString(), responseEntity.getBody().toString(), responseEntity.getStatusCode().toString()); verify(httpActionService,times(1)).create(eq(httpActionAudit)); }

Target:
public void shouldLogAuditIfRequestAreMade() throws IOException { MotechEvent motechEvent = new MotechEvent(EventSubjects.HTTP_REQUEST, new HashMap<String, Object>() {{ put(EventDataKeys.URL, url); put(EventDataKeys.DATA, data); put(EventDataKeys.METHOD, Method.DELETE); put(EventDataKeys.HEADERS, headers); }}); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("key1", "value1"); httpHeaders.add("key2", "value2"); request = new HttpEntity<String>(data,httpHeaders); responseEntity = new ResponseEntity<String>(body,HttpStatus.OK); when(restTempate.exchange(eq(url),eq(HttpMethod.DELETE),eq(request), eq(String.class))).thenReturn((ResponseEntity<String>) responseEntity); httpClientEventListener.handle(motechEvent); HTTPActionAudit httpActionAudit = new HTTPActionAudit(url, request.toString(), responseEntity.getBody().toString(), responseEntity.getStatusCode().toString()); verify(httpActionService).create(eq(httpActionAudit)); }
Source:
private List<String> filterStopwords(List<String> terms, IndexReader reader, boolean tweetsearch, int numDocs) throws IOException { List<String> filteredTerms = new LinkedList<>(); for (String term: terms){ if (isStopword(term,reader,tweetsearch,numDocs)){ continue; }else{ filteredTerms.add(term); } } return filteredTerms; }

Target:
private List<String> filterStopwords(List<String> terms, IndexReader reader, boolean tweetsearch, int numDocs) throws IOException { return terms.stream().filter(term -> { try { return !isStopword(term, reader, tweetsearch, numDocs); } catch (IOException e) { e.printStackTrace(); LOG.warn("Fail to test " + term ); return false; } } ).collect(Collectors.toList()); }
Source:
public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { if (! isContentReferenceSupported(targetContentReference)) { throw new ContentIOException("ContentReference not supported"); } long startTime = System.currentTimeMillis(); String remotePath = getRelativePath(targetContentReference.getUri()); try { Long contentLength = sourceFile.length(); try { Upload xfer = tm.upload(s3BucketName, remotePath, sourceFile); xfer.waitForCompletion(); } catch (InterruptedException e) { logger.error("Upload was interrupted: "+e.getMessage()); Thread.currentThread().interrupt(); throw new ContentIOException("Failed to write content", e); } ObjectMetadata metadata = s3.getObjectMetadata( new GetObjectMetadataRequest(s3BucketName, remotePath)); long storedContentLength = metadata.getContentLength(); if (logger.isWarnEnabled()) { if ((contentLength != null) && (storedContentLength != contentLength)) { logger.warn("Metadata length differs - expected " + contentLength + ", actual "+ storedContentLength); } } if (logger.isDebugEnabled()) { logger.debug("Upload file: " + s3BucketName + ":" + remotePath + " (in "+(System.currentTimeMillis()-startTime)+" msecs)"); } return storedContentLength; } catch (AmazonClientException e) { throw new ContentIOException("Failed to write content", e); } }

Target:
public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { if (! isContentReferenceSupported(targetContentReference)) { throw new ContentIOException("ContentReference not supported"); } long startTime = System.currentTimeMillis(); String remotePath = getRelativePath(targetContentReference.getUri()); try { long contentLength = sourceFile.length(); try { Upload xfer = tm.upload(s3BucketName, remotePath, sourceFile); xfer.waitForCompletion(); } catch (InterruptedException e) { logger.error("Upload was interrupted: "+e.getMessage()); Thread.currentThread().interrupt(); throw new ContentIOException("Failed to write content", e); } ObjectMetadata metadata = s3.getObjectMetadata( new GetObjectMetadataRequest(s3BucketName, remotePath)); long storedContentLength = metadata.getContentLength(); if (logger.isWarnEnabled()) { if (storedContentLength != contentLength) { logger.warn("Metadata length differs - expected " + contentLength + ", actual "+ storedContentLength); } } if (logger.isDebugEnabled()) { logger.debug("Upload file: " + s3BucketName + ":" + remotePath + " (in "+(System.currentTimeMillis()-startTime)+" msecs)"); } return storedContentLength; } catch (AmazonClientException e) { throw new ContentIOException("Failed to write content", e); } }
Source:
static <R> CompletableFuture<R> toCompletableFuture(Future<R> future, Executor executor) { Supplier<R> supplier = () -> { try { return future.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }; if (executor != null) { return CompletableFuture.supplyAsync(supplier, executor); } else { return CompletableFuture.supplyAsync(supplier); } }

Target:
static <R> CompletableFuture<R> toCompletableFuture(Future<R> future, Executor executor) { Supplier<R> supplier = () -> { try { return future.get(); } catch (InterruptedException | ExecutionException e) { throw new CompletionException(e); } }; if (executor != null) { return CompletableFuture.supplyAsync(supplier, executor); } else { return CompletableFuture.supplyAsync(supplier); } }
Source:
public void shouldKeepDirAttribute() { String html = "<html><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>", toCompactString(result)); }

Target:
public void shouldKeepDirAttribute() { String html = "<html><head></head><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals(html, toCompactString(result)); }
Source:
public void init() throws Exception { createBaseContainer(RepositoryPathConstants.CONTENT_BASE); repoObjLoader.init(); }

Target:
public void init() throws Exception { createBaseContainer(RepositoryPathConstants.CONTENT_BASE); }
Source:
private SessionInfo getSessionInfo(String sessionId) { SessionInfo sessionInfo = null; for (SessionInfo currentSessionInfo : sessionInfoMap.values()) { if (currentSessionInfo.sessionId.equals(sessionId)) { sessionInfo = currentSessionInfo; break; } } return sessionInfo; }

Target:
private SessionInfo getSessionInfo(String sessionId) { return sessionInfoMap.get(sessionId); }
Source:
public EventList(List<ITimeEvent> list, long startTime, long endTime) { if (list != null) { fEventList = Collections.unmodifiableList(list); } fStartTime = startTime; fEndTime = endTime; }

Target:
public EventList(List<ITimeEvent> list, long startTime, long endTime) { if (list != null) { fEventList = Collections.unmodifiableList(list); } else { fEventList = null; } fStartTime = startTime; fEndTime = endTime; }
Source:
public void addEntryBadInputTest() throws StoreException { FileSpan fileSpan = state.log.getFileSpanForMessage(state.index.getStartOffset(), 1); IndexValue value = new IndexValue(1, state.index.getStartOffset(), IndexValue.FLAGS_DEFAULT_VALUE, Utils.Infinite_Time, Utils.Infinite_Time, Account.UNKNOWN_ACCOUNT_ID, Container.UNKNOWN_CONTAINER_ID); try { state.index.addToIndex(new IndexEntry(state.getUniqueId(), value), fileSpan); fail("Should have failed because filespan provided < currentIndexEndOffset"); } catch (IllegalArgumentException e) { } if (isLogSegmented) { Offset startOffset = state.index.getCurrentEndOffset(); String nextLogSegmentName = LogSegmentNameHelper.getNextPositionName(startOffset.getName()); Offset endOffset = new Offset(nextLogSegmentName, 0); fileSpan = new FileSpan(startOffset, endOffset); try { state.index.addToIndex(new IndexEntry(state.getUniqueId(), value), fileSpan); fail("Should have failed because fileSpan provided spanned across segments"); } catch (IllegalArgumentException e) { } } }

Target:
public void addEntryBadInputTest() throws StoreException { FileSpan fileSpan = state.log.getFileSpanForMessage(state.index.getStartOffset(), 1); IndexValue value = new IndexValue(1, state.index.getStartOffset(), IndexValue.FLAGS_DEFAULT_VALUE, Utils.Infinite_Time, state.time.milliseconds(), Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM)); try { state.index.addToIndex(new IndexEntry(state.getUniqueId(), value), fileSpan); fail("Should have failed because filespan provided < currentIndexEndOffset"); } catch (IllegalArgumentException e) { } if (isLogSegmented) { Offset startOffset = state.index.getCurrentEndOffset(); String nextLogSegmentName = LogSegmentNameHelper.getNextPositionName(startOffset.getName()); Offset endOffset = new Offset(nextLogSegmentName, 0); fileSpan = new FileSpan(startOffset, endOffset); try { state.index.addToIndex(new IndexEntry(state.getUniqueId(), value), fileSpan); fail("Should have failed because fileSpan provided spanned across segments"); } catch (IllegalArgumentException e) { } } }
Source:
protected boolean isDatasetOrViewUri(String uriOrName) { return (uriOrName.startsWith("dataset:") || uriOrName.startsWith("view:")); }

Target:
protected static boolean isDatasetOrViewUri(String uriOrName) { return (isDatasetUri(uriOrName) || isViewUri(uriOrName)); }
Source:
public ProgressiveDecoder( final Consumer<CloseableReference<CloseableImage>> consumer, final ProducerContext producerContext) { super(consumer); mProducerContext = producerContext; mProducerListener = producerContext.getListener(); mImageDecodeOptions = producerContext.getImageRequest().getImageDecodeOptions(); mIsFinished = false; JobRunnable job = new JobRunnable() { @Override public void run(EncodedImage encodedImage, boolean isLast) { if (encodedImage != null) { if (mDownsampleEnabled) { ImageRequest request = producerContext.getImageRequest(); if (mDownsampleEnabledForNetwork || !UriUtil.isNetworkUri(request.getSourceUri())) { if (!EncodedImage.isMetaDataAvailable(encodedImage)) { encodedImage.parseMetaData(); } encodedImage.setSampleSize(DownsampleUtil.determineSampleSize( request, encodedImage)); } } doDecode(encodedImage, isLast); } } }; mJobScheduler = new JobScheduler(mExecutor, job, mImageDecodeOptions.minDecodeIntervalMs); mProducerContext.addCallbacks( new BaseProducerContextCallbacks() { @Override public void onIsIntermediateResultExpectedChanged() { if (mProducerContext.isIntermediateResultExpected()) { mJobScheduler.scheduleJob(); } } }); }

Target:
public ProgressiveDecoder( final Consumer<CloseableReference<CloseableImage>> consumer, final ProducerContext producerContext) { super(consumer); mProducerContext = producerContext; mProducerListener = producerContext.getListener(); mImageDecodeOptions = producerContext.getImageRequest().getImageDecodeOptions(); mIsFinished = false; JobRunnable job = new JobRunnable() { @Override public void run(EncodedImage encodedImage, boolean isLast) { if (encodedImage != null) { if (mDownsampleEnabled) { ImageRequest request = producerContext.getImageRequest(); if (mDownsampleEnabledForNetwork || !UriUtil.isNetworkUri(request.getSourceUri())) { encodedImage.setSampleSize(DownsampleUtil.determineSampleSize( request, encodedImage)); } } doDecode(encodedImage, isLast); } } }; mJobScheduler = new JobScheduler(mExecutor, job, mImageDecodeOptions.minDecodeIntervalMs); mProducerContext.addCallbacks( new BaseProducerContextCallbacks() { @Override public void onIsIntermediateResultExpectedChanged() { if (mProducerContext.isIntermediateResultExpected()) { mJobScheduler.scheduleJob(); } } }); }
Source:
public void releaseAllListeners() { orderedListenerCount.set(0); aSyncListenersSet.clear(); syncListenersSet.clear(); }

Target:
public void releaseAllListeners() { orderedListenerCount.set(0); aSyncListenersSet.clear(); syncListenersSet.clear(); synchronized (this) { if (eventThreadLocal instanceof EventThreadLocalImpl) { eventThreadLocal = new NoOpEventThreadLocalImpl(); } } }
Source:
public Optional<U> generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return Optional.of(linkedProfile); } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { return Optional.ofNullable(profile); } } }

Target:
public U generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return linkedProfile; } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { return profile; } } }
Source:
public CloudDestination getCloudDestination() throws IllegalStateException { try { AzureCloudDestination dest = new AzureCloudDestination(cloudConfig, azureCloudConfig, azureMetrics); dest.testAzureConnectivity(); return dest; } catch (Exception e) { logger.error("Initializing Azure destination", e.getMessage()); throw (e instanceof IllegalStateException) ? (IllegalStateException) e : new IllegalStateException(e); } }

Target:
public CloudDestination getCloudDestination() throws IllegalStateException { try { AzureCloudDestination dest = new AzureCloudDestination(cloudConfig, azureCloudConfig, azureMetrics); dest.testAzureConnectivity(); return dest; } catch (Exception e) { logger.error("Error initializing Azure destination: {}", e.getMessage()); throw (e instanceof IllegalStateException) ? (IllegalStateException) e : new IllegalStateException(e); } }
Source:
protected boolean canThisBeBilledByBillingFrequency() { LOG.info("canThisBeBilledByBillingFrequency: Both must be TRUE to allow LOC billedByBillingFrequency: " + " currentDate and lastBilledDate !(isSameDay) = " + (!KfsDateUtils.isSameDay(currentDate, lastBilledDate)) + " AND lastBilledDate and calculatePreviousDate !(isSameDay) = " + !KfsDateUtils.isSameDay(lastBilledDate, calculatePreviousDate(currentDate))); return (!KfsDateUtils.isSameDay(currentDate, lastBilledDate) && !KfsDateUtils.isSameDay(lastBilledDate, calculatePreviousDate(currentDate))); }

Target:
protected boolean canThisBeBilledByBillingFrequency() { boolean currentDateisNotSameDayAsLastBilledDate = !KfsDateUtils.isSameDay(currentDate, lastBilledDate); boolean lastBilledDateIsNotSameDayAsCalculatedPreviousDayBasedOnCurrentDate = !KfsDateUtils.isSameDay(lastBilledDate, calculatePreviousDate(currentDate)); LOG.info("canThisBeBilledByBillingFrequency: Both must be TRUE to allow LOC billedByBillingFrequency: " + " currentDate and lastBilledDate NOT(isSameDay) = " + currentDateisNotSameDayAsLastBilledDate + " AND lastBilledDate and calculatePreviousDate !(isSameDay) = " + lastBilledDateIsNotSameDayAsCalculatedPreviousDayBasedOnCurrentDate); return (currentDateisNotSameDayAsLastBilledDate && lastBilledDateIsNotSameDayAsCalculatedPreviousDayBasedOnCurrentDate); }
Source:
public void redraw() { if (fRelayoutRequired) { layout(true); return; } if (fCachedTextViewer != null && fCachedTextViewer.getTextWidget() != null && fCanvas != null && !fCanvas.isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { fCanvas.redraw(); fCanvas.update(); } else { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } }

Target:
public void redraw() { if (fRelayoutRequired) { layout(true); return; } if (!isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { fCanvas.redraw(); fCanvas.update(); } else { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } }
Source:
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { IProject project = SessionManager.getProject(request); IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession"); AccountObject account = session.getAccount(); String UserID = account.getUsername(); String UserName = account.getNickName(); String userInfo = UserID + "(" + UserName + ")"; String projectInfo = ""; if (project != null) { projectInfo = project.getName(); } TopTitleInfoUI ttiui = new TopTitleInfoUI(userInfo, projectInfo); Gson gson = new Gson(); response.setContentType("text/html; charset=utf-8"); try { response.getWriter().write(gson.toJson(ttiui)); response.getWriter().close(); } catch (IOException e) { e.printStackTrace(); } return null; }

Target:
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { IProject project = SessionManager.getProject(request); IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession"); AccountObject account = session.getAccount(); String userName = account.getUsername(); String nickName = account.getNickName(); String userInfo = userName + "(" + nickName + ")"; String projectInfo = ""; if (project != null) { projectInfo = project.getName(); } TopTitleInfoUI ttiui = new TopTitleInfoUI(userInfo, projectInfo); Gson gson = new Gson(); response.setContentType("text/html; charset=utf-8"); try { response.getWriter().write(gson.toJson(ttiui)); response.getWriter().close(); } catch (IOException e) { e.printStackTrace(); } return null; }
Source:
public String[] extractPartitions(Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); String result[] = { defaultDate }; if (jsonObject != null) { Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); Object inputPattern = mConfig.getMessageTimestampInputPattern(); if (fieldValue != null && inputPattern != null) { try { SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString()); SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd"); result[0] = "dt=" + outputFormatter.format(inputFormatter.parse(fieldValue.toString())); return result; } catch (Exception e) { LOG.warn("Impossible to convert date = " + fieldValue.toString() + " for the input pattern = " + inputPattern.toString() + ". Using date default=" + result[0]); } } } return result; }

Target:
public String[] extractPartitions(Message message) { JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload()); String result[] = { defaultDate }; if (jsonObject != null) { Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); Object inputPattern = mConfig.getMessageTimestampInputPattern(); if (fieldValue != null && inputPattern != null) { try { SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString()); SimpleDateFormat outputFormatter = new SimpleDateFormat(defaultFormatter); Date dateFormat = inputFormatter.parse(fieldValue.toString()); result[0] = "dt=" + outputFormatter.format(dateFormat); return result; } catch (Exception e) { LOG.warn("Impossible to convert date = " + fieldValue.toString() + " for the input pattern = " + inputPattern.toString() + ". Using date default=" + result[0]); } } } return result; }
Source:
public void show(final String value) { final String dataTypeName = extractItemDefinitionName(value); final Optional<ItemDefinition> itemDefinition = itemDefinitionUtils.findByName(dataTypeName); if (itemDefinition.isPresent()) { final DataType dataType = dataTypeFactory.makeDataType(itemDefinition.get()); treeGrid.setupItems(dataType); superShow(); } }

Target:
public void show(final String value) { final String dataTypeName = extractItemDefinitionName(value); final Optional<ItemDefinition> itemDefinition = itemDefinitionUtils.findByName(dataTypeName); itemDefinition.ifPresent(i -> { final DataType dataType = dataTypeFactory.makeDataType(i); treeGrid.setupItems(dataType); superShow(); }); }
Source:
private boolean isCandidateForRefactoring(String oldClassName, String newClassName, File file) { return !Objects.equals(file.getName(), oldClassName + ".java") && !Objects.equals(file.getName(), newClassName + ".java"); }

Target:
private boolean isCandidateForRefactoring(String oldClassName, String newClassName, File file) { final String fileName = file.getName(); final String sourceFileName = oldClassName + ".java"; final String targetFileName = newClassName + ".java"; return !Objects.equals(fileName, sourceFileName) && !Objects.equals(fileName, targetFileName); }
Source:
public void init(Boolean flag) throws IOException { conf = HBaseConfiguration.create(); conf.setBoolean(COPROCESSORS_ENABLED_CONF_KEY, true); conf.setBoolean(USER_COPROCESSORS_ENABLED_CONF_KEY, true); TableName tableName = TableName.valueOf(name.getMethodName()); regionInfo = RegionInfoBuilder.newBuilder(tableName).build(); TableDescriptor tableDesc = null; if (flag == null) { tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(SimpleRegionObserver.class.getName()).build(); } else if (flag) { tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(TempRegionObserver.class.getName()).build(); } else { conf.set(REGION_COPROCESSOR_CONF_KEY, TempRegionObserver.class.getName()); tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(SimpleRegionObserver.class.getName()).build(); } region = mock(HRegion.class); when(region.getRegionInfo()).thenReturn(regionInfo); when(region.getTableDescriptor()).thenReturn(tableDesc); rsServices = mock(RegionServerServices.class); }

Target:
private void init(Boolean flag) throws IOException { conf = HBaseConfiguration.create(); conf.setBoolean(COPROCESSORS_ENABLED_CONF_KEY, true); conf.setBoolean(USER_COPROCESSORS_ENABLED_CONF_KEY, true); TableName tableName = TableName.valueOf(name.getMethodName()); regionInfo = RegionInfoBuilder.newBuilder(tableName).build(); TableDescriptor tableDesc = null; if (flag == null) { tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(SimpleRegionObserver.class.getName()).build(); } else if (flag) { tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(TempRegionObserver.class.getName()).build(); } else { conf.set(REGION_COPROCESSOR_CONF_KEY, TempRegionObserver.class.getName()); tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(SimpleRegionObserver.class.getName()).build(); } region = mock(HRegion.class); when(region.getRegionInfo()).thenReturn(regionInfo); when(region.getTableDescriptor()).thenReturn(tableDesc); rsServices = mock(RegionServerServices.class); }
Source:
public static void main(String[] args){ Server server = new Server(); boolean showHelp = false; if (args.length > 0) { switch (args[0]) { case "load": if (args.length == 2) { try { server.newGame(GridLoader.loadGrid(args[1])); } catch(NullPointerException e) { System.out.println("Error: Failed to locate json file."); showHelp = true; } } else { showHelp = true; } break; case "random": if (args.length == 5) { try { Dimension dimension = new Dimension(Integer.parseInt(args[1]), Integer.parseInt(args[2])); server.newGame(GridGenerator.createRandomGrid(dimension, Integer.parseInt(args[3]), Integer.parseInt(args[4]))); } catch(NumberFormatException e) { showHelp = true; } } else { showHelp = true; } break; case "help": showHelp = true; break; } } else { showHelp = true; } if (showHelp) { System.out.println("Usage: server <command>"); System.out.println("Available commands:"); System.out.println(" load <gridName> Load a predefined json grid"); System.out.println(" random <width> <height> <# players> <seed> Generate a random grid"); System.out.println(" help Show this help file"); System.exit(0); } else { System.out.println("Server now running with initial grid of: "); System.out.println(server.grid.toString()); } }

Target:
public static void main(String[] args){ Server server = new Server(); server.newGame(CLAParser.parse(args)); System.out.println("Server now running with initial grid of: "); System.out.println(server.grid.toString()); }
Source:
CounterAddHandler() { super(); }

Target:
CounterAddHandler() { }
Source:
private int sampleFromTerms(final double randomVar, final double[] terms, final List<Integer> nonzeroIndices) { double val = randomVar; for (final Integer nonzeroIndex : nonzeroIndices) { if (val < terms[nonzeroIndex]) { return nonzeroIndex; } val -= terms[nonzeroIndex]; } throw new RuntimeException("randomVar have to be smaller than summation of all nonzero terms"); }

Target:
private int sampleFromTerms(final double randomVar, final double[] terms, final List<Integer> nonzeroIndices) { double val = randomVar; for (final int nonzeroIndex : nonzeroIndices) { if (val < terms[nonzeroIndex]) { return nonzeroIndex; } val -= terms[nonzeroIndex]; } throw new RuntimeException("randomVar has to be smaller than summation of all nonzero terms"); }
Source:
public void onFieldResponse(@Observes FormEditorContextResponse response) { if(disabled) { return; } else if (!response.getFormId().equals(formId)) { return; } else if (field != null && !response.getFieldId().equals(fieldId)) { return; } editorHelper = response.getEditorHelper(); init(editorHelper.getRenderingContext(), editorHelper.getFormField(response.getFieldId())); renderContent(); if (showProperties) { propertiesRenderer.render(propertiesRendererHelper); } }

Target:
public void onFieldResponse(@Observes FormEditorContextResponse response) { if(disabled) { return; } else if (!formId.filter(s -> response.getFormId().equals(s)).isPresent()) { return; } else if (field != null && !fieldId.filter(s->response.getFieldId().equals(s)).isPresent()) { return; } editorHelper = response.getEditorHelper(); init(editorHelper.getRenderingContext(), editorHelper.getFormField(response.getFieldId())); renderContent(); if (showProperties) { propertiesRenderer.render(propertiesRendererHelper); } }
Source:
public void parse(String fileURL, String charset) { this.charset = charset; Reader reader = null; try { DefaultHandler hd = null; SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); spf.setFeature(DISALLOW_DOCTYPE_DECL, true); SAXParser saxParser = null; if (ignoreDTD) { spf.setFeature("<LINK_0>", false); } saxParser = spf.newSAXParser(); if (rootPath == null || rootPath.equals("")) { hd = newHandler(); } else { hd = newHandler2(); } saxParser.setProperty("<LINK_1>", hd); reader = new UnicodeReader(new java.io.FileInputStream(fileURL), this.charset); org.xml.sax.InputSource inSource = new org.xml.sax.InputSource(reader); saxParser.parse(inSource, hd); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }

Target:
public void parse(String fileURL, String charset) { this.charset = charset; Reader reader = null; try { DefaultHandler hd = null; SAXParser saxParser = createSaxParser(); if (rootPath == null || rootPath.equals("")) { hd = newHandler(); } else { hd = newHandler2(); } saxParser.setProperty("<LINK_1>", hd); reader = new UnicodeReader(new java.io.FileInputStream(fileURL), this.charset); org.xml.sax.InputSource inSource = new org.xml.sax.InputSource(reader); saxParser.parse(inSource, hd); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
public synchronized RawPacket[] doReverseTransform(RawPacket[] pkts) { Set<Integer> flexFecPacketsToRemove = new HashSet<>(); for (Map.Entry<Integer, RawPacket> entry : fecPackets.entrySet()) { FlexFec03Packet flexFecPacket = FlexFec03Packet.create(entry.getValue()); if (flexFecPacket == null) { continue; } reconstructor.setFecPacket(flexFecPacket); if (reconstructor.complete()) { flexFecPacketsToRemove.add(flexFecPacket.getSequenceNumber()); continue; } if (reconstructor.canRecover()) { logger.debug("Attemping recovery of missing sequence " + "number " + reconstructor.missingSequenceNumber); flexFecPacketsToRemove.add(flexFecPacket.getSequenceNumber()); RawPacket recovered = reconstructor.recover(); if (recovered != null) { logger.info("Recovered packet " + recovered.getSequenceNumber()); statistics.numRecoveredPackets++; saveMedia(recovered); pkts = ArrayUtils.insert(recovered, pkts, RawPacket.class); } else { logger.error("Recovery of packet " + reconstructor.missingSequenceNumber + " failed even" + " though it should have been possible"); statistics.failedRecoveries++; } } } for (Integer flexFecSeqNum : flexFecPacketsToRemove) { fecPackets.remove(flexFecSeqNum); } return pkts; }

Target:
protected synchronized RawPacket[] doReverseTransform(RawPacket[] pkts) { Set<Integer> flexFecPacketsToRemove = new HashSet<>(); for (Map.Entry<Integer, RawPacket> entry : fecPackets.entrySet()) { FlexFec03Packet flexFecPacket = FlexFec03Packet.create(entry.getValue()); if (flexFecPacket == null) { continue; } reconstructor.setFecPacket(flexFecPacket); if (reconstructor.complete()) { flexFecPacketsToRemove.add(flexFecPacket.getSequenceNumber()); continue; } if (reconstructor.canRecover()) { if (logger.isDebugEnabled()) { logger.debug("Attempting recovery of missing sequence " + "number " + reconstructor.missingSequenceNumber); } flexFecPacketsToRemove.add(flexFecPacket.getSequenceNumber()); RawPacket recovered = reconstructor.recover(); if (recovered != null) { logger.info("Recovered packet " + recovered.getSequenceNumber()); statistics.numRecoveredPackets++; saveMedia(recovered); pkts = ArrayUtils.insert(recovered, pkts, RawPacket.class); } else { logger.error("Recovery of packet " + reconstructor.missingSequenceNumber + " failed even" + " though it should have been possible"); statistics.failedRecoveries++; } } } for (Integer flexFecSeqNum : flexFecPacketsToRemove) { fecPackets.remove(flexFecSeqNum); } return pkts; }
Source:
public void should_enable_schema_programmatically_when_disabled_in_config() { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .withBoolean(DefaultDriverOption.METADATA_SCHEMA_ENABLED, false) .build(); try (CqlSession session = SessionUtils.newSession(ccmRule, loader)) { assertThat(session.isSchemaMetadataEnabled()).isFalse(); assertThat(session.getMetadata().getKeyspaces()).isEmpty(); session.setSchemaMetadataEnabled(true); assertThat(session.isSchemaMetadataEnabled()).isTrue(); ConditionChecker.checkThat( () -> assertThat(session.getMetadata().getKeyspaces()).isNotEmpty()) .becomesTrue(); assertThat(session.getMetadata().getKeyspaces()) .containsKeys( CqlIdentifier.fromInternal("system"), CqlIdentifier.fromInternal("system_traces"), sessionRule.keyspace()); assertThat(session.getMetadata().getClusterName().get()).isEqualTo("ccm_1"); session.setSchemaMetadataEnabled(null); assertThat(session.isSchemaMetadataEnabled()).isFalse(); } }

Target:
public void should_enable_schema_programmatically_when_disabled_in_config() { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .withBoolean(DefaultDriverOption.METADATA_SCHEMA_ENABLED, false) .build(); try (CqlSession session = SessionUtils.newSession(ccmRule, loader)) { assertThat(session.isSchemaMetadataEnabled()).isFalse(); assertThat(session.getMetadata().getKeyspaces()).isEmpty(); session.setSchemaMetadataEnabled(true); assertThat(session.isSchemaMetadataEnabled()).isTrue(); ConditionChecker.checkThat( () -> assertThat(session.getMetadata().getKeyspaces()).isNotEmpty()) .becomesTrue(); assertThat(session.getMetadata().getKeyspaces()) .containsKeys( CqlIdentifier.fromInternal("system"), CqlIdentifier.fromInternal("system_traces"), sessionRule.keyspace()); session.setSchemaMetadataEnabled(null); assertThat(session.isSchemaMetadataEnabled()).isFalse(); } }
Source:
private String findHostId(String hostName) throws DotDataException { String hostId = null; DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTID_BY_NAME_QUERY); dc.addParam(hostName); List<Map<String,String>> result = dc.loadResults(); if(!result.isEmpty()){ hostId = result.get(0).get("identifier").toString(); } return hostId; }

Target:
private String findHostId(String hostName) throws DotDataException { String hostId = null; DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTID_BY_NAME_QUERY); dc.addParam(hostName); List<Map<String, String>> result = dc.loadResults(); if (!result.isEmpty()) { hostId = result.get(0).get("identifier"); } return hostId; }
Source:
public Enumeration<URL> getResources(String name) throws IOException { List<URL> result = new ArrayList<>(); for (ClassLoader classLoader : loaders) { result.addAll(Collections.list(classLoader.getResources(name))); } ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader != null) { result.addAll(Collections.list(contextLoader.getResources(name))); } else { result.addAll(Collections.list(super.getResources(name))); } return Collections.enumeration(result); }

Target:
public Enumeration<URL> getResources(String name) throws IOException { Set<URL> result = new LinkedHashSet<>(); for (ClassLoader classLoader : loaders) { result.addAll(Collections.list(classLoader.getResources(name))); } ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader != null) { result.addAll(Collections.list(contextLoader.getResources(name))); } else { result.addAll(Collections.list(super.getResources(name))); } return Collections.enumeration(result); }
Source:
public Notification registerThresholdNotification(Category category) { Notification notification = null; if (category.getThreshold() > 0) { Double totalAmountSpent = expenseDao.getTotalAmountByCategoryForCurrentMonth(category.getId()); if (totalAmountSpent != null && totalAmountSpent > 0) { if (totalAmountSpent >= category.getThreshold()) { String thresholdExceededMessage = this.createThresholdExceededMessage(category, totalAmountSpent); notification = this.createNotification(category, NotificationPriority.HIGH, thresholdExceededMessage); notification = notificationDao.save(notification); } } } return notification; }

Target:
public Notification registerThresholdNotification(Category category) { Notification notification = null; if (category.getThreshold() > 0) { Double totalAmountSpent = expenseDao.getTotalAmountByCategoryForCurrentMonth(category.getId()); if (totalAmountSpent != null && totalAmountSpent > 0) { if (totalAmountSpent >= category.getThreshold()) { String thresholdExceededMessage = this.createThresholdExceededMessage(category, totalAmountSpent); notification = this.createNotification(category, NotificationPriority.HIGH, thresholdExceededMessage); notification = notificationDao.save(notification); } else { try { if (shouldCreateMediumPriorityNotification(category.getThreshold(), totalAmountSpent, thresholdMediumNotificationPercent)) { String thresholdWarningMessage = this.createThresholdPercentCloseToLimitMessage(category, totalAmountSpent); notification = this.createNotification(category, NotificationPriority.MEDIUM, thresholdWarningMessage); notification = notificationDao.save(notification); } } catch (ServiceException e) { LOGGER.warning(" ---- ERROR: " + e.getMessage()); } } } } return notification; }
Source:
public boolean defaultNetworkRules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIpStr); final String result = cmd.execute(); if (result != null) { return false; } return true; }

Target:
public boolean defaultNetworkRules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIpStr); final String result = cmd.execute(); if (result != null) { return false; } return true; }