auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void sendMessage(CarbonMessage carbonMessage, Message jmsMessage) throws ClientConnectorException { int deliveryMode = DeliveryMode.PERSISTENT; if (getHeader(carbonMessage, JMSConstants.JMS_DELIVERY_MODE). equalsIgnoreCase(JMSConstants.NON_PERSISTENT_DELIVERY_MODE)) { deliveryMode = DeliveryMode.NON_PERSISTENT; } int priority = JMSConstants.DEFAULT_PRIORITY; String value = carbonMessage.getHeader(JMSConstants.JMS_PRIORITY); if (value != null) { priority = Integer.parseInt(value); } long ttl = 0; value = carbonMessage.getHeader(JMSConstants.JMS_EXPIRATION); if (value != null) { ttl = Long.parseLong(value); } try { messageProducer.send(jmsMessage, deliveryMode, priority, ttl); } catch (JMSException e) { throw new ClientConnectorException("Error occurred while sending the message to JMS provider. " + e.getMessage(), e); } }

Target:
private void sendMessage(CarbonMessage carbonMessage, Message jmsMessage) throws ClientConnectorException { int deliveryMode = DeliveryMode.PERSISTENT; if (getHeader(carbonMessage, JMSConstants.JMS_DELIVERY_MODE). equalsIgnoreCase(JMSConstants.NON_PERSISTENT_DELIVERY_MODE)) { deliveryMode = DeliveryMode.NON_PERSISTENT; } int priority = JMSConstants.DEFAULT_PRIORITY; String value = carbonMessage.getHeader(JMSConstants.JMS_PRIORITY); if (value != null) { priority = Integer.parseInt(value); } long timeToLive = 0; value = carbonMessage.getHeader(JMSConstants.JMS_EXPIRATION); if (value != null) { timeToLive = Long.parseLong(value); } try { messageProducer.send(jmsMessage, deliveryMode, priority, timeToLive); } catch (JMSException e) { throw new ClientConnectorException("Send Failed with priority " + priority + " , delivery mode " + deliveryMode + " [ " + e.getMessage() + " ]", e); } }
Source:
public void memoizationTest() { final List<Integer> res = new ArrayList<>(); final PackageStats toplevel = Metrics.getTopLevelPackageStats(); ASTCompilationUnit acu = parseAndVisitForClass15(MetricsVisitorTestData.class); acu.jjtAccept(new JavaParserVisitorReducedAdapter() { @Override public Object visit(ASTMethodOrConstructorDeclaration node, Object data) { res.add((int) toplevel.compute(opMetricKey, node, true, Version.STANDARD)); return super.visit(node, data); } @Override public Object visit(ASTAnyTypeDeclaration node, Object data) { res.add((int) toplevel.compute(classMetricKey, node, true, Version.STANDARD)); return super.visit(node, data); } }, null); System.out.println(); final List<Integer> cmp = new ArrayList<>(); acu.jjtAccept(new JavaParserVisitorReducedAdapter() { @Override public Object visit(ASTMethodOrConstructorDeclaration node, Object data) { cmp.add((int) toplevel.compute(opMetricKey, node, false, Version.STANDARD)); return super.visit(node, data); } @Override public Object visit(ASTAnyTypeDeclaration node, Object data) { cmp.add((int) toplevel.compute(classMetricKey, node, false, Version.STANDARD)); return super.visit(node, data); } }, null); assertEquals(res, cmp); }

Target:
public void memoizationTest() { ASTCompilationUnit acu = parseAndVisitForClass15(MetricsVisitorTestData.class); List<Integer> expected = visitWith(acu, true); List<Integer> real = visitWith(acu, false); assertEquals(expected, real); }
Source:
public Response createFromYaml( String data, @ApiParam(value = "Provide extended validation messages") @DefaultValue("false") @QueryParam("verbose") boolean verbose) throws ServerException, ConflictException, NotFoundException, ValidationException, BadRequestException { WorkspaceImpl workspace; try { Devfile devfile = devfileManager.parse(data, verbose); workspace = devfileManager.createWorkspace(devfile, null); } catch (DevfileFormatException | DevfileRecipeFormatException e) { throw new BadRequestException(e.getMessage()); } catch (JsonProcessingException e) { throw new ServerException(e.getMessage()); } return Response.status(201) .entity(asDto(workspace).withLinks(linksGenerator.genLinks(workspace, getServiceContext()))) .build(); }

Target:
public Response createFromYaml( String data, @ApiParam(value = "Provide extended validation messages") @DefaultValue("false") @QueryParam("verbose") boolean verbose) throws ServerException, ConflictException, NotFoundException, ValidationException, BadRequestException { WorkspaceImpl workspace; try { Devfile devfile = devfileManager.parse(data, verbose); workspace = devfileManager.createWorkspace(devfile, null); } catch (DevfileException e) { throw new BadRequestException(e.getMessage()); } catch (JsonProcessingException e) { throw new ServerException(e.getMessage(), e); } return Response.status(201) .entity(asDto(workspace).withLinks(linksGenerator.genLinks(workspace, getServiceContext()))) .build(); }
Source:
public void addConfig(Config config) { addToMetricsMessage(GROUP_NAME_FOR_DIAGNOSTICS_MANAGER, CONFIG, config); }

Target:
public void addConfig(Config config) { addToMetricsMessage(GROUP_NAME_FOR_DIAGNOSTICS_MANAGER, CONFIG_METRIC_NAME, (Map<String, String>) config); }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == FORM_PREFERENCES_KEY) { refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); questionsView.setBinaryData(sb, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), true); break; case SIGNATURE_CAPTURE: boolean saved = ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), false); if (saved) { ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); if (nextButton.getTag().equals(NAV_STATE_NEXT) && !questionsView.isQuestionList()) { next(); } } break; case IMAGE_CHOOSER: ImageCaptureProcessing.processImageChooserResponse(this, getInstanceFolder(), intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); questionsView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: case HIERARCHY_ACTIVITY_FIRST_START: if (resultCode == FormHierarchyActivity.RESULT_XPATH_ERROR) { finish(); } else { refreshCurrentView(false); } break; } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == FORM_PREFERENCES_KEY) { refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); questionsView.setBinaryData(sb, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), true); break; case SIGNATURE_CAPTURE: boolean saved = ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), false); if (saved) { advance(); } break; case IMAGE_CHOOSER: ImageCaptureProcessing.processImageChooserResponse(this, getInstanceFolder(), intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); questionsView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: case HIERARCHY_ACTIVITY_FIRST_START: if (resultCode == FormHierarchyActivity.RESULT_XPATH_ERROR) { finish(); } else { refreshCurrentView(false); } break; } }
Source:
public void testPropsToMap() { Properties props = new Properties(); props.put(1, 2); assertThrows(ConfigException.class, () -> Utils.propsToMap(props)); props.remove(1); props.put("key", 22); assertEquals(Utils.propsToMap(props).get("key"), 22); }

Target:
public void testPropsToMap() { assertThrows(ConfigException.class, () -> { Properties props = new Properties(); props.put(1, 2); Utils.propsToMap(props); }); assertValue(false); assertValue(1); assertValue("string"); assertValue(1.1); assertValue(Collections.emptySet()); assertValue(Collections.emptyList()); assertValue(Collections.emptyMap()); }
Source:
private void fetchMediaList(boolean loadMore) { if (!NetworkUtils.isNetworkAvailable(getActivity())) { updateEmptyView(EmptyViewMessageType.NETWORK_ERROR); setRefreshing(false); return; } if (!TextUtils.isEmpty(mSearchTerm)) { setRefreshing(false); return; } if (!mIsRefreshing) { mIsRefreshing = true; updateEmptyView(EmptyViewMessageType.LOADING); setRefreshing(true); String mimeType; switch (mFilter) { case FILTER_AUDIO: mimeType = MediaUtils.MIME_TYPE_AUDIO; case FILTER_DOCUMENTS: mimeType = MediaUtils.MIME_TYPE_APPLICATION; case FILTER_IMAGES: mimeType = MediaUtils.MIME_TYPE_IMAGE; case FILTER_VIDEOS: mimeType = MediaUtils.MIME_TYPE_VIDEO; default: mimeType = null; } FetchMediaListPayload payload = new FetchMediaListPayload(mSite, loadMore, mimeType); mDispatcher.dispatch(MediaActionBuilder.newFetchMediaListAction(payload)); } }

Target:
private void fetchMediaList(boolean loadMore) { if (!NetworkUtils.isNetworkAvailable(getActivity())) { updateEmptyView(EmptyViewMessageType.NETWORK_ERROR); setRefreshing(false); return; } if (!TextUtils.isEmpty(mSearchTerm)) { setRefreshing(false); return; } if (!mIsRefreshing) { setRefreshing(true); updateEmptyView(EmptyViewMessageType.LOADING); FetchMediaListPayload payload = new FetchMediaListPayload(mSite, NUM_MEDIA_PER_FETCH, loadMore, mFilter.toMimeType()); mDispatcher.dispatch(MediaActionBuilder.newFetchMediaListAction(payload)); } }
Source:
private static boolean shouldValidate(String namespaceUri) { Integer index = NAMESPACE_URI_ORDERING.get(namespaceUri); return index != null && index >= VALIDATE_SINCE_NAMESPACE_URI_INDEX; }

Target:
private static boolean shouldValidate(String namespaceUri) { Integer index = NAMESPACE_URI_ORDERING.get(namespaceUri); boolean result = index != null && index >= VALIDATE_SINCE_NAMESPACE_URI_INDEX; if (log.isDebugEnabled()) { log.debug("Should validate with XML schema for namspace URI '"+ namespaceUri +"'? "+ result); } return result; }
Source:
public void widgetCreated(XWidget xWidget, FormToolkit toolkit, Artifact art, SwtXWidgetRenderer dynamicXWidgetLayout, XModifiedListener modListener, boolean isEditable) throws OseeCoreException { super.widgetCreated(xWidget, toolkit, art, dynamicXWidgetLayout, modListener, isEditable); if (xWidget.getLabel().equals("WAS Branch")) { branchWidget = (XBranchSelectWidget) xWidget; branchWidget.setEditable(false); } else if (xWidget.getLabel().equals("Publish As Diff")) { final XCheckBox checkBox = (XCheckBox) xWidget; checkBox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); branchWidget.setEditable(checkBox.isChecked()); if (!checkBox.isChecked()) { branchWidget.setSelection(null); } } }); } else if (xWidget.getLabel().equals("Master Template")) { final XCombo masterCombo = (XCombo) xWidget; masterCombo.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (masterCombo.get().contains("srsMaster")) { slaveWidget.setEnabled(true); } else { slaveWidget.setEnabled(false); slaveWidget.set(""); } } }); } else if (xWidget.getLabel().equals("Slave Template")) { slaveWidget = (XCombo) xWidget; slaveWidget.setEnabled(false); } }

Target:
public void widgetCreated(XWidget xWidget, FormToolkit toolkit, Artifact art, SwtXWidgetRenderer dynamicXWidgetLayout, XModifiedListener modListener, boolean isEditable) throws OseeCoreException { super.widgetCreated(xWidget, toolkit, art, dynamicXWidgetLayout, modListener, isEditable); if (xWidget.getLabel().equals(WAS_BRANCH)) { branchWidget = (XBranchSelectWidget) xWidget; branchWidget.setEditable(false); } else if (xWidget.getLabel().equals(PUBLISH_AS_DIFF)) { final XCheckBox checkBox = (XCheckBox) xWidget; checkBox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); branchWidget.setEditable(checkBox.isChecked()); if (!checkBox.isChecked()) { branchWidget.setSelection(null); } } }); } else if (xWidget.getLabel().equals(MASTER_TEMPLATE)) { final XCombo masterCombo = (XCombo) xWidget; masterCombo.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (masterCombo.get().contains("srsMaster")) { slaveWidget.setEnabled(true); } else { slaveWidget.setEnabled(false); slaveWidget.set(""); } } }); } else if (xWidget.getLabel().equals(SLAVE_TEMPLATE)) { slaveWidget = (XCombo) xWidget; slaveWidget.setEnabled(false); } }
Source:
public String printPendingRanges() { StringBuilder sb = new StringBuilder(); for (Map.Entry<Range<Token>, List<Replica>> entry : this) { Range<Token> range = entry.getKey(); for (Replica replica : entry.getValue()) { sb.append(replica).append(':').append(range); sb.append(System.getProperty("line.separator")); } } return sb.toString(); }

Target:
public String printPendingRanges() { StringBuilder sb = new StringBuilder(); for (Map.Entry<Range<Token>, ReplicaList> entry : this) { Range<Token> range = entry.getKey(); for (Replica replica : entry.getValue()) { sb.append(replica).append(':').append(range); sb.append(System.getProperty("line.separator")); } } return sb.toString(); }
Source:
protected void execute() { logger.debug("execute() method is called!"); try { openPort(); for (DavisBindingProvider provider : providers) { Collection<DavisCommand> commands = DavisValueType.getReadCommandsByKeys(provider.getConfiguredKeys()); for (DavisCommand command : commands) { if (wakeup()) { sendCommand(command); } else { logger.warn("Wakeup failed, trying reset sequence!"); resetAfterError(); } } } closePort(); } catch (InitializationException e) { logger.error(e.getMessage()); } logger.debug("execute() method is finished!"); }

Target:
protected void execute() { logger.trace("execute() method is called!"); try { openPort(); for (DavisBindingProvider provider : providers) { Collection<DavisCommand> commands = DavisValueType.getReadCommandsByKeys(provider.getConfiguredKeys()); for (DavisCommand command : commands) { if (wakeup()) { sendCommand(command); } else { logger.warn("Wakeup failed, trying reset sequence!"); resetAfterError(); } } } closePort(); } catch (InitializationException e) { logger.error(e.getMessage()); } logger.trace("execute() method is finished!"); }
Source:
public void updateParticipantEmailCannotBeChanged() { STUDY.setEmailVerificationEnabled(true); mockHealthCodeAndAccountRetrieval("persisted@email.com", null); when(account.getEmailVerified()).thenReturn(Boolean.TRUE); StudyParticipant participant = new StudyParticipant.Builder().copyOf(PARTICIPANT) .withEmail("updated@email.com").withEmailVerified(Boolean.FALSE).build(); participantService.updateParticipant(STUDY, ImmutableSet.of(), participant); verify(accountDao).updateAccount(accountCaptor.capture()); Account account = accountCaptor.getValue(); verify(account, never()).setEmail(anyString()); verify(account, never()).setEmailVerified(Boolean.FALSE); verify(accountWorkflowService, never()).sendEmailVerificationToken(eq(STUDY), eq(ID), anyString()); }

Target:
public void updateParticipantEmailCannotBeChanged() { STUDY.setEmailVerificationEnabled(true); mockHealthCodeAndAccountRetrieval("persisted@email.com", null); when(account.getEmailVerified()).thenReturn(Boolean.TRUE); StudyParticipant participant = new StudyParticipant.Builder().copyOf(PARTICIPANT) .withEmail("updated@email.com").withEmailVerified(Boolean.FALSE).build(); participantService.updateParticipant(STUDY, ImmutableSet.of(), participant); verify(accountDao).updateAccount(accountCaptor.capture()); Account account = accountCaptor.getValue(); verify(account, never()).setEmail(anyString()); verify(account, never()).setEmailVerified(anyBoolean()); verify(accountWorkflowService, never()).sendEmailVerificationToken(eq(STUDY), eq(ID), anyString()); }
Source:
private Ordering<Row> dimensionOrdering(final String dimension, final StringComparator comparator) { return Ordering.from( Comparator.comparing( (Row row) -> row.getDimension(dimension).isEmpty() ? null : row.getDimension(dimension).get(0), Comparator.nullsFirst(comparator) )); }

Target:
private Ordering<Row> dimensionOrdering(final String dimension, final StringComparator comparator) { return Ordering.from( Comparator.comparing((Row row) -> getDimensionValue(row, dimension), Comparator.nullsFirst(comparator)) ); }
Source:
public KillBillHttpClient(final String kbServerUrl, final String username, final String password, final String apiKey, final String apiSecret, final String proxyHost, final Integer proxyPort, final Integer connectTimeOut, final Integer readTimeOut, final Integer requestTimeout) { this.kbServerUrl = kbServerUrl; this.username = username; this.password = password; this.apiKey = apiKey; this.apiSecret = apiSecret; this.httpTimeOut = MoreObjects.firstNonNull(requestTimeout, DEFAULT_HTTP_TIMEOUT_SEC * 1000); final AsyncHttpClientConfig.Builder cfg = new AsyncHttpClientConfig.Builder(); cfg.setConnectTimeout(MoreObjects.firstNonNull(connectTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setReadTimeout(MoreObjects.firstNonNull(readTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setRequestTimeout(this.httpTimeOut); cfg.setUserAgent(USER_AGENT); if (proxyHost != null && proxyPort != null) { final ProxyServer proxyServer = new ProxyServer(proxyHost, proxyPort); cfg.setProxyServer(proxyServer); } this.httpClient = new AsyncHttpClient(cfg.build()); mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); }

Target:
public KillBillHttpClient(final String kbServerUrl, final String username, final String password, final String apiKey, final String apiSecret, final String proxyHost, final Integer proxyPort, final Integer connectTimeOut, final Integer readTimeOut, final Integer requestTimeout) { this.kbServerUrl = kbServerUrl; this.username = username; this.password = password; this.apiKey = apiKey; this.apiSecret = apiSecret; final AsyncHttpClientConfig.Builder cfg = new AsyncHttpClientConfig.Builder(); if (requestTimeout != null) { cfg.setRequestTimeout(requestTimeout); int timeoutSec = (int) TimeUnit.MILLISECONDS.toSeconds(requestTimeout); if (TimeUnit.SECONDS.toMillis(timeoutSec) != requestTimeout) { timeoutSec+=1; } requestTimeoutSec = timeoutSec; } else { cfg.setRequestTimeout(DEFAULT_HTTP_TIMEOUT_SEC*1000); requestTimeoutSec = DEFAULT_HTTP_TIMEOUT_SEC; } cfg.setConnectTimeout(MoreObjects.firstNonNull(connectTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setReadTimeout(MoreObjects.firstNonNull(readTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setUserAgent(USER_AGENT); if (proxyHost != null && proxyPort != null) { final ProxyServer proxyServer = new ProxyServer(proxyHost, proxyPort); cfg.setProxyServer(proxyServer); } this.httpClient = new AsyncHttpClient(cfg.build()); mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); }
Source:
public static HashSet<String> getRoles() { if (!isEnabled) { return EMPTY_HASHSET; } Subject subject = org.apache.shiro.SecurityUtils.getSubject(); HashSet<String> roles = new HashSet<>(); Map allRoles = null; if (subject.isAuthenticated()) { Collection realmsList = SecurityUtils.getRealmsList(); for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); if (name.equals("org.apache.shiro.realm.text.IniRealm")) { allRoles = ((IniRealm) realm).getIni().get("roles"); break; } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) { try { AuthorizationInfo auth = ((LdapRealm) realm).queryForAuthorizationInfo( new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()), ((LdapRealm) realm).getContextFactory() ); if (auth != null) { roles = new HashSet<>(auth.getRoles()); break; } } catch (Throwable t) { if (log.isDebugEnabled()) { String msg = "Realm [" + realm + "] threw an exception during a multi-realm authorization attempt:"; log.debug(msg, t); } } } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) { allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles(); break; } } if (allRoles != null) { Iterator it = allRoles.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (subject.hasRole((String) pair.getKey())) { roles.add((String) pair.getKey()); } } } } return roles; }

Target:
public static HashSet<String> getRoles() { if (!isEnabled) { return EMPTY_HASHSET; } Subject subject = org.apache.shiro.SecurityUtils.getSubject(); HashSet<String> roles = new HashSet<>(); Map allRoles = null; if (subject.isAuthenticated()) { Collection realmsList = SecurityUtils.getRealmsList(); for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); if (name.equals("org.apache.shiro.realm.text.IniRealm")) { allRoles = ((IniRealm) realm).getIni().get("roles"); break; } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) { try { AuthorizationInfo auth = ((LdapRealm) realm).queryForAuthorizationInfo( new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()), ((LdapRealm) realm).getContextFactory() ); if (auth != null) { roles = new HashSet<>(auth.getRoles()); break; } } catch (Throwable t) { String msg = "Realm [" + realm + "] threw an exception during a multi-realm authorization attempt:"; log.warn(msg, t); } } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) { allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles(); break; } } if (allRoles != null) { Iterator it = allRoles.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (subject.hasRole((String) pair.getKey())) { roles.add((String) pair.getKey()); } } } } return roles; }
Source:
public boolean hasAllEvents(String[] names) { for (int i = 0; i < names.length; i++) { if (!hasEvent(names[i])) { return false; } } return true; }

Target:
public boolean hasAllEvents(String[] names) { for (String name : names) { if (!hasEvent(name)) { return false; } } return true; }
Source:
static void normalizeReadCountsByTargetFactors(final ReadCountCollection readCounts, final double[] targetFactors) { final RealMatrix counts = readCounts.counts(); final int targetCount = counts.getRowDimension(); final int columnCount = counts.getColumnDimension(); for (int i = 0; i < targetCount; i++) { final double factorInverse = 1.0 / targetFactors[i]; for (int j = 0; j < columnCount; j++) { counts.setEntry(i, j, counts.getEntry(i, j) * factorInverse); } } }

Target:
static void normalizeReadCountsByTargetFactors(final ReadCountCollection readCounts, final double[] targetFactors) { final RealMatrix counts = readCounts.counts(); if (targetFactors.length != counts.getRowDimension()) { throw new GATKException("Number of target factors does not correspond to the number of rows."); } counts.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(final int row, final int column, final double value) { return value / targetFactors[row]; } }); }
Source:
public void save(final boolean saveInSession, final U profile, final boolean multiProfile) { profile.addAttribute(SESSION_CLIENT_ID, context.getRequestParameter(REQUEST_CLIENT_ID)); super.save(saveInSession, profile, multiProfile); }

Target:
public void save(final boolean saveInSession, final U profile, final boolean multiProfile) { profile.addAuthenticationAttribute(SESSION_CLIENT_ID, context.getRequestParameter(REQUEST_CLIENT_ID)); super.save(saveInSession, profile, multiProfile); }
Source:
public void buildInfo(Model model) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try ( InputStream buildInfoStream = classLoader.getResourceAsStream("/buildInfo.properties"); InputStream runtimeEnvironmentStream = classLoader.getResourceAsStream("/runtimeEnvironment.properties"); ) { if (runtimeEnvironmentStream != null) { try { Properties runtimeEnvironmentProperties = new Properties(); runtimeEnvironmentProperties.load(runtimeEnvironmentStream); runtimeEnvironmentProperties.setProperty("java.version", System.getProperty("java.version")); model.addAttribute("runtimeEnvironment", runtimeEnvironmentProperties); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (buildInfoStream != null) { try { Properties buildInfoProperties = new Properties(); buildInfoProperties.load(buildInfoStream); model.addAttribute("buildInfo", buildInfoProperties); } catch (IOException e) { logger.error(e.getMessage(), e); } } } catch (IOException e) { logger.error(e.getMessage(), e); } }

Target:
public void buildInfo(Model model) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try ( InputStream buildInfoStream = classLoader.getResourceAsStream("/buildInfo.properties"); InputStream runtimeEnvironmentStream = classLoader.getResourceAsStream("/runtimeEnvironment.properties"); ) { if (runtimeEnvironmentStream != null) { try { Properties runtimeEnvironmentProperties = new Properties(); runtimeEnvironmentProperties.load(runtimeEnvironmentStream); runtimeEnvironmentProperties.setProperty("java.version", System.getProperty("java.version")); model.addAttribute("runtimeEnvironment", runtimeEnvironmentProperties); } catch (IOException e) { logger.error("failed to read 'runtimeEnvironment.properties' resource", e); } } if (buildInfoStream != null) { try { Properties buildInfoProperties = new Properties(); buildInfoProperties.load(buildInfoStream); model.addAttribute("buildInfo", buildInfoProperties); } catch (IOException e) { logger.error("failed to read 'buildInfo.properties' resource", e); } } } catch (IOException e) { logger.error(e.getMessage(), e); } }
Source:
public void validateSources() { if (Files.notExists(sourcesFile)) { logger.warn("sources.json not found: {}", sourcesFile); throw new PackageManagerException("sources.json is missing"); } if (!validateSchema(sourcesFile)) { throw new PackageManagerException("There were errors reading sources.json"); } }

Target:
public boolean validateSources() { if (Files.notExists(sourcesFile)) { logger.warn("sources.json not found: {}", sourcesFile); copyDefaultSources(); return true; } logger.trace("Validating '{}'", sourcesFile); try ( InputStream schemaIn = getClass().getResourceAsStream(SOURCES_SCHEMA); InputStream sourcesJson = Files.newInputStream(sourcesFile); InputStream sourcesJsonForGson = Files.newInputStream(sourcesFile) ) { InputStreamReader reader = new InputStreamReader(sourcesJsonForGson); Gson gson = new GsonBuilder() .registerTypeAdapter(DatabaseRepository.class, new DatabaseRepositoryDeserializer()) .create(); gson.fromJson(reader, DatabaseRepository[].class); JSONObject rawSchema = new JSONObject(new JSONTokener(schemaIn)); Schema schema = SchemaLoader.load(rawSchema); JSONArray toValidate = new JSONArray(new JSONTokener(sourcesJson)); schema.validate(toValidate); return true; } catch (ValidationException e) { logger.error("sources.json has invalid value at: {}", e.getPointerToViolation()); } catch (JSONException | JsonSyntaxException e) { logger.error("sources.json has syntax error: {}", e.getMessage()); } catch (IOException e) { logger.error("Failed to validate sources.json: {}", e.getMessage()); } return false; }
Source:
public int hashCode() { return Objects.hash(position, base, referenceBase, code); }

Target:
public int hashCode() { if (code == NO_CODE) { return Objects.hash(position); } return Objects.hash(position, base, referenceBase); }
Source:
private static TreeNode convertListToTreeNode(SampleList sampleList, boolean isFolderOnly) { TreeNode treeNode = new TreeNode(); treeNode.setKey(sampleList.getId().toString()); treeNode.setTitle(sampleList.getListName()); treeNode.setIsFolder(sampleList.isFolder() ? true : false); treeNode.setIsLazy(false); if (treeNode.getIsFolder()) { treeNode.setIcon(AppConstants.FOLDER_ICON_PNG.getString()); } else { treeNode.setIcon(AppConstants.BASIC_DETAILS_PNG.getString()); } if (isFolderOnly && !treeNode.getIsFolder()) { return null; } return treeNode; }

Target:
private static TreeNode convertListToTreeNode(SampleList sampleList, boolean isFolderOnly) { TreeNode treeNode = new TreeNode(); treeNode.setKey(sampleList.getId().toString()); treeNode.setTitle(sampleList.getListName()); treeNode.setIsFolder(sampleList.isFolder()); treeNode.setIsLazy(false); if (treeNode.getIsFolder()) { treeNode.setIcon(AppConstants.FOLDER_ICON_PNG.getString()); } else { treeNode.setIcon(AppConstants.BASIC_DETAILS_PNG.getString()); } if (isFolderOnly && !treeNode.getIsFolder()) { return null; } return treeNode; }
Source:
public static IClasspathContainer readMavenClasspath(IJavaProject javaProject) { IFile file = javaProject.getProject().getFile(".codenvy/classpath.maven"); IClasspathEntry[] entries; if (file.exists()) { try { char[] chars = Util.getResourceContentsAsCharArray(file); String content = new String(chars); if (!content.isEmpty()) { String[] split = content.split(":"); List<IClasspathEntry> classpathEntry = new ArrayList<>(); for (String path : split) { String srcPath = path.substring(0, path.lastIndexOf('.')) + "-sources.jar"; classpathEntry.add(JavaCore.newLibraryEntry(new org.eclipse.core.runtime.Path(path), new org.eclipse.core.runtime.Path(srcPath), null)); } entries = classpathEntry.toArray(new IClasspathEntry[classpathEntry.size()]); } else { entries = EMPTY; } } catch (JavaModelException e) { LOG.error("Can't read maven classpath.", e); entries = EMPTY; } } else { entries = EMPTY; } return new MavenClasspathContainer(entries); }

Target:
public static IClasspathContainer readMavenClasspath(IJavaProject javaProject) { IFile file = javaProject.getProject().getFile(".codenvy/classpath.maven"); IClasspathEntry[] entries; if (file.exists()) { try { char[] chars = Util.getResourceContentsAsCharArray(file); String content = new String(chars); if (!content.isEmpty()) { String[] pathToJars = content.split(":"); List<IClasspathEntry> classpathEntry = new ArrayList<>(); for (String path : pathToJars) { String srcPath = path.substring(0, path.lastIndexOf('.')) + "-sources.jar"; classpathEntry.add(JavaCore.newLibraryEntry(new org.eclipse.core.runtime.Path(path), new org.eclipse.core.runtime.Path(srcPath), null)); } entries = classpathEntry.toArray(new IClasspathEntry[classpathEntry.size()]); } else { entries = EMPTY; } } catch (JavaModelException e) { LOG.error("Can't read maven classpath.", e); entries = EMPTY; } } else { entries = EMPTY; } return new MavenClasspathContainer(entries); }
Source:
private String[] getConfigLoadString() { List<String> v = new ArrayList<String>(); for (PluginInfoWrapper pi : pluginWrappers) { v.add(pi.getFilename()); } synchronized (pluginWrappers) { if (!started) { return toStart; } v.addAll(pluginsFailedLoad.keySet()); } return v.toArray(new String[v.size()]); }

Target:
private String[] getConfigLoadString() { synchronized (loadedPlugins) { if (!started) { return toStart; } } List<String> v = new ArrayList<String>(); for (PluginInfoWrapper pi : loadedPlugins.getLoadedPlugins()) { v.add(pi.getFilename()); } v.addAll(loadedPlugins.getFailedPluginNames()); return v.toArray(new String[v.size()]); }
Source:
protected Annotation createAndValidateTag(String inputFile) throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return createAndValidateTag(inputFile, true); }

Target:
protected Annotation createAndValidateTag(String inputFile) throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return createTag(inputFile, true); }
Source:
private IMessage addMesssage(IResource target, int lineNumber, int offset, int length, int severity, String preferenceKey, String textMessage, String[] messageArguments, int quickFixId) { IMessage message = null; if(messageCounter<=getMaxNumberOfMarkersPerFile(target.getProject())) { if(lineNumber<0) { try { lineNumber = document.getLineOfOffset(offset) + 1; } catch (BadLocationException e) { CommonPlugin.getDefault().logError(e); } } message = addMesssage(validationManager, shouldCleanAllAnnotations(), this.reporter, offset, length, target, lineNumber, severity, textMessage, messageArguments, getMessageBundleName()); if(message!=null && quickFixId != -1) { message.setAttribute(MESSAGE_ID_ATTRIBUTE_NAME, quickFixId); } messageCounter++; if(preferenceKey != null){ message.setAttribute(PREFERENCE_KEY_ATTRIBUTE_NAME, preferenceKey); } String type = getProblemType(); if(type!=null) { message.setAttribute(MESSAGE_TYPE_ATTRIBUTE_NAME, type); } if(message != null) { String id = getId(); if(id != null) { message.setAttribute(VALIDATOR_ID_ATTRIBUTE, id); } if(asYouTypeTimestamp != 0) { message.setAttribute(VALIDATOR_TIMESTAMP_ATTRIBUTE, new Integer(asYouTypeTimestamp)); } } } return message; }

Target:
private IMessage addMesssage(IResource target, int lineNumber, int offset, int length, int severity, String preferenceKey, String textMessage, String[] messageArguments, int quickFixId) { IMessage message = null; if(messageCounter<=getMaxNumberOfMarkersPerFile(target.getProject())) { if(lineNumber<0) { try { lineNumber = document.getLineOfOffset(offset) + 1; } catch (BadLocationException e) { CommonPlugin.getDefault().logError(e); } } message = addMesssage(validationManager, shouldCleanAllAnnotations(), this.reporter, offset, length, target, lineNumber, severity, textMessage, messageArguments, getMessageBundleName()); if(message!=null && quickFixId != -1) { message.setAttribute(MESSAGE_ID_ATTRIBUTE_NAME, quickFixId); } messageCounter++; if(preferenceKey != null){ message.setAttribute(PREFERENCE_KEY_ATTRIBUTE_NAME, preferenceKey); } String type = getProblemType(); if(type!=null) { message.setAttribute(MESSAGE_TYPE_ATTRIBUTE_NAME, type); } message.setAttribute(VALIDATOR_ID_ATTRIBUTE, getId()); if(asYouTypeTimestamp != 0) { message.setAttribute(VALIDATOR_TIMESTAMP_ATTRIBUTE, new Integer(asYouTypeTimestamp)); } } return message; }
Source:
public XmlMetaStoreElement( String filename ) throws MetaStoreException { this(); setIdWithFilename( filename ); FileInputStream in = null; try { in = new FileInputStream( filename ); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse( in ); Element dataTypeElement = document.getDocumentElement(); loadElement( dataTypeElement ); loadAttribute( dataTypeElement ); loadSecurity( dataTypeElement ); } catch ( Exception e ) { throw new MetaStoreException( "Unable to load XML metastore attribute from file '" + filename + "'", e ); } finally { try { in.close(); } catch ( Throwable t ) { } } }

Target:
public XmlMetaStoreElement( String filename ) throws MetaStoreException { this(); setIdWithFilename( filename ); FileInputStream in = null; try { in = new FileInputStream( filename ); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse( in ); Element dataTypeElement = document.getDocumentElement(); loadElement( dataTypeElement ); loadAttribute( dataTypeElement ); loadSecurity( dataTypeElement ); } catch ( Exception e ) { throw new MetaStoreException( "Unable to load XML metastore attribute from file '" + filename + "'", e ); } finally { try { in.close(); } catch ( Throwable ignored ) { } } }
Source:
void handleLabelClick(PickerLabel label) { if (!queryField.isDisabled()) { queryField.setDisable(true); } finalAssignedLabels = updateFinalAssignedLabels(label); populatePanes(new ArrayList<>(), Optional.empty()); }

Target:
private void handleLabelClick(PickerLabel label) { queryField.setDisable(true); state.updateAssignedLabels(label); populatePanes(state); }
Source:
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if(element == null) return; element.replace(GoElementFactory.createExpression(project, DEFAULT_STRING)); }

Target:
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element == null || !element.isValid()) return; if (element instanceof GoExpression) { element.replace(GoElementFactory.createExpression(project, DEFAULT_STRING)); } }
Source:
public Location getDefaultLocation() throws APIException { Location location = null; String locationGP = Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME); if (StringUtils.hasText(locationGP)) { location = Context.getLocationService().getLocation(locationGP); } else if(location == null){ location = getDefaultLocation(null, locationGP); } return location; }

Target:
public Location getDefaultLocation() throws APIException { Location location = null; String locationGP = Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME); if (StringUtils.hasText(locationGP)) { location = Context.getLocationService().getLocation(locationGP); } return StringUtils.hasText(locationGP) ? Context.getLocationService().getLocation(locationGP) : getDefaultLocation(null, ""); }
Source:
public int getSizeEstimate() { byte[] tempData = data; if (tempData != null) { return tempData.length + metadataMap.size() + DataType.values().length; } else if (lastKnownSize != NOT_KNOWN) { return lastKnownSize; } log.warn("getSizeEstimate: LogData size estimate is defaulting to 1," + " this might cause leaks in the cache!"); return 1; }

Target:
public int getSizeEstimate() { if (lastKnownSize != NOT_KNOWN) { return lastKnownSize; } return 1; }
Source:
private void refreshViewer() { if (viewer.getControl().isDisposed()) { return; } viewer.getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() { if (viewer.getControl().isDisposed()) { return; } viewer.refresh(); } }); }

Target:
private void refreshViewer() { if (fViewer.getControl().isDisposed()) { return; } fViewer.getControl().getDisplay().asyncExec(() -> { if (!fViewer.getControl().isDisposed()) { fViewer.refresh(); } }); }
Source:
private void copyVmPermissions(UniquePermissionsSet permissionsToAdd) { if (!isVmInDb || !getParameters().isCopyVmPermissions()) { return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<Permissions> vmPermissions = dao.getAllForEntity(getVmId(), getCurrentUser().getId(), getSessionId(), false); for (Permissions vmPermission : vmPermissions) { permissionsToAdd.addPermission(vmPermission.getad_element_id(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate); } }

Target:
private void copyVmPermissions(UniquePermissionsSet permissionsToAdd) { if (!isVmInDb || !getParameters().isCopyVmPermissions()) { return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<Permissions> vmPermissions = dao.getAllForEntity(getVmId(), getSessionId(), false); for (Permissions vmPermission : vmPermissions) { permissionsToAdd.addPermission(vmPermission.getad_element_id(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate); } }
Source:
private void doStagefrightTest(int rid) throws Exception { Context ctx = getContext(); File pocdir = new File(ctx.getFilesDir(), "pocs"); pocdir.mkdir(); final String name = ctx.getResources().getResourceEntryName(rid); File pocfile = new File(pocdir, name + ".mp4"); extractRaw(ctx, rid, pocfile); Log.i(TAG, "Testing file: " + name); class MediaPlayerCrashListener implements MediaPlayer.OnErrorListener { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.i(TAG, "In error handler with error " + what); if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { crashed = true; } return true; } public boolean hasCrashed() { return crashed; } private boolean crashed = false; } MediaPlayer mp = new MediaPlayer(); MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(); mp.setOnErrorListener(mpcl); mp.setDataSource(pocfile.getPath()); try { mp.prepare(); } catch (IOException e) { } pocfile.delete(); String cve = name.replace("_", "-").toUpperCase(); assertFalse("Device *IS* vulnerable to " + cve, mpcl.hasCrashed()); }

Target:
private void doStagefrightTest(int rid) throws Exception { Context ctx = getContext(); AssetFileDescriptor fd = ctx.getResources().openRawResourceFd(rid); String name = ctx.getResources().getResourceEntryName(rid); Log.i(TAG, "Testing file: " + name); class MediaPlayerCrashListener implements MediaPlayer.OnErrorListener { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.i(TAG, "In error handler with error " + what); if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { crashed = true; } return true; } public boolean hasCrashed() { return crashed; } private boolean crashed = false; } MediaPlayer mp = new MediaPlayer(); MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(); mp.setOnErrorListener(mpcl); mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); try { mp.prepare(); } catch (IOException e) { } String cve = name.replace("_", "-").toUpperCase(); assertFalse("Device *IS* vulnerable to " + cve, mpcl.hasCrashed()); }
Source:
public void testProject() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); EnvironmentSettings envSettings = EnvironmentSettings.newInstance() .useBlinkPlanner() .inStreamingMode() .build(); StreamTableEnvironment tEnv = StreamTableEnvironment.create(env, envSettings); tEnv.executeSql( "CREATE TABLE " + INPUT_TABLE + "(" + "id BIGINT," + "timestamp6_col TIMESTAMP(6)," + "timestamp9_col TIMESTAMP(9)," + "time_col TIME," + "real_col FLOAT," + "double_col DOUBLE," + "decimal_col DECIMAL(10, 4)" + ") WITH (" + " 'connector'='jdbc'," + " 'url'='" + DB_URL + "'," + " 'table-name'='" + INPUT_TABLE + "'," + " 'scan.partition.column'='id'," + " 'scan.partition.num'='2'," + " 'scan.partition.lower-bound'='0'," + " 'scan.partition.upper-bound'='100'" + ")" ); Iterator<Row> collected = tEnv.executeSql("SELECT id,timestamp6_col,decimal_col FROM " + INPUT_TABLE + " LIMIT 1").collect(); List<String> result = CollectionUtil.iteratorToList(collected).stream() .map(Row::toString) .sorted() .collect(Collectors.toList()); List<String> expected = Stream.of( "1,2020-01-01T15:35:00.123456,100.1234", "2,2020-01-01T15:36:01.123456,101.1234") .sorted().collect(Collectors.toList()); assertEquals(expected, result); }

Target:
public void testProject() throws Exception { tEnv.executeSql( "CREATE TABLE " + INPUT_TABLE + "(" + "id BIGINT," + "timestamp6_col TIMESTAMP(6)," + "timestamp9_col TIMESTAMP(9)," + "time_col TIME," + "real_col FLOAT," + "double_col DOUBLE," + "decimal_col DECIMAL(10, 4)" + ") WITH (" + " 'connector'='jdbc'," + " 'url'='" + DB_URL + "'," + " 'table-name'='" + INPUT_TABLE + "'," + " 'scan.partition.column'='id'," + " 'scan.partition.num'='2'," + " 'scan.partition.lower-bound'='0'," + " 'scan.partition.upper-bound'='100'" + ")" ); Iterator<Row> collected = tEnv.executeSql("SELECT id,timestamp6_col,decimal_col FROM " + INPUT_TABLE).collect(); List<String> result = CollectionUtil.iteratorToList(collected).stream() .map(Row::toString) .sorted() .collect(Collectors.toList()); List<String> expected = Stream.of( "1,2020-01-01T15:35:00.123456,100.1234", "2,2020-01-01T15:36:01.123456,101.1234") .sorted().collect(Collectors.toList()); assertEquals(expected, result); }
Source:
private void mapExpandedElements(Object[] expandedElements) { HashMap elementMap = new HashMap(); for (Object expandedElement : expandedElements) { elementMap.put(((DateHistoryCategory) expandedElement).getName(), null); } ArrayList expandable = new ArrayList(); for (AbstractHistoryCategory categorie : categories) { if (elementMap.containsKey(categorie.getName())) { expandable.add(categorie); } } elementsToExpand = new Object[expandable.size()]; elementsToExpand = expandable.toArray(new Object[expandable.size()]); }

Target:
private void mapExpandedElements(Object[] expandedElements) { HashMap elementMap = new HashMap(); for (Object expandedElement : expandedElements) { elementMap.put(((DateHistoryCategory) expandedElement).getName(), null); } ArrayList expandable = new ArrayList(); for (AbstractHistoryCategory category : categories) { if (elementMap.containsKey(category.getName())) { expandable.add(category); } } elementsToExpand = new Object[expandable.size()]; elementsToExpand = expandable.toArray(new Object[expandable.size()]); }
Source:
protected GlusterVolumeTaskStatusEntity updateStatusEntity(GlusterVolumeTaskStatusEntity status) { setStartAndStopTime(status); updateLatestStatus(status); return updateHostDetails(status); }

Target:
protected GlusterVolumeTaskStatusEntity updateStatusEntity(GlusterVolumeTaskStatusEntity status) { if (status != null) { setStartAndStopTime(status); updateLatestStatus(status); return updateHostDetails(status); } else { return null; } }
Source:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().denyAll() .and() .exceptionHandling() .defaultAccessDeniedHandlerFor(new TeapotAccessDeniedHandler(), new HelloRequestMatcher()) .defaultAccessDeniedHandlerFor(new AccessDeniedHandlerImpl(), AnyRequestMatcher.INSTANCE) .and() .csrf().disable(); }

Target:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().denyAll() .and() .exceptionHandling() .defaultAccessDeniedHandlerFor( this.teapotDeniedHandler, new AntPathRequestMatcher("/hello/**")) .defaultAccessDeniedHandlerFor( new AccessDeniedHandlerImpl(), AnyRequestMatcher.INSTANCE); }
Source:
public Response retrieveDetailsForIp(@QueryParam("ip") String ipAddress) { if (!isUserInRole("cp,ops")) { return ResponseFactory.accessDenied(); } VirtualIpLoadbalancerDetails rLbDetails; try { rLbDetails = virtualIpService.getLoadbalancerDetailsForIp(ipAddress); } catch (Exception e) { return ResponseFactory.getErrorResponse(e, null, null); } if (rLbDetails.getAccountId() == null) { return Response.status(Response.Status.NO_CONTENT).build(); } return Response.status(200).entity(rLbDetails).build(); }

Target:
public Response retrieveDetailsForIp(@QueryParam("ip") String ipAddress) { if (!isUserInRole("cp,ops")) { return ResponseFactory.accessDenied(); } VirtualIpLoadbalancerDetails rLbDetails; try { rLbDetails = virtualIpService.getLoadbalancerDetailsForIp(ipAddress); } catch (Exception e) { return ResponseFactory.getErrorResponse(e, null, null); } if (rLbDetails.getAccountId() == null) { return Response.status(Response.Status.NO_CONTENT).build(); } return Response.status(Response.Status.OK).entity(rLbDetails).build(); }
Source:
public boolean isAjax(final WebContext context) { final boolean xmlHttpRequest = AJAX_HEADER_VALUE.equalsIgnoreCase(context.getRequestHeader(AJAX_HEADER_NAME).orElse(null)); final boolean hasDynamicAjaxParameter = Boolean.TRUE.toString() .equalsIgnoreCase(context.getRequestHeader(IS_AJAX_REQUEST).orElse(null)); final boolean hasDynamicAjaxHeader = Boolean.TRUE.toString() .equalsIgnoreCase(context.getRequestParameter(IS_AJAX_REQUEST).orElse(null)); return xmlHttpRequest || hasDynamicAjaxParameter || hasDynamicAjaxHeader; }

Target:
public boolean isAjax(final WebContext context) { final boolean xmlHttpRequest = context.getRequestHeader(AJAX_HEADER_NAME) .map(h -> AJAX_HEADER_VALUE.equalsIgnoreCase(h)) .orElse(false); final boolean hasDynamicAjaxParameter = context.getRequestHeader(IS_AJAX_REQUEST) .map(dap -> Boolean.TRUE.toString().equalsIgnoreCase(dap)) .orElse(false); final boolean hasDynamicAjaxHeader = context.getRequestParameter(IS_AJAX_REQUEST) .map(h -> Boolean.TRUE.toString().equalsIgnoreCase(h)) .orElse(false); return xmlHttpRequest || hasDynamicAjaxParameter || hasDynamicAjaxHeader; }